Q: How do I create an export to Google Sheet button on a web page? Say I have a page like this:

textarea {width:300px;height:200px}
button {display:block}
<textarea value="f">id,value
2,alpha
3,beta
14,test</textarea>
<button>Open in Google Sheet</button>

I want the user to click the button "Open in Google Sheet" and open the csv as a spreadsheet.
I saw that Google Analytics and some other Google products have this button. But I didn't find 3rdparty webapps have this. Is that possible for me to use it?

A: I believe your goal is as follows.

*

*From I want the user to click the button "Open in Google Sheet" and open the CSV as a spreadsheet., you want to retrieve the text value from the textarea tab and create a Google Spreadsheet using the text value, and then, want to open the Google Spreadsheet.

In order to achieve your goal, how about the following flow?

*

*Retrieve the text value from the textarea tab.

*Send the text value to Web Apps created by Google Apps Script.

*At Web Apps, a new Google Spreadsheet is created and the text value is put to the sheet.

*In order to open the created Spreadsheet, change the permission of the Spreadsheet. In this case, it is publicly shared as the read-only. This is the sample situation.

*Return the URL of the Spreadsheet.

When this flow is reflected in the script, it becomes as follows.
Usage:
1. Create a new project of Google Apps Script.
Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.
If you want to directly create it, please access https://script.new/. In this case, if you are not logged in to Google, the log-in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.
2. Sample script.
Please copy and paste the following script to the created Google Apps Script project and save it. This script is used for Web Apps. In this sample, the value is sent as the POST request.
function doPost(e) {
  const csv = Utilities.parseCsv(e.postData.contents);
  const ss = SpreadsheetApp.create("sample");
  ss.getSheets()[0].getRange(1, 1, csv.length, csv[0].length).setValues(csv);
  DriveApp.getFileById(ss.getId()).setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  return ContentService.createTextOutput(ss.getUrl());
}

3. Deploy Web Apps.
The detailed information can be seen at the official document.

*

*On the script editor, at the top right of the script editor, please click "click Deploy" -> "New deployment".

*Please click "Select type" -> "Web App".

*Please input the information about the Web App in the fields under "Deployment configuration".

*Please select "Me" for "Execute as".

*

*This is the importance of this workaround.

*Please select "Anyone" for "Who has access".

*

*In this case, the user is not required to use the access token. So please use this as a test case.

*Of course, you can also access to your Web Apps using the access token. Please check this report.

*Please click "Deploy" button.

*Copy the URL of the Web App. It's like https://script.google.com/macros/s/###/exec.

*

*When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.

*You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

4. Testing.
As the test of this Web Apps, I modified your script as follows. Before you use this script, please set the URL of your Web Apps to url. When you open this HTML and click the button, a new Spreadsheet including the text value in the textarea tab is opened with new window as the read-only.
<textarea id="sampletext" value="f">id,value
2,alpha
3,beta
14,test</textarea>
<button onclick="sample()">Open in Google Sheet</button>

<script>
function sample() {
  const url = "https://script.google.com/macros/s/###/exec"; // Please set the URL of your Web Apps.

  fetch(url, { method: "POST", body: document.getElementById("sampletext").value })
    .then((res) => res.text())
    .then((url) => window.open(url, "_blank"));
}
</script>

Note:

*

*When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.

*You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

*My proposed script is a simple script. So please modify it for your actual situation.

References:

*

*Web Apps

*Taking advantage of Web Apps with Google Apps Script


Q: Audio players in Chrome packaged apps I'm trying to embed a music player in a Chrome app, and at the moment I'm using the default  tag to embed music, but the problem is that I can't seek the song unless the song has been fully downloaded before playing (I'm streaming it from a file host).
The file host has its own music player, but is made in flash and so it doesn't work in Chrome apps. What should I do?


Q: How does knockout dataFor/contextFor work, exactly? Background:
When the equivalent of javascript blur happens, I want to be able to edit the selectedOptions bound to a select list through knockout. For instance, select a specific element from a list, or clear the selection.
I found this topic which suggests two methods of implementing the "blur" part.
I would prefer to use the solution offered by Chris Pratt, as the system involves a lot of generated code, and it is much simpler if I don't have to change the knockout portion of it. All of my attempts so far have been using Chris Pratt's solution.
In my javascript, I am getting a handle on the relevant DOM elements with no problems. However, I am having difficulties getting a handle on the selectedOptions koobservablearray which is bound to the select. When I call ko.dataFor(DOMobject), it seems to return functions which return regular javascript arrays which are copies of my koobservablearrays, meaning that I can't edit them in order to change which option is selected.
Question:
So, is it possible to achieve what I am trying to do from "outside" of knockout, using methods like ko.dataFor or ko.contextFor? How are these methods intended to work? What are they good for?
Thanks!


Q: Replace() function with multiple values simultaneously recoded in r This is a very basic question, but I am using the replace() function to recode values that switch half-way through the years of reporting in my dataset. The key switches, so I am converting old character values to new ones.
Example: For the variable "animaltype": Old code, cat is reported as "CAT". New code, cat is reported as "CAT_unit"
I use the basic code:
animaltype = replace(animaltype, animaltype == "CAT", "CAT_unit")
within my dplyr piping to make sure all old responses of "CAT" and the new ones coded as "CAT_unit" are now both counted as "CAT_unit".
Individually, this works. However, I want to do this for other units. For example, I want to simultaneously convert all "DOG"s to "DOG_unit". Is there a way to do this within the same function/line of code. Or, do I need to create another replace function entirely?
I have seen using casewhen and ifelse as alternatives, but for convenience it would be ideal to use the replace function within my dplyr piping. I particularly want to avoid casewhen to avoid the conversion of other unspecified values to NAs, because I only have to recode certain units and retain the majority as is. Is this possible? Or would I have to recode them all individually? What is the most succinct way to do this?


Q: Querying MongoDB, List all unique using GROUP BY and INNER JOIN in the same query I'm doing a college job, but I'm not able to do these queries in the MongoDB database, I'll put the database links right down here for those who are kind enough to test, because I'm not getting it.
Question: List all unique employees’ last and first names (using GROUP BY method) that have a current salary (i.e. to_date equals to 9999-01-01) greater than 90000, outputting both names in descending order (sort by the last name first and then the first name) and also displaying their current salaries (using the INNER JOIN method).
I have tried some SQL conversions on Studio 3T, but I do not know what is wrong:
SELECT employees.emp_id, employees.first_name, employees.last_name, salaries.salary FROM employees
INNER JOIN salaries ON employees.emp_id = salaries.emp_id
WHERE to_date=9999-01-01 and salary > 90000
GROUP BY employees.emp_id

Some Data Employees:
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacf6"),
    "birth_date" : "1953-09-02",
    "emp_id" : NumberInt(10001),
    "first_name" : "Georgi",
    "gender" : "M",
    "hire_date" : "1986-06-26",
    "last_name" : "Facello",
    "email_address" : "gfacello@gmail.com"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacf7"),
    "birth_date" : "1964-06-02",
    "emp_id" : NumberInt(10002),
    "first_name" : "Bezalel",
    "gender" : "F",
    "hire_date" : "1985-11-21",
    "last_name" : "Simmel",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacf8"),
    "birth_date" : "1959-12-03",
    "emp_id" : NumberInt(10003),
    "first_name" : "Parto",
    "gender" : "M",
    "hire_date" : "1986-08-28",
    "last_name" : "Bamford",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacf9"),
    "birth_date" : "1954-05-01",
    "emp_id" : NumberInt(10004),
    "first_name" : "Chirstian",
    "gender" : "M",
    "hire_date" : "1986-12-01",
    "last_name" : "Koblick",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacfa"),
    "birth_date" : "1955-01-21",
    "emp_id" : NumberInt(10005),
    "first_name" : "Kyoichi",
    "gender" : "M",
    "hire_date" : "1989-09-12",
    "last_name" : "Maliniak",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacfb"),
    "birth_date" : "1953-04-20",
    "emp_id" : NumberInt(10006),
    "first_name" : "Anneke",
    "gender" : "F",
    "hire_date" : "1989-06-02",
    "last_name" : "Preusig",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacfc"),
    "birth_date" : "1957-05-23",
    "emp_id" : NumberInt(10007),
    "first_name" : "Tzvetan",
    "gender" : "F",
    "hire_date" : "1989-02-10",
    "last_name" : "Zielinski",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacfd"),
    "birth_date" : "1958-02-19",
    "emp_id" : NumberInt(10008),
    "first_name" : "Saniya",
    "gender" : "M",
    "hire_date" : "1994-09-15",
    "last_name" : "Kalloufi",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacfe"),
    "birth_date" : "1952-04-19",
    "emp_id" : NumberInt(10009),
    "first_name" : "Sumant",
    "gender" : "F",
    "hire_date" : "1985-02-18",
    "last_name" : "Peac",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dacff"),
    "birth_date" : "1963-06-01",
    "emp_id" : NumberInt(10010),
    "first_name" : "Duangkaew",
    "gender" : "F",
    "hire_date" : "1989-08-24",
    "last_name" : "Piveteau",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dad00"),
    "birth_date" : "1953-11-07",
    "emp_id" : NumberInt(10011),
    "first_name" : "Mary",
    "gender" : "F",
    "hire_date" : "1990-01-22",
    "last_name" : "Sluis",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dad01"),
    "birth_date" : "1960-10-04",
    "emp_id" : NumberInt(10012),
    "first_name" : "Patricio",
    "gender" : "M",
    "hire_date" : "1992-12-18",
    "last_name" : "Bridgland",
    "email_address" : "fred.bloggs@company.ie"
}
{
    "_id" : ObjectId("5fc157d9ba1b05372b2dad02"),
    "birth_date" : "1963-06-07",
    "emp_id" : NumberInt(10013),
    "first_name" : "Eberhardt",
    "gender" : "M",
    "hire_date" : "1985-10-20",
    "last_name" : "Terkki",
    "email_address" : "fred.bloggs@company.ie"
}

Some Salaries data:
{
    "_id" : ObjectId("5fc157daba1b05372b2db050"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1986-06-26",
    "salary" : NumberInt(60117),
    "to_date" : "1987-06-26"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db052"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1987-06-26",
    "salary" : NumberInt(62102),
    "to_date" : "1988-06-25"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db054"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1988-06-25",
    "salary" : NumberInt(66074),
    "to_date" : "1989-06-25"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db056"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1989-06-25",
    "salary" : NumberInt(66596),
    "to_date" : "1990-06-25"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db058"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1990-06-25",
    "salary" : NumberInt(66961),
    "to_date" : "1991-06-25"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db059"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1991-06-25",
    "salary" : NumberInt(71046),
    "to_date" : "1992-06-24"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db05b"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1992-06-24",
    "salary" : NumberInt(74333),
    "to_date" : "1993-06-24"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db05d"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1993-06-24",
    "salary" : NumberInt(75286),
    "to_date" : "1994-06-24"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db05f"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1994-06-24",
    "salary" : NumberInt(75994),
    "to_date" : "1995-06-24"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db062"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1995-06-24",
    "salary" : NumberInt(76884),
    "to_date" : "1996-06-23"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db064"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1996-06-23",
    "salary" : NumberInt(80013),
    "to_date" : "1997-06-23"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db066"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1997-06-23",
    "salary" : NumberInt(81025),
    "to_date" : "1998-06-23"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db068"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1998-06-23",
    "salary" : NumberInt(81097),
    "to_date" : "1999-06-23"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db06a"),
    "emp_id" : NumberInt(10001),
    "from_date" : "1999-06-23",
    "salary" : NumberInt(84917),
    "to_date" : "2000-06-22"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db06c"),
    "emp_id" : NumberInt(10001),
    "from_date" : "2000-06-22",
    "salary" : NumberInt(85112),
    "to_date" : "2001-06-22"
}
{
    "_id" : ObjectId("5fc157daba1b05372b2db06e"),
    "emp_id" : NumberInt(10001),
    "from_date" : "2001-06-22",
    "salary" : NumberInt(85097),
    "to_date" : "2002-06-22"
}

Employees table image
Salaries table image
MongoDbDump BSON files: employees.agz
Employees sample database (created by Fusheng Wang and Carlo Zaniolo
at Siemens Corporate Research)
Thanks

A: You can do with $project and $lookup.

*

*$project to include or exclude the fields $project

*$lookup to join collections. Here I have used uncorrelated-sub-queries. But there is a standard $lookup too

Here is the code
db.Employees.aggregate([
  {
    "$project": {
      _id: 1,
      emp_id: 1,
      first_name: 1,
      last_name: 1
    }
  },
  {
    "$lookup": {
      "from": "Salaries",
      let: { eId: "$emp_id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: [ "$$eId", "$emp_id" ] },
                { $gt: [ "$salary", 80000 ] },
                { $eq: [ "$to_date", "2002-06-22" ] }
              ]
            }
          }
        }
      ],
      "as": "salary"
    }
  }
])

Working Mongo playground


Q: Why doesn't 100vh fill whole page? I'm currently using React and I'm having issues getting a div to equal 100% of the height of the page. Originally, I had an issue with there always being about 24px of empty space above the body. I couldn't fit it no matter what. I eventually used this on my app.css (a reset)
* {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

It fixed the issue, but still, a measurement of 100% or 100vh doesn't actually equal 100% of the total view. Here's a screenshot of the page:
https://gyazo.com/3407b6bd0032f402f3bb97acdb725e40
The blue div is a div that fills 100vh. Yet, it doesn't fully fill the page. I tried 100% as well.
Blue div:
.loginWrapper {
  margin-left: 260px;
  height: 100vh;
  background-color: #29B6F6;
}

I noticed that the html had this styling on it, yet even when removed no changes were noticeable:
html {
    box-sizing: border-box;
}

If someone could please explain this phenomenon, I would be very grateful. If you need any extra information, just let me know. Thanks!

A: You will have to reset the basics margin and padding if applied from html and other top level tags.
body, html {margin: 0;padding: 0;}

Or just use something like reset.css
http://meyerweb.com/eric/tools/css/reset/


Q: JDA cant find the gateway intents class I have built my jda discord to a jar file and it raises the class not found error for the gateway intents class saying that its not found or this error specifically
Exception in thread "main" java.lang.NoClassDefFoundError: net/dv8tion/jda/api/requests/GatewayIntent
        at banos.bot.Main.main(Main.java:14)
Caused by: java.lang.ClassNotFoundException: net.dv8tion.jda.api.requests.GatewayIntent
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
        ... 1 more

Edit: Here is my build.gradle if that helps.
plugins {
    id 'java'
    id 'com.github.johnrengelman.shadow' version "7.1.0"
    id 'application'
}

group 'banos.bot'
version '1.1.0-SNAPSHOT'

ext {
    javaMainClass = "banos.bot.Main"
}

application {
    mainClass = 'banos.bot.Main'
}

repositories {
    mavenCentral()
    maven {
        name 'm2-dv8tion'
        url 'https://m2.dv8tion.net/releases'
    }
    maven {
        name 'duncte123-jfrog'
        url 'https://duncte123.jfrog.io/artifactory/maven'
    }}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2'
    implementation group: 'net.dv8tion', name: 'JDA', version: '4.3.0_324'
    implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'
    implementation group: 'me.duncte123', name: 'botCommons', version: '2.3.9'
}

test {
    useJUnitPlatform()
}

jar {
    manifest {
        attributes 'Main-Class': 'banos.bot.Main', 'Class-Path': './build/libs/Banos_Bot-1.1.0-SNAPSHOT.jar'
    }
}


Q: Using jQuery to set multiple selects using each I have a page full of selects, and they all have a common class.  I need to set every one of them to their first option.  Easy, right?  But what I finally wound up getting to work feels like such a hack... is there a better way?
$('.myclass').each(function() {
    var firstOptSelector = '#' + $(this).attr('id') + ' option:first'; // HACK
    $(firstOptSelector).attr('selected','selected');
});

A: Try like below,
$('.myclass').each(function() {
   this.selectedIndex = 0;
});

DEMO: http://jsfiddle.net/ZDYjP/

A: How about this short one?
$(".myclass :first-child").prop("selected", true);

DEMO: http://jsfiddle.net/u8S54/

A: Do it like this:
$('.myclass').each(function() {
    $(this).find('option:first').attr('selected','selected');
});

A: You don't need to use each. Here's an example.
$('.select').find('option:first').prop('selected', true );

A: $("option:first", ".myselect").prop('selected', true);

Working sample

A: If you remove the selected property then the first one by default is what is shown.
$('.myclass').find('option:selected').removeAttr("selected");


Q: How to record error messages when mapping a shared server to a network drive with VBS? The following snippet of script maps shared servers, stored as strings ( "\server\shared" ), in an array to the (A:) drive and record any errors encountered during the process. Then removes it to map the following item.
When some drives are mapped, depending on the user's administrative privileges, it may display an "access is denied" error message.
How can I write that message to a file in case it occurs.
Set objNetwork = WScript.CreateObject("WScript.Network")

' loop through array and write shared servers to reult excel sheet
For Each item in arrServerValues

  Echo item
  objNetWork.MapNetworkDrive "A:", item
  ' record potential error message to a result file: Results.txt
  objNetWork.RemoveNetworkDrive "A:"

Next

A: Learn about the following:

*

*On Error statement: to catch the error

*Err object: to grab the error message

*File operations (File System Object): to write to a file


Q: Character Repetition I am writing a simple program to calculate the repetition of characters in a string sequence. The program I have for now is as below, but I am looking to see if it can be optimized any further. I believe the program right now is O(n) worst case time and I would like to see if there is something that can give me O(log n) running time.
using System;
using System.Collections.Generic;

namespace Algos
{
    class CharacterRepitition
    {
        private char[] checkStringArray;
        private bool[] discovered;

        public CharacterRepitition(string toCheck)
        {
                checkStringArray= toCheck.ToCharArray();
                discovered= new bool[checkStringArray.Length];
                for (int i = 0; i < checkStringArray.Length; i++)
                {
                    discovered[i] = false;
                }
        }

        public void CheckRepetitions()
        {
            int charIndex=0;
            Dictionary<char, int> repetitions = new Dictionary<char, int>();
            while (charIndex < checkStringArray.Length)
            {
                int count = 0;

                if(discovered[charIndex].Equals(false))
                {
                    count = RunThroughTheString(charIndex, checkStringArray);
                    if (count > 0)
                    {
                        repetitions.Add(checkStringArray[charIndex], count+1);
                    }
                }
                charIndex++;
            }

            if (repetitions.Count == 0)
            {
                Console.WriteLine("\nNo characters repeated.");
            }
            else
            {
                foreach (KeyValuePair<char, int> result in repetitions)
                {
                    Console.WriteLine("\n'"+ result.Key + "' is present: " + result.Value + " times.");
                }
            }
        }

        private int RunThroughTheString(int currentCharIndex, char[] checkStringArray)
        {
            int counter = 0;
            for (int i = 0; i < checkStringArray.Length; i++)
            {
                if (checkStringArray[currentCharIndex].Equals(checkStringArray[i]) && i !=currentCharIndex)
                {
                    counter++;
                    discovered[i] = true;
                }
            }
            return counter;
        }

    }
}

I know i can achieve this with LINQ as well. But that is not something I am looking for. Appreciate your help.

A: Not sure if I read the question correctly, but would this work in you situation
    public void FindCharRepetitions(string toCheck)
    {
        var result = new Dictionary<char, int>();
        foreach (var chr in toCheck)
        {
            if (result.ContainsKey(chr))
            {
                result[chr]++;
                continue;
            }
            result.Add(chr, 1);
        }

       foreach (var item in result)
       {
           Console.WriteLine("Char: {0}, Count: {1}", item.Key, item.Value);
       }
    }

A: If the number of different characters is known (say only A-Z) then the code could be like this:
int[] counters = new int['Z' - 'A' + 1];
foreach(char c in toCheck)
    if (c >= 'A' && c <= 'Z')
        counters[c - 'A']++;


Q: Could someone explain the regex /(.*)\.(.*)/? I want to get the file extension in Groovy with a regex, for let's say South.6987556.Input.csv.cop.
http://www.regexplanet.com/advanced/java/index.html shows me that the second group would really contain the cop extension. Which is what I want.
0: [0,27] South.6987556.Input.csv.cop
1: [0,23] South.6987556.Input.csv
2: [24,27] cop

I just don't understand why the result won't be
0: [0,27] South.6987556.Input.csv.cop
1: [0,23] South
2: [24,27] 6987556.Input.csv.cop

What should be the regex to get this kind of result?

A: To get the desired output, your regex should be:
((.*?)\.(.*))

DEMO
See the captured groups at right bottom of the DEMO site.
Explanation:
(         group and capture to \1:
  (       group and capture to \2:
    .*?   any character except \n (0 or more
          times) ? after *  makes the regex engine
          to does a non-greedy match(shortest possible match).
  )       end of \2
  \.      '.'
  (       group and capture to \3:
    .*    any character except \n (0 or more
          times)
  )       end of \3
)         end of \1

A: Here is a visualization of this regex
(.*)\.(.*)

Debuggex Demo
in words

*

*(.*) matches anything als large as possible and references it

*\. matches one period, no reference (no brackets)

*(.*) matches anything again, may be empty, and references it

in your case this is

*

*(.*) : South.6987556.Input.csv

*\. : .

*(.*) : cop
it isn't just only South and 6987556.Input.csv.cop because the first part (.*) isn't optional but greedy and must be followed by a period, so the engine tries to match the largest possible string.
Your intended result would be created by this regex: (.*?)\.(.*). The ? after a quantifier (in this case *) switches the behaviour of the engine to ungreedy, so the smallest matching string will be searched. By default most regex engines are greedy.


Q: Form submit function seems to only change a value for a split second I have a list that changes value according to gold and silver spot prices. So having the ability to edit these always changing spot prices is crucial but i can't seem to get my form submit button to do anything permanently.
HTML
  <form>
    Silver Spot: <input type="text" name="fname" id="silverSpotPrice">

    Gold Spot: <input type="text" name="lname" id="goldSpotPrice">

    <button class ="submit" onclick="submitSpots()">SUBMIT</button>
   </form>

Javascript function the form button submits too (variables are called at begining of the javascript form)
    function submitSpots(){
    silverSpot = document.getElementById("silverSpotPrice").value;
    document.getElementById('silverSpot').innerHTML = silverSpot;

    goldSpot = document.getElementById("goldSpotPrice").value;
    document.getElementById('goldSpot').innerHTML = goldSpot;
}

the function does change the form for a split second when I click it rapidly, but always goes back to the original HTML side preset.
      Spot
      SilverSpot
      GoldSpot

I.E. the silverSpot and goldSpot spots go back to "SilverSpot" and "GoldSpot".  after showing another piece of text for only a split second.


Q: Making strings equal when compared to public class StringEqual
  {
 public static void main(String[] args)
   {
  String str1 = "abcd";
  String str2 = "abcdefg";
  String str3 = str1 + "efg";
  System.out.println("str2 = " + str2);
  System.out.println("str3 = " + str3);
  if (str2 == str3)
  {
     System.out.println("The strings are equal");
  }
  else
  {
     System.out.println("The strings are not equal");
  }
   }
  }

so far i've created this code. Now i am trying to figure out how do i make it so that str2 and str3 are equal when they are compared?

A: If you ant compare strings you have to use equals method:
if (str2.equals(str3))

A: == compares the Object Reference
String#equals compares the content
So replace str2==str3 with
  String str2 = "abcdefg";
  String str3 = str1 + "efg";
  str2.equals(str2); // will return true

A: You know, you need to differentiate between string equality and object idendity. The other answers already told you that it would work with .equals().
But if you actually asking on how to get the same object by your string expressions: if it is a compile time constant expression it will be the same object. The str3 would come from the constant pool if it is a constant expression, and in order for that, you may only use final string variables or string literals:
public class FinalString
{
final static String fab  = "ab";
static String        ab  = "ab";
static String        abc = "abc";
static String     nonfin = ab  + "c"; // nonfinal+literal
static String        fin = fab + "c"; // final+literal

public static void main(String[] args)
{
    System.out.println(" nonfin: "  + (nonfin == abc));
    System.out.println("  final: " + (fin == abc));
    System.out.println(" equals? " + fin.equals(nonfin));
}
}

prints
 nonfin: false
  final: true
 equals? true


Q: Represent a Mixture with a Django Model I'm trying to represent a mixture in Django. Something like:
Chemical #1 - 50%
Chemical #2 - 30%
Chemical #3 - 20%

I figured I would use a wrapper called composition as follows:
class Composition(models.Model):
    """ Just a Wrapper """
    def save(...):
        #Validate ingredients add up to 100% and such

class Ingredient(models.Model):
    composition = models.ForeignKey('Composition',related_name='ingredients')
    name = models.CharField(max_length = 10)
    percentage = models.IntegerField()

I'm pretty sure there's a better way to do this. Keep in mind that I'm doing it like this so I can later use inlines in the Django admin. What do you guys recommend? Thanks a lot =)

A: It seems to me as though it would be preferable to keep a list of ingredients then reference those when you create your compositions, rather than entering the ingredient names each time. You could do it using a many to many relationship and a through table, like so:
class Ingredient(models.Model):
    name = models.CharField(max_length=10)

class Composition(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient, through='CompositionIngredient')

    def save(...):
        #Validate ingredients add up to 100% and such

class CompositionIngredient(models.Model):
    composition = models.ForeignKey(Composition)
    ingredient = models.ForeignKey(Ingredient)
    proportion = models.DecimalField()

See the Django docs for more information.
EDIT: Here's the documentation on how to deal with through tables in the admin interface.


Q: STL-Like range, What could go wrong if I did this? I am writing (as a self-teaching exercise) a simple STL-Like range. It is an Immutable-Random-Access "container". My range, keeps only the its start element, the the number of elements and the step size(the difference between two consecutive elements):
struct range
{
...
private:
  value_type m_first_element, m_element_count, m_step;
};

Because my range doesn't hold the elements, it calculates the desired element using the following:
// In the standards, the operator[]
// should return a const reference.
// Because Range doesn't store its elements
// internally, we return a copy of the value.
value_type operator[](size_type index)
{
    return m_first_element + m_step*index;
}

As you can see, I am not returning a const reference as the standards say. Now, can I assume that a const reference and a copy of the element are the same in terms of using the non-mutating algorithms in the standard library?
Any advice about the subject is greatly appreciated.

@Steve Jessop: Good point that you mentioned iterators.
Actually, I used sgi as my reference. At the end of that page, it says:
Assuming x and y are iterators from the same range:

Invariants Identity
x == y if and only if &*x == &*y

So, it boils down to the same original question I've asked actually :)

A: Items in STL containers are expected to be copied around all the time; think about when a vector has to be reallocated, for example. So, your example is fine, except that it only works with random iterators. But I suspect the latter is probably by design. :-P

A: Do you want your range to be usable in STL algorithms? Wouldn't it be better off with the first and last elements? (Considering the fact that end() is oft required/used, you will have to pre-calculate it for performance.) Or, are you counting on the contiguous elements (which is my second point)?

A: The standard algorithms don't really use operator[], they're all defined in terms of iterators unless I've forgotten something significant. Is the plan to re-implement the standard algorithms on top of operator[] for your "ranges", rather than iterators?
Where non-mutating algorithms do use iterators, they're all defined in terms of *it being assignable to whatever it needs to be assignable to, or otherwise valid for some specified operation or function call. I think all or most such ops are fine with a value.
The one thing I can think of, is that you can't pass a value where a non-const reference is expected. Are there any non-mutating algorithms which require a non-const reference? Probably not, provided that any functor parameters etc. have enough const in them.
So sorry, I can't say definitively that there are no odd corners that go wrong, but it sounds basically OK to me. Even if there are any niggles, you may be able to fix them with very slight differences in the requirements between your versions of the algorithms and the standard ones.
Edit: a second thing that could go wrong is taking pointers/references and keeping them too long. As far as I can remember, standard algorithms don't keep pointers or references to elements - the reason for this is that it's containers which guarantee the validity of pointers to elements, iterator types only tell you when the iterator remains valid (for instance a copy of an input iterator doesn't necessarily remain valid when the original is incremented, whereas forward iterators can be copied in this way for multi-pass algorithms). Since the algorithms don't see containers, only iterators, they have no reason that I can think of to be assuming the elements are persistent.

A: Since you put "container" in "quotes" you can do whatever you want.
STL type things (iterators, various member functions on containers..) return references because references are lvalues, and certain constructs (ie, myvec[i] = otherthing) can compile then. Think of operator[] on std::map. For const references, it's not a value just to avoid the copy, I suppose.
This rule is violated all the time though, when convenient. It's also common to have iterator classes store the current value in a member variable purely for the purpose of returning a reference or const reference (yes, this reference would be invalid if the iterator is advanced).
If you're interested in this sort of stuff you should check out the boost iterator library.


Q: Enable SSL on tomcat on Docker I have local docker running up on my linux system. I'm trying to enable SSL on the docker container which runs tomcat. However I'm unable to get the SSL working.
I get the below error when I try to access the REST endpoint deployed locally on docker.
Aug 13, 2018 5:36:25 AM org.apache.coyote.http11.AbstractHttp11Processor process
INFO: Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.

I have added the below code to the server.xml:
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS"
           keystoreFile="/usr/java/default/lib/security/***.cert.p12" keystoreType="PKCS12" keystorePass="***" />

The same piece of code works fine when I try to deploy my java application on my local tomcat without docker.
Why is the same thing not working in tomcat on docker?


Q: npm local prefix always set to current working directory I've been searching for a while to try to find the answer to this. I've tried everything I've found that makes sense and more. Nothing has worked. Here's the breakdown:

*

*I'm on linux (12.3-RELEASE FreeBSD 12.3-RELEASE r371270 NFSN64  amd64)

*I've installed a package called hexo-cli using npm.

*My home directory is /home/private

*My global npm install directory is /home/private/.npm-global

*My npm prefix -g location is: /home/private/.npm-global

*When my cwd is /home/public/ and I execute hexo, hexo runs

*hexo then fails to find itself because it's using the npm prefix (this is my guess)

*When I type npm prefix it always returns my cwd

*I have checked /home/private/.npmrc file. A grep "prefix" /home/private/.npmrc returns:

*prefix=/home/private/.npm-global

*There are no other lines or entries returned from the grep

*npm config set prefix=/home/private/.npm-global only modifies the global prefix, not my local prefix

How do I get my local prefix var to be /home/private/.npm-global?
Edit:
Here is the output of my terminal when running hexo:
[username /home/public]$ hexo
ERROR Cannot find module 'hexo' from '/home/public'
ERROR Local hexo loading failed in /home/public
ERROR Try running: 'rm -rf node_modules && npm install --force'

Edit #2:
Forgot to mention. I also tried adding the following two lines to my ~/.profile file:
export PATH=~/.npm-global/bin:$PATH
export PATH=~/.npm-global/lib/node_modules:$PATH

I would then source ~/.profile.
This made absolutely no difference.
Edit #3:
Fixed a path in the 6th bullet point.
Edit #4
This is the output of my npm config list:
[username /home/public]$ npm config list
; "user" config from /home/private/.npmrc

prefix = "/home/private/.npm-global"

; node bin location = /usr/local/bin/node
; node version = v16.16.0
; npm local prefix = /home/public
; npm version = 8.13.0
; cwd = /home/public
; HOME = /home/private/
; Run `npm config ls -l` to show all defaults.

Notice it says npm local prefix. Attempting to npm config set local prefix ... does not work. local prefix is not a variable you can assign a value to. I tried localprefix as well. This did not work.

A: I don't know what the problem was. However I've nuked everything from orbit and started over. I deleted everything except a single html file in my /home/public directory. I deleted /home/private/.npm-global. I recreated /home/private/.npm-global. I followed the steps listed in the answer to:
Global Node modules not installing correctly. Command not found
Specifically the steps provided by Vicente, posted Feb 9, 2019 at 16:30. Which were:
[username /home/public]$ mkdir /home/private/.npm-global
[username /home/public]$ npm config set prefix '~/.npm-global'
[username /home/public]$ export PATH=~/.npm-global/bin:$PATH
[username /home/public]$ source ~/.profile
[username /home/public]$ npm install -g hexo-cli

Then I tried to run from /home/public: hexo init blog
This command worked and it creates a blog directory in the cwd. However, then I tried to run hexo server from the same directory I was still in. This did not work. I changed directories to /home/public/blog/ and then typed hexo server. This still did not work and would only print out some help message about a few commands you could run.
Their website says this is generally due to a missing version line in the dependency of the blog/package.json file. I edited the file and added version 3.2.2, and then re-ran it as hexo --version. When I did this, it dumped out some Validating config output with a bunch of dependencies and their version numbers. The version number specified for hexo was hexo: 6.3.0. I went to open the blog/package.json file again to update the version from 3.2.2 to 6.3.0. However, hexo had already updated the file for me.
Then I typed hexo server while still in /home/public/blog and then the hexo server started up. It errored out with some NaN is not a valid date! error, but the server was still running.
In a separate terminal connected to the same machine and inside the /home/public/blog directory I typed hexo new "Hello Hexo". This worked. Then I typed hexo generate to generate the static files. This also worked.
Everything seems to be working now. Not sure what the problem was earlier. Would still like to know how to set the local prefix to a specific path though, if possible.


Q: Work with and change the layout of an csv file in pandas I read a csv data with pandas and now I would like to change the layout of my dataset. My dataset from excel looks like this:

I run the code with df = pd.read_csv(Location2)
This is what I get:

I would like to have a separated column for time and Watt and their values.
I looked at the documentation but I couldn't find something to make it work.

A: Use read_excel
df = pd.read_excel(Location2)

A: It seems as if you'd need to set up the correct delimiter that separates the two fields. Try adding delimiter=";" to the parameters

A: I think you need parameter sep in read_csv, because default separator is ,:
df = pd.read_csv(Location2, sep=';')

Sample:
import pandas as pd
from pandas.compat import StringIO

temp=u"""time;Watt
0;00:00:00;50
1;01:00:00;45
2;02:00:00;40
3;00:03:00;35"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), sep=";")
print (df)
       time  Watt
0  00:00:00    50
1  01:00:00    45
2  02:00:00    40
3  00:03:00    35

Then is possible convert time column to_timedelta:
df['time'] = pd.to_timedelta(df['time'])
print (df)
      time  Watt
0 00:00:00    50
1 01:00:00    45
2 02:00:00    40
3 00:03:00    35

print (df.dtypes)
time    timedelta64[ns]
Watt              int64
dtype: object


Q: Intelligent credit cards fields iOS i'm currently developing an app for iOS 8 in swift with a credit card payment functionality.
I searched on the web for a library with intelligent credit card fields, but all i could find is BKMoneyKit, which is not really customizable, and doesn't fit my needs.
What i want is something with fancy features, like telling you if your card is a visa/mastercard when you enter the number, adding the "/" between month and year of expiration date etc... I've already used card.io, but it doesn't offer the possibility to include it's intelligent fields in my view, like said here by the developer himself.
Does anybody knows a tool like this ?
Thanks in advance for help :)

A: The functionalities you are asking for are provided by the PaymentKit library.


Q: How to store and pass information between list views The functionality of my app can be modeled after something like wanelo.
The user will enter a search term for what they want to buy in one Activity. They will get presented with a list of items that match that search term. So, the ListView will contain Items. An Item has many attributes, the main ones being:

*

*id - corresponds to the Item's id in a database

*date_modified - timestamp to know whether the Item was updated

*remote_directory - a URL to the base directory of the Item's assets like icon and other images. The URL is formatted like this: http://my.domain.com/items/a1bc234d/ where a1bc234d is randomly generated, seeded by date_modified.

*remote_dir_name - a substring of remote_directory. From the example above, this value would be a1bc234d.

From the list of search results, the user can mark an item to be viewed later. This will trigger a couple of things:

*

*First, I want to ad the Item to a different ListView that represents the Items the user has "downloaded".

*Then, I want to actually download of all of the Item's data: description, all assets in remote_directory. These things get stored my app's internal storage in folders remote_dir_name: /data/data/my.app.package.name/files/a1bc234d/.

These "downloaded" items are meant to be viewable in offline mode.
This "downloaded" ListView corresponds to a different Activity and will have list items that show a progress bar of the download status for an Item. Also, this ListView should be editable: use should be able to delete and re-order the Items in the list.
Finally, the "downloaded" ListView needs to be persistent. It should preserve order. The ListView of search results need not persist.
I'm having a lot of trouble figuring out how to store the list of Items getting downloaded. The "download" ListView needs to know when to update a list item's progress bar if it's getting downloaded. I think it's a little overkill to store the Items in a database because I'll be constantly updating a row's column until the download finishes. How should I pass this download status information between these two ListViews?

A: I am not entirely sure I am grasping the whole picture here, but it seems to me that you need two ArrayList fields.
List<Item> downloadedItems = new ArrayList<Item>;
List<Item> searchItems = new ArrayList<Item>;

then what you need to do is create your own custom ListAdapter for the DownloadListView and create your own custom download_item.xml that you will inflate inside of the ListAdapter. In your case it sounds like this download_item.xml will consist of a textview, and a progressbar, and will need the containing (or top layer) layout set to wrap content.
Now in the on click listener for the SearchListView set it so that it will call a function that will take the item that was tapped and add it to the downloadedItems ArrayList and start the download, as well as refresh the listadapter dataset so it knows to update the items in the list.
The download should be in a AsyncTask, and you will want to use the @Override publishProgress() portion of this, so that you can update the status of the download bar.
forgive me for any mis sights or mistakes, I just woke up.


Q: calling instance method on model and passing its parameters I have model.rb
class Foo
  def baz(param1, param2, param3, param4)
    puts 'something'
  end
end

controller.rb
def signup
  param4 = params[:param4] || 'N'
  begin
    @foo.baz(Integer(params[:param1]),
                              params[:param2],
                              params[:param3],
                              param4)
    head :ok
  rescue ArgumentError => e
    render_error(:bad_request, e.message)
  end
end

Is this the right way to call instance method on model? also should this param4 = params[:param4] || 'N' be done in model?

A:
Is this the right way to call instance method on model?

Yes, if @foo is an instance of Foo

should this param4 = params[:param4] || 'N' be done in model?

You can set the last parameter variable on you model to be option like so
class Foo
  def baz(param1, param2, param3, param4 = 'N')
    puts 'something'
  end
end

And remove the need to set it within the controller
def signup
  @foo.baz(Integer(params[:param1]),
                            params[:param2],
                            params[:param3],
                            params[:param4])
  head :ok
rescue ArgumentError => e
  render_error(:bad_request, e.message)
end

Since if params[:param4] is nil it will be set to 'N' as specified within the baz method on the Foo model.
Whether or not if you should set param4 in the model is up to you:

*

*Yes, if setting the last parameter param4 to 'N' should or need to occur outside the controller, or

*No, if setting a default value for param4 is unique to the signup controller action and param4 should not have default set, since it might be used elsewhere

A: I think you should handle it in model:
class Foo
  def baz(param)
    param1 = Integer(params[:param1])
    param2 = params[:param2]
    param3 = params[:param2]
    param4 =  params[:param4] || 'N'
    puts 'something'
  end
end


Q: Wordpress Custom Fields not displaying the section I have added a new layout in the Wordpress Custom fields plugin, and after adding it I have added the fields in the corresponding php file too. But for some reason, its printing the code in the browser. I am not sure what I am doing wrong here. I am new to WordPress, so can someone please help me?
Screenshots attached for reference.
PHP file code - https://codeshare.io/GklExO

A: Figured it out, I had to add an image tag and then it worked fine.
However, there are other PHP files in the site, where
<?php the_sub_field('image'); ?> displays the image, but in this particular case I had to write it as
<img src="<?php echo esc_url($image['url']); ?>"/>

Still trying to understand how this works.


Q: Covert name part after "ACCOUNTS\\" to lower case? I have web method to get user from this.User.Identity.Name.string username  = "ACCOUNTS\Ninja.Developer" I want to convert username part after "ACCOUNTS\" to lower case  to be username  = "ACCOUNTS\ninja.developer"
public User GetUser()
{
    var user = new User
    {
        Username = this.User.Identity.Name,<-- convert it here
        IsAuthenticated = this.User.Identity.IsAuthenticated
    };

    return user;
}

note: double \ not single \

A: Use this code:
var Identity = this.User.Identity.Name;
var Username = Identity.Split('\\')[0] + @"\\" + Identity.Split('\\')[2].ToLower();

Of course you should check before in the name have the \ character, etc.

A: You can use Regex.Replace to achieve it :
Username = Regex.Replace(this.User.Identity.Name, @"(?<=ACCOUNTS\\).+", n => n.Value.ToLower()),

The regex pattern (?<=ACCOUNTS\\).+ will match for anything after ACCOUNTS\, and the match is then replaced by its lower case equivalent.

A: As mentioned in other answers, you can use Regex or Split, but here's a substring approach specific to your case.
var user = new User
{
    Username = this.User.Identity.Name.Substring(0,9) + this.User.Identity.Name.Substring(9, name.Length - 9).ToLower(),
    IsAuthenticated = this.User.Identity.IsAuthenticated
};


Q: Swift 2.0 NSJSONSerialization fails if response has only one item Here is a snippet of my code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
            do {
                guard let json = try NSJSONSerialization.JSONObjectWithData
(data!, options: .MutableContainers) as? [NSDictionary] else {
                    throw HttpError.ParsingFailed
                }
                completionHandler(success: true, data:json, error: nil)
            }
            catch HttpError.ParsingFailed {
...

It works fine, if the response data has more than one element.
However the NSJSONSerialization.JSONObjectWithData fails (goes in the else block which throws the exception), if there is only one item in the response.
Why doesn't it still parse the response in this case, and returns an array with one element inside?
How should be this problem generally solved?
Of course it would help to do an other parsing in the catch block with as? NSDictionary instead of as? [NSDictionary], but I would avoid this when possible.
EDIT:
object to be parsed which works:
[
    {
    "id": 1,
    "idConsumer": 12
    },
    {
    "id": 2,
    "idConsumer": 12
  }
]

and which does not work:
   {
    "id": 65,
    "delivery": {
    "id": 29,
    "idConsumer": 19
    },
    "postman": {
       "id": 13,
       "email": "testpostman"
     },
     "price": 89
    }

A: It's failing because you are casting your JSON to [NSDictionary]. When you get multiple objects, you get an array of dictionaries, but when you get a single object, you get a single dictionary.
You should try to cast to NSDictionary if casting to [NSDictionary] fails.
If both fail then you should throw the error.


Q: Read a text file into a pandas dataframe or numpy array I have a file that looks like this - http://pastebin.com/u1A7v1CV
It's just a sample of two rows from a file.
The rows contain word_label_id followed by freq.
For example, word_label_id 1237 occurs 1 time in the first row, 1390 occurs 1 time and so on...
I need to use this sparse representation but I'm unable to convert it into a DataFrame or any other usable format.
Edit: I know that pandas has a read_csv method where I can use a space as the delimiter. This is not ideal as I need two separators - one between word_label_id and freq and a different separator between this pair and the next.

A: Ok, it's not ideal but you can use notepad++.
It had a "find and replace" feature and you can use \t to replace tabs as \n
Then you can record a macro to move any given line to the previous, skipping lines.
Then you can use pandas, pd.from_csv but you have to define delimiters as tabs instead of commas
Another option is to read each line,and process it separately.  Basically a while loop with the condition being not m_line == null
Then inside the loop, split the string up with str.split ()
And have another loop that makes a dictionary, for each row.  In the end, you'd have a list of dictionaries where each entry is ID:frequency

A: Have you tried work separately with each item?
For example:
Open document:
with open('delimiters.txt') as r:
    lines = r.readlines()
    linecontent = ' '.join(lines)

Create a list for each item:
result = linecontent.replace(' ', ',').split(',')

Create sublist for ids and freqs:
newResult = [result[x:x+2] for x in range(0, len(result), 2)]

Working with each data type:
ids = [x[0][:] for x in newResult]
freq = [x[1][:] for x in newResult]

Create a DataFrame
df = pandas.DataFrame({'A ids': ids, 'B freq': freq})

A: Here's what I did.
This creates a dictionary containing key-value pairs
from each row.
data = []

with open('../data/input.mat', 'r') as file:
    for i, line in enumerate(file):
        l = line.split()
        d = dict([(k, v) for k, v in zip(l[::2], l[1::2])])
        data.append(d)


Q: Getting cache info using C/C++ with inline assembly/intrinsics in osx I wrote the following program using both gcc __get_cpuid and inline assembly to get the cache info of my laptop but fail to identify them on the table about (Encoding of Cache and TLB Descriptors) I found online.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <stdint.h>
#include <math.h>
#include <cpuid.h>

static inline void cpuid(uint32_t *eax, uint32_t *ebx,
                         uint32_t *ecx, uint32_t *edx);

int main() {
    uint32_t a, b, c, d;
    uint32_t eax, ebx, ecx, edx;
    eax = 2; /* processor info and feature bits */
    uint32_t command = 2;
    cpuid(&eax, &ebx, &ecx, &edx);
    __get_cpuid(command, &a, &b, &c, &d);

    printf("eax: %08x\n", eax);
    printf("ebx: %08x\n", ebx);
    printf("ecx: %08x\n", ecx);
    printf("edx: %08x\n", edx);

    printf("a: %08x\n", a);
    printf("b: %08x\n", b);
    printf("c: %08x\n", c);
    printf("d: %08x\n", d);
}

static inline void cpuid(uint32_t *eax, uint32_t *ebx,
                         uint32_t *ecx, uint32_t *edx)
{
        /* ecx is often an input as well as an output. */
        asm ("cpuid"
            : "=a" (*eax),
              "=b" (*ebx),
              "=c" (*ecx),
              "=d" (*edx)
            : "0" (*eax));
}

my output:
eax: 76036301
ebx: 00f0b5ff
ecx: 00000000
edx: 00c10000
a: 76036301
b: 00f0b5ff
c: 00000000
d: 00c10000

I found this table from here

I use sysctl hw.cachesize and find that
L1 cache: 32KB
L2 cache: 256KB
L3 cache: 6MB

My Environment:
system: os x 10.10.1
compiler: clang-602.0.53
CPU: I7-4850 HQ 2.3HZ

What's wrong with my program? My program should work since both methods give the same result... I am confused about this. Thank you!
EDIT:
I try what Mats' suggested and get the following as my output:
gcc intrinsic
a: 76036301
b: 00f0b5ff
c: 00000000
d: 00c10000
eax: 2
eax: 76036301
ebx: 00f0b5ff
ecx: 00000000
edx: 00c10000
eax: 4, ecx: 0
eax: 1c004121
ebx: 01c0003f
ecx: 0000003f
edx: 00000000
eax: 4, ecx: 1
eax: 1c004122
ebx: 01c0003f
ecx: 0000003f
edx: 00000000
eax: 4, ecx: 2
eax: 1c004143
ebx: 01c0003f
ecx: 000001ff
edx: 00000000
eax: 4, ecx: 3
eax: 1c03c163
ebx: 02c0003f
ecx: 00001fff
edx: 00000006
eax: 4, ecx: 4
eax: 1c03c183
ebx: 03c0f03f
ecx: 00001fff
edx: 00000004
eax: 4, ecx: 5
eax: 00000000
ebx: 00000000
ecx: 00000000
edx: 00000000

I look up the table at here
static cpuid_cache_descriptor_t intel_cpuid_leaf2_descriptor_table[] = {
//  -------------------------------------------------------
//  value   type    level       ways    size    entries
//  -------------------------------------------------------
    { 0x00, _NULL_, NA,     NA, NA, NA  },
    { 0x01, TLB,    INST,       4,  SMALL,  32  },
    { 0x02, TLB,    INST,       FULLY,  LARGE,  2   },
    { 0x03, TLB,    DATA,       4,  SMALL,  64  },
    { 0x04, TLB,    DATA,       4,  LARGE,  8   },
    { 0x05, TLB,    DATA1,      4,  LARGE,  32  },
    { 0x06, CACHE,  L1_INST,    4,  8*K,    32  },
    { 0x08, CACHE,  L1_INST,    4,  16*K,   32  },
    { 0x09, CACHE,  L1_INST,    4,  32*K,   64  },
    { 0x0A, CACHE,  L1_DATA,    2,  8*K,    32  },
    { 0x0B, TLB,    INST,       4,  LARGE,  4   },
    { 0x0C, CACHE,  L1_DATA,    4,  16*K,   32  },
    { 0x0D, CACHE,  L1_DATA,    4,  16*K,   64  },
    { 0x0E, CACHE,  L1_DATA,    6,  24*K,   64  },
    { 0x21, CACHE,  L2,     8,  256*K,  64  },
    { 0x22, CACHE,  L3_2LINESECTOR, 4,  512*K,  64  },
    { 0x23, CACHE,  L3_2LINESECTOR, 8,  1*M,    64  },
    { 0x25, CACHE,  L3_2LINESECTOR, 8,  2*M,    64  },
    { 0x29, CACHE,  L3_2LINESECTOR, 8,  4*M,    64  },
    { 0x2C, CACHE,  L1_DATA,    8,  32*K,   64  },
    { 0x30, CACHE,  L1_INST,    8,  32*K,   64  },
    { 0x40, CACHE,  L2,     NA, 0,  NA  },
    { 0x41, CACHE,  L2,     4,  128*K,  32  },
    { 0x42, CACHE,  L2,     4,  256*K,  32  },
    { 0x43, CACHE,  L2,     4,  512*K,  32  },
    { 0x44, CACHE,  L2,     4,  1*M,    32  },
    { 0x45, CACHE,  L2,     4,  2*M,    32  },
    { 0x46, CACHE,  L3,     4,  4*M,    64  },
    { 0x47, CACHE,  L3,     8,  8*M,    64  },
    { 0x48, CACHE,  L2,     12,     3*M,    64  },
    { 0x49, CACHE,  L2,     16, 4*M,    64  },
    { 0x4A, CACHE,  L3,     12,     6*M,    64  },
    { 0x4B, CACHE,  L3,     16, 8*M,    64  },
    { 0x4C, CACHE,  L3,     12,     12*M,   64  },
    { 0x4D, CACHE,  L3,     16, 16*M,   64  },
    { 0x4E, CACHE,  L2,     24, 6*M,    64  },
    { 0x4F, TLB,    INST,       NA, SMALL,  32  },
    { 0x50, TLB,    INST,       NA, BOTH,   64  },
    { 0x51, TLB,    INST,       NA, BOTH,   128 },
    { 0x52, TLB,    INST,       NA, BOTH,   256 },
    { 0x55, TLB,    INST,       FULLY,  BOTH,   7   },
    { 0x56, TLB,    DATA0,      4,  LARGE,  16  },
    { 0x57, TLB,    DATA0,      4,  SMALL,  16  },
    { 0x59, TLB,    DATA0,      FULLY,  SMALL,  16  },
    { 0x5A, TLB,    DATA0,      4,  LARGE,  32  },
    { 0x5B, TLB,    DATA,       NA, BOTH,   64  },
    { 0x5C, TLB,    DATA,       NA, BOTH,   128 },
    { 0x5D, TLB,    DATA,       NA, BOTH,   256 },
    { 0x60, CACHE,  L1,     16*K,   8,  64  },
    { 0x61, CACHE,  L1,     4,  8*K,    64  },
    { 0x62, CACHE,  L1,     4,  16*K,   64  },
    { 0x63, CACHE,  L1,     4,  32*K,   64  },
    { 0x70, CACHE,  TRACE,      8,  12*K,   NA  },
    { 0x71, CACHE,  TRACE,      8,  16*K,   NA  },
    { 0x72, CACHE,  TRACE,      8,  32*K,   NA  },
    { 0x78, CACHE,  L2,     4,  1*M,    64  },
    { 0x79, CACHE,  L2_2LINESECTOR, 8,  128*K,  64  },
    { 0x7A, CACHE,  L2_2LINESECTOR, 8,  256*K,  64  },
    { 0x7B, CACHE,  L2_2LINESECTOR, 8,  512*K,  64  },
    { 0x7C, CACHE,  L2_2LINESECTOR, 8,  1*M,    64  },
    { 0x7D, CACHE,  L2,     8,  2*M,    64  },
    { 0x7F, CACHE,  L2,     2,  512*K,  64  },
    { 0x80, CACHE,  L2,     8,  512*K,  64  },
    { 0x82, CACHE,  L2,     8,  256*K,  32  },
    { 0x83, CACHE,  L2,     8,  512*K,  32  },
    { 0x84, CACHE,  L2,     8,  1*M,    32  },
    { 0x85, CACHE,  L2,     8,  2*M,    32  },
    { 0x86, CACHE,  L2,     4,  512*K,  64  },
    { 0x87, CACHE,  L2,     8,  1*M,    64  },
    { 0xB0, TLB,    INST,       4,  SMALL,  128 },
    { 0xB1, TLB,    INST,       4,  LARGE,  8   },
    { 0xB2, TLB,    INST,       4,  SMALL,  64  },
    { 0xB3, TLB,    DATA,       4,  SMALL,  128 },
    { 0xB4, TLB,    DATA1,      4,  SMALL,  256 },
    { 0xBA, TLB,    DATA1,      4,  BOTH,   64  },
    { 0xCA, STLB,   DATA1,      4,  BOTH,   512 },
    { 0xD0, CACHE,  L3,     4,  512*K,  64  },
    { 0xD1, CACHE,  L3,     4,  1*M,    64  },
    { 0xD2, CACHE,  L3,     4,  2*M,    64  },
    { 0xD3, CACHE,  L3,     4,  4*M,    64  },
    { 0xD4, CACHE,  L3,     4,  8*M,    64  },
    { 0xD6, CACHE,  L3,     8,  1*M,    64  },
    { 0xD7, CACHE,  L3,     8,  2*M,    64  },
    { 0xD8, CACHE,  L3,     8,  4*M,    64  },
    { 0xD9, CACHE,  L3,     8,  8*M,    64  },
    { 0xDA, CACHE,  L3,     8,  12*M,   64  },
    { 0xDC, CACHE,  L3,     12,     1536*K, 64  },
    { 0xDD, CACHE,  L3,     12,     3*M,    64  },
    { 0xDE, CACHE,  L3,     12,     6*M,    64  },
    { 0xDF, CACHE,  L3,     12, 12*M,   64  },
    { 0xE0, CACHE,  L3,     12, 18*M,   64  },
    { 0xE2, CACHE,  L3,     16, 2*M,    64  },
    { 0xE3, CACHE,  L3,     16, 4*M,    64  },
    { 0xE4, CACHE,  L3,     16, 8*M,    64  },
    { 0xE5, CACHE,  L3,     16, 16*M,   64  },
    { 0xE6, CACHE,  L3,     16, 24*M,   64  },
    { 0xF0, PREFETCH, NA,       NA, 64, NA  },
    { 0xF1, PREFETCH, NA,       NA, 128,    NA  }
};

The problem right now is that I still cannot get the correct size of my L3 cache(when ecx=1, I get 22 i.e. 512K, but the correct value is 6MB). Also, there seems to be some conflicts in terms of the size of my L2 cache(43(when ecx=2) and 21(when ecx=0) )

A: So, your data seems to be reasonably correct, just that you are using an old reference. Unfortunately, Intel's website is either broken presently or it doesn't like Firefox and/or Linux.
76036301
76 means trace cache with 64K ops.
03 means 4 way DATA TLB with 64 entries.
63 is 32KB L1 cache - the source here shows that value, which is not in your docs.
01 means 4 way Instruction TLB with 32 entries.
00f0b5ff gives
00 "nothing"
f0 prefetch, 64 entries.
0b Instruction 4 way TLB for large pages, 4 entries.
b5 is not documented even on that link. [guessing small data TLB]
To get L2 and L3 cache sizes, you need to use CPUID with EAX=4, and set ECX to 0, 1, 2, ... for each caching level. The linked code shows this, and Intel's docs have details on which bits mean what.

A: Intel's Instruction Set Reference has all the relevant information you need (at around page 263), and is actually up to date unlike every other source I have found.
Probably the best way to get the cache info is mentioned in that reference.
When eax = 4 and ecx is the cache level,
Ways = EBX[31:22]

Partitions = EBX[21:12]

LineSize = EBX[11:0]

Sets = ECX

Total Size = (Ways + 1) * (Partitions + 1) * (Line_Size + 1) * (Sets + 1)

So when CUPID is called with eax = 4 and ecx = 3, you can get your L3 cache size by doing the computation above. Using the OP's posted data:
ebx: 02c0003f
ecx: 00001fff

Ways = 63
Partitions = 0
LineSize = 11
Sets = 8191

Total L3 cache size = 6291456
Which is what was expected.


Q: Android 6 Permissions - managing foreign apps permissions Using the package manager I can see what permissions foreign apps request. But is it possible to find out what permissions the user allows for other apps? And can you change the permissions of other apps from your application? These questions apply on non-rooted devices.

A: I solved this problem in a rooted device; the way I follow to manage permission require root privileges:
Process su = Runtime.getRuntime().exec("su");
            DataOutputStream dos = new DataOutputStream(su.getOutputStream());
        dos.writeBytes("pm revoke/grant " + packageName + " " + permissionName);
        dos.flush();
        dos.close();

Maybe studing android security architecture you will be cabable to find a way to solve the problem on non-rooted devices but you'll waste a lot of time.


Q: 0 value not working when import excel sheet for if condition in laravel excel Excel file as below
Id |   pro name | status
1  |   test.          | 0

*

*Laravel 5.6

*PHP 7.2

*Maatwebsite/excel 2.*

Below my Laravel code
$data = Excel::load($path)->get();

if print $data then its show me 0.
echo $data[0]->status; // output:0

if($data[0]->status === ""){
    echo "Status field required"; exit;
}
if($data[0]->status === 0 || $data[0]->status === 1){
    echo "successfully";exit;
}else{
    echo "status format 0 or 1 required"; exit;
}

if I set 0 value in the status column then also print Status field required.
if I set (int)$data[0]->status then Null value show as 0.so how can i solve this issues ?

A: Excel sheet import value always return in string format so you try below code
$status = $data[0]->status;
if(is_null($status)){
    echo "Status field required";exit;
}else{
    $status = (int)$status;
}
if($status === 0 || $status === 1){
    echo "successfully";exit;
}else{
    echo "status format 0 or 1 required"; exit;
}


Q: Attempting to set variable based on conditional statement in Python So today is literally my first day of learning a programming language so I'm very new to Python. I'm taking the online Python for Informatics course at the University of Michigan and our first real assignment is to create a simple gross pay rate calculator.
That was simple enough so I decided I wanted to expand what the program could do to calculate net pay and account for taxes. The trouble I'm having is determining how I can dynamically (if that's even the right word) set the value of the variable "taxrate" based on a series of conditional statements.
I have yet to find the answer in searching through Python's site and Stack Overflow. I think my limited understanding of programming probably is limiting my ability to interpret properly what I have found.
Just looking for a little help:
Code:
#This program is intended to calculate the net pay of employees
#This first section includes a loop for mistakes and finds gross pay

while True:

hours = raw_input('How many hours do you work weekly?')
hours1 = float(hours)
rate = raw_input('What is your hourly rate of pay?')
rate1 = float(rate)
grosspay = hours1 * rate1
taxstatus = raw_input('Do you pay taxes?')

#This secdtion is establishing the tax bracket the user falls into
taxbracket = taxrate
if grosspay <= 1000:
    taxrate = 0.90
if grosspay > range(1000,1500):
    taxrate = 0.78
if grosspay >= 1501:
    taxrate = 0.63

# This section is intended to calculate pay after taxes
grosspay = hours1 * rate1
if taxstatus == 'yes':
    netpay = grosspay * taxrate
print'Your weekly pay after taxes is',netpay
if not taxstatus:
    print grosspay

When I run this in PyCharm it lets me know that "taxrate" hasn't been defined. I ultimately want the program to set the "taxrate" based on what the users "grosspay" is. Is what I'm trying to do possible? I'm assuming it is and that I just don't understand how to do it.
Any help is greatly appreciated and in case someone is wondering what the loop is for I've got a user error checker that I'm working on after this portion of the program completes.

A: Your logic is a bit suspect in if grosspay > range(1000, 1500). What would it mean to be "greater" than a range of numbers? my guess is that the grosspay you input is, in fact, within the range [1000, 1500), so it hits this logic bug in your code and fails to assign it to anything.
The usual way to check if a number is within a range is to use the in operator.
if some_num in range(1, 10):
    print("some_num is 1, 2, 3, 4, 5, 6, 7, 8, or 9")

However you'll notice that some_num MUST be contained in the integer range [1, 9] for this to trigger. If some_num is 7.5, this will fail. This is incredibly likely in the case of gross pay. What are the chances of someone's pay coming out to an exactly even dollar amount?
Instead what you could do is:
if grosspay <= 1000:
    taxrate = 0.90
elif 1000 < grosspay <= 1500:
    taxrate = 0.78
elif 1500 < grosspay:
    taxrage = 0.63

using elif instead of a series of ifs makes the code slightly more efficient, since if/elif/else is by definition one block that is mutually exclusive. In other words:
a = 1
b = 2

if a == 1:
    print("This gets done!")
if b == 2:
    print("This gets done!")

if a == 1:
    print("This gets done!")
elif b == 2:
    print("BUT THIS DOESN'T!")
else:
    print("(this doesn't either...)")


Q: unknown permission android.permission.RECORD_VIDEO Suddenly in my logs in "warn" I've found this :
unknown permission android.permission.RECORD_VIDEO

And this happened on a device that fails to do a MediaRecorder.start() method with simple and uninformative "start fails" error message.
java.lang.RuntimeException: start failed.
    at android.media.MediaRecorder.start(Native Method)
    at com.vladdrummer.headsup.ScreenVideoRecorder.record(ScreenVideoRecorder.java:94)

App is working on many devices, but some have this kind of a problem - it fails to start, although , preparing went fine
So, may be theese two errors are connected? what should I do with "unknown permission android.permission.RECORD_VIDEO" ??

A: There is no permission as
android.permission.RECORD_VIDEO

See here
Ideally you should be using these permission
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Also manifest should have
<uses-feature android:name="android.hardware.Camera"/>


Q: How to edit a user in ASP.NET Identity I am new to the ASP.NET Identity framework and I am trying to do some things. What I want to do is to edit the user who has already register and then update the user details to the database...
Previously, I use entity framework, and then its generated my controller view and model it self. But I want to update my user details and getting a list of users into a list..
How do I do these stuff? I have seen role methods..but I never understand,
How can I do? without using role..Because, I don't need administrator purposes. Only, I want to update my user details.

A: There is a class that comes with asp.net identity called UserManager
this class will help with the user information management you can first find a user using either

*

*FindByIdAsync

*FindByEmailAsync

*FindByUserName

with the user object, you can then update it with new information for the user profile
and then use the method UpdateAsync to update the user information in the database.
when it comes to getting a list of users you can use the IdentityDbContext class to get the list of users from.

A: Create a dbcontext object "context" and you also need to create a model class "UserEdit" and include those fields in it which you wants to edit.
private ApplicationDbContext context = new ApplicationDbContext();
// To view the List of User
 public ActionResult ListUsers ()
        {
            return View(context.Users.ToList());
        }

public ActionResult EditUser(string email)
        {
            ApplicationUser appUser = new ApplicationUser();
            appUser = UserManager.FindByEmail(email);
            UserEdit user = new UserEdit();
            user.Address = appUser.Address;
            user.FirstName = appUser.FirstName;
            user.LastName = appUser.LastName;
            user.EmailConfirmed = appUser.EmailConfirmed;
            user.Mobile = appUser.Mobile;
            user.City = appUser.City;

            return View(user);
        }

    [HttpPost]
    public async Task<ActionResult> EditUser(UserEdit model)
    {

        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
        var manager = new UserManager<ApplicationUser>(store);
        var currentUser = manager.FindByEmail(model.Email);
        currentUser.FirstName = model.FirstName;
        currentUser.LastName = model.LastName;
        currentUser.Mobile = model.Mobile;
        currentUser.Address = model.Address;
        currentUser.City = model.City;
        currentUser.EmailConfirmed = model.EmailConfirmed;
        await manager.UpdateAsync(currentUser);
        var ctx = store.Context;
        ctx.SaveChanges();
        TempData["msg"] = "Profile Changes Saved !";
        return RedirectToAction("ListUser");
    }

// for deleting a user
public ActionResult DeleteUser(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = context.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(context.Users.Find(id));
        }

        public async Task<ActionResult> UserDeleteConfirmed(string id)
        {
            var user = await UserManager.FindByIdAsync(id);

            var result = await UserManager.DeleteAsync(user);
            if (result.Succeeded)
            {
                TempData["UserDeleted"] = "User Successfully Deleted";
                return RedirectToAction("ManageEditors");
            }
            else
            {
                TempData["UserDeleted"] = "Error Deleting User";
                return RedirectToAction("ManageEditors");
            }
        }

Below is the View for ListUser:

@model IEnumerable<SampleApp.Models.ApplicationUser>

@{
    ViewBag.Title = "ListUsers";
}

@ViewBag.Message

ManageEditors

                        S.No.

                        Email

                     EmailConfirmed

                       FirstName

                       LastName

                        Mobile

                @{ int sno = 1;
                   foreach (var item in Model)
                {

                         @(sno++)

                            @Html.DisplayFor(modelItem => item.Email)

                            @Html.DisplayFor(modelItem => item.EmailConfirmed)

                            @Html.DisplayFor(modelItem => item.FirstName)

                            @Html.DisplayFor(modelItem => item.LastName)

                            @Html.DisplayFor(modelItem => item.Mobile)

                            @Html.ActionLink("Edit", "EditUser", new { email=item.Email})
                            @Html.ActionLink("Delete", "DeleteUser", new { id = item.Id })

                }
}

// below is my UserEdit Model
 public class UserEdit
    {
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Display(Name = "Mobile")]
        public string Mobile { get; set; }

        [Display(Name = "Address")]
        public string Address { get; set; }

        [Display(Name = "City")]
        public string City { get; set; }

        public bool EmailConfirmed { get; set; }
    }

//below is my IdentityModel.cs class which have ApplicationDbContext class
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace SampleApp.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
        //Extra column added to auto generated Table by Code First approach (ASPNETUSERS) by Entity Framework
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string DOB { get; set; }
        public string Sex { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Mobile { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}

Hope this help you :)


Q: ASP.NET C# OData Service + Navigation Property + $expand = null. What am I missing? I will try to explain my problem as thoroughly as possible with a simplified example. Please note that I am NOT using Entity Framework.
I have this model:
public class Person
{
    [Key]
    public Guid Id { get; set; }
    public string GivenName { get; set; }
    public string FamilyName { get; set; }
    public List<Employment> Employments { get; set; }
}

public class Employment
{
    public string Role { get; set; }
    public Guid? ManagerId { get; set; }
    public virtual Person Manager { get; set; }
}

I create an in-memory data source:
public class MyDataSource
{
    private static MyDataSource instance = null;
    public static MyDataSource Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new MyDataSource();
            }
            return instance;
        }
    }
    public List<Person> Persons  { get; set; }
    private MyDataSource()
    {
        this.Persons = new List<Person>();
        this.Persons.AddRange(new List<Person>
        {
            new Person()
            {
                Id = Guid.Parse("00000000-0000-0000-0000-000000000001"), //Just for simplicity
                GivenName = "John",
                FamilyName = "Doe",
                Employments = new List<Employment>()
                {
                    new Employment()
                    {
                        Role = "Boss"
                    }
                }
            },
            new Person()
            {
                Id = Guid.Parse("00000000-0000-0000-0000-000000000002"), //Just for simplicity
                GivenName = "Clark",
                FamilyName = "Kent",
                Employments = new List<Employment>()
                {
                    new Employment()
                    {
                        Role = "Worker",
                        ManagerId = Guid.Parse("00000000-0000-0000-0000-000000000001"), //Just for simplicity
                    }
                }
            }
        });
    }
}

I have this controller:
[EnableQuery]
public class PersonsController : ODataController
{
    public IHttpActionResult Get()
    {
        return Ok(MyDataSource.Instance.Persons)
    }
}

I configure the EndPoint:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapODataServiceRoute("ODataRoute", "odata", CreateEdmModel());
        config.Select().Expand().Filter().OrderBy().MaxTop(null).Count()
    }

    public static IEdmModel CreateEdmModel()
    {
        var builder = new ODataConventionModelBuilder();
        var persons = builder.EntitySet<Person>("Persons");
        builder.ComplexType<Employment>().HasOptional(e => e.Manager, (e, p) => e.ManagerId == p.Id);
        return builder.GetEdmModel();
    }
}

Checking the $metadata I see this:
<NavigationProperty Name="Manager" Type = "MyNamespace.Person">
    <ReferentialConstraint Property="ManagerId" ReferenceProperty="Id" />
</NavigationProperty

Everything looks fine from what I can tell but:
https://example.com/odata/persons?$expand=Employments/Manager
receives everything fine but:
Manager is null for both persons. I was expecting to see John Doe on Clark Kents employment.
What am I missing?

A: I have solved it myself.
I realised that it doesn't work like I thought and that I have to add a reference to the manager directly in MyDataSource. After that it works to $expand the manager.


Q: HH:MM:SS:Msec to HH:MM:SS in stored procedure I have a stored procedure which update a table based on such calculation and the calculation is done as column name (Calendatedate) - (Current System Date Time) and update this information to a column (TimeSpent) and display the value in  Hh:Mm:SS:Msec format.
The query is working fine but I want to update it in such a way so that the time spent should be only HH:MM:SS format. Please help me that how I remove that Msec from the time spent.
CREATE procedure St_Proc_UpdateTimeSpent
@timeEntryID int,
@status int output
as begin
set nocount on;
declare @Date dateTime;
set @Date=GETDATE();
    update Production set TimeSpent=(SELECT CONVERT(VARCHAR(20),DateAdd(SS,Datediff(ss,CalendarDate, @Date)%(60*60*24),0),114)),
    IsTaskCompleted=1
    where productionTimeEntryID=@timeEntryID
    set @status=1;
    return @status;
end

A: You can just use style 108 instead of 114 in the CONVERT function to get only the hh:mm:ss:
CREATE PROCEDURE dbo.St_Proc_UpdateTimeSpent
     @timeEntryID int,
     @status int output
AS BEGIN
   SET NOCOUNT ON;

   DECLARE @Date DATETIME;
   SET @Date = GETDATE();

   UPDATE dbo.Production
   SET TimeSpent = CONVERT(VARCHAR(20), DATEADD(SS, DATEDIFF(ss, CalendarDate, @Date)%(60*60*24),0), 108),
       IsTaskCompleted = 1
   WHERE
       productionTimeEntryID = @timeEntryID

   SET @status = 1;

   RETURN @status;
END

See the excellent MSDN documentation on CAST and CONVERT for a comprehensive list of all supported styles when converting DATETIME to VARCHAR (and back)
BTW: SQL Server 2008 also introduced a TIME datatype which would probably be a better fit than a VARCHAR to store your TimeSpent values ... check it out!


Q: Add(3)(5) nn.Sequential. How it works? class Add(nn.Module):
    def __init__(self, value):
        super().__init__()
        self.value = value

    def forward(self, x):
        return x + self.value

calculator = nn.Sequential(
    Add(3),
    Add(2),
    Add(5),
)

x = torch.tensor([1])
output = calculator(x)
print(output) # tensor([11])

I made Add Model. but I can't understand how 'nn.Sequential' works.
at the firsttime, I understood like this
add = Add(torch.tensor([1]))
add(3) # tensor([4])
add = Add(add(3))
add(2) # tensor([6])
add = Add(add(2))
add(5) # tensor([11])

but Add(3)(1) also works.
I can't understand why 'Add(3)(1)' works. help me plz

A: The core thing to remember is that when you instantiate a Module class, you are creating a callable object, i.e. something that can behave like a function.
In plain English and step by step:

*

*When you write something like add5 = Add(5), what you are doing is assigning an "instance" of the PyTorch model Add to add5

*More specifically, you are passing 5 to the Add class's __init__ method, and so its value attribute is set to 5.

*PyTorch Modules are "callable" meaning you can call them like functions. The function you call when you use an instance of a Module is that instance's forward method. So concretely, with our add5 object, if we pass a value, x = 10, by writing something like add5(10) it is like we ran x + add5.value, which equals 10 + 5 = 15.

Now putting this together, we should view the Sequential interface for building neural network models that don't have branching structures as just sequentially invoking each of the instantiated Modules' forward methods.
Omitting the definition of Add and focussing just on calculator as a series of computations we have the following (I've added the comments to show you what you should think of at each step)
calculator = nn.Sequential(
            # given some input tensor x...
    Add(3), # run: x = x + self.value with self.value = 3
    Add(2), # run: x = x + self.value with self.value = 2
    Add(5), # run: x = x + self.value with self.value = 5
)

Now we can see that it's reasonable to expect that if we pass the value 1 (albeit wrapped up as a PyTorch Tensor) we are just doing 1 + 3 + 2 + 5 which of course equals 11. PyTorch returns us back the value still as a Tensor object.
x = torch.tensor([1])
output = calculator(x)
print(output) # tensor([11])

Finally, Add(3)(5)* works for exactly this same reason! With Add(3) we are getting an instance of the Add class with the value to add being 3. We then use it immediately with the somewhat unintuitive syntax Add(3)(5) to return the value 3 + 5 = 8.
*I think you intended the capitalised class name, not an instance of the class

A: You understand it right, the Sequential class in a nutshell just calls provided modules one by one. Here's the code of the forward method
    def forward(self, input):
        for module in self:
            input = module(input)
        return input

here, for module in self just iterates through the modules provided in a constructor (Sequential.__iter__ method in charge of it).
Sequential module calls this method when you call it using () syntax.
calculator = nn.Sequential(
    Add(3),
    Add(2),
    Add(5),
)
output = calculator(torch.tensor([1]))

But how does it work? In python, you could make objects of a class callable, if you add __call__ method to the class definition. If the class does not contain this method explicitly, it means that it possibly was inherited from a superclass. In case of Add and Sequential, it's Module class that implements __call__ method. And __call__ method calls 'public' forward method defined by a user.
It could be confusing that python uses the same syntax for the object instantiation and function or method call. To make a difference visible to the reader, python uses naming conventions. Classes should be named in a CamelCase with a first capital letter, and objects in a snake_case (it's not obligatory, but it's the rule that better to follow).
Just like in you example, Add is a class and add is a callable object of this class:
add = Add(torch.tensor([1]))

So, you can call add just like you have called a calculator in you example.
>>> add = Add(torch.tensor([1]))
>>> add(2)
Out: tensor([3])

But that won't work:
>>> add = Add(torch.tensor([1]))
>>> add(2)(1)
Out:
----> 3 add(2)(1)
TypeError: 'Tensor' object is not callable

That means that add(2) returns a Tensor object that does not implement __call__ method.
Compare this code with
>>> Add(torch.tensor([1]))(2)
Out:
tensor([3])

This code is the same as the first example, but rearranged a little bit.
--
To avoid confusion, I usually name objects differently: like add_obj = Add(1). It helps me to highlight a difference.
If you are not sure what you're working with, use functions type and isinstance. They would help to find out what's going on.
For example, if you check the add object, you could see that it's a callable object (i.e., it implements __call__)
>>> from typing import Callable
>>> isinstance(add, Callable)
True

And for a tensor:
>>> from typing import Callable
>>> isinstance(add, torch.tensor(1))
False

Hence, it will rase TypeError: 'Tensor' object is not callable in case you call it.
If you'd like to understand how python double-under methods like init or call work, you could read this page that describes python data model
(It could be a bit tedious, so you could prefer to read something like Fluent Python or other book)


Q: DialogFragment return onClick result to MainActivity This has been asked and answered at least a dozen times yet I still can't get mine going. I've tried 4 or more of the listed answers and get no errors, a result simply isn't returned. here's the most recent code that I've tried. I really wanted this solution to work because it was the most readable to me.
I welcome any suggestions, Thanks.
MainActivity
...
private void showAlertDialog() {
    FragmentManager fm = getSupportFragmentManager();
    MyAlertDialogFragment alertDialog =
    MyAlertDialogFragment.newInstance("Some title");
    alertDialog.setTargetFragment(alertDialog, 1);
    alertDialog.show(fm, "fragment_alert");
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intentdata)
{
    // Stuff to do, dependent on requestCode and resultCode
    if(requestCode == 1)  // 1 is an arbitrary number, can be any int
    {
        // This is the return result of your DialogFragment
        if(resultCode == 1) // 1 is an arbitrary number, can be any int
        {
            Toast.makeText(MainActivity.this, "result received",
            Toast.LENGTH_SHORT).show();
            Log.d("onActivityResult", "result received" + resultCode);
        }
    }
}

MyDialogFragment
...
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;

...

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String title = getArguments().getString("title");
    AlertDialog.Builder alertDialogBuilder = new
    AlertDialog.Builder(getActivity());
    alertDialogBuilder.setTitle(title);
    alertDialogBuilder.setMessage("Are you sure?");
    alertDialogBuilder.setPositiveButton("OK",  new
    DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // on success
        }
    });
    alertDialogBuilder.setNegativeButton("Cancel", new
    DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            getTargetFragment().onActivityResult(getTargetRequestCode(),
            1, getActivity().getIntent());
            dialog.dismiss();
        }
    });

    return alertDialogBuilder.create();
}

A: I found it, added a onDialogOKPressed method to my MainActivity and put this inside the onClick of my dialog ((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed();
so now it looks like this
MyDialogFragment
...
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String title = getArguments().getString("title");
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    alertDialogBuilder.setTitle(title);
    alertDialogBuilder.setMessage("Are you sure?");
    alertDialogBuilder.setPositiveButton("OK",  new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // on success
            ((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed();
        }
    });
    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            getTargetFragment().onActivityResult(getTargetRequestCode(), 1, getActivity().getIntent());
            dialog.dismiss();
        }
    });

    return alertDialogBuilder.create();
}

MainActivity
...
public void onDialogOKPressed () {
    // Stuff to do, dependent on requestCode and resultCode
    Toast.makeText(MainActivity.this, "OK pressed", Toast.LENGTH_SHORT).show();
}


Q: Bitbucket call webhook php code not executing git command and when I execute from command prompt same command runs perfectly When I commit my code form source tree bitbucket triggers a webhook that hit php code
exec('cd /d ' . $web_root_dir . ' && '. $git_bin_path  . ' pull origin master');

it won't execute but when I copy the same command by copying from the log on command prompt it execute perfectly.
I've tried my heart out on this but no result.


Q: Android, Java, Eclipse: Syntax Error on token "if", ( expected after this token Why do i get the following Syntax error ?
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences pvtPref = getPreferences(MODE_PRIVATE);
    Boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
    if (isFirstLaunch == true) {   // <<<< Syntax Error ?
    // Do Something
    }
}

Error:
Multiple Markers at this line
-Syntax error on token "if", ( expected after this token
-Line breakpoint:LaunchEngine[line:30] - onCreate(Bundle)

A: Try it like this:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences pvtPref = getPreferences(MODE_PRIVATE);
    boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
    if (isFirstLaunch) {   // <<<< Syntax Error ?
    // Do Something
    }
}

A: Try this...

*

*First see that you have declared isFirstLaunch as boolean, if you have it should work.

*No need to use isFirstLaunch == true
if(isFirstLaunch)

A: You are getting a Boolean instead of a boolean. So you should use either :
Boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch.booleanValue()) {
}

or :
boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch) {
}

And try to click on the error icon on the left, and choose "Clear all lint marker" (if it's there).


Q: Firefox and IE6 issue with document.ready() I have created an html page with a Tabber tab functionality.

*

*Each tab has its own table that loads when the tab is clicked and only loads once on the initial tab click to stop the tables loading more than once.

*Each tab table exists in its own .jsp html file and is loaded through javascript using the $("#tab1").load('tabqtable.jsp'); call.

I currently have a document.ready() within the individual tab html files to run when each tab loads. The scripts run and work perfectly in Chrome, but the document.ready() functions don't run in Firefox and IE6.
I can put an alert(); outside of the document.ready() function and it works, so I know the script tag is being run. I also tried moving all the javascript to the return function call in the .load() function so the javascript will run when the .load() runs successfully from the m/ain html page, but still ended up with the same result.
I am at a loss and would really appreciate some help on this issue if I could get it. The tables load perfectly, I just don't get any of the functionality I need in order to interact with the table. It's not the scripts I am running either, because they all work with the main html page. Thanks for any help in advance.

A: well it looks like you are already using a framework like jquery...use $(document).ready (assuming that's jquery you are using...) the point of frameworks like jquery is that it (in principle) should be crossbrowser compatible.


Q: How to increase the base address of this string? I'm trying to get a pointer to the fourth element of this array, but I keep getting type mismatch errors when doing so. What am I doing wrong? How do I fix this?
    int main()
    {
        char str[]="0111010";
        str = str+3;
        printf("%s",str);
        return 0;
    }

A: The line
str = str + 3;

isn't legal C code. In C, you can't assign one array variable to another. (There's no fundamental reason why the language couldn't have made this work; it's just not supported.)
That being said, the expression str + 3 is a perfectly legal expression that results in a pointer to the third (zero-indexed) element of the array. You could either print it by writing
printf("%s\n", str + 3);

or by writing
char* midPtr = str + 3;
printf("%s\n", midPtr);

Either approach works. That first one is probably easier if you just need to do this once, and the second one is a bit easier if you plan on using that pointer more than once.