text:
Q: Is there a sane way to parse a nested JSON with unknown structure into an object or a dictionary in Swift 5? Disclaimer: There are quite a few similar questions posted, but not one of them seems to duplicate my own
Suppose my app receives a JSON from quite poorly engineered API, and that JSON that looks something like this:
{
    "matches": {
        "page1": [{
            "name": "John",
            "surname": "Doe",
            "interests": [{
                    "id": 13,
                    "text": "basketball"
                },
                {
                    "id": 37,
                    "text": "competitive knitting"
                },
                {
                    "id": 127,
                    "text": "romcoms"
                }
            ]
        }],
        "page2": [{
            "name": "Dwayne",
            "surname": "Johnson",
            "interests": [{
                    "id": 42,
                    "text": "sci-fi"
                },
                {
                    "id": 255,
                    "text": "round numbers"
                }
            ]
        }]
    }
}

If I want to get, say, all the interests from all the matches, in native Swift functionality I'd first have to do some like this:
struct MatchesData: Codable {
    let matches: Matches
}

struct Matches: Codable {
    let page1: Page1
    let page2: Page2
}

struct Page1: Codable {
    let interests: [Interest]
}

struct Page2: Codable {
    let interests: [Interest]
}

struct Interest: Codable {
    let id: Int
    let text: String
}

Then, I'd have to use the structs I created, in a manner like this:
func handleJSON(_ response: Data) {
        let decoder = JSONDecoder()
        do {
            let decodedData = try decoder.decode(MatchesData.self, from: response)
            // Only here I can start actually working with the data API sent me, it's in decodedData
            ...
        } catch {
            // Handle the errors somehow
            return
        }
}

While this kinda works, it has two major drawbacks.
Firstly, that all put together is an insane amount of preparation and code in general for a task that simple, and it doesn't comply with the DRY principle.
Lastly, this approach simply doesn't work if you don't know the exact structure of the JSON beforehand. For instance, in my example, what if the amount of pages wasn't fixed to 2, but could rather be anywhere between, say, 1 and 50?
In other languages that have sane in-built tools for working with JSON, I'd just parse the JSON and recursively iterate through matches to do what I need with the content.
Examples (without safety precautions to improve readability):
JS:
const handleJSON = jsonStr => {
  const jsonObj = JSON.parse(jsonStr)
  const matches = jsonObj.matches
  Object.values(matches).forEach(page => {
    // Recursively process every page to find what I need and process it
  })
}

Python 3:
import json

def handleJSON(jsonStr):
  jsonObj = json.loads(jsonStr)
  matches = jsonObj['matches']
  for page in matches:
    # Recursively process every page to find what I need and process it

PHP:
function handleJSON($jsonStr) {
    $jsonObj = json_decode($jsonStr);
    $matches = $jsonObj->matches;
    foreach ($matches as $page) {
        // Recursively process every page to find what I need and process it
    }
}

So, the question is, how do I achieve the same in Swift in a sane manner, just like in the examples above (which definitely means roughly the same amount of code)? If you know a 3rd party lib that does just that, I'd happily accept such a lib for an answer.
UPDATE: Just found out about Jsonify, which seems to be at least as good of a solution to my issues as SwiftyJSON, maybe even better. One should probably try both out for a while to decide which one suits their taste and needs better

A: First of all, keep in mind that there is no need for structs to be global in scope. You can define a struct "temporarily" within a function just for the purposes of helping you dip down into the JSON and fetch out a value. Thus the overall architecture of the code is in no way marred.
Second, your own example JSON is not as insane as you suggest; what's insane is your own structs. First, your use of two identical structs. There is no purpose whatever to having a struct Page1 and a struct Page2. Second, there is no purpose to your Matches either. That isn't what your JSON is. In your MatchesData, the matches property should be merely a dictionary of type [String:[Person]] (you don't have a Person type but that is what these things seem to be).
If your claim is that the dictionary should have been an array in the JSON, fine, I agree. If the keys are always going to be named "page1", "page2", etc., the JSON is silly in that respect. But then you can later transform the [String:[Person]] into an array of Person ordered by the numbers on the end of the String "page" keys. And then you can map that into an array of Interest if you want to throw away the rest of the Person info.
In other words: How you parse the data that arrives to you and how you maintain the data you are interested in, are two completely different matters. Parse the data just get yourself out of the JSON world and into the object world; then transform it into a form that is useful to you, keeping what you need and ignoring what you don't.
Here's an example of the sort of thing you might do:
let data = s.data(using: .utf8)!

struct Result : Codable {
    let matches:[String:[Person]]
}
struct Person : Codable {
    let name:String
    let surname:String
    let interests:[Interests]
}
struct Interests : Codable {
    let id:Int
    let text:String
}
let result = try! JSONDecoder().decode(Result.self, from: data)

Okay, so now we've parsed the darned data. But we hate its structure. So change it!
// okay, but dictionary is silly: flatten to an array
let persons1 = Array(result.matches)
func pageNameToNumber(_ s:String) -> Int {
    let num = s.dropFirst(4)
    return Int(num)!
}
let persons2 = persons1.map {(key:pageNameToNumber($0.key), value:$0.value)}
let persons3 = persons2.sorted {$0.key < $1.key}
let persons4 = persons3.map { $0.value }

But we still have the silly one-element arrays to deal with:
// okay, but the one-element array is silly, so flatten that too
let persons5 = persons4.map {$0.first!}

And now you say you never cared about the person stuff at all, all you want is the list of interests:
// okay but all I care about are the interests
let interests = persons5.map {$0.interests}

(And then you could flatten the interests as well, or whatever.)
Now, if all of that were done in a method, then only the Interests struct would need to be public; everything else is just a tool to get the values extracted, and can be private to the interior of the method. Only make public the structs that your app really needs / wants for the maintenance of the data. The overall lesson, though, is: just parse the darned JSON into objects: now you are in the Swift object world, and can re-parse those objects in whatever way is ultimately useful to you.

A: If you are looking for an external library that does this, you can try SwiftyJSON, which allows you to get all the interests like this:
    let json = JSON(parseJSON: jsonString)
    let matchesObject = json["matches"]
    // I assume the total number of pages is stored in numberOfPages
    let interests = (0..<2).flatMap {
        matchesObject["page\($0 + 1)"].arrayValue.flatMap {
            $0["interests"].arrayValue.map {
                // using the same Interest struct as in your question
                Interest(id: $0["id"].intValue, text: $0["text"].stringValue)
            }
        }
    }


text:
Q: How do I set the DispayMember and ValueMember Properties of a ComboBox w/ DataSource set to an Object using Powershell? What I am trying to do doesn't seem like it should be that hard but I can't seem to get it to work.  I have comboboxes in use elsewhere using a dataset as the datasoure that work just fine but in this case I wanted to use an object.
Here are the relevant portions of my code generalized.
The Object:
$RemoteScript = {Get-ADUser -Filter {enabled -eq $true} -SearchBase "OU=Users,DC=DOMAIN,DC=local" }
# Returns an ADUser Object
$CurrentUsers = Invoke-Command -Session $mySession -ScriptBlock $RemoteScript

The above block of code returns the ADUser object with the following relevant properties:
DistinguishedName
Name
UserPrincipalName

The Following Code attaches the Data to my combobox:
$cbComboBox.ValueMember = "UserPrincipalName"
$cbComboBox.DisplayMember = "Name"
$cbComboBox.DataSource = $CurrentUsers

When the combobox displays, it uses the "DistinguishedName" to populate the Display and Value members rather than the members I have specified.  I can force it to use a single value using $cbComboBox.DataSource = $CurrentUsers.Name but that would leave me looping through the $CurrentUsers with a ForEach to extract the "UserPrincipalName".
What am I missing?
EDIT
To clarify the loop I was referring to.
The above code should display the Name property to the user.  In the button handler I was planning to use $cbComboBox.SelectedValue to grap the "UserPrincipalName" from the combobox. Since the combobox is not recognizing the ValueMember or the DisplayMember properties, the  SelectedVlaue is returning the DistinguishedName property instead.
If I can't get the combobox to work properly I will have to force the Name property as I mentioned above and put the following code in the button handler instead.
ForEach ($User in $CurrentUsers) {
    If ($User.Name -eq $cbComboBox.SelectedValue) {
        $myUser = $User.UserPrincipal
    }
}

A: No loop needed, just do something like this:
$myUser = $CurrentUsers | Where{$_.Name -eq $cbComboBox.SelectedValue} | Select -ExpandProperty UserPrincipal

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the Current User IP in Python / Django I am trying to capture the IP Address and the System Name of the current Login user during the login Process.
I Use following code for the same:
import socket
system = socket.gethostname()
IPAddr = socket.gethostbyname(system)

It works fine in Local Server but when I push to Server it takes the server name and server IP instead of user IP.


text:
Q: Predefined symbol to tell armeabi-v7a apart? Is there a pre#defined symbol in Android NDK/GCC that would let me distinguish between armeabi and armeabi-v7a builds?
For now, I make do with following lines in Android.mk
ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)
LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS) -D ARMv7
endif

but that's kinda crude.

A: For runtime support have a look into $NDK/docs/CPU-FEATURES.html.
or see machine/cpu-features.h for various possible defines.


text:
Q: Обработка EditText и передача в БД Подскажите, как я могу считать данные с EditText и прогнать их через метод в другом классе?
Вот мой MainActivity:
public class MainActivity extends AppCompatActivity {

CoverDB coverDB;
Button btn_addDepartment;
EditText departmentName,description;

String nameDepartment;
String descriptionDepatment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Stetho.initializeWithDefaults(this);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final AlertDialog.Builder addDepartmentWindow = new AlertDialog.Builder(this);
    View linearlayout = getLayoutInflater().inflate(R.layout.dialog_add_departments, null);
    addDepartmentWindow.setView(linearlayout);

    departmentName = (EditText) linearlayout.findViewById(R.id.departmentName);
    description = (EditText) linearlayout.findViewById(R.id.description);
    btn_addDepartment = (Button) linearlayout.findViewById(R.id.btn_addDepartment);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            addDepartmentWindow.setTitle("Add Department");
            addDepartmentWindow.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            addDepartmentWindow.create();
            addDepartmentWindow.show();
        }
    });

    ReaderDB readerDB = new ReaderDB(this);
    coverDB = new CoverDB(readerDB);
    coverDB.addDepartments(nameDepartment, descriptionDepatment);

    btn_addDepartment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // обработка нажатия на кнопку Добавить
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Мой метод, который обрабатывает добавление (Лежит в классе CoverDB)
public void addDepartments(String name, String description) {
    ContentValues values = new ContentValues();
    values.put(StructureDB.TableDepartments.COLUMN_NAME_TITLE, name);
    values.put(StructureDB.TableDepartments.COLUMN_NAME_DESCRIPTION, description);
    SQLiteDatabase db = this.db;
    db.insert(StructureDB.TableDepartments.TABLE_NAME, null, values);
}

A: Алгоритм действий должен быть примерно таким:

*

*Назначаем слушатель нажатия на ОК кнопку диалога.

*В нём вытаскиваем текст из полей ввода и передаём в ваш метод:

addDepartmentWindow.setPositiveButton("OK",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                ReaderDB readerDB = new ReaderDB(this);
                coverDB = new CoverDB(readerDB);
                coverDB.addDepartments(departmentName.getText().toString(), description.getText().toString());
            }
        });


text:
Q: Pass Json Object and String Value at once in Ajax I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
            var jdata = ko.mapping.toJSON(viewModel);
            var Cid = $(this).val();
            //alert(intCountry);
            $.ajax({
                url: '@Url.Action("PopulateDropDown", "Pepmytrip")',
                type: 'POST',
                data: jdata,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (data.redirect) {
                        location.href = resolveUrl(data.url);

                    }
                    else {
                        ko.mapping.fromJS(data, viewModel);
                    }
                },
                error: function (error) {
                    alert("There was an error posting the data to the server: " + error.responseText);
                },

            });
        });

My Action Method
 public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
        {
            wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
            return Json(wrapper);
        }

I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.

A: you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
  url: '@Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
  ...

server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
        {
            wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
            return Json(wrapper);
        }

OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);

server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
        {
            var cid = wrapper.Cid;
            wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
            return Json(wrapper);
    }

A: I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.

A: You can achieve this is two ways:

*

*You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.

*Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter


text:
Q: Replace 1 character from the link Google has an old link:
http://example.com/blog/?top-name-electronics-at-great-prices

And i need old link to work and redirect to:
http://example.com/blog/top-name-electronics-at-great-prices

I know it supposed to be easy but tried so many things and only getting errors.

A: You can use this rule as your very first rule in your .htaccess:
RewriteEngine On

RewriteCond %{QUERY_STRING} .
RewriteRule ^blog/?$ /$0%{QUERY_STRING}? [L,NC,R=301,NE]

However, if there is already a .htaccess inside blog/ then use this rule:
RewriteCond %{QUERY_STRING} .
RewriteRule ^/?$ /blog/%{QUERY_STRING}? [L,R=301,NE]


text:
Q: Adding .split into my code I'm creating a console program in Java with an array, I need to enter all of my code on one line in the following format up to 100 times.
car_make_name : car_model_name : car_model_tax : car_model_price
It's two strings and two int variables, I have code written out but I don't know how to use .split to enter the correct information into the corresponding variable.
This is my code:
public class Main {

    public static void main (String[] args)

    {
        //Arrays declared
          String[] cars = new String[20];
          String[] car_model_name = new String[20];
          int[] car_model_tax = new int[20];
          String[] car_make_name = new String[20];
          int[] car_model_price = new int[20];

          Scanner scan = new Scanner (System.in);

          //Loop??
          while (scanner.hasNextLine()) {
           String line = scanner.nextLine();
           if (line.equals("quit", "QUIT", "Quit")) {

           }

          }
            break;

            for (int x = 0; x < cars.length; x++){
                   System.out.println("Enter details, separating each with a ':' ");
                   cars[x] = System.console().readLine();

            }

    }

}

A: First, you may prefer List but not array to store your information if you read input from console and you can't control the input length of your user.
Second, you may want to use String#split to split and convert it if necessary.
    System.out.println("Enter details, separating each with a ':' ");
    Scanner scan = new Scanner(System.in);
    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        if (line.equals("quit")) {
            break;
        }
        final String[] split = line.split(":");
        // handle it
    }

Third, A good book can improve your programming level so much.If you have no experience of programming, I recommend Head First Java. Otherwise, I recommend Thinking In Java.


text:
Q: TableView rows hide and show as Bool function As shown in image, initially I need to hide last 2 rows (my profile and update profile) in my table view when the user fills the form accessed via the "Become a merchant" row. I need to hide the "Become a Merchant" row and show the last two rows. This is done by Bool function(true/false).

How could I do this?
var arrdata = ["Home", "Orders", "Change Password", "Log Out", "Become A Merchant", "My Profile", "Update Profile"]

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var isMerchantProfile: Bool = UserDefaults.standard.bool(forKey: "isFillMerchant")
        if isMerchantProfile == true {
            return 4
        }

        return arrdata.count
}

A: Remove / add the rows you want to show from your data array and then use the table view functions insertRowsAt / deleteRowsAt. Do bulk updates using the performBatchUpdates function.
Refer to the UITableView documentation.
I would also recommend in this case using an enum to define your rows and rather than raw strings representing the titles of the rows.
e.g. (inside your view controller class is fine)
enum Row {
    case home, orders, changePassword, logout, becomeMerchant, myProfile, updateProfile

    var title: String {
        switch self {
        case .home:
            return NSLocalizedString("Home", comment: "Row title")
        // … etc
        }
    }
}

Then it's a bit easier to find the rows you want to remove / where to insert your rows and keep your code clean.

A: I would adjust the data/array when reloadTable is called to match the expected behavior.
var arrdata = ["Home", "Orders", "Change Password", "Log Out", "My Profile", "Update Profile"] and then later:
var arrdata = ["Home", "Orders", "Change Password", "Log Out", "Become A Merchant", "My Profile", "Update Profile"] when you want this to show.

A: I think first you need to be able to establish whether or not the user has filled the form out. Maybe using an enum type with different user levels to display different content. So maybe something like this.
enum UserType {
   case basic
   case merchant
}

Then when you load the data into the table view just switch on UserType and load the proper data set. That would allow you to use this implementation elsewhere throughout your app as well if you needed to add/remove data/views based on user type. So your menus would look something like this:
let basicUserMenu = ["Home", "Orders", "Change Password", "Log Out", "Become Merchant"]
let merchantUserMenu = basicUserMenu + ["My Profile", "Update Profile"]

And then your table view implementation would look something like this where userType is your stored UserType enum value. By default it would be .basic but after the user fills out the form successfully changes to .merchant
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch userType {
        case .basic:
            return basicUserMenu.count
        case .merchant:
            return merchantUserMenu.count
    }
 }

Then do the same thing for cellForTowAtIndexPath


text: Q: How do you change the title bar color in Visual Studio 2019 C++ WinForms? Hello I am a beginner at WinForms for C++ but in C++ i have gotten up to the point of where I am learning classes and objects. I would like to know how to personalize the color of the title bar in the most simple way as I am a beginner. If you want me to send you the code that is in the header file (.h file) I can.


text:
Q: How to make a thicker text shadow using css? I want to achieve this text style like so:

I want to wrap the text with color white like the image above I tried using
   text-shadow: 0px 0px 5px #fff;

but it turns out that the shadow will get blurry. Is there any chance that I can do it using css (if so how)? or should I just convert it into image?

A: The effect you seek is called stroke and sadly not possible (yet) with CSS in a cross browser compatible way.
Faking it with shadows will not work for a stroke thicker than 1 or 2 pixels, or require a ton of layered shadows, slowing down rendering. Other faking techniques are possible but not quite fantastic.
For now the best bet remains to use images for the rare occasions where this is useful.

A: You can simulate it, doing like this:
CSS
span{
  text-shadow: 2px 2px 0px  #fff, -2px -2px 0px  #fff, 2px -2px 0px  #fff, -2px 2px 0px  #fff;
}

DEMO HERE

A: Ran into this today and at least for Webkit browsers, there's a better solution. You can follow this old article using the code
-webkit-text-stroke-width: 1px;
-webkit-text-stroke-color: black;

and also try using text shadows with it. It worked well for me after some pixel-pushing. I have some bigger letters, so I ended up using a text shadow like this
text-shadow: 4px 4px 0px #010000, 2px 3px 0px #010000, 4px 5px 0px #010000, 4px 6px 0px #010000;

I hope that helps!


text:
Q: ghettoVCB: ERROR: Unable to backup MACHINE-NAME due to error in VMDK backup I'm on VMware ESXI 5.0.0 Update 1 and wanted to use the ghettoVCB script for backuping my VMs.
The dryrun went perfectly fine:
2012-10-24 11:47:46 -- info: ###### Final status: OK, only a dryrun. ######

But when I try to do an actual backup, I get the following message for every VM on my host:
2012-10-24 11:48:43 -- info: Initiate backup for Willert-Tools
2012-10-24 11:48:43 -- info: Creating Snapshot "ghettoVCB-snapshot-2012-10-24" for Willert-Tools

2012-10-24 11:48:47 -- info: ERROR: error in backing up of "/vmfs/volumes/datastore1/Willert-Tools/Willert-Tools_1.vmdk" for Willert-Tools

2012-10-24 11:48:47 -- info: ERROR: error in backing up of "/vmfs/volumes/datastore1/Willert-Tools/Willert-Tools.vmdk" for Willert-Tools
2012-10-24 11:48:50 -- info: Removing snapshot from Willert-Tools ...
2012-10-24 11:48:50 -- info: Compressing VM backup "/vmfs/volumes/Cluster-Backup/Willert-Tools/Willert-Tools-2012-10-24_11-48-31.gz"...
2012-10-24 11:48:50 -- info: Successfully compressed backup for Willert-Tools!

2012-10-24 11:48:50 -- info: Backup Duration: 7 Seconds
2012-10-24 11:48:50 -- info: ERROR: Unable to backup Willert-Tools due to error in VMDK backup!

What am I doing wrong? As I didn't want to paste every configuration snippet from my configuration, please ask if you need more specific information.
The backup is supposed to be saved to a NFS share which is correctly mounted on my ESXi host.
Thanks for your help :-).

A: the most I can suggest by seeing the output is:
1) Are you sure the path to your NFS mount or datastore is correct in the ghettoVCB configs?  Double check all NFS configs for ghettoVCB.
And...
2) Is your NFS share accepting anonymous access and granting read/write permissions?
Judging by the output, the script was able to create the snapshot but then 5 seconds later it said it could not back up the VMDK.  My guess is this is a permissions issue on NFS mount.  That, or lack of free space.

A: I recently began seeing this error on a system that had long been running flawlessly, and which had not been changed.  One difference is that ghettoVCB was successfully backing up the other VMs on the system.
Direct execution of vmkfstools clone command resulted in the same error, with 3 different target file systems.  The VM was powered down for this attempt.
This is a windows 7 pro VM.  What ultimately worked for me was the following:

*

*defrag the drive (used defraggler)

*zero the free space (\sdelete\sdelete -z c:)

*chkdsk c: /f

*reboot

*shutdown

*ssh to esxi 5.5 box

*vmkfstools -i /path/to/disk.vmdk -d thin /path/to/disk_backup.vmdk

*

*note the "-d thin" is useless when writing to the same physical medium as the source disk.

SUCCESS!

*

*vmkfstools -E /path/to/disk.vmdk /path/to/renamed_disk.vmdk

*vmkfstools -E /path/to/disk_backup.vmdk /path/to/disk.vmdk

*Start up the vm to test

*run ghettoVCB against the VM while the VM was "powered up" (with the added benefit that the "thin" parameter applies when writing from the source to the NFS target).

SUCCESS!
I suspect the sdelete command was the key operation.
Remember to remove the renamed_disk.vmdk and renamed_disk-flat.vmdk

addenda (2020-11-03)
This issue recently came up in the ghettoVCB mailing list (Error in VMDK backup (#202)). This is the thread for ghettoVCB on GitHub.
the user described this issue, then later posted this fix:

So I made one change, and that was to mount my backup datastore as
nfs3 instead of nfs4. This seems t have solved the issue. Not sure why
it is, but posting this in case anyone else runs into a similar issue.

There was also a handy tip for troubleshooting in the thread, contributed by another user:

Some times is difficult to find an error on vmkfstools phase, like a
bad block on a storage, the returned error is a generic error.
Using -v 10 on vmkfstools line, like above, you can watch and find the
error, but when ghettoVCB.sh runs on CRON schedule, the captured log
does not includes the debug lines from vmkfstools:
Lines changed:
if [[ -z "${FORMAT_OPTION}" ]] ; then
logger "debug" > "${VMKFSTOOLS_CMD} -i "${SOURCE_VMDK}" -a "${ADAPTER_FORMAT}" "${DESTINATIO ...
${VMKFSTOOLS_CMD} -v 10 -i "${SOURCE_VMDK}" -a "${ADAPTER_FORMAT}" "${DESTINATION_VMDK}" > "${V...
else
logger "debug" "${VMKFSTOOLS_CMD} -i "${SOURCE_VMDK}" -a "${ADAPTER_FORMAT}" -d "${FORMAT_...
${VMKFSTOOLS_CMD} -v 10 -i "${SOURCE_VMDK}" -a "${ADAPTER_FORMAT}" -d "${FORMAT_OPTION}" "${DES
fi

where "lines changed" are in the ghettoVCB.sh script.


text:
Q: Preventing open file locks when site is shut down A file is opened by a thread for writing. The reference to the file is a local variable in a method and therefore unable to be cleaned up by dispose or a finalizer.
The code uses a using statement to make sure that the file is closed and all locks are released during normal operation. However, in the instance of a site be shut down, the using statement might not get a chance to clean up the FileStream. However, the IIS process may stay open, so the lock will not be released unless the server is restarted.
What is the best way to prevent a file lock from hanging if the site is stopped or restarted?
Or does the way IIS shut down a site mitigate this concern?

A: It is a good principle to minimise resource locks as much as possible, and you are seeing one consequence of not doing this. I suggest you only open and lock the file when you actually need to write to it, and release the lock and close the file immediately afterwards. If you are worried about the performance overhead of repeatedly opening the file (and seeking to the end to append), then you should profile the code to see if the performance is acceptable.


text:
Q: Discord.js bot not loading image urls in MessageEmbeds(), was previously So one of my bots has a majority of it's commands contain imagery via the Discord.MessageEmbed() function, which has worked since I first tried it. Now, however, out of nowhere, the images no longer load in, however with my meme command (I have it set to log the image link) it does log the correct link. It is with all of my commands that contain imagery, as stated.
I have tried re-installing each of the packages the bot uses, and it still doesn't work. I tried looking it up online, however nothing applied to me

A: There seems to be an issue with the whole discord system at the moment. If you try sending a link, there won't be an embed either.
The discord team is actively working to fix the issue at the moment.


text:
Q: Shorten the php code by loop Happy new year everyone!Here is my codes.Is there any way to short the code by using a loop?In a loop,the first field display once and the corresponding subfield display 5 elements.
For example:
   first field: Web browser
   subfield elements:firefox,chrome,IE,opera,maxthon

<?php
$sort=get_field('category');
         echo "

".$sort[ 0 ]['fenlei']."

";
$websites = get_field('classification');
$row_count = count($websites);
   for ($i = 0; $i <= 4; $i++){
        include( get_stylesheet_directory() . '/template.php');
       }

?>

<?php
$sort=get_field('category');
         echo "

".$sort[ 1 ]['fenlei']."

";
$websites = get_field('classification');
$row_count = count($websites);
   for ($i = 5; $i <= 9; $i++){
        include( get_stylesheet_directory() . '/template.php');
       }

?>

<?php
$sort=get_field('category');
         echo "

".$sort[ 2 ]['fenlei']."

";
$websites = get_field('classification');
$row_count = count($websites);
   for ($i = 10; $i <= 14; $i++){
        include( get_stylesheet_directory() . '/template.php');
       }

?>

the content of template.php

        <a href="<?php echo $websites[ $i ]['link']; ?>" title=<?php echo $websites[ $i ]['name']; ?> target="_blank">
          <img src="<?php echo $websites[ $i ]['icon']; ?>" width="194" height="97" />

            <a href="<?php echo $websites[ $i ]['link']; ?>" title="Firefox" target="_blank"><?php echo $websites[ $i ]['name']; ?>

<?php echo $websites[ $i ]['description'];; ?>

Download:

            <a href="<?php echo $websites[ $i ]['download']; ?>" target="_blank">32Bit

A: Probably not in a meaningful way, but a function is in order:
function echoCode($sortIndex,$start,$stop) {
    $sort=get_field('category');
    echo "

".$sort[$sortIndex]['fenlei']."

";
    $websites = get_field('classification');
    $row_count = count($websites);
    for ($i = $start; $i <= $stop; $i++)
        include( get_stylesheet_directory() . '/template.php');
}

then just call this twice with (0,0,4) and (1,5,9).

A: <?php

function print_row($sort, $websites) {
  return function($limit_offset, $i) use($sort, $websites) {
    $start = $limit_offset[0];
    $end = $limit_offset[0] + $limit_offset[1];
    return "

"
      . $sort[$i]['fenlei']
      . "

"
      . implode('', array_map(range($start, $end), row_template($websites)));
    };
  }

  function row_template($websites) {
    return function($i) use($websites) {
      ob_start();
      include(get_stylesheet_directory() . '/template.php');
      return ob_get_contents();
    };
  }

  $sort = get_field('category');
  $websites = get_field('classification');
  $offsets = [[0, 4], [5, 4], [10, 4]];
  $results = array_map($offsets, print_row($sort, $websites));

  print implode('', $results);


text:
Q: Failed to install rabbitmq-server on Linux(Oracle Linux Server release 6.7/RHEL) I am getting following error while installing.
$ sudo yum install rabbitmq-server
Loaded plugins: aliases, changelog, fastestmirror, kabi, presto, refresh-packagekit, security, tmprepo, ulninfo, verify, versionlock
Loading support for kernel ABI
Setting up Install Process
Loading mirror speeds from cached hostfile
 * epel: archive.linux.duke.edu
 * ol6_UEKR3: slcac475.us.oracle.com
 * ol6_latest: slcac475.us.oracle.com
Resolving Dependencies
--> Running transaction check
---> Package rabbitmq-server.noarch 0:3.1.5-1.el6 will be installed
--> Finished Dependency Resolution`
...
...
...
groupadd: Can't get unique system GID (no more available GIDs)
useradd: group 'rabbitmq' does not exist
error: %pre(rabbitmq-server-3.1.5-1.el6.noarch) scriptlet failed, exit status 6
Error in PREIN scriptlet in rpm package rabbitmq-server-3.1.5-1.el6.noarch
error:   install: %pre scriptlet failed (2), skipping rabbitmq-server-3.1.5-1.el6
Verifying  :
 rabbitmq-server-3.1.5-1.el6.noarch

Failed
rabbitmq-server.noarch 0:3.1.5-1.el6
Complete!

Note: I have already installed the erlang
I have refereed few posts already there
Installing rabbitmq-server on RHEL
RabbitMQ install issue on Centos 5.5

A: Go to /etc/login.defs and check if you have something like this, if not add it into it.
SYS_GID_MIN               2000
SYS_GID_MAX               9000


text:
Q: MS-Tests: How to maintain test-setting across different dev-environments? I am setting up a solution that is used by multiple developers/ teams that are working on different features of the next release of an application.
In my IntegrationTest-project I need to maintain the test-setting for the different teams. Basically each team uses a different test-server /web-services.
I can create a ".testsettings" file but I cannot find the section where I could define simple key-values pairs. For the testing I only need a few key-value pairs (server_url, webservice_url, ...)
Furthermore: How to I access the ".testsettings" at runtime form my unit-tests?


text:
Q: IntentService onCreate() called but onHandleIntent() not I'm starting an IntentService with the following method:
private void startMyService(Data data) {
    Intent intent = new Intent(this, MyService.class);
    intent.putExtra(KEY_DATA, data.toJson());
    startService(intent);
}

The Data class:
public class Data extends ArrayList<MyObject> {

    public Data() {
        super();
    }

    public Data(Collection<MyObject> myObjects) {
        super(myObjects);
    }

    public String toJson() {
        return new Gson().toJson(this);
    }

    public static Data fromJson(String jsonString) {
        return new Gson().fromJson(jsonString, Data.class);
    }
}

The relevant part of the IntentService:
public class MyService extends IntentService {

    private Data data;

    public MyService() {
        super("myServiceName");
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // this gets called properly
        Log.d("myTag", "Service onCreate()");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // this is not called in case of the bigger dataset
        Log.d("myTag", "Service onHandleIntent()");

        String dataJson = intent.getStringExtra(KEY_DATA);
        data = Data.fromJson(dataJson);

        // doing stuff with data
    }
}

I have 2 test scenarios:

*

*Data holds 2000 objects

*Data holds 4000 objects

With 2000 objects, the Service runs flawlessly.
With 4000 objects, the onCreate() method of the Service is called and that's it... onHandleIntent() is not called. The app just throws an ANR after a while.
I've tested with both Log.d() calls and breakpoints on the first line of onHandleIntent(), it is not called at all when Data holds 4000 objects.
TransactionTooLargeException is not thrown.
I get no Exceptions thrown at all, no idea what's wrong.
What could be the cause of this behaviour?

A: You may not see the TransactionTooLargeException if you are filtering the logcat. There is a reasonable limit to the amount of data that you can pass in an Intent. 4000 objects serialized to JSON is definitely too mucn! This is the wrong approach. Your application architecture is flawed.
You can simply store the 4000 objects in a static variable so that the Service can get to them without having to serialize them, pass them from Activity to Service, then deserialize them.
Alternatively, you need to serialize the 4000 objects to a file, or use a database to hold the data.


text:
Q: how to output a tring from an nfc tag to a text file using arduino uno and pn532? iam in a deep trouble , I have an Arduino uno and a pn532 connected to it in SPI mode , I want to read a string from an nfc tag and output it to a text file , I have already managed to read from nfc tag and write on it easily , but what Iam facing now is how to output the string contained in the nfc tag to a text file instead of outputting it to the serial monitor of the Arduino studio , any help would be greatly appreciated , thanks a lot in advance .

A: If you want to write the file from the Arduino itself, you have a few options, depending on the available extra hardware and where you want to save the file.
The easier is to use a SD card and the standard SD Library. On the official reference page there are lots of examples.
If you want to save it on the PC, there are several virtual terminal applications that enables you to save the sent and received data. Coolterm is one of them, Putty is another one.
You can also make your own application that receives the data from the arduino through serial communication, and handle the file saving on this application.


text:
Q: Easy ring questions Let R be a ring and $p$ a fixed prime number. Then $I_p = \{r \in R $ : additive order of $r$ is a power of $p$ $\}$ is an ideal of $R$.
Approach: Pick $r_1,r_2 \in I_p$ and $r \in  R$. Then, $a^pr_1 = 0 = b^pr_2$. We want to show that $r_1 - r_2$ has additive order power of $p$ and $rr_1$ has the additive order power of $p$. Well, since $a^p(rr_1) = 0$, then $rr_1 \in I_P$. But, Im not seeing how to show $r_1 - r_2 $ is in $I_p$.

A: Let $x, y \in I_p$.
There exist positive integers $k, l$ such that $p^k x = 0, p^l y = 0$.
Let $m = max(k, l)$.
Then $p^m(x + y) = p^m x + p^m y = 0$.
Hence $x + y \in I_p$.
Let $a \in R$.
$p^k(ax) = a(p^k x) = 0$.
Hence $ax \in I_p$.
$p^k(xa) = (p^k x)a = 0$.
Hence $xa \in I_p$.
Therefore $I_p$ is an ideal of $R$.

A: Hint $\ $ Let $\rm\:M\subset \Bbb N\:$ be any set such that $\rm\:jk\in M\iff j,k\in M,\:$ i.e. $\rm\:M\:$ is a saturated submonoid of $\rm\:\Bbb N,\:$ and let $\rm\:I_M = \{r\in R:\,$ additive order of $\rm\,r\,$ is $\rm\in M \}.\:$ If $\rm\:r,s\in I_M\:$ then $\rm\:jr = 0 = ks,\,\ j,k\in M,\:$ so $\rm\ jk(r-s) = k(jr)-j(ks)=0\:$ hence $\rm\: ord(r\!-\!s)\mid jk\in M\:$ $\Rightarrow$ $\rm\:ord(r\!-\!s)\in M\:$ $\Rightarrow$ $\rm\:r\!-\!s\in I_M.$


text:
Q: I want to get the total of 3 or more column in one select query example query:
i create a query that get the total in one month and i want to add the 3 column
SELECT
            SUM(vatPrivate) AS vatPrivate,
            SUM(vatGovernment) AS vatGovernment,
            SUM(vatZero) AS vatZero

            FROM transaction gl
            WHERE (gl.entryDate) BETWEEN '2019-11-05' AND '2019-11-29'
FROM `transaction`;

A: The "new" columns aren't available yet. Wrap the query up as a derived table (the subquery):
select dt.*, vatPrivate + vatGovernment + vatExempt
from
(
    SELECT  SUM(CASE WHEN entryDate BETWEEN '2019-11-05' AND '2019-11-31'
                    THEN vatPrivate END) AS vatPrivate,
        SUM(CASE WHEN entryDate BETWEEN '2019-11-05' AND '2019-11-31'
                    THEN vatGovernment END) AS vatGoverment,
        SUM(CASE WHEN entryDate BETWEEN '2019-11-05' AND '2019-11-31'
                    THEN vatExempt END) AS vatExempt
    FROM `transaction`
) dt

A: Sql select syntax is executed in unknown order, so you can't use select aliases in same select. You sholud use CTE or subquery to do this. For future: you sholud tag sql db engine in your question.

A: The simplest solution is just to repeat the SUM expressions.
SELECT SUM(vatPrivate) AS vatPrivate,
       SUM(vatGovernment) AS vatGovernment,
       SUM(vatZero) AS vatZero,
       SUM(vatPrivate) + SUM(vatGovernment) + SUM(vatZero) AS vatTotal
FROM transaction gl
WHERE (gl.entryDate) BETWEEN '2019-11-05' AND '2019-11-29'

You can probably rely on the query optimiser to notice you've repeated them and not compute them twice. If you want to be certain they're not re-computed, use a subquery:
SELECT vatPrivate, vatGovernment, vatZero,
       vatPrivate + vatGovernment + vatZero AS vatTotal
FROM (
    SELECT SUM(vatPrivate) AS vatPrivate,
           SUM(vatGovernment) AS vatGovernment,
           SUM(vatZero) AS vatZero
    FROM transaction gl
    WHERE (gl.entryDate) BETWEEN '2019-11-05' AND '2019-11-29'
) sums


text:
Q: WPF Clickable Links in Text I have a textbox that display some messages...
        <TextBox VerticalAlignment="Center"
          HorizontalAlignment="Left"
          TextWrapping="Wrap"
          FontFamily="{StaticResource LatoRegular}"
          Foreground="Black"
          FontSize="{StaticResource FontSizeRegular}"
          Text="{Binding Message}"
           Background="Transparent"
           BorderThickness="0"
           Padding="0"
           Margin="0"
           IsReadOnly="True"
                                       />

If user sent a link in the message, i would wish to be able to detect and click it and open up the page on the browser.
My situation:
My message could contain other texts or even more than 1 link. E.g "Hi Please visit google.com for more info". i would want the google.com to be recognize as a link and be clickable.
Anyone have any idea how can i do it?
Or else beside textbox what else can i use.. i need it to blind to the message behind

A: You can use a TextBlock instead of a TextBox in the following way:
<TextBlock>
        <Hyperlink NavigateUri="{Binding Message}" RequestNavigate="Hyperlink_RequestNavigate">
            <TextBlock Text="{Binding Message}"/>
        </Hyperlink>
</TextBlock>

Hyperlink_RequestNavigate: will be your event handler where you will open the browser through Process.Start
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}

This will be the basic implementation, for your requirement where you don't know whether the user will send a link or some text -

*

*Have two controls in the same place:
a. One simple text block to display text which is not a hyperlink.
b. One hyperlink text block shown above.

*Create a flag for the visibility for each of the controls, validate the message when the user sends and set the flag based on whether the message is a link or just plain text.
Or
You can also define a data template for the text block which will change to a hyperlink or a normal text block based on some flag which you need to set after validating what message the user has sent whether it is a hyperlink or a just plain text.


text:
Q: Getting image from path & crop the Image Its open the "choose from galary" option but i dont want this. I want directly showing the croping option on image. I have used intent for that
// Crop.java
private String defaultImagePath;
final int PIC_CROP = 1;
private Uri mCropImagedUri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.crop);
    cropImage = (ImageView) this.findViewById(R.id.imageView4);
    seekBarCrop = (SeekBar) findViewById(R.id.seekBarCrop);

    Bundle b = getIntent().getExtras();
    String imagePath = b.getString("imagePath");
    defaultImagePath = imagePath;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    bitmap = BitmapFactory.decodeFile(imagePath, options);
    cropImage.setImageBitmap(bitmap);
    cropImageActivity(defaultImagePath, cropImage);
}

private void cropImageActivity(String path, View cropImage) {

        try {
            mCropImagedUri = Uri.parse(path);
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            cropIntent.setDataAndType(mCropImagedUri, "image/*");
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            cropIntent.putExtra("scale", true);
            cropIntent.putExtra("outputX", 500);
            cropIntent.putExtra("outputY", 500);
            cropIntent.putExtra("return-data", false);

            // start the activity - we handle returning in onActivityResult
            startActivityForResult(cropIntent, PIC_CROP);

        } catch (ActivityNotFoundException anfe) {
            // display an error message
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Toast toast = Toast
                    .makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");

            cropImage.setImageBitmap(selectedBitmap);
        }
    }

}


text:
Q: using imfuse in Matlab to alpha blend grayscale images I'm trying to overlay 2 gray scale images in Matlab using the imfuse function. In the "overlap" region, I'd like to take 50% of image A and 50% of image B. What I'm getting instead is the sum of A and B in the overlap region. This code demonstrates:
A = 50*ones(100,100);
A = padarray(A,[50 50],'both');
RA = imref2d(size(A));

B = 50*ones(100,100);
B = padarray(B,[100 100],'pre');
RB = imref2d(size(B));

[C,RC] = imfuse(A,RA,B,RB,'blend');

imshow(C,RC,[]);

Is there a way to control the blend parameters so I can get a 50/50 mix??

A: A simple way is to just divide the overlapping areas by 2:
C(A~=0 & B~=0) = C(A~=0 & B~=0)./2;

This only works if zero exclusively marks padded areas. If a zero value exists in any image those pixels will not get averaged.


text:
Q: Convert DataFrame Column to Factors R, RStudio

How do I convert DataFrame column to Factors?
I wish 0 is "North", 1 is "South", 2 is "East" and 3 is "West".
directions <- data.frame(
                          state=c("New York","New Jersey","Deleware","Texax","Alaska"),
                          travel=c(0,0,3,2,1)
                        )

head(directions)

Outputs
       state travel
1   New York      0
2 New Jersey      0
3   Deleware      3
4      Texax      2
5     Alaska      1

I tried the following, but the entire travel column is NA
directions$travel <- factor(directions$travel,levels=c("North","South","East","West"))
head(directions)

Outputs
state travel
1   New York   <NA>
2 New Jersey   <NA>
3   Deleware   <NA>
4      Texax   <NA>
5     Alaska   <NA>

A: We need to specify it in labels
factor(directions$travel,labels=c("North","South","East","West"))
#[1] North North West  East  South
#Levels: North South East West

If we need a custom grouping, then specify the levels as well
factor(directions$travel,levels = c(0, 1, 2, 3),
         labels=c("North","South","East","West"))


text:
Q: Jackknife estimation and testing I'm using jacknife method to get the uncertainty of my estimation. My estimation restricted to (0,1) and some can be very small. For example, the jackknife estimate for variable A is 0.0000503 and corresponding jackknife SE is 1.998e-04. The jackknife estimate for variable B is 0.27 and corresponding jackknife SE is 0.07. My questions are:

*

*I want to find a uniform criteria to report uncertainty and/or importance across variables since the estimation and CI are small simutaneouly. In the above example, even though the jackknife SE is really small for variable A, the estimation is also small which might means variable A is not even needed.

*I wonder if any hypothesis testing(t-test or wald test) can be performed to see if the estimation is 0. If so, should the variance being jackknife SE^2?
Any suggestion will be appreciated!


text:
Q: When i type cqlsh Iam getting connection refused error I have installed cassandra in ubuntu 18.04 successfully. When i run below command i
get the following output.
●sudo systemctl status cassandra

cassandra.service - LSB: distributed storage system for structured
  data    Loaded: loaded (/etc/init.d/cassandra; generated)    Active:
  active (exited) since Sun 2019-01-06 06:15:28 UTC; 10s ago
       Docs: man:systemd-sysv-generator(8)   Process: 9453 ExecStop=/etc/init.d/cassandra stop (code=exited, status=0/SUCCESS)
  Process: 9472 ExecStart=/etc/init.d/cassandra start (code=exited,
  status=0/SUCCESS)
Jan 06 06:15:28 ip-172-31-4-16 systemd[1]: Stopped LSB: distributed
  storage system for structured data. Jan 06 06:15:28 ip-172-31-4-16
  systemd[1]: Starting LSB: distributed storage system for structured
  data... Jan 06 06:15:28 ip-172-31-4-16 systemd[1]: Started LSB:
  distributed storage system for structured data.

When i type cqlsh i get the below error.

Connection error: ('Unable to connect to any servers', {'127.0.0.1':
  error(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error:
  Connection refused")})

I have checked logs in /var/log/cassandra/system.log. and i did not find any error logs..
Here are some of the contents inside /etc/cassandra/cassandra.yaml file
listen_address: localhost
storage_port: 7000
ssl_storage_port: 7001
start_native_transport: true
native_transport_port: 9042
start_rpc: false
rpc_address: localhost
rpc_port: 9160
rpc_keepalive: true

A: The Cassandra process isn't running as you can see in the status: active (exited).
On Ubuntu 18.04 the most probable cause of this is that Ubuntu is shipped with Java 10 by default that isn't supported by existing Cassandra releases. Please install Java 8 (via sudo apt install openjdk-8-jdk) and make it as default - after that it should work.

A: Change the owner of /var/lib/cassandra to cassandra:
chown cassandra:cassandra /var/lib/cassandra


text:
Q: Deriving Logit Maximum Likelihood Estimator According to Verbeek, we can obtain the logit model by simplifying the first order condition of the log-likelihood function. Where,
$$logL(\beta) = \Sigma^N_{i=1} y_i logF(x^{'}_i\beta)+ \Sigma^N_{i=1}(1-y_i)log(1-F(x^{'}_i\beta))$$
and the first-order condition is:
$$\frac{{\partial L(\beta)}}{{\partial \beta}} = \Sigma^{N}_{i=1} [\frac{{y_i-F(x^{'}_i\beta)}}{{F(x^{'}_i\beta)(1-F(x^{'}_i\beta))}} f(x^{'}_i\beta)]x_i=0$$
where F is some distribution function and f = F' (the derivative of the distribution function)
And we obtain, $$\frac{{\partial L(\beta)}}{{\partial \beta}} = \Sigma^{N}_{i=1} [y_i -\frac{{exp(x^{'}_i\beta)}}{{1+exp(x^{'}_i\beta))}}]x_i=0$$
However, I don't understand how this is simplified and I'm not certain how the first order condition is solved, is it an application of the chain rule?
Thank you.

A: The general first order condition is an application of the chain rule and the definition that
$$f(\eta) := \frac{\partial F(\eta)}{\partial \eta}$$
A good place to start is the following expression
$$l_i(\eta) := y_i \log F(\eta) + (1-y_i) \log (1-F(\eta)),$$
which is more simple than the log-likelihood because we ignore the sum and because we ignore $x_i'\beta$. Then simply differentiate with respect to $\eta$ to get
$$y_i \frac{f(\eta)}{F(\eta)} - (1-y_i) \frac{f(\eta)}{1-F(\eta)},$$
isolate factor $f(\eta)$ and multiply the term $f(\eta)/F(\eta)$ with $1-F(\eta)$ in numerator and denominator and multiply fraction $f(\eta)/(1-F(\eta))$ with $F(\eta)$ in numerator and denominator. This gets you
$$f(\eta) \left[ \frac{y_i(1-F)}{F(1-F)} - \frac{(1-y_i)F}{F(1-F)}\right]$$
multiply through in numerators and get the expression
$$f(\eta) \left[ \frac{y_i-F(\eta)}{F(\eta)(1-F(\eta))}\right] = \frac{\partial l_i(\eta)}{\partial \eta} \ \ (1),$$
you have now succesfully differentiated the individual $i$'th contribution of the log-likelihood with respect to $\eta$.
When $\eta = x'\beta$ - as it is in the current case - and you want to differentiate with respect to $\beta$ it follows by chain rule that
$$\frac{\partial l_i (x_i'\beta)}{\partial \beta} = \frac{\partial l_i(\eta)}{\partial \eta} \frac{\partial \eta}{\partial \beta} = \frac{ \partial l_i(\eta)}{\partial \eta} x_i,$$
so simply combine this with (1) and insert $\eta = x_i'\beta$ to get the general first order condition
$$(2)\ \ \ x_i f(x_i'\beta) \left[ \frac{y_i-F(x_i'\beta)}{F(x_i'\beta)(1-F(x_i'\beta))}\right] $$
Now under the specific assumption that
$$F(\eta) = \frac{\exp(\eta)}{1+\exp(\eta)},$$
it follows that
$$f(\eta) = \frac{\partial F(\eta)}{\partial \eta} = \frac{\exp(\eta) (1+\exp(\eta)) - \exp(\eta) \exp(\eta)}{(1+\exp(\eta))^2},$$
when reading this term you should look for the probabilities $Pr(y_i = 1) = F(\eta) = \exp(\eta)/(1+\exp(\eta))$ to notice that this simplifies to
$$f(\eta) =  \frac{\exp(\eta) (1+\exp(\eta)) - \exp(\eta) \exp(\eta)}{(1+\exp(\eta))^2} = F - F^2 = F(1-F).$$
When you see that $f = F(1-F)$ it is easy to see that (2) reduces to
$$x_i  (y_i-F(x_i'\beta)),$$
which is what you wanted given that $F(x_i'\beta) = exp(x_i'\beta)/(1+\exp(x_i'\beta))$.


text:
Q: How to change read only file to writeable Running SPSS 23,
When trying to save a file I get the following error message:

The specified file or directory is read-only and cannot be written to.
  The file will not be saved.  Save the file with another name or to a
  different  location or change the access permissions first

A: First make sure you are trying to write to a directory you have permission to write on - if you gave no path, by default SPSS will write to the SPSS install directory which might require administrator rights.
You can change the default directory for this session by running:
cd "c:\users\santosh\somedirectory"

If this is not enough and you are sure that the file you are trying to write to is not open, try the following syntax:
PERMISSIONS FILE='yourpath\yourfile.sav' /PERMISSIONS WRITEABLE.

And try again.
Please make sure, before you overwrite the existing file, that important information is backed up and safe - if a file was locked for editing, there might be a good reason.


text:
Q: Lagged difference between specific row and previous rows in R I have this dataframe with time in minutes. I want to create a new column that indicates the timedifference (in minutes), between the row in which a substitution occurs and the previous rows.
# Data

dat <- structure(list(game_id = c(303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L), minute = c(57L, 57L, 57L, 57L, 57L,
60L, 60L, 60L, 60L, 61L, 62L, 62L, 62L, 62L, 62L, 62L, 62L, 62L,
62L, 62L, 62L, 62L, 62L, 62L, 63L, 63L, 63L, 64L, 64L, 64L, 65L,
65L, 65L, 65L, 65L, 65L, 65L, 65L, 65L, 65L, 65L, 65L, 65L, 65L,
65L, 65L, 65L, 65L, 66L), team_name = c("Getafe", "Getafe", "Getafe",
"Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe",
"Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe",
"Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe",
"Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe",
"Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe",
"Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe", "Getafe",
"Getafe", "Getafe", "Getafe", "Getafe"), type_name = c("pass",
"dribble", "pass", "foul", "foul", "foul", "foul", "dribble",
"pass", "throw_in", "tackle", "dribble", "tackle", "pass", "dribble",
"interception", "pass", "dribble", "pass", "dribble", "pass",
"dribble", "cross", "pass", "dribble", "interception", "take_on",
"clearance", "dribble", "pass", "dribble", "pass", "dribble",
"freekick_short", "pass", "dribble", "pass", "dribble", "pass",
"dribble", "pass", "dribble", "pass", "dribble", "pass", "dribble",
"cross", "shot", "substitution"), target = c(1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1), timediff = c(0, 0, 0, 0, 0, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9)), row.names = 150:198, class = "data.frame")

I want to calculate the difference in minutes between a specific row, which is set by the name "substitution", and the rows before that. I currently have created the dataframe below using the following code:
dat$timediff <- ave(dat$minute, dat$game_id, FUN=function(x) replace(x - x[1], 1, 0))

However, this leads to the inverse of what I want to achieve, namely:
Output
    game_id minute team_name      type_name target timediff
150  303377     57    Getafe           pass      1        0
151  303377     57    Getafe        dribble      1        0
152  303377     57    Getafe           pass      1        0
153  303377     57    Getafe           foul      1        0
154  303377     57    Getafe           foul      1        0
155  303377     60    Getafe           foul      1        3
156  303377     60    Getafe           foul      1        3
157  303377     60    Getafe        dribble      1        3
158  303377     60    Getafe           pass      1        3
159  303377     61    Getafe       throw_in      1        4
160  303377     62    Getafe         tackle      1        5
161  303377     62    Getafe        dribble      1        5
162  303377     62    Getafe         tackle      1        5
163  303377     62    Getafe           pass      1        5
164  303377     62    Getafe        dribble      1        5
165  303377     62    Getafe   interception      1        5
166  303377     62    Getafe           pass      1        5
167  303377     62    Getafe        dribble      1        5
168  303377     62    Getafe           pass      1        5
169  303377     62    Getafe        dribble      1        5
170  303377     62    Getafe           pass      1        5
171  303377     62    Getafe        dribble      1        5
172  303377     62    Getafe          cross      1        5
173  303377     62    Getafe           pass      1        5
174  303377     63    Getafe        dribble      1        6
175  303377     63    Getafe   interception      1        6
176  303377     63    Getafe        take_on      1        6
177  303377     64    Getafe      clearance      1        7
178  303377     64    Getafe        dribble      1        7
179  303377     64    Getafe           pass      1        7
180  303377     65    Getafe        dribble      1        8
181  303377     65    Getafe           pass      1        8
182  303377     65    Getafe        dribble      1        8
183  303377     65    Getafe freekick_short      1        8
184  303377     65    Getafe           pass      1        8
185  303377     65    Getafe        dribble      1        8
186  303377     65    Getafe           pass      1        8
187  303377     65    Getafe        dribble      1        8
188  303377     65    Getafe           pass      1        8
189  303377     65    Getafe        dribble      1        8
190  303377     65    Getafe           pass      1        8
191  303377     65    Getafe        dribble      1        8
192  303377     65    Getafe           pass      1        8
193  303377     65    Getafe        dribble      1        8
194  303377     65    Getafe           pass      1        8
195  303377     65    Getafe        dribble      1        8
196  303377     65    Getafe          cross      1        8
197  303377     65    Getafe           shot      1        8
198  303377     66    Getafe   substitution      1        9

I would like to achieve the opposite, so the row where type_name == substitution takes place, should have timediff == 0, and then build up the timediff with the rows before:
    game_id minute team_name      type_name target timediff

173  303377     62    Getafe           pass      1        4
174  303377     63    Getafe        dribble      1        3
175  303377     63    Getafe   interception      1        3
176  303377     63    Getafe        take_on      1        3
177  303377     64    Getafe      clearance      1        2
178  303377     64    Getafe        dribble      1        2
179  303377     64    Getafe           pass      1        2
180  303377     65    Getafe        dribble      1        1
181  303377     65    Getafe           pass      1        1
182  303377     65    Getafe        dribble      1        1
183  303377     65    Getafe freekick_short      1        1
184  303377     65    Getafe           pass      1        1
185  303377     65    Getafe        dribble      1        1
186  303377     65    Getafe           pass      1        1
187  303377     65    Getafe        dribble      1        1
188  303377     65    Getafe           pass      1        1
189  303377     65    Getafe        dribble      1        1
190  303377     65    Getafe           pass      1        1
191  303377     65    Getafe        dribble      1        1
192  303377     65    Getafe           pass      1        1
193  303377     65    Getafe        dribble      1        1
194  303377     65    Getafe           pass      1        1
195  303377     65    Getafe        dribble      1        1
196  303377     65    Getafe          cross      1        1
197  303377     65    Getafe           shot      1        1
198  303377     66    Getafe   substitution      1        0

A: You can use match to get the minute value where type_name is 'substitution' and subtract it with  every minute value.
library(dplyr)

dat %>%
  group_by(game_id) %>%
  mutate(timediff = minute[match('substitution', type_name)] - minute) %>%
  ungroup

If you have multiple substitutions in a game, you can use -
dat %>%
  group_by(game_id, grp = cumsum(lag(type_name, default = '') == 'substitution')) %>%
  mutate(timediff = minute[match('substitution', type_name)] - minute) %>%
  ungroup


text:
Q: How to put a div and nested divs with min height of all body I have my body with border:5px solid blue, and I want to put my green div, as well as yellow div and orange div with min-height of 100% of the body.
I want my body Tag (and also my orange div and yellow div) to be at least 100% of the screen and it should grow if the content is added.
My code:

html {
  height: 100%;
}

body {
  min-height: 100%;
}

.top-menu {
  padding: 0%;
  margin: 0px;
}

.main-content {
  position: relative;
  width: 96.5%;
  left: 3.5%;
}

.wrapper {
  position: relative;
  min-height: 100%;
}

.left-menu {
  position: absolute;
  height: 100%;
  width: 3.5%;
  float: left;
  z-index: 0;
  overflow: visible;
}

      < O que é o Lorem Ipsum? O Lorem Ipsum é um texto modelo da indústria tipográfica e de impressão. O Lorem Ipsum tem vindo a ser o texto padrão usado por estas indústrias desde o ano de 1500, quando uma misturou os caracteres de um texto para criar um
        espécime de livro. Este texto não só sobreviveu 5 séculos, mas também o salto para a tipografia electrónica, mantendo-se essencialmente inalterada. Foi popularizada nos anos 60 com a disponibilização das folhas de Letraset, que continham passagens
        com Lorem Ipsum, e mais recentemente com os programas de publicação como o Aldus PageMaker que incluem versões do Lorem Ipsum. Porque é que o usamos? É um facto estabelecido de que um leitor é distraído pelo conteúdo legível de uma página quando
        analisa a sua mancha gráfica. Logo, o uso de Lorem Ipsum leva a uma distribuição mais ou menos normal de letras, ao contrário do uso de "Conteúdo aqui, conteúdo aqui", tornando-o texto legível. Muitas ferramentas de publicação electrónica e editores
        de páginas web usam actualmente o Lorem Ipsum como o modelo de texto usado por omissão, e uma pesquisa por "lorem ipsum" irá encontrar muitos websites ainda na sua infância. Várias versões têm evoluído ao longo dos anos, por vezes por acidente,
        por vezes propositadamente (como no caso do humor). De onde é que ele vem? Ao contrário da crença popular, o Lorem Ipsum não é simplesmente texto aleatório. Tem raízes numa peça de literatura clássica em Latim, de 45 AC, tornando-o com mais de 2000
        anos. Richard McClintock, um professor de Latim no Colégio Hampden-Sydney, na Virgínia, procurou uma das palavras em Latim mais obscuras (consectetur) numa passagem Lorem Ipsum, e atravessando as cidades do mundo na literatura clássica, descobriu
        a sua origem. Lorem Ipsum vem das secções 1.10.32 e 1.10.33 do "de Finibus Bonorum et Malorum" (Os Extremos do Bem e do Mal), por Cícero, escrito a 45AC. Este livro é um tratado na teoria da ética, muito popular durante a Renascença. A primeira
        linha de Lorem Ipsum, "Lorem ipsum dolor sit amet..." aparece de uma linha na secção 1.10.32. O pedaço mais habitual do Lorem Ipsum usado desde os anos 1500 é reproduzido abaixo para os interessados. As secções 1.10.32 e 1.10.33 do
        "de Finibus Bonorum et Malorum" do Cícero também estão reproduzidos na sua forma original, acompanhados pela sua tradução em Inglês, versões da tradução de 1914 por H. Rackham. Onde posso arranjar algum?O que é o Lorem Ipsum? O Lorem Ipsum é um texto modelo da indústria tipográfica
        e de impressão. O Lorem Ipsum tem vindo a ser o texto padrão usado por estas indústrias desde o ano de 1500, quando uma misturou os caracteres de um texto para criar um espécime de livro. Este texto não só sobreviveu 5 séculos, mas também o salto
        para a tipografia electrónica, mantendo-se essencialmente inalterada. Foi popularizada nos anos 60 com a disponibilização das folhas de Letraset, que continham passagens com Lorem Ipsum, e mais recentemente com os programas de publicação como o
        Aldus PageMaker que incluem versões do Lorem Ipsum. Porque é que o usamos? É um facto estabelecido de que um leitor é distraído pelo conteúdo legível de uma página quando analisa a sua mancha gráfica. Logo, o uso de Lorem Ipsum leva a uma distribuição
        mais ou menos normal de letras, ao contrário do uso de "Conteúdo aqui, conteúdo aqui", tornando-o texto legível. Muitas ferramentas de publicação electrónica e editores de páginas web usam actualmente o Lorem Ipsum como o modelo de texto usado por
        omissão, e uma pesquisa por "lorem ipsum" irá encontrar muitos websites ainda na sua infância. Várias versões têm evoluído ao longo dos anos, por vezes por acidente, por vezes propositadamente (como no caso do humor).

Output:

Expected output:

A: I've used Flexbox to achieve this with flex-grow:

* {
    box-sizing: border-box;
}

*:before,
*:after {
    box-sizing: inherit;
}

html {
    height: 100vh;
}

body {
    min-height: 100%;
    border: 5px solid blue;
    display: flex;
    flex-direction: column;
}

.top-menu {
    padding: 0%;
    margin: 0px;
}

.main-content {
    width: 96.5%;
}

.wrapper {
    display: flex;
    flex-grow: 1;
}

.left-menu {
    width: 3.5%;
}

            O que é o Lorem Ipsum? O Lorem Ipsum é um texto modelo da indústria tipográfica e de impressão. O Lorem
            Ipsum
            tem vindo a ser o texto padrão usado por estas indústrias desde o ano de 1500, quando uma misturou os
            caracteres de um texto para criar um espécime de livro. Este texto não só sobreviveu 5 séculos, mas também o
            salto para a tipografia electrónica, mantendo-se essencialmente inalterada. Foi popularizada nos anos 60 com
            a disponibilização das folhas de Letraset, que continham passagens com Lorem Ipsum, e mais recentemente com
            os programas de publicação como o Aldus PageMaker que incluem versões do Lorem Ipsum. Porque é que o usamos?
            É um facto estabelecido de que um leitor é distraído pelo conteúdo legível de uma página quando analisa a
            sua mancha gráfica. Logo, o uso de Lorem Ipsum leva a uma distribuição mais ou menos normal de letras, ao
            contrário do uso de "Conteúdo aqui, conteúdo aqui" , tornando-o texto legível. Muitas ferramentas de
            publicação electrónica e editores de páginas web usam actualmente o Lorem Ipsum como o modelo de texto usado
            por omissão, e uma pesquisa por "lorem ipsum" irá encontrar muitos websites ainda na sua infância. Várias
            versões têm evoluído ao longo dos anos, por vezes por acidente, por vezes propositadamente (como no caso do
            humor). De onde é que ele vem? Ao contrário da crença popular, o Lorem Ipsum não é simplesmente texto
            aleatório. Tem raízes numa peça de literatura clássica em Latim, de 45 AC, tornando-o com mais de 2000 anos.
            Richard McClintock, um professor de Latim no Colégio Hampden-Sydney, na Virgínia, procurou uma das palavras
            em Latim mais obscuras (consectetur) numa passagem Lorem Ipsum, e atravessando as cidades do mundo na
            literatura clássica, descobriu a sua origem. Lorem Ipsum vem das secções 1.10.32 e 1.10.33
            do "de Finibus Bonorum et Malorum" (Os Extremos do Bem e do Mal), por Cícero, escrito a 45AC. Este livro é
            um tratado na teoria da ética, muito popular durante a Renascença. A primeira linha de Lorem
            Ipsum, "Lorem ipsum dolor sit amet..." aparece de uma linha na secção 1.10.32. O pedaço mais habitual do
            Lorem Ipsum usado desde os anos 1500 é reproduzido abaixo para os interessados. As secções 1.10.32 e 1.10.33
            do "de Finibus Bonorum et Malorum" do Cícero também estão reproduzidos na sua forma original, acompanhados
            pela sua tradução em Inglês, versões da tradução de 1914 por H. Rackham. Onde posso arranjar algum?O que é o
            Lorem Ipsum? O Lorem Ipsum é um texto modelo da indústria tipográfica e de impressão. O Lorem Ipsum tem
            vindo a ser o texto padrão usado por estas indústrias desde o ano de 1500, quando uma misturou os caracteres
            de um texto para criar um espécime de livro. Este texto não só sobreviveu 5 séculos, mas também o salto para
            a tipografia electrónica, mantendo-se essencialmente inalterada. Foi popularizada nos anos 60 com a
            disponibilização das folhas de Letraset, que continham passagens com Lorem Ipsum, e mais recentemente com os
            programas de publicação como o Aldus PageMaker que incluem versões do Lorem Ipsum. Porque é que o usamos? É
            um facto estabelecido de que um leitor é distraído pelo conteúdo legível de uma página quando analisa a sua
            mancha gráfica. Logo, o uso de Lorem Ipsum leva a uma distribuição mais ou menos normal de letras, ao
            contrário do uso de "Conteúdo aqui, conteúdo aqui" , tornando-o texto legível. Muitas ferramentas de
            publicação electrónica e editores de páginas web usam actualmente o Lorem Ipsum como o modelo de texto usado
            por omissão, e uma pesquisa por "lorem ipsum" irá encontrar muitos websites ainda na sua infância. Várias
            versões têm evoluído ao longo dos anos, por vezes por acidente, por vezes propositadamente (como no caso do
            humor).

I've also set the box model to border-box so that the elements specified width and height aren't affected by padding or borders. Find out more about box-sizing here.
Find out more about the CSS Flexbox here.

A: try this

html,body {
  height: 100%;
}
* {
box-sizing: border-box;
}
.wrapper {
  position: relative;
  height: calc(100% - 60px);
}
.main-content {
  height:100%;
}
.main-content div {
  height: 100%;
  overflow-y:auto;
  position:absolute;
  left:0;
  top:0;
  width:100%;
  height:100%;
}
.left-menu {
  position: absolute;
  height: 100%;
  width: 100%;
  left:0;
  top:0;
  float: left;
  z-index: 0;
  overflow: visible;
}

 que é o Lorem Ipsum? O Lorem Ipsum é um texto modelo da indústria tipográfica e de impressão. O Lorem Ipsum tem vindo a ser o texto padrão usado por estas indústrias desde o ano de 1500, quando uma misturou os caracteres de um texto para criar um
        espécime de livro. Este texto não só sobreviveu 5 séculos, mas também o salto para a tipografia electrónica, mantendo-se essencialmente inalterada. Foi popularizada nos anos 60 com a disponibilização das folhas de Letraset, que continham passagens
        com Lorem Ipsum, e mais recentemente com os programas de publicação como o Aldus PageMaker que incluem versões do Lorem Ipsum. Porque é que o usamos? É um facto estabelecido de que um leitor é distraído pelo conteúdo legível de uma página quando
        analisa a sua mancha gráfica. Logo, o uso de Lorem Ipsum leva a uma distribuição mais ou menos normal de letras, ao contrário do uso de "Conteúdo aqui, conteúdo aqui", tornando-o texto legível. Muitas ferramentas de publicação electrónica e editores
        de páginas web usam actualmente o Lorem Ipsum como o modelo de texto usado por omissão, e uma pesquisa por "lorem ipsum" irá encontrar muitos websites ainda na sua infância. Várias versões têm evoluído ao longo dos anos, por vezes por acidente,
        por vezes propositadamente (como no caso do humor). De onde é que ele vem? Ao contrário da crença popular, o Lorem Ipsum não é simplesmente texto aleatório. Tem raízes numa peça de literatura clássica em Latim, de 45 AC, tornando-o com mais de 2000
        anos. Richard McClintock, um professor de Latim no Colégio Hampden-Sydney, na Virgínia, procurou uma das palavras em Latim mais obscuras (consectetur) numa passagem Lorem Ipsum, e atravessando as cidades do mundo na literatura clássica, descobriu
        a sua origem. Lorem Ipsum vem das secções 1.10.32 e 1.10.33 do "de Finibus Bonorum et Malorum" (Os Extremos do Bem e do Mal), por Cícero, escrito a 45AC. Este livro é um tratado na teoria da ética, muito popular durante a Renascença. A primeira
        linha de Lorem Ipsum, "Lorem ipsum dolor sit amet..." aparece de uma linha na secção 1.10.32. O pedaço mais habitual do Lorem Ipsum usado desde os anos 1500 é reproduzido abaixo para os interessados. As secções 1.10.32 e 1.10.33 do
        "de Finibus Bonorum et Malorum" do Cícero também estão reproduzidos na sua forma original, acompanhados pela sua tradução em Inglês, versões da tradução de 1914 por H. Rackham. Onde posso arranjar algum?O que é o Lorem Ipsum? O Lorem Ipsum é um texto modelo da indústria tipográfica
        e de impressão. O Lorem Ipsum tem vindo a ser o texto padrão usado por estas indústrias desde o ano de 1500, quando uma misturou os caracteres de um texto para criar um espécime de livro. Este texto não só sobreviveu 5 séculos, mas também o salto
        para a tipografia electrónica, mantendo-se essencialmente inalterada. Foi popularizada nos anos 60 com a disponibilização das folhas de Letraset, que continham passagens com Lorem Ipsum, e mais recentemente com os programas de publicação como o
        Aldus PageMaker que incluem versões do Lorem Ipsum. Porque é que o usamos? É um facto estabelecido de que um leitor é distraído pelo conteúdo legível de uma página quando analisa a sua mancha gráfica. Logo, o uso de Lorem Ipsum leva a uma distribuição
        mais ou menos normal de letras, ao contrário do uso de "Conteúdo aqui, conteúdo aqui", tornando-o texto legível. Muitas ferramentas de publicação electrónica e editores de páginas web usam actualmente o Lorem Ipsum como o modelo de texto usado por
        omissão, e uma pesquisa por "lorem ipsum" irá encontrar muitos websites ainda na sua infância. Várias versões têm evoluído ao longo dos anos, por vezes por acidente, por vezes propositadamente (como no caso do humor).


text:
Q: English equivalent to the Japanese saying "高転びに転ぶ" - A haughty man should tumble down? I was asked by my friend who happened to see my question I posted before about English equivalents to Chinese (and Japanese) proverbs, 塞翁失馬 Life is like old Sai's horse, whether there is an English equivalent to the Japanese saying, '高転びに転ぶ' meaning 'a haughty man should tumble down,' in connection with vicissitudes of human life.
It is known the phrase, '高転びに転ぶ – Takakorobini korobu' was pronounced by Ankokujii Ekei, a Zen priest who became a military strategist and diplomat later in the Age of Provincial War during the late 16th century in Japan.
Ekei predicted the fall of Oda Nobunaga who succeeded in unifying divided warring countries and became the virtual ruler of Japan around 1580, by saying '高転びに転ぶ - A haughty man should tumble down' well before the new ruler's unexpected early death.
As a matter of fact, Oda Nobunaga was assassinated by his right-hand military commander, Akechi Mituhide in Honnnoji Temple in Kyoto, where he hosted a tea party on the same day, June 2, 1582, and Oda's rule was terminated.
'高転びに転ぶ' is a phrase to admonish you, you can't be too cautious of your behavior when you are at the height of prosperity, fulfilment and pride.
Are there English proverbs corresponding to Ankokuji Ekei's warning issued about 430 years ago?

A: The most common proverb about pride is certainly the one quoted in the other answers, Pride comes before a fall.
Not quite about pride, but about the less attractive side of ruling is a saying,

Uneasy lies the head that wears the crown.

Though stated in those words by Shakespeare (Henry IV. Part II, 1597), it is a very old saying from before the time of the Greeks, and is told most famously in the story of Damocles and Dionysius.
Regarding pride and position, there is the saying

The higher you climb, the greater the fall.

That may have its roots in the Biblical account of the tower of Babel, but is also seen in the story of Icarus. There is no hint here, though, of rulers.

A: Here are three sayings about proud people getting their comeuppance.
Saying "the bigger they are, the harder they fall"

said to emphasize that the more important or powerful a
  person is, the more difficult it is for them when they lose their
  power or importance.  - English Dictionary (Cambridge)

Saying "...is riding for a fall"

(informal) Be acting in a reckless way that is likely to  end in trouble or disaster: "with your present attitude, you're riding for a
  fall."  oxforddictionaries

Saying  "Too big for his boots"

too big for your boots UK (US too big for your britches) informal ›
  behaving as if you are more important than you really are: He's been
  getting a bit too big for his boots since he got that promotion.
  (Cambridge)

A: For centuries, English translations of the ancient Greek historian Herodotus have retold his story of Solon (the famous lawgiver of the Athenians) and Crœsus (a highly cultured and fabulously wealthy king of Lydia who also happened to be very successful in war). The story ends with a moral (and a proverbial saying) that seems similar in import to the one that Yoichi Oishi cites in his question.
After having established his laws in Athens, Solon traveled through various parts of Asia Minor and eventually met King Crœsus in his capital at Sardis. Crœsus showed him his various treasures and thought to dazzle him with his wealth, but Solon seemed unimpressed. And when Crœsus asked Solon who (in Solon's opinion) was the most truly happy person he had met with in his travels, Solon identified first a citizen of Athens who had served his city well, raised well-esteemed children, lived to see his grandchildren, watched his country flourish, and died fighting in its defense; and second, two brothers who had loved each other and done a remarkable deed to honor their mother (a priestess), and who died peacefully in their sleep at the height of their acclaim.
Crœsus then asked why Solon didn't list his host as among the happiest of men, and Solon told him that it was much too early to form any such judgment about him:

"Therefore, in our opinion," continued he, "no man can be esteemed happy, but he whose happiness God continues to the end of his life[.]"

Years later, the Medes under Cyrus defeated the Lydian army and captured Crœsus, who was condemned to be burned alive—and here we pick up the story as recounted by Charles Rollin in The Ancient History of the Egyptians, Assyrians, Babylonians, Lydians, Persians and Medes (1832):

Accordingly, the funeral pile was prepared, and that unhappy prince being laid thereon, and just upon the point of execution, recollecting the conversation he had formerly had with Solon, was woefully convinced of the truth of that philosopher's admonition, and in remembrance thereof, cried aloud three times, "Solon! Solon! Solon!" Cyrus, who, with the chief officers of his court was present at this spectacle, was curious to know why Crœsus pronounced that celebrated philosopher's name with so much vehemence in this extremity. Being told the reason, and reflecting upon the uncertain state of all sublunary things, he was touched with commiseration at the prince's misfortune, caused him to be taken from the pile, and treated him afterwards, as long as he lived, with honour and respect. Thus had Solon the glory, with one single word, to save the life of one king, and give a wholesome lesson of instruction to another.

Solon's advice to Crœsus has been summarized in various ways. According to Martin Manser, The Facts on File Dictionary of Proverbs, second edition (2007), Solon's wording was "Call no man happy before he dies, he is at best fortunate," and Sophocles expressed the same idea as "Deem no man happy until he passes the end of his life without suffering grief." Manser gives the proverb as

call no man happy till he dies

A: The meaning of, "A haughty man should tumble down" is one of several found in, "It is easier for a camel to go through the eye of a needle than for a rich man to enter the kingdom of God."
For a camel to accomplish this, the camel has to obey its owner, get down on its knees then crawl through a small opening in a dirt wall, called 'the eye of the needle', in order to enter the place where his master and the camel will be staying.
In contrast, a rich man wants to be the center of everyone's attention as he passes through the main gates of the place he has decided to stay.
So, a rich man will refuse to get down on his knees and then crawl through a small, dirty hole, in order to pass into the place he desires to enter.
Another way to look at this is, a haughty, rich and powerful man will never submit to God (kneel and bow his head), nor will he follow God's laws (he does what he wants). Due to these choices, he will be unable to enter Heaven and stay where God does.
Tying all of this together and answering your question.
A haughty, rich and powerful man needs to fall from his place of power in order to gain a drastically different perspective that will allow him to obtain what was unobtainable before, to acquire that which is the most valuable of all.

A: The Biblical phrase, "Pride comes before the Fall"
Proverbs 16:18
http://biblehub.com/proverbs/16-18.htm

A: The biblical proverb (Proverbs 16:18)
"Pride goeth before destruction, and an haughty spirit before a fall," has been rephrased as the frequently used proverb "Pride goeth before a fall" or "Pride goes before a fall."

A: Also, in addition to the excellent answers regarding "Pride comes before a fall", in informal conversation one may use "he needs to be taken down a peg or two". Of course, this is a figure of speech and not a proverb.

A: "Pigs get fat, hogs get slaughtered."

This idiom is used to express being satisfied with enough, that being greedy or too ambitious will be your ruin.


text:
Q: UA-Platform-Version header not working for webpages I get the following code added between <head> and </head> to detect Windows 11:
<meta http-equiv="Accept-CH" content="Sec-CH-UA-Platform-Version">

But I couldn't find this Accept-CH on my webpage. It should signify the platform version (like "14.0.0") . Now it only shows for the other files like js, css and image.
How can I get this header working?

A: That's a HTML header.
You should set it to in a HTTP header on server side (PHP).
header('accept-ch', 'Sec-CH-UA-Platform-Version');

then, your browser will send it.


text:
Q: What's the correct way to write our names? Most people who live in my locality write their names with initials at the
end.  Usually these initials are abbreviations of long family names, like
Joseph Alex TP, where TP stands for Thevalliparambil (a family
name here).
How should we write that "TP"?

*

*Joseph Alex TP

*Joseph Alex T.P

*Joseph Alex Tp

*Joseph Alex T.p

What is the correct way to do this?

A: You seem to be asking about a local convention:

Many people in my locality...
Usually these initials are abbreviations of long family names

Outside the convention, it's uncertain whether the TP in the question would be understood as an abbreviation of a surname. Changing the convention is a moot question.
Within the area where that convention is understood, it's uncertain whether changing the convention means it will continue to be understood.
Consequently, if it's normally written as Joseph Alex TP, then that's what the convention expects.
If you choose to change that, I'd certainly suggest that the abbreviation be signalled with the full stop after it rather than in the middle, "Tp." instead of "T.p", but it's not something that can be answered outside the area where that convention is adopted.
We no longer have the "too localised" close reason, but this question is too localised.


text:
Q: How to bypass "connection is not private" on a staging website I have a staging website, that is only accessible by changing the hosts file.
This however causes the browsers to throw the error "connection is not private".
The production website obviously does not have said issue.
And having the error message pop up every 30 seconds makes it pretty hard to understand if a bug is caused by the message popping up or not.

Although it is probably irrelevant, the error in question is the following:
NET::ERR_CERT_COMMON_NAME_INVALID

Question
Is there a way to stop the error messages for only that one site?

I am currently testing on Chrome for Android.
I would also like to know if there is a workaround for other browsers, such as Edge and Safari.


text:
Q: Why does this JavaScript destroys my layout in Internet Explorer? I'm using a small CMS for a small site (http://www.ovlu.li/cms/). There I include a JavaScript on the first site to open an image in a popup:
<script type="text/javascript">
function pop(file)
{
helpwindow = window.open(file, "Vaterland", "width=600, height=796",  "directories=no", "toolbar=no", "location=no", "status=no", "menubar=no", "resizable=no");
helpwindow.focus();
return false;
}
</script>

This works fine in FireFox, Chrome and Safari, but unfortunately, in Internet Explorer this script totally destroys the layout of the site where it is contained. Nevertheless it works. And all other sites are also working correctly. Any hints?

A: I think your main problem is that the script is located before <html>. It should be inside of <head>.
Other than that, your javascript is wrong. The third parameter is features. Instead, you're passing features as a heap of paramters, divided. see window.open reference
This is what it should like:
window.open(file, "Vaterland", "width=600, height=796, directories=no,
    toolbar=no, location=no, status=no, menubar=no, resizable=no");

(line break added for readability. not to be included in final code)
... but this last remark is not what's causing your layout issues. If you're sure it's all because of the script, then it's because it's placed outside of <html>


text:
Q: Xamarin: Method does not have correct signature I am trying to create simple multi-screen App.
I added Content Page and button to it.
MapPage.xaml.cs:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MapPage : ContentPage
{
    public MapPage ()
    {
        InitializeComponent ();
    }

    void ShowMap(object s, EventArgs e)
    {
    }
}

MapPage.xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App14"
             x:Class="App14.MapPage">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin Forms!" />
            <Button Text="show map"
                    Clicked="ShowMap"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

I am getting error: ShowMap Method does not have correct signature
What I am doing wrong?

A: change the event handler from private (the default if not specified) to protected
protected void ShowMap(object s, EventArgs e)
        {

        }


text:
Q: Create an email account with PhP - With some things I need to work around I need to create an email account in PhP. I found a ton of code samples online that do this, however I have a few problems:

*

*I'm on a shared server host with the default php.ini, and my host won't change it

*I need to create it via a URL, not with forms (something like: mywebsite.com/email.php?username=user)

*The password and quota created needs to be the same every time, so the only thing after the ? I need is the username

I have 0 experience with PhP so I can't just edit one I find online, so sorry if this is easy. If someone could point me in the direction of a script someone made or something that'd be great! Thanks.

A: From your reply, it turns out that you are using cPanel. This is quite helpful, as cPanel provides its own XML API for some administrative tasks, including creating email accounts.
You can find a ready made script that uses the cPanel XML API and does what you require in this forum post:
http://forums.glowhost.com/programming-talk/using-cpanel-api-creating-email-account-forwarders-your-own-php-scripts-2798.html
This SO question contains information on how to use the cPanel XML API yourself.
If for some reason you can't get the XML API to work, there's another script that makes regular HTTP calls to cPanel itself over here:
http://www.zubrag.com/scripts/cpanel-create-email-account.php


text:
Q: How can I use question mark correctly?
*

*What is your father's name, mother's name, and brother's name ?

*Can you answer the following?
                        Or the following:

*Are you well?...or not?
Which is\are correct among the three? And please correct my fault.

A: The first is the one that is complete, correct, and natural.
The second would be correct in either case, though the colon is more natural. However, the list that follows would have to be a list of questions. It could be replaced with "please provide:" and a list of items that aren't questions.
The third will be seen (or at least heard), but it is more correct to say "are you ... or not?", usually used where someone has been asked the question bare and been evasive.


text:
Q: How to emulate Internet in multi machine environment with Vagrant I'm creating a vagrant multi machine configuration file. Here is a chunk:
Vagrant.configure(2) do |config|

  config.vm.box = "chef/centos-7.0"

  config.vm.define "radius" do |radius|
    radius.vm.hostname = "radius-server"
  end

  config.vm.define "mysql" do |mysql|
    mysql.vm.hostname = "mysql-server"
  end
end

how can I emulate the situation in which the above two virtual machines are in different networks separated by Internet?
I could create two different private networks having two different private ip addresses like 192.168.1.3 for the first virtual machine and 192.168.2.3 for the second virtual machine. in this case the machines would be in different networks. But could they talk to each other?

A: Yes, they can talk.
You need a router (the 3rd node) connected to both of these networks.
The router acts as the (mini) Internet:
A=[192.168.1.3] <=> [*.*.1.1]=router=[*.*.2.1] <=> [192.168.2.3]=B

Details
The easiest way is to assign the router role to the physical host because it has IP addresses on both of these networks (I guess they are 192.168.1.1 and  192.168.2.1 in your example). Otherwise, they are just numbers and, if Vagrant does not complain, network will function with IP addresses from public ranges as well (just be careful to disconnect physical network for clean testing).

*

*Just enable routing (forwarding) in the OS on the physical host - googled example for Linux.

*And make sure routes are configured on both of the virtual machines to each other via this router:
A's shell> ip route add default via 192.168.1.1
B's shell> ip route add default via 192.168.2.1

NOTE: Technically, because the networks use private IP addresses, they are not routable on the Internet (AFAIK, real Internet routers drop packets with these private IP addresses, while home routers NAT them).
Working Vagrant file
Tested example using libvirt provider.
Note that VMs are connected to two different networks.
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.provider "libvirt"

  config.vm.define "rhel7_minion" do |rhel7_minion|
    rhel7_minion.vm.box = "uvsmtid/centos-7.1-1503-gnome"
    rhel7_minion.vm.synced_folder '.', '/vagrant', disabled: true
    rhel7_minion.vm.network 'private_network',
        :libvirt__network_name => 'primary_vagrant_private_net',
        ip: '192.168.1.2',
        :libvirt__netmask => '255.255.255.0',
        :libvirt__forward_mode => 'route',
        :libvirt__dhcp_enabled => true
  end

  config.vm.define "rhel5_minion" do |rhel5_minion|
    rhel5_minion.vm.box = "uvsmtid/centos-5.5-minimal"
    rhel5_minion.vm.synced_folder '.', '/vagrant', disabled: true
    rhel5_minion.vm.network 'private_network',
        :libvirt__network_name => 'secondary_vagrant_private_net',
        ip: '192.168.2.3',
        :libvirt__netmask => '255.255.255.0',
        :libvirt__forward_mode => 'route',
        :libvirt__dhcp_enabled => true
  end

end


text:
Q: How do you import XML data into Excel using Office Add-ins (formerly Apps for Office) programmatically using JavaScript Is it possible to import XML data into Excel using Office Add-ins (formerly Apps for Office) programmatically using JavaScript
I do this in VSTO (c#) using this method:-
        ActiveWorkbook.XmlImport(Url, out xMap, true, Cell);
but would like to do it using JavaScript in the new Office Add-ins.
Thanks in advance

A: There is no explicit "importFromXml" method. However, especially if you're using Office 2016, you could use an ajax call to get the XML, and then create a Range or Table object and populate its values based on the received XML.  Something like:
$.ajax("url").done(function(data) {
    Excel.run(function(ctx) {
        var sheet = ctx.workbook.worksheets.getActiveSheet();
        var firstCell = sheet.getCell(0,0);
        var lastCell = sheet.getCell(data.values.length, data.values[0].length);
        firstCell.getBoundingRect(lastCell).values = data.values;
    }).catch(errorHandler);
}).fail(errorHandler);

~ Michael Zlatkovsky, developer on Office Extensibility team, MSFT