text:
Q: how to Direct fetch of the record after registration by Ajax I want to fetch the records by Ajax immediately after each record is set by Ajax and show it by the table.
I was able to save the records in the database with Ajax, but after registering the records with Ajax, I want to call them as a list with Ajax without refreshing the page.
I want to fetch the records by Ajax immediately after each record is set by Ajax and show it by the table.
I was able to save the records in the database with Ajax, but after registering the records with Ajax, I want to call them as a list with Ajax without refreshing the page.

 [HttpPost]
public IActionResult UpdateSubmitProjectStap2(Project project)
{
    var pro = _context.Projects.Find(TempData["ProID"]);
    pro.KhdamatHesabrsee = project.KhdamatHesabrsee;
    pro.SabteProjectDate = DateTime.Now;
    pro.MablghGhrardad = project.MablghGhrardad;
    pro.ShoroeeProjectDate = project.ShoroeeProjectDate;
    pro.PayanProjectDate = project.PayanProjectDate;
    pro.MashmolArzeshAfzoode = project.MashmolArzeshAfzoode;

    _context.SaveChanges();

    return Json(new { status = "ok" });

}

                <form >

                                نوع خدمات
                                مبلغ قرارداد
                                تاریخ شروع
                                تاریخ پایان
                                مشمول ارزش افزوده
                                عملیات

      <select class="form-control" asp-for="KhdamatHesabrsee"  required autocomplete="off">

                                    <option value="" default="" selected="">انتخاب کنید</option>
                                    <option value="1">حسابرسی</option>
                                    <option value="2">مالیاتی</option>
                                    <option value="3">منابع انسانی</option>

                                </select>

   <input class="form-control"  asp-for="MablghGhrardad" autocomplete="off" />

                                    <input id="bgainDate" type="text" autocomplete="off" class="form-control" asp-for="ShoroeeProjectDate" />

                                    <input  id="EndDate" type="text" autocomplete="off" class="form-control" asp-for="PayanProjectDate" />

 <input type="checkbox" style="width: 1.25rem; height: 1.25rem; top: .8rem; " class="flat-red" value="1" asp-for="MashmolArzeshAfzoode">

4

                                <button id="btn-send" class="btn btn-sm btn-outline-success" >  ذخیره </button>

                </form>

$("#btn-send").on('click', function () {

$.ajax({
    type: "Post",
    url: '@Url.Action("UpdateSubmitProjectStap2", "Project")',
    data: {
        'KhdamatHesabrsee': $("#KhdamatHesabrsee").val(),
        'MablghGhrardad': $("#MablghGhrardad").val(),
        'ShoroeeProjectDate': $("#ShoroeeProjectDate").val(),
        'PayanProjectDate': $("#PayanProjectDate").val(),
        'MashmolArzeshAfzoode': $("#MashmolArzeshAfzoode").val(),

    }
}).done(function (res) {
    if (res.status == 'ok') {
        $("#ohsnap").removeClass('hidden').removeClass('alert-danger').addClass('alert-success').html('گام دوم با موفقیت ثبت شد');
    }
    else if (res.status == 'error') {
         $("#divmsg").removeClass('hidden').addClass('alert-danger').html('در ثبت اطلاعات خطایی رخ داده است');
    }
});

});

A: If you want to display the list in current page, you can follow the steps below:
Model:
public class Project
{
    public int Id { get; set; }
    public string KhdamatHesabrsee { get; set; }
    public DateTime SabteProjectDate { get; set; }
    public DateTime ShoroeeProjectDate { get; set; }
    public DateTime PayanProjectDate { get; set; }
    public string MablghGhrardad { get; set; }
    public bool MashmolArzeshAfzoode { get; set; }
}

View:
@model Project
<form>

            //...

                    <input id="bgainDate" type="text" autocomplete="off" class="form-control" asp-for="ShoroeeProjectDate" />

                    <input id="EndDate" type="text" autocomplete="off" class="form-control" asp-for="PayanProjectDate" />

                <input type="checkbox" style="width: 1.25rem; height: 1.25rem; top: .8rem; " class="flat-red" asp-for="MashmolArzeshAfzoode">

                <button type="button" id="btn-send" class="btn btn-sm btn-outline-success">  ذخیره </button>

</form>

JS:
@section Scripts
{

}

Partial view(_ProjectList.cshtml):
@model List<Project>

            @Html.DisplayNameFor(model=>model[0].KhdamatHesabrsee)
            @Html.DisplayNameFor(model=>model[0].MablghGhrardad)
            @Html.DisplayNameFor(model=>model[0].MashmolArzeshAfzoode)
            @Html.DisplayNameFor(model=>model[0].PayanProjectDate)
            @Html.DisplayNameFor(model=>model[0].SabteProjectDate)
            @Html.DisplayNameFor(model=>model[0].ShoroeeProjectDate)

        @foreach (var item in Model)
        {

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

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

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

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

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

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

        }

Controller:
[HttpPost]
public IActionResult UpdateSubmitProjectStap2(Project project)
{
    try
    {
        var pro = _context.Projects.Find(TempData["ProID"]);
        pro.KhdamatHesabrsee = project.KhdamatHesabrsee;
        pro.SabteProjectDate = DateTime.Now;
        pro.MablghGhrardad = project.MablghGhrardad;
        pro.ShoroeeProjectDate = project.ShoroeeProjectDate;
        pro.PayanProjectDate = project.PayanProjectDate;
        pro.MashmolArzeshAfzoode = project.MashmolArzeshAfzoode;
        _context.Update(pro);   // be sure add update or insert operation...
        _context.SaveChanges();
    }
    catch (Exception)
    {
        throw;
    }
    return PartialView("_ProjectList",_context.Projects.ToList());
}

Update:
If you want to display the data in another page, you can use  window.location in frontend.
View:
@model Project
<form>

            //...
            <input class="form-control" value="dsf" disabled asp-for="MablghGhrardad" autocomplete="off" />

                    <input id="bgainDate" type="text" autocomplete="off" class="form-control" asp-for="ShoroeeProjectDate" />

                    <input id="EndDate" type="text" autocomplete="off" class="form-control" asp-for="PayanProjectDate" />

                <input type="checkbox" style="width: 1.25rem; height: 1.25rem; top: .8rem; " class="flat-red" asp-for="MashmolArzeshAfzoode">

            4

                <button type="button" id="btn-send" class="btn btn-sm btn-outline-success">  ذخیره </button>

</form>

JS:
@section Scripts
{

}

Another View named Test.cshtml(the same with _ProjectList.cshtml):
@model List<Project>

            @Html.DisplayNameFor(model=>model[0].KhdamatHesabrsee)
            //...
            @Html.DisplayNameFor(model=>model[0].SabteProjectDate)
            @Html.DisplayNameFor(model=>model[0].ShoroeeProjectDate)

        @foreach (var item in Model)
        {

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

                //...

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

        }

Controller(must contain an action called Test):
[HttpPost]
public IActionResult UpdateSubmitProjectStap2(Project project)
{
    try
    {
        var pro = _context.Projects.FirstOrDefault();
        pro.KhdamatHesabrsee = project.KhdamatHesabrsee;
        pro.SabteProjectDate = DateTime.Now;
        pro.MablghGhrardad = project.MablghGhrardad;
        pro.ShoroeeProjectDate = project.ShoroeeProjectDate;
        pro.PayanProjectDate = project.PayanProjectDate;
        pro.MashmolArzeshAfzoode = project.MashmolArzeshAfzoode;
        _context.Update(pro);
        _context.SaveChanges();
    }
    catch (Exception)
    {
        throw;
    }
    return Ok();

}
public IActionResult Test()
{
    return View(_context.Projects.ToList());
}


text:
Q: threes shader won't compile- various errors So I am trying to load an image.  Originally it is out of S3/Cloudfront but im discovering that its not even working locally.
    var imageTexture = new THREE.TextureLoader();
    imageTexture.load('/mypicture.jpg');

    imageTexture.minFilter = THREE.LinearFilter;

    var img = new THREE.MeshBasicMaterial({
             map:imageTexture
    });
    img.map.needsUpdate = true;

This is the error I am getting.
three.js:18053 THREE.WebGLProgram: shader error:  0 gl.VALIDATE_STATUS false gl.getProgramInfoLog invalid shaders
ERROR: 0:269: 'mapTexelToLinear' : no matching overloaded function found
ERROR: 0:269: '=' : dimension mismatch
ERROR: 0:269: 'assign' : cannot convert from 'const mediump float' to 'highp 4-component vector of float'

When I use this
var imageTexture = THREE.ImageUtils.loadTexture('/mypicture');

It works but when I try and load in image on CloudFront I get CORS errors.
Any ideas?

A: You are sending the loader to the shader, not a texture.
The THREE.TextureLoader() load() function returns a texture.
Try something like this:
var loader = new THREE.TextureLoader();
var texture = loader.load('/mypicture.jpg');

texture.minFilter = THREE.LinearFilter;

var img = new THREE.MeshBasicMaterial({
         map:texture
});
img.map.needsUpdate = true;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show recent products first but "sold out last" in query I am using WooCommerce and would would like to show the "out of stock" products last in the query on the archive page. How can I do that?
Currently we are making the newest product show first with the following custom query:
add_action( 'pre_get_posts', 'mik_exclude_category' );
function mik_exclude_category( $query ) {
    if ( $query->is_main_query() ) {
        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'DESC' );
    }
}

So, we would like to do both. Show the newest products first, but show "out of stock" products last no matter how new they are.
Sincerely,
Mika

A: If we only have two stock statuses, namely outofstock and instock, we can very easily achieve sorting with pre_get_posts
add_action( 'pre_get_posts', function ( $q ) {
    if (   !is_admin()                 // Target only front end
         && $q->is_main_query()        // Only target the main query
         && $q->is_post_type_archive() // Change to suite your needs
    ) {
        $q->set( 'meta_key', '_stock_status' );
        $q->set( 'orderby',  'meta_value'    );
        $q->set( 'order',    'ASC'           );
    }
}, PHP_INT_MAX );

You should adjust that to your needs


text:
Q: Counts for distinct values in different tables where columns are common to separate tables I have no idea if that title conveys what I want it to.
I have two tables containing phone records (one for each account) and I'd like to get call counts for the numbers that are common to each account. In other words:
Table 1
Number  ...
8675309
8675309
8675310
8675310
8675312

Table 2
Number  ...
8675309
8675309
8675309
8675310
8675311

Querying with something like:
SELECT DISTINCT table1.number, COUNT(table1.number), COUNT(table2.number) FROM table1, table2 WHERE table1.number = table2.number GROUP BY table1.number

would hopefully produce:
8675309|2|3
8675310|2|1

Instead, it currently produces something like:
8675309|6|6
8675310|2|2

It appears to be multiplying the count from each table. Presumably, this is because I'm not joining the tables the way I should for this goal. Or because by the time I ask for COUNT(table1.number) the tables have already been joined in some multiplicative way. Should I not be doing a JOIN and instead something that would read like: "where table2.number CONTAINS(table1.number)"?
Any tips?

A: One way is to use a couple of derived tables to compute your counts separately and then join them to produce your final summary:
select t1.number, t1.count1, t2.count2
from (select number, count(number) as count1 from table1 group by number) as t1
join (select number, count(number) as count2 from table2 group by number) as t2
  on t1.number = t2.number

There are probably other ways but that should work and it is the first thing that came to mind.
You're getting your "multiplicative" effect pretty much for the reasons you suspect. If you have this:
table1(id,x)    table2(id,x)
------------    ------------
1, a            4, a
2, a            5, a
3, b            6, b

Then joining them on x will give you this:
1,a, 4,a
1,a, 5,a
2,a, 4,a
2,a, 5,a
...

Usually you could use a GROUP BY to sort out the duplicates but you can't do that because it would mess up your per-table counts.

A: Try this:
select tab1.number,tab1.num1,tab2.num2
from
(SELECT number, COUNT(number) as num1 from table1 group by number) as tab1
 left join
(SELECT number, COUNT(number) as num2 from table2 group by number) as tab2
on tab1.number = tab2.number

A: One way is with subqueries:
SELECT t1.number, t1.table1Count, t2.table2Count
 from (select number, count(*) table1Count
        from table1
        group by number) t1
  inner join (select number, count(*) table2Count
               from table2
               group by number) t2
   on t2.number = t1.number

This assumes that you only want to list numbers that appear in both tables. If you want to list all numbers that appear in one table and optionally the other, you'd use a left or right outer join; if you wanted all numbers that appeared in either or both tables, you'd use a full outer join.
Another and potentially more efficient way requires the presence of a single column that uniquely identifies each row in each table:
SELECT
   t1.number
  ,count(distinct t1.PrimaryKeyValue) table1Count
  ,count(distinct t2.PrimaryKeyValue) table2Count
 from table1 t1
  inner join table2 t2
   on t2.number = t1.number
 group by t1.number

This makes the same assumptions as before, and can also be adjusted modified via outer joins.


text:
Q: Logical operation of a k8s multi-entry selector This k8s service definition have multiple entries under selector section.
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-app
    tier: back-end
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376
Which operation does this selector follows, ( app == my-app && tier == back-end ) or ( app == my-app || tier == back-end )?

A: From the docs here

A label selector can be made of multiple requirements which are
  comma-separated. In the case of multiple requirements, all must be
  satisfied so the comma separator acts as a logical AND (&&) operator.
Caution: For both equality-based and set-based conditions there is no
  logical OR (||) operator. Ensure your filter statements are structured
  accordingly


text:
Q: Upload image from current HTML page I have an image on my HMTL page.  This is generated by DevExpress library at runtime and the src url points to a DevExpress script with a cache key:
<img id="Chart_89_IMG" src="/DXB.axd?DXCache=30f02093-de66-4ed6-8557-2382065c701a" />

I'm trying to get this file onto the server in a subsequent form post to use in an email.  I've tried just passing the url in my form, but by the time it gets to the server, I get a 404 (assuming the cache key is expired).
I've also tried using canvas to get the bytes and pass that to the server, but was having trouble converting that byte stream back to an image, and canvas won't work for IE8, which I need to support.
My last idea was to include a file upload input on my form and pass the image to the server that way.  But, how can I create a file from an image in javascript to use as an upload?
Any other ideas would be appreciated too!

A: Since this was DevExpress, I was able to change the BinaryStorageMode to the session:
settings.BinaryStorageMode = BinaryStorageMode.Session;

Then after I posted the form, the chart's bytes were accessible in the Session:
byte[] bytes = ((DevExpress.Web.ASPxClasses.BinaryStorageData)HttpContext.Current.Session[sessionKey]).Content;


text:
Q: EMGU 2.4.0 BruteForceMatcher KNNMATCH not working? Here is a snapshot of my code,
Matrix<byte> mask;
int k = 2;
VectorOfKeyPoint modelKeyPoints;
VectorOfKeyPoint observedKeyPoints;
SURFDetector surfCPU = new SURFDetector(500, false);
modelKeyPoints = surfCPU.DetectKeyPointsRaw(modelImage, null);
Matrix<float> modelDescriptors = surfCPU.ComputeDescriptorsRaw(modelImage, null, modelKeyPoints);
observedKeyPoints = surfCPU.DetectKeyPointsRaw(observedImage, null);
Matrix<float> observedDescriptors = surfCPU.ComputeDescriptorsRaw(observedImage, null, observedKeyPoints);
BruteForceMatcher<float> matcher = new BruteForceMatcher<float>(DistanceType.L2);
matcher.Add(modelDescriptors);
indices = new Matrix<int>(observedDescriptors.Rows, k);
using (Matrix<float> dist = new Matrix<float>(observedDescriptors.Rows, k))
{
      matcher.KnnMatch(observedDescriptors, indices, dist, k, null);
}

I always get the following exception at KnnMatch()
Emgu.CV.Util.CvException occurred
Message: OpenCV: queryDescriptors.type() == trainDescCollection[0].type()
I have tried so hard to get rid of this exception and no hope :(

A: I finally found the cause of this problem
it was one of  modelKeyPoints or observedKeyPoints null :)

A: Very similar to Zaher's answer - my modelKeyPoints was not null, but it was empty (modelKeyPoints.Size == 0).
Using a different model image helped.


text:
Q: Correctly parsing through nested JSON using data model for multiple reuse. Swift I'm trying to find the best solution to parse through nested JSON. I know there are plenty examples of ways to parse JSON but I've been told the best practice is to make a Class/Struct model for the data I wish to pull out.
Here is a sample JSON data:
{
  "description": "Birds of Antarctica, grouped by family",
  "source": "https://en.wikipedia.org/wiki/List_of_birds_of_Antarctica",
  "birds": [
    {
      "family": "Albatrosses",
      "members": [
        "Wandering albatross",
        "Grey-headed albatross",
        "Black-browed albatross",
        "Sooty albatross",
        "Light-mantled albatross"
      ]
    },
    {
      "family": "Terns",
      "members": [
        "Arctic tern",
        "Antarctic tern"
      ]
    }
  ]
}

This is my Birds class:
class Birds {

    let family: String?
    let members: String?

    init?(json: JSON) {

        guard let family = json["family"] as? String, let members = json["members"] as? String else { return nil }

        self.family = family
        self.members = members

    }
}

This is my DataService:
typealias JSON = [String: Any]

class DataService {

    private init() {}
    static let shared = DataService()

    func getData(completion: (Data) -> Void) {

        guard let path = Bundle.main.path(forResource: "bird_data", ofType: "json") else {return}

        let url = URL(fileURLWithPath: path)

        do {

            let data = try Data(contentsOf: url)
            completion(data)

        } catch {
            print(error.localizedDescription)

        }
    }

Finally this is how I call it in the viewController:
func getData() {
        DataService.shared.getData { (data) in
            do {
                guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? JSON else { return }

                print(json)
            } catch {
                print(error)
            }
        }
    }

So how would I get to print just the family and display it on a table for example.? Correct me if there is already a clear example for this.
I am aware there lots of third party to help like SwiftyJSON and Gloss but I'd like to understand it the standard way.

A: I think depending on the structure of your json, you need to form two model classes one for the whole json and one for the individual birds, so you can do something like this :
class Bird {

    let family: String?
    let members: [String]?

    init?(json: JSON) {

        guard let family = json["family"] as? String, let members = json["members"] as? [String] else { return nil }

        self.family = family
        self.members = members

    }
}

class JsonData {

    var birds: [Bird]?
    var description: String?
    var sourceUrl: String?

    init?(json: JSON) {

        guard let description = json["description"] as? String, let sourceUrl = json["source"] as? String, let birds = json["birds"] as? [JSON] else { return nil }

        self.description = description
        self.sourceUrl = sourceUrl
        self.birds = [Bird]()
        for singleBird in birds {
            let singleBirdObj = Bird(singleBird)
            self.birds?.append(singleBirdObj)
            //you can add birds to shared manager array like this (after discussion with OP)
            BirdManager.shared.appendBird(singleBirdObj)
        }

    }

}

func getData() {
        DataService.shared.getData { (data) in
            do {
                guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? JSON else { return }

                let jsonDataObject = JsonData(json)
                //here you have jsonDataObject that has all the json data

                print(print(jsonDataObject?.description))
            } catch {
                print(error)
            }
        }
    }

A: If you're using Swift 4, you can use Codable protocol like this:
struct Bird: Codable {
    let family: String
    let members: [String]
}

struct Root: Codable {
    let description: String
    let source: URL
    let birds: [Bird]
}

You can try it in Swift Playground like this:
let jsonData = """
{
  "description": "Birds of Antarctica, grouped by family",
  "source": "https://en.wikipedia.org/wiki/List_of_birds_of_Antarctica",
  "birds": [
    {
      "family": "Albatrosses",
      "members": [
        "Wandering albatross",
        "Grey-headed albatross",
        "Black-browed albatross",
        "Sooty albatross",
        "Light-mantled albatross"
      ]
    },
    {
      "family": "Terns",
      "members": [
        "Arctic tern",
        "Antarctic tern"
      ]
    }
  ]
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let parsedObject = try decoder.decode(Root.self, from: jsonData)

You can read more info (e.g. custom keys, custom date parsing, etc) about Swift 4 Codable protocol here: http://benscheirman.com/2017/06/ultimate-guide-to-json-parsing-with-swift-4/


text:
Q: Can I dim the top bar? The color changes to the top bar now make it SCREAM AT THE USER .. as if it contained neon icons. All the icons are an eye magnet with the dark background.
It's not so bad on Stack Exchange sites where the page background is white (like here at meta or any beta site) or when there's a color bar below it (also like here at meta) or when its dark on light such as Stack Overflow.
Is there any way to tone down the white?
It's kind of hard to express how distracting they are on the main Stack Exchange site I visit. It's seriously just a constant pull on the eyes, as if someone is shining a flashlight at your eye and as much as you try and just accept it and ignore it... you can't help but notice it constantly.
I'd accept that perhaps this is a design failure at Graphic Design which does not have the color bar below the top bar or a white page background. So the grey page background against the top bar just makes the icons SCREAM louder.

A: We've updated the topbar item color on the forced dark topbar (as seen on non-Stack Overflow sites) to be a tad dimmer. The previous color was taken from the old topbar styles' font color and applied across all items, including icons. This turned out to be a tad too high contrast for most people, so we've reduced the color to somewhere in between the new and old styles.
A visual comparison of the old vs new vs newer colors (on the current topbar component) and their WCAG contrast ratings:

A: This is only a temporary workaround until they hopefully revert the change. Just use Greasemonkey / Violentmonkey or any other custom CSS tool you may have.
Luckily, CSS offers a brightness filter that just seems made for issues like this one...
// ==UserScript==
// @name     Save My Eyes
// @include     https://*.stackexchange.com/*
// @include     https://*.superuser.com/*
// @include     https://*.serverfault.com/*
// @include     https://*.stackapps.com/*
// @include     https://*.mathoverflow.net/*
// @include     https://*.askubuntu.com/*
// @grant    GM_addStyle
// @run-at   document-start
// ==/UserScript==

GM_addStyle ( `
   .s-topbar .s-topbar--content .s-topbar--item  > .svg-icon
   {
      filter: brightness(75%) !important;
   }
` );

Using a brightness 75% setting seems quite acceptable:

Note, the > .svg-icon was added to the CSS selector in order to prevent the avatar from being dimmed too. If you copied the script before the update, please upgrade to the last version above.

A: Thankfully.. the icons appear to have been ever-so-slightly tweaked in color overnight.
The change is so slight that it almost goes unnoticed.. but, the "neon" aspect of the icons has been diminished considerably.

Thank you to whoever is responsible! This is much better.


text:
Q: Cross Domain Error with self built API The server sending JSON to the API is a Tomcat server in the Gradle packages (it is built in Java).
I am having trouble's making an API call with Angular.  I know my API is working because I can view it on "Postman."
 var app = angular.module("todo", []);
 app.controller("AppCtrl", function($http){

 $http.get("192.168.5.100:8080/aggregators/datafile")
    .success(function(data){
        console.log(data)
    })

})

When I run it I get the following error:
XMLHttpRequest cannot load %3192.168.5.100:8080/aggregators/datafile. Cross origin requests are only supported for HTTP.

A: The problem you're running into is that you can't make cross origin requests from the browser without CORS or using JSONP.
Postman operates outside of the context of the browser (as if you had issued a cURL request, if you're familiar with cURL).
This is for security reasons.
So, how do you implement JSONP?  It really depends on the server, but in general, your resource would look for a GET request that had a pre-determined querystring parameter (normally callback for simplicity):
http://192.168.5.100:8080/aggregators/datafile?callback=mycallback

How do you make a JSONP call?
The server wraps the JSON in that callback, causing it to look something like the following:
mycallback({json:object});

This Stack Overflow answer goes into more detail.
The callback is the function the browser should hit when the request is executed, and that's what allows for cross-domain requests.
Now, on to CORS.
CORS is a system for allowing the browser to communicate with the server to determine whether or not it should accept a cross domain request.  It's a bit complicated, but in general it involves settings up certain Headers on your API Server; and then executing an Ajax request in a particular fashion (for JQuery, use the withCredentials property for $.ajax).  The server checks where the request is from, and if it's a valid source, it let's the browser know and the browser allows the request (I'm being simplistic).
MDN has a thorough explanation of CORS that is worth reading.


text:
Q: How to change class member value in vector #include <iostream>
#include <string>

using namespace std;

class Owner{
    protected:
        string ownerName;
        int balance;
        int numPetsCheckin;
        string pet[100];

    public:
        Owner();
        Owner(const string& ownerName, int balance);
        string getOwnerName(){return ownerName;}
        int getBalance(){return balance;}
        int getNumPetsCheckin(){return numPetsCheckin;}

        void pushListPet(string a){
            pet[numPetsCheckin] = a;
            numPetsCheckin++;
            //cout << numPetsCheckin;
        }
        void showOwners(){
            cout << "Owners { name: " << ownerName << ", balance: " << balance << ", numPetsCheckin: " << numPetsCheckin << "}\n";
        }

};

Owner:: Owner()
    : ownerName("No name"), balance(0), numPetsCheckin(0){}
Owner:: Owner(const string& theName, int theBalance)
    : ownerName(theName), balance(theBalance), numPetsCheckin(0){}

int main(){
    int people = 0;
    Owner owner[100];

    Owner A( "A", 10);
    owner[people] = A;
    people++;

    Owner B("B", 20);
    owner[people] = B;
    people++;
    A.showOwners();
    A.pushListPet("momo");
    A.showOwners();

    cout << "owner[0].getOwnerName: " << owner[0].getOwnerName() << endl;
    cout << "owner[0].getNumPetsCheckin: " << owner[0].getNumPetsCheckin() << endl;
    cout << "A.getNumPetsCheckin: " << A.getNumPetsCheckin() << endl;
}

Owners { name: A, balance: 10, numPetsCheckin: 0}
Owners { name: A, balance: 10, numPetsCheckin: 1}
owner[0].getOwnerName: A
owner[0].getNumPetsCheckin: 0
A.getNumPetsCheckin: 1

Q: why owner[0].getNumPetsCheckin() and A.getNumPetsCheckin() are different?
I set A's numPetsCheckin plus 1 in A.pushListPet("momo"){(numPetsCheckin++;)}, but owner[0].getNumPetsCheckin() still 0...
A and owner[0] are different?
Q: How can solve it?????????????????

A: As people have explained in the comments, the bytes representing A and owner[0] were different.  One can store pointers to point to the same memory, but often the intent is simply to store in some contiguous memory and access specific points in it.
Consider making A and B the references (which the compiler may implement as pointers in some cases) rather than making an array of pointers.
Owner& A = owner[people];
A = Owner("A",10);
people++;
...

A: Q: why owner[0].getNumPetsCheckin() and A.getNumPetsCheckin() are different?

They are different objects, after the satement owner[people] = A;, the object  A is copied to owner[people]. You can verify it with print the address:
  std::cout << &owner[people] << ' ' << &A << std::endl;

Got output on my machine, they are different objects. So you change on object A doesn't affect owner[people]
0x7ffd10410f90 0x7ffd1040f530

Q: How can solve it?

Use a reference:
  auto& Aref = owner[0];
  Aref.showOwners();
  Aref.pushListPet("momo");
  Aref.showOwners();

Or directly modify the object owner[0]
  owner[0].showOwners();
  owner[0].pushListPet("momo");
  owner[0].showOwners();

Your code does not make good use of modern c++ as the comments mentioned, I just refine it with c++17 to make it more clear:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Owner {
 protected:
  // default value
  std::string ownerName = "No name";
  int balance = 0;
  // use vector instead of fixed sized array
  std::vector<std::string> pet;

 public:
  // the default construct is enough
  Owner() = default;
  Owner(const string &ownerName, int balance);
  string getOwnerName() { return ownerName; }
  int getBalance() { return balance; }
  // just return the size of vector
  int getNumPetsCheckin() { return pet.size(); }
  // move the temporary argument
  void pushListPet(string a) { pet.push_back(std::move(a)); }
  void showOwners() {
    cout << "Owners { name: " << ownerName << ", balance: " << balance
         << ", numPetsCheckin: " << getNumPetsCheckin() << "}\n";
  }
};

Owner::Owner(const string &theName, int theBalance)
    : ownerName(theName), balance(theBalance) {}

int main() {
  // use vector instead of fixed sized array
  std::vector<Owner> owner;
  // emplace back will construct a new object at the end of vector, and return
  // the reference
  auto &a = owner.emplace_back("A", 10);
  a.showOwners();
  a.pushListPet("momo");
  a.showOwners();

  // construct a new object at the end of vector, again
  owner.emplace_back("B", 20);

  cout << "owner[0].getOwnerName: " << owner[0].getOwnerName() << endl;
  cout << "owner[0].getNumPetsCheckin: " << owner[0].getNumPetsCheckin()
       << endl;
  // The reference object a is invalidated, since the vector have growed size,
  // now we can only reference it with only `owner[0]` or owner.front()
  cout << "A.getNumPetsCheckin: " << owner.front().getNumPetsCheckin() << endl;
}

Online demo


text:
Q: Unity - Stockfish API on Android run error I am trying to run the stockfish armv7 file (available here: https://stockfishchess.org/download/) on my Unity project using System.Diagnostics.Process.
However, I get the following error message (from adb logcat) when trying to start the process:
03-13 17:15:03.114 25020 27066 E Unity   : Win32Exception: ApplicationName='/storage/emulated/0/Android/data/com.DefaultCompany.MyChessGame/files/stockfish.android.armv7.so', CommandLine='', CurrentDirectory='', Native error= mono-io-layer-error (5)
03-13 17:15:03.114 25020 27066 E Unity   :   at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x002dc] in <3df7f9ca50404bbc8bd4e7b954e70293>:0
03-13 17:15:03.114 25020 27066 E Unity   :   at System.Diagnostics.Process.Start () [0x0003a] in <3df7f9ca50404bbc8bd4e7b954e70293>:0
03-13 17:15:03.114 25020 27066 E Unity   :   at (wrapper remoting-invoke-with-check) System.Diagnostics.Process.Start()
03-13 17:15:03.114 25020 27066 E Unity   :   at AI.Awake () [0x00076] in C:\Program Files (x86)\Unity Projects\My Chess Game\Assets\Game\Scripts\Players\AI.cs:62

My code for the Android build of the Unity project is as such:
        string fileName = Path.Combine(Application.persistentDataPath, "stockfish.android.armv7.so");

        if (!File.Exists(fileName))
        {
            string _path = Path.Combine(Application.streamingAssetsPath, "stockfish.android.armv7.so");
            UnityWebRequest request = UnityWebRequest.Get(_path);
            request.SendWebRequest();
            while (!request.isDone)
            {
                if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
                    return;
            }
            File.WriteAllBytes(fileName, request.downloadHandler.data);
        }
        Debug.Log(fileName);
        Debug.Log(File.Exists(fileName));

        p = new System.Diagnostics.Process();
        p.StartInfo.FileName = fileName;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.CreateNoWindow = true;
        p.Start();

The Debug.Log(File.Exists(fileName)) shows that the file exists. I'm not sure what mono-io-layer-error (5) is?
I would be grateful for any help.
Update
I've found this list of Win32 error codes:
https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d
From this, I believe the issue may be that access was denied. In which case, I will need to find out how to change the access of the file. Does anyone know how to do this on Unity?


text:
Q: Efficiently generate a sawtooth with rounded peaks. I'd like to have an efficient function that would generate a wave that is close to a sawtooth but has slightly rounded peaks. The wave needs to be continuous at all points.  I will be doing this in directx and opengl shaders so I have access to vector units and matrix multiplies.
EDIT: I can efficiently generate a sawtooth with the following line of code: (assuming t [0,1])
saturate(t*10.0) - t;

The problem with this is that the line isn't continuous.  I'm considering sampling 4 points on the line (2 before t and 2 after) and then doing a Catmul Rom spline, but I'd be interested in any suggestions for a better way to do the smoothing.

A: The following polynomial gives a single 'tooth' on domain $[-1, 1]$. The higher $n$, the sharper the peak.
$$
p\left(x\right)=x\left(1-x^{2n}\right)
$$
Repeat the function to extend the domain to $\mathbb{R}$:
$$
f\left(x\right)=p\left(\left(x\bmod 2\right)-1\right)
$$
A screenshot from Desmos:

Note: $f$ and $f'$ are continuous, but the second derivative is not continuous.
As for efficiency: $n$ is integer, so $x^{2n}$ can be calculated with a sequence of $\mathcal{O}(\log n)$ multiplications.

A: In case anyone needs a smooth sawtooth function that is infinitely differentiable ($C^{\infty}$):
there are various ways to construct such a function, typically by combining trigonometric functions.
One way is to start with a smooth square wave like:
$$
s\left(x\right)=\tanh\left(n\cos x\right)
$$
or:
$$
s\left(x\right)=\frac{2}{\pi}\arctan\left(n\cos x\right)
$$
(the higher $n$, the sharper the edges)
Let the square wave flip a triangle wave to produce a sawtooth:
$$
f\left(x\right)=\arcsin\left(s\left(x\right)\sin x\right)
$$
Screenshot from Desmos:

Obviously, this is likely to be more computationally expensive than the polynomial in my other answer.
But that one, being a piecewise function, offers only $C^{1}$ continuity.
Other suggestions can be found here: https://mathematica.stackexchange.com/q/38293


text:
Q: React delete item component via button deletes items in list after that item too Please help! Not sure what's wrong with my code below. I'm trying to only delete child component after the delete API call returns but somehow all items after the item to delete also get removed from list. Luckily the delete API call only gets hit once for the correct item.
`
import "./styles.css";
import {useEffect, useState} from "react";
export default function App() {
  return (
    <TopList />
  );
}

function TopList() {

  const [list, setList] = useState([
    {
      "id": "something1",
      "title": "something1"
    },
    {
      "id": "something2",
      "title": "something2"
    },
    {
      "id": "something3",
      "title": "something3"
    }
  ]);

  const onHandleDelete = (itemDelete) => {
    setList(list.filter(item => item !== itemDelete))
  }

  return

      {list.map(item => <ListItem item={item} onDelete={() => onHandleDelete(item)} />)}

}

function ListItem({item, onDelete}) {
  const [deleteClicked, setDeleteClicked] = useState(false)

  const onClickDelete = () => {
    !deleteClicked && setDeleteClicked(true);
    // Do delete API call
  }

  useEffect(() => {
    // Also check API call finished
    if(deleteClicked) {
      onDelete();
    }
  }, [deleteClicked, onDelete])

  return
{item.title} <button onClick={onClickDelete}>Delete</button>

}

`
Expecting only the item that had the delete button clicked should be removed from item list.
I've also tried adding a key (generated from item properties) to the components but that didn't seem to work either. Maybe I added in wrong places.

A: Add key={item.id} to your <ListItem in the map. And it is better to compare id than the whole object in your filter


text:
Q: GetList возвращает 1 элемент    <?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
    CModule::IncludeModule('iblock');
$arSelect = Array("ID", "IBLOCK_ID", "NAME", "PROPERTY_*");
$arFilter = Array('IBLOCK_ID' => 8);
$res = CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect);
while($ob = $res->GetNextElement()){
$arResult['PROP'] = $ob;
    }
    file_put_contents($_SERVER['DOCUMENT_ROOT'].'/log.txt',
    (print_r($arResult['PROP'],true)));
    ?>

ShowCount до цикла 24
в цикле счетчик 24 раза срабатывает.
В полученном массиве только первый элемент.

A: Метод GetNextElement возвращает объект. Далее из этого объекта можно получить поля и свойства из инфоблока с помощью методов GetFields и GetProperties. Также вы в каждой итерации цикла перетираете данные, т.е. в один и тот же ключ добавляете новые данные.
CModule::IncludeModule('iblock');
$arSelect = Array("ID", "IBLOCK_ID", "NAME", "PROPERTY_*");
$arFilter = Array('IBLOCK_ID' => 8);
$res = CIBlockElement::GetList(Array(), $arFilter, false, false, array());
while($ob = $res->GetNextElement()){ // получаем объект
    $arFields = $ob->GetFields();// получаем поля инфоблока итерации
    $arProp = $ob->GetProperties();// получаем свойства итерации
    // сохраняем данные в новый элемент массива []
    $arResult['PROP'][] = array(
        'FIELDS' => $arFields,
        'PROP' => $arProp,
    );
}
echo "
".print_r($arResult['PROP'], true)."
";

Если используете GetNextElement, то $arSelect не учитывается.
Такой вариант выборки очень не оптимальный, и если у вас много данных, выборка будет очень долгая. Лучший вариант – это сделать выборку через Fetch и указать только нужные поля и свойства в $arSelect к примеру:
CModule::IncludeModule('iblock');
$arSelect = Array("ID", "IBLOCK_ID", "NAME", "PROPERTY_TITLE", "PROPERTY_KEYWORDS"); // указываем все поля и свойства которые нам нужны PROPERTY_код свойства или id
$arFilter = Array('IBLOCK_ID' => 2);
$res = CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect);
while($ar = $res->Fetch()){ // получаем сразу массив данных а не объект
    $arResult['PROP'][] = $ar; // сохраняем все в переменную в новый массив
}
echo "
".print_r($arResult['PROP'], true)."
";

Подробнее можно почитать в документации


text:
Q: ms access get file name selected from FileDialog This is my code, and I want to know how to get name of file selected
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = True
If f.Show Then
    For i = 1 To f.SelectedItems.Count
        MsgBox f.SelectedItems(i)
    Next
EndIf

A: You mean like this?
Sub Sample()
    Dim f As Object

    Set f = Application.FileDialog(3)

    f.AllowMultiSelect = True

    If f.Show Then
        For i = 1 To f.SelectedItems.Count
            MsgBox Filename(f.SelectedItems(i))
        Next
    End If
End Sub

Public Function Filename(ByVal strPath As String) As String
    If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
        Filename = Filename(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
    End If
End Function


text:
Q: Match data through User ID and return 'TRUE' OR 'FALSE' I have 2 spreadsheets, 1 is the 'master data' sheet and the second is the 'verification' sheet (to check.
I want to match the data from the 'verification' sheet with 'the master data' sheet through User ID  to match DOB, Name, organization name, and user ID to return 'TRUE' or 'FALSE'.
The screenshot is attached for reference.
MasterSheet

Verification Sheet 2

Thank you in advance

A: Use INDEX/MATCH functions combination.
=INDEX($A$2:$E$4,MATCH($B9,$A$2:$A$4,0),MATCH(G$8,$A$1:$E$1,0))=INDEX($B$9:$E$11,MATCH($B9,$B$9:$B$11,0),MATCH(G$8,$B$8:$E$8,0))

A: You can try with this in F3. Change MasterSheet with the actual name of your sheet:
=MAKEARRAY(COUNTA(A3:A),3,LAMBDA(r,c,INDEX(B2:D,r,c)=INDEX(FILTER({MasterSheet!B2:B,MasterSheet!E2:E,MasterSheet!D2:D},MasterSheet!A2:A=INDEX(A3:A,r)),,c)))


text:
Q: What is < and [ in Regular Expression? I've got
var $pBracketVisualOpenRegExp = /[/ ;

and
var $pBracketFunctionOpenRegExp = /</ ;

in my Javascript.
but it doesent works with .match()
$MatchArray = $String.match(/</);

the other Brackets and Signs { ( " works fine.

A: /[/ is not a valid RegEx. See http://regex101.com/r/qO5hR4.
/</ should match < literally though. Try some regex playground when developing the expressions. Im much faster this way. Good places are http://regex101.com and http://lea.verou.me/regexplained/.

A: /[/ is not a valid RegEx. I tried your code for /</ and it works.
var $pBracketFunctionOpenRegExp = /</ ;

$String = 'aaa<lklkd';
$MatchArray = $String.match($pBracketFunctionOpenRegExp); //result ['<']

A: "\<" will match the empty string at the beginning of word.


text:
Q: Can the word 'quote' mean only one word? According to Google quote is '

repeat or copy out (a group of words from a text or speech), typically
  with an indication that one is not the original author or speaker'

can a single word qualify as a quote?
EDIT:
Besides: One word sentences like "yes","no","okay".
To put the question in perspective: The question came up when my co-worker and I were trying to use this website and we were arguing if it is necessary to provide more than one word.

A: Yes it's perfectly possible for a quote to be one word, and this is done frequently in reporting.

The leader called the attacks "disgusting".

In this sentence the word "disgusting" is a quote, and is the only thing the leader is actually stated to have said.
Even simple words can be a quote.

Asked if he was intending to run as a candidate, the politician said "Yes."

A single word quote can even stand on its own.

Rosebud! Citizen Kane


text:
Q: The company I work at has this thing we have to say every morning. What is it called? The company I work at (a US branch of a Japanese firm) has a thing we have to say every morning. We stand up and each take turns reading a line from the poster on the wall. It goes like this:

*

*We meet challenges with courage and creativity to realize our dreams.

*Once a decision is made we move quickly to carry out the plan with passion.

*As a good corporate citizen we do what is right and contribute to society.

*We seek to do our best, act professionally, and take responsibility for our actions.

... and so on (8 lines total).

What is this thing we read called?  "Every morning at work, we read a/an/the _____."

A: This sounds like a company motto.

2: a short expression of a guiding principle

Posters like that in the workplace have also been called "motivators," and parodies of them with cute pictures and sarcastic, nihilistic messages are "demotivators."

A: This can be called pledge.
From Merriam-Webster:

PLEDGE (noun):
a binding promise or agreement to do or forbear.
a token, sign, or earnest of something else

A: I would call this a company values statement.  (Or possibly a vision statement.)
I wouldn't call it a mission statement or manifesto, because it doesn't define what the company does; only how it does it.
Nor would I call it a credo or mantra, because it doesn't list things that employees believe, only things that they do.
It could be a company pledge, vow, oath, or similar (as per other answers) — but if so, I'd expect everyone to be saying every line, all together.
(And you wouldn't get UK employees to spout this rubbish every morning without a lot of sarcasm…!)

A: Another idea that comes to my mind posting as a separate answer to allow independent evaluation
All employees of your company, commit themselves to follow that rules.
Ergo, we can simply say that these are their commitments definition from www.vocabulary.com

A: The first thing I thought of was litany:

*

*A series of petitions for use in church services or processions, usually recited by the clergy and responded to in a recurring formula by the people.

*A tedious recital or repetitive series.

Source: Oxford
One of the things you didn't specify was how you felt about having to say all this stuff.  "Litany" is a good sarcastic word to describe a tedious, pseudo-religious rectiation of empty formulae, something ridiculous that bosses make employees do just to demonstrate who's in charge.

A:
Every morning at work, we recite the company manifesto.

manifesto
 a written statement of the beliefs, aims, and policies of an
  organization, especially a political party:

In the West, we use this mainly in political contexts, but from your description it sounds like this is not so removed from a political or religious situation.

A: My suggestions:
"vow"

*

*A solemn promise to perform some act, or behave in a specified manner, especially a promise to live and act in accordance with the
  rules of a religious order.

*A declaration or assertion.

"oath"

*

*A solemn pledge or promise, [..] to attest to the truth of a statement or sincerity of one's desire to fulfill a contract or promise

*A statement or promise which is strengthened (affirmed) by such a pledge.

"pledge"

*

*A solemn promise to do something.

or even "promise"

*

*(countable) an oath or affirmation; a vow

wiktionary: pledge oath promise vow

A: This is called a Mission Statement. It's a set of goals and objectives the company tries to achieve.

A mission statement is a short statement of an organization's purpose, what its overall goal is, identifying the goal of its operations: what kind of product or service it provides, its primary customers or market, and its geographical region of operation. It may include a short statement of such fundamental matters as the organization's values or philosophies, a business's main competitive advantages, or a desired future state—the "vision".

You can find out more about it here

A: Wow, some of the words given are definitely very laden with connotation.
The specific word most commonly used would be "Mission", or more commonly, "Mission Statement".  "Core Values" or "Values Statement" are also common, but mission will be your best bet for a single word.
I've worked for a lot of companies, from retail to corporate, offices to stores.  While I might agree that at the time I worked for Best Buy (~1994) "manifesto" probably felt more accurate, no company would call it that, or vow, or affirmation (except possibly a strongly religious company, that I could see, but have no experience with).  Creed and mantra make sense from a definition perspective, but I'd be shocked to learn of a company calling it that, also.

A: Affirmations - statements that we tell ourselves in order to spark self-change (Steele, 1988)

A: I would call this 'the company mission'.
According to Merriam-Webster's Dictionary:
MISSION (noun) -
a specific task with which a person or a group is charged.
For example, 'Their mission was to help victims of the disaster.'

A: I work for Panasonic where we have a similar activity*, and their English web site calls our 7 things seven principles - see about halfway down the page. Perhaps your company has a similar English page that has an official name for them?
* At least we only have to repeat them once a week!
Additionally, I decided to look up the Japanese definition. First, the OP's thing is the TB Way, and the Japanese version also calls it the TB Way - see the English heading about halfway down.
As for Panasonic, they are called 七精神, nana (7) seishin, and seishin can be translated as spirit.

A: The Company Credo. Merriam Webster says about credo:

Credo comes straight from the Latin word meaning "I believe", and is
  the first word of many religious credos, or creeds, such as the
  Apostles' Creed and the Nicene Creed. But the word can be applied to
  any guiding principle or set of principles. Of course, you may choose
  a different credo when you're 52 than when you're 19. But here is the
  credo of the writer H. L. Mencken, written after he had lived quite a
  few years: "I believe that it is better to tell the truth than to lie.
  I believe that it is better to be free than to be a slave. And I
  believe that it is better to know than to be ignorant".

Many thanks to @ThunderGuppy for suggesting a definition from Collins English Dictionary that fits the question better and acknowledges that a credo does not have to start with I believe.

A credo is a set of beliefs, principles, or opinions that strongly
  influence the way a person lives or works.

A: This can be considered a mantra.

a word or phrase that is repeated often or that expresses someone's basic beliefs

[MW]
Typically a mantra is smaller, but the word evokes the kind of thoughtless droning mantra implies. I imagine this is the case in your office.

A: Real things that are hidden behind, are your company core values (definition from yourdictionary.com)
The 'material' ('touchable') thing you can see is implementation/manifestation/embodiment of your company core values.

A: This sort of company or organizational statement can have several different definitions, depending on how it is used. It could certainly be a mission statement or pledge, and comes out of your companies core values, as suggested in other answers. The ritual manner used to recite this statement is similar to a mantra, as suggested in another. These words all have different nuances. In your particular case, though, this is specifically the TB Way (TB, as in the Toyota Boshoku Company). It is part of their corporate philosophy. (See below for the complete version from the above link).
Way in this context refers to the manner in which the company does things.  Many Japanese companies have one, and they are typically translated as "the [company name] way".  So...

Every morning at work we stand up and recite the company way.

See definition 1.
Oxford:

way:
1. A method, style, or manner of doing something; an optional or alternative form of action.

From the Toyota Boshoku website:

TB Way:

*

*We contribute to society by developing leading-edge technologies and manufacturing high-quality products.

*We meet challenges with courage and creativity, to realize our dreams.

*We carry out kaizen continuously, aiming to achieve higher goals.

*We practice Genchi-Genbutsu by going to the source to analyze problems and find their root causes.

*Once a decision is made, we move quickly to carry out the plan, with passion and a sense of mission.

*We seek to do our best, act professionally and take responsibility for our actions.

*We respect the values of other cultures and accept differences, with an open mind and a global perspective.

*As a good corporate citizen, we do what is right and contribute to society.

*We respect the individual and use teamwork to produce the best result.

A: I would say that this could be considered tenets of the company/team.
Definition of tenet (from Oxford Living Dictionaries: English)

A principle or belief, especially one of the main principles of a religion or philosophy.
'the tenets of classical liberalism'
Synonyms:  principle, belief, doctrine, precept, creed, credo, article of faith, dogma, canon, rule

A: Covenant
Oxford English Dictionary:

A mutual agreement between two or more persons to do or refrain from
  doing certain acts; a compact, contract, bargain; sometimes, the
  undertaking, pledge, or promise of one of the parties.

A: If it is done in the following style:

*

*Leader reads one line out loud

*Everyone reads that same line out loud together

*Leader reads the next line out loud

*Everyone together ... etc

Then I have heard it termed "Chinese School".
I don't have a reference for that, and it is not widespread.

A: propaganda
According to Wiktionary:

A concerted set of messages aimed at influencing the opinions or behavior of large numbers of people.

It is derived from Congregātiō dē Propagandā Fide, "congregation for propagating the faith".

A: A phrase you say to prove you are part of a community, rather than any meaning the phrase may have is a shibboleth

Noun
  shibboleth (plural shibboleths)
  A word, especially seen as a test, to distinguish someone as belonging to a particular nation, class, profession etc.

A: The definition of mantra quoted above is that it is "repeated" or "expressed", thus an action and not the words themselves that would make it a mantra.  It is not the thing you say but the action of saying or expressing them that delineates the mantra.
The words that are determined or defined to be conveyed, make up the creed (or credo) of the business (in this case).
The "thing" in my view is a creed (or credo).  The act of reciting it, is performing a mantra.
I can't comment yet or I would have done that, so instead, I answer.


text:
Q: setTrackDrawable on android Switch resulting wrong image My android app has permanent WebSocket connection to Server. There's also a switch that provides the ability to turn off that connection. So now switch has 2 colors. If switch is on then WS is connected and switch is green. If switch is off then WS is disconnected and switch is red.

So only user can change switch state on/off. But now lets assume that switch was on and internet went down. I want to show to user that state. So added 3rd state - yellow (which means smth is wrong)

my_layout.xml
<Switch
      android:checked="true"
      android:gravity="left"
      android:text="Online"
      android:thumb="@drawable/switch_thumb"
      android:track="@drawable/switch_back"/>

switch_thumb.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid
        android:color="@android:color/white"/>
    <stroke android:width="4dp" android:color="@android:color/transparent" />
    <size
        android:width="24dp"
        android:height="24dp"/>
</shape>

switch_back.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/toggle_on" android:state_checked="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/toggle_on" android:state_checked="true" android:state_focused="false"/>
    <item android:drawable="@drawable/toggle_off" android:state_checked="false" android:state_pressed="true"/>
    <item android:drawable="@drawable/toggle_off" android:state_checked="false" android:state_focused="false"/>
</selector>

switch_back_broken.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/toggle_broken" android:state_checked="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/toggle_broken" android:state_checked="true" android:state_focused="false"/>
    <item android:drawable="@drawable/toggle_off" android:state_checked="false" android:state_pressed="true"/>
    <item android:drawable="@drawable/toggle_off" android:state_checked="false" android:state_focused="false"/>
</selector>

toogle_on.xml/toogle_off.xml/toggle_broken.xml:
ovals of different colors: ON is green, OFF is red, broken is orange.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@android:color/transparent" />
    <corners android:radius="15dp"/>
    <solid
        android:color="@color/colorCheckGreen"/>
    <size
        android:width="40dp"
        android:height="24dp"/>
</shape>

Here's the implementation:
private Switch onlineSwitch;
int currentSwitchBack = R.drawable.switch_back;
@Subscribe
public void wsStatusChange(WsStatusChange event) {
    boolean isOnline = WsStatusChange.Status.OPENED.equals(event.getStatus());
    int newBackId = isOnline ? R.drawable.switch_back : R.drawable.switch_back_broken;
    if (currentSwitchBack != newBackId) {
        currentSwitchBack = newBackId;
        onlineSwitch.setTrackDrawable(getResources().getDrawable(newBackId));
    }
}

So the idea behind is to change background to switch_back_broken.xml when websocket goes down. Note that this background has same red color for offline mode, the only thing that's different is yellow online color. So thus both backgrounds cover all possible situations.
Now to the issue:
When switch is on and I change TrackDrawable from switch_back.xml (which is green) to switch_back_broken.xml (which is yellow) the UI displays RED background (notice that switch is in state ON), which should NEVER happen. Neither of my backgrounds contain red color for ON switch state. But if I double click on switch (meaning just retrigerring layout) colors go back to normal.

I guess this behaviour comes from base state of switch, that's off by default. So switch component is painted with wrong layout guessing that it should be initially in state of off. Has anybody faced this issue?
Any suggestions how to come around? Any kind of help is appreciated!
Best regards,

A: I end up with ugly solution. Just manually retriggering switch:
private boolean block = false;
...
if (onlineSwitch.isChecked()) {
    block = true;
    onlineSwitch.setChecked(false);
    onlineSwitch.setChecked(true);
    block = false;
}

Note block is needed if you have onCheckedChanged listeners, so you just don't trigger them:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (block) {
        return;
    }
/// your code
}

I wonder if there's another way out. Maybe something like requestLayout or ...?


text:
Q: Problems working with the ACL of a folder in Google Cloud Storage I've created an object inside a folder in Google Cloud Storage whith the following OptionsBuilder object:
GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
  .setBucket("bucket")
  .setKey("folder/obj.csv")
  .setMimeType("text/csv");

Making the next structure:
bucket >> folder >> obj.csv
When I run the gsutil command to get ACL for "bucket" and "obj.csv" works fine, however when I execute it for "folder" throws this exception:
GSResponseError: status=404, code=NoSuchKey, reason=Not Found.
The exactly command I run is: gsutil getacl gs://bucket/folder/ > acl.txt
How I can get and set permissions on a folder?

A: You can only retrieve the ACL of an object or a bucket. There is no such thing as a "folder" in GCS, so you can't set or get the ACL of a folder. I suggest you read the Concepts and Terminology section of the developer guide carefully. In particular, the section on object names:

Object names
An object name is just metadata to Google Cloud Storage. Object names
  can contain any combination of Unicode characters (UTF-8 encoded) less
  than 1024 bytes in length. A common character to include in file names
  is a slash (/). By using slashes in an object name, you can make
  objects appear as though they're stored in a hierarchical structure.
  For example, you could name one object /europe/france/paris.jpg and
  another object /europe/france/cannes.jpg. When you list these objects
  they appear to be in a hierarchical directory structure based on
  location; however, Google Cloud Storage sees the objects as
  independent objects with no hierarchical relationship whatsoever.


text:
Q: Do I need to manually rewrite all the trait bounds for every impl block in my Rust code if I defined it in struct block? struct Vec2<T: Sub<Output = T> + Add<Output = T> + Copy> {
    x: T,
    y: T
}

impl<T: Sub<Output = T> + Add<Output = T> + Copy> Add for Vec2<T> {
    type Output = Vec2<T>;
    fn add(self, rhs: Self) -> Self::Output {
        Vec2 {
            x: self.x + rhs.x,
            y: self.y + rhs.y
        }
    }
}

Do I need to rewrite this not-so-beautiful <T: Sub<Output = T> + Add<Output = T> + Copy> every time, or is there another, more elegant method that I am not familiar with?
I know one hack that can achive behaviour that I want by douing like so:
trait Numeric<T> : Sub<Output = T> + Add<Output = T> + Copy {}

macro_rules! add_impl {
    ($($t:ty)*) => ($(
        impl Numeric<$t> for $t {}
    )*)
}

add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }

#[derive(Debug)]
struct Vec2<T: Numeric<T>> {
    x: T,
    y: T
}

impl<T: Numeric<T>> Add for Vec2<T> {
    type Output = Vec2<T>;
    fn add(self, rhs: Self) -> Self::Output {
        Vec2 {
            x: self.x + rhs.x,
            y: self.y + rhs.y
        }
    }
}

This, while partially solving my problem, looks even messier in my opinion.
And I know that "you shoud not put trait bounds in the struct definition", but i really want the compiler to give an error if the end user will try to:
let v = Vec2 {
        x: "Hello", // ERROR WANTED HERE
        y: "World"
    };

A: Trait aliases are unstable, but if you are using a nightly toolchain, you can alias your long trait bounds into a shorter one to actually specify in your impl blocks:
#![feature(trait_alias)]

use core::ops::{Add, Sub};

trait Numeric<T> = Sub<Output = T> + Add<Output = T> + Copy;

struct Vec2<T: Numeric<T>> {
    x: T,
    y: T
}

impl<T: Numeric<T>> Add for Vec2<T> {
    type Output = Vec2<T>;
    fn add(self, rhs: Self) -> Self::Output {
        Vec2 {
            x: self.x + rhs.x,
            y: self.y + rhs.y
        }
    }
}

A more normal method of implementing your second approach is to just impl Numeric for all types satisfying a trait bound, which removes the need for your macros:
impl<T> Numeric<T> for T where T: Sub<Output = T> + Add<Output = T> + Copy {}


text:
Q: proxypass /jenkins to port 8080? Hi I have a VPS running cpanel and it is also running Jenkins on port 8080 I have used proxypass in the Apache config to redirect jenkins.rystuff.net to port 8080 but was wondering if there is a way to redirect rystuff.net/jenkins to port 8080 so that ever way you get to my jenkins page
This is what I have used in my httpd.conf to redirect jenkins.rystuff.net to port 8080
<VirtualHost 23.227.161.55:80>
    ServerName jenkins.rystuff.net
    ServerAlias jenkins.rystuff.net
    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/
</VirtualHost>

Thanks in advance

A: Create another vhost:
<VirtualHost 23.227.161.55:80>
    ServerName rystuff.net
    ProxyPass /jenkins http://localhost:8080/
    ProxyPassReverse /jenkins http://localhost:8080/
</VirtualHost>

You do not need ServerAlias if its the same as ServerName


text:
Q: Installing Ubuntu 12.04 LTS I have a separate machine Dell 1545 laptop. I was wondering how to have  a full install using 12.04 LTS on my Vista machine? Can I just put the burned ISO disc in the disc tray and restart then go into Bios- selecting Boot from CD or is it more different than that? I Do Not want to Dual Boot!
Thanks.

A: Copy pasted from: http://www.ubuntu.com/download/desktop/install-desktop-long-term-support
It's easy to install Ubuntu from a CD. Here's what you need to do:
Put the Ubuntu CD into the CD/DVD-drive.
Restart your computer. You should see a welcome screen prompting you to choose your language and giving you the option to install Ubuntu or try it from the CD.
If you don't get this menu, read the booting from the CD guide for more information.
Using a USB drive?
Most newer computers can boot from USB. You should see a welcome screen prompting you to choose your language and giving you the option to install Ubuntu or try it from the CD.
If your computer doesn't automatically do so, you might need to press the F12 key to bring up the boot menu, but be careful not to hold it down - that can cause an error message.
2
Prepare to install Ubuntu
We recommend you plug your computer into a power source
You should also make sure you have enough space on your computer to install Ubuntu
We advise you to select Download updates while installing and Install this third-party software now
You should also stay connected to the internet so you can get the latest updates while you install Ubuntu
If you're not connected to the internet, we'll help you set up wireless at the next step

3
Set up wireless
If you are not connected to the internet, you will be asked to select a wireless network, if available. We advise you to connect during the installation so we can ensure your machine is up to date. So, if you set up your wireless network at this point, it's worth then clicking the Back button to go back to the last screen (Preparing to install Ubuntu) and ticking the box marked 'Download updates while installing'.
4
Allocate drive space
Use the checkboxes to choose whether you'd like to Install Ubuntu alongside another operating system, delete your existing operating system and replace it with Ubuntu, or — if you're an advanced user — choose the 'Something else' option
5
Begin the installation
Depending on your previous selections, you can now verify that you have chosen the way in which you would like to install Ubuntu. The installation process will begin when you click the Install Now button.
Ubuntu needs about 4.5 GB to install, so add a few extra GB to allow for your files.
Not sure about this step? Windows users can use the Windows installer, which will install and uninstall Ubuntu in the same way as any other Windows application. It's simpler and completely safe.
6
Select your location
If you are connected to the internet, this should be done automatically. Check your location is correct and click 'Forward' to proceed. If you're unsure of your time zone, type the name of the town you're in or click on the map and we'll help you find it.
TIP: If you're having problems connecting to the Internet, use the menu in the top-right-hand corner to select a network.
7
Select your preferred keyboard layout
Click on the language option you need. If you're not sure, click the 'Detect Keyboard Layout' button for help.
8
Enter your login and password details
9
Learn more about Ubuntu while
the system installs…
…or make a cup of tea!
10
That's it.
All that's left is to restart your computer and start enjoying Ubuntu!

A: If you are not interested in dual boot with vista 7. I'd recommend you to check the option erase disk and install ubuntu 12.04 and just follow the instructions.
I'd Recommend you to have a working internet connection since you might have to install the latest updates for your system.
And If there is a graphics card in your system make sure you install the driver otherwise you may heat up your system.


text:
Q: Check Python List/Dict based on user input & display from the same index value in another list So we ask the user to input a number and match that number in a list:
numbers = [1, 2, 3]
num_words = ['One', 'Two', 'Three']
print('Type a number from 1 -3: ')
user = int(input())
if user in numbers:
  print(f"{user} is the digit you typed " + ???)

Once that is done I'd like to match what the user typed that was found in the numbers list and print out the corresponding index value in the next list.
So the user types in 1 and it checks numbers and if it finds it, it would print: One
from the num_words list to the user.
I also tried a dictionary, but couldn't figure out how to show the matching value to the user based on their input and matching to the dict key:
nums = {1: 'One', 2: 'Two', 3: 'Three'}
print ('Type 1, 2, or 3: ')
user = int(input())

if user in nums.keys():
   print(num.values) #Need it to print the nums.value based on the users input at match to nums.keys
else:
   print('Goodbye!')

However, my Google searching isn't finding anything similar to what I'm trying to do. I found topics on here (example: Stackover Flow Tpoic, Stackover Flow topic 2, but it didn't help because as far as I could understand (and current understanding of Python) it didn't 100% match what I was trying to do.

A: For the first example with lists, use .index() to find the index location of the number in the first list, then use that value to find the item in the second list:
if user in numbers:
    location = numbers.index(user)
    print(num_words[location])

For the second example with a dictionary, just use standard dict lookup:
if user in nums:
    print(nums[user])

A: The syntax to get the value from a dictionary is dictionary_name[key].  This will raise a KeyError if the key is not found, so you can use try/except instead of checking ahead of time and doing if/else:
nums = {1: 'One', 2: 'Two', 3: 'Three'}
print ('Type 1, 2, or 3: ')
user = int(input())

try:
    print(f"{user} is the digit you typed {nums[user]}")
except KeyError:
   print('Goodbye!')

If you don't want this code to raise a ValueError on an invalid integer input, you can just use strings as the dictionary keys:
nums = {'1': 'One', '2': 'Two', '3': 'Three'}
print ('Type 1, 2, or 3: ')
user = input()

A: Here it is.  You can add error capture to it, but that's probably for a future lesson:
numbers = [1, 2, 3]
num_words = ['One', 'Two', 'Three']
print('Type a number from 1 -3: ')
user = int(input())
if user in numbers:
  print(f"You typed: {num_words[numbers.index(user)]}")

#output:
Type a number from 1 -3:
2
You typed: Two


text:
Q: Questions about responseText Overview:
I'm using the JQuery Form Plugin to send Form Data to a remote file via AJAX. The File then processes the form data and inserts it into the MySQL Database.
Problem:
The Problem is, however, when I want to run code on a successful add, (usually completed using the "success" option, it never runs. Doing further research I found that I needed to send back "responseText" to make the function under "success" run.
Questions:
1) Is this true?
2) How do I go about sending back responseText?
3) (If number on is that it is not true) How do I get the function under success to run?
A few code Snippets:
JQuery (Using the JQuery Form Plugin):
$("#form1").ajaxForm({url: 'submit.php', type: 'post', resetForm: true, success: function () {  $('#new-paste').modal({show: false}) }});

I can provide the contents of the remote file (submit.php) if needed.
Thank you in advance!

A: Change your success to:
function(response) {
    $('#new-paste').modal({show: false});
    alert(response); // response is the output from the php script it submitted to.
}

Hope this helps.

A: Alright, so I found the solution.
The Script had to be included on the page itself, not in a remote .js file.
so:
<script>
        // wait for the DOM to be loaded
        $(document).ready(function() {
            // bind 'myForm' and provide a simple callback function
            $('#myForm').ajaxForm(function() {
                alert("Thank you for your comment!");
            });
        });
    </script>

Should be included in the head.


text:
Q: Writing enumitem's to a file I am a teacher and often need to make worksheets and reviews that have answer keys.  With the help of TeX StackExchange, I have a fairly robust system at this point with the notable exception that it does not work with enumitem.  The error message that I am getting is beyond my LaTeX wisdom.  Is there anyone who can help me out?
MWE:
\documentclass[10pt]{article}

\usepackage{pgfplots}
\usepackage{enumitem}

\newwrite\answerkeyfile

\AtBeginDocument{%
   \immediate\openout\answerkeyfile=\jobname.keys
}

\begingroup
\catcode`\#=12
\gdef\hashchar{#}%
\endgroup

\makeatletter
\newcommand{\answerkey}[1]{%
  \begingroup
  \let\#\hashchar
  \immediate\write\answerkeyfile{\@currentlabel.\ }
  \immediate\write\answerkeyfile{\unexpanded{#1}}%
  \immediate\write\answerkeyfile{ }
  \endgroup
}
\makeatother

\AtEndDocument{%
  \immediate\closeout\answerkeyfile
}

\begin{document}

Answer these questions:

%% With \begin{enumerate}, this code works.  Switch to
%% \begin{enumerate}[label=\emph{\alph*)}] and it fails.
%\begin{enumerate}
\begin{enumerate}[label=\emph{\alph*)}]
   \item Question 1 \answerkey{Answer 1}
   \item Question 2 \answerkey{$\frac{1}{2}$}
   \item Question 3 \answerkey{\begin{tikzpicture}
                          \draw (0,0) rectangle (1,1);
                          \end{tikzpicture}}
\end{enumerate}

Answer Key:

% Copy the mwe.keys to mwe.ans, then use this to show the answers.
%\input{mwe.ans}

\end{document}

As noted in the comments, switch the enumerate line to the one that uses enumitem features and this will fail.  What can I do to not compromise the
system I have and yet still use enumitem?
Here is the error that I am getting:

! Use of \@item doesn't match its definition. \text@command #1->\def
  \reserved@a {#1}\ifx \reserved@a \@empty \let \check@... l.37   \item
  Question 1 \answerkey{Answer 1}

UPDATE:
The comment below that it is not actually the enumitem code but rather the \emph (or similarly \textbf, \textit, etc) in the label that is the issue was interesting.  The solution below that creates a "fake" label is the least invasive/complicated, while adding the functionality that label formatting makes it through to the answer key document.  The code I started with did not put the answers into a true enumerate environment, so the solution proposed below which does this is overkill for my situation.  In the end, based on the help/guidance below, I rewrote the \answerkey command as follows:
\newcommand{\answerkey}[2][.]{%
  \begingroup
  \let\#\hashchar
  \immediate\write\answerkeyfile{\expandafter\unexpanded
         \expandafter{\@currentlabel}#1\ }
  \immediate\write\answerkeyfile{\unexpanded{#2}}%
  \immediate\write\answerkeyfile{ }
  \endgroup
}

In actual use, it looks like this:
If the default item labels are used:
\begin{enumerate}
    \item Question 1 \answerkey{Answer 1}

If enumitem label formatting is used:
\begin{enumerate}[label={\arabic*.}]
    \item Question 1 \answerkey[]{Answer 1}

A: You should use the ref feature of enumitem, also exploiting the fact that the package braces the \@currentlabel.
Define \answeritem as you like.
\documentclass[10pt]{article}

\usepackage{pgfplots}
\usepackage{enumitem}

\newwrite\answerkeyfile

\AtBeginDocument{%
   \immediate\openout\answerkeyfile=\jobname.keys
}

\edef\hashchar{\string#}

\makeatletter
\newcommand{\answerkey}[1]{%
  \begingroup
  \let\#\hashchar
  \immediate\write\answerkeyfile{\answeritem\@currentlabel}
  \immediate\write\answerkeyfile{\unexpanded{#1}^^J}%
  \endgroup
}
\protected\def\answeritem#1{\item[\emph{#1})]}
\makeatother

\begin{document}

Answer these questions:

%% With \begin{enumerate}, this code works.  Switch to
%% \begin{enumerate}[label=\emph{\alph*)}] and it fails.
%\begin{enumerate}
\begin{enumerate}[label=\emph{\alph*}),ref=\alph*]
   \item Question 1 \answerkey{Answer 1}
   \item Question 2 \answerkey{$\frac{1}{2}$}
   \item Question 3 \answerkey{\begin{tikzpicture}
                          \draw (0,0) rectangle (1,1);
                          \end{tikzpicture}}
\end{enumerate}

Answer Key:

\immediate\closeout\answerkeyfile
\begin{enumerate}
\input{\jobname.keys}
\end{enumerate}

\end{document}

Here's the output in \jobname.keys:
\answeritem {a}
Answer 1

\answeritem {b}
$\frac {1}{2}$

\answeritem {c}
\begin {tikzpicture} \draw (0,0) rectangle (1,1); \end {tikzpicture}

Some more words about the problem.
The key ref defines what's stored in \@currentlabel (typically written in the .aux file, but you're using it yourself). Writing in the .aux file is safe, because \protected@write is used by LaTeX; however you're using \write and \emph is not a command TeX likes to see there. You could use \protected@iwrite (you find how to define it on the site), but the trick I suggest above is even better because you can then decide what \answeritem gets expanded to. It's important its definition is \protected, so it will remain untouched during the \write operation.

A: I suggest to expand \@currentlabel and write that content to the file with \unexpanded, however, this will place 'fake' item labels and not really \item layout in the file.
A better strategy would be to 'replicate' the enumerate environment in the output file.
\documentclass[10pt]{article}

\usepackage{pgfplots}
\usepackage{enumitem}

\newwrite\answerkeyfile

\AtBeginDocument{%
   \immediate\openout\answerkeyfile=\jobname.keys
}

\begingroup
\catcode`\#=12
\gdef\hashchar{#}%
\endgroup

\makeatletter
\newcommand{\answerkey}[1]{%
  \begingroup
  \let\#\hashchar
  \immediate\write\answerkeyfile{\expandafter\unexpanded\expandafter{\@currentlabel}.\ }
  \immediate\write\answerkeyfile{\unexpanded{#1}}%
  \immediate\write\answerkeyfile{ }
  \endgroup
}
\makeatother

\AtEndDocument{%
  \immediate\closeout\answerkeyfile
}

\begin{document}

Answer these questions:

%% With \begin{enumerate}, this code works.  Switch to
%% \begin{enumerate}[label=\emph{\alph*)}] and it fails.
%\begin{enumerate}
\begin{enumerate}[label=\emph{\alph*)}]
   \item Question 1 \answerkey{Answer 1}
   \item Question 2 \answerkey{$\frac{1}{2}$}
   \item Question 3 \answerkey{\begin{tikzpicture}
                          \draw (0,0) rectangle (1,1);
                          \end{tikzpicture}}
\end{enumerate}

Answer Key:

% Copy the mwe.keys to mwe.ans, then use this to show the answers.
\immediate\closeout\answerkeyfile
\input{\jobname.keys}

\end{document}

Another approach by writing \begin{answerenumerate} to the file, which is a copy of enumerate, basically:
\documentclass[10pt]{article}

\usepackage{pgfplots}
\usepackage{enumitem}

\newwrite\answerkeyfile

\AtBeginDocument{%
   \immediate\openout\answerkeyfile=\jobname.keys
}

\begingroup
\catcode`\#=12
\gdef\hashchar{#}%
\endgroup

\makeatletter
\newcommand{\answerkey}[1]{%
  \begingroup
  \let\#\hashchar
  \immediate\write\answerkeyfile{\string\item}
  \immediate\write\answerkeyfile{\unexpanded{#1}}%
  \immediate\write\answerkeyfile{ }
  \endgroup
}
\makeatother

\AtEndDocument{%
  \immediate\closeout\answerkeyfile
}

\begin{document}

Answer these questions:

\newlist{answerenumerate}{enumerate}{1}
\setlist[answerenumerate]{label=\emph{\alph*)}}

\setlist[enumerate,1]{label=\emph{\alph*)},
  before={\immediate\write\answerkeyfile{\string\begin{answerenumerate}}},
    after={\immediate\write\answerkeyfile{\string\end{answerenumerate}}}
}

\begin{enumerate}
   \item Question 1 \answerkey{Answer 1}
   \item Question 2 \answerkey{$\frac{1}{2}$}
   \item Question 3 \answerkey{\begin{tikzpicture}
                          \draw (0,0) rectangle (1,1);
                          \end{tikzpicture}}
\end{enumerate}

Answer Key:

% Copy the mwe.keys to mwe.ans, then use this to show the answers.
\immediate\closeout\answerkeyfile
\input{\jobname.keys}

\end{document}


text:
Q: vim-cmd connection refused in management console I'm trying to manage VMs on the local management console of an ESXi 5 host (due to a problem accessing it through VI client and needing to do some VM management prior to attempting a reboot on the host.)
I will enter a command such as:
vim-cmd vmsvc/getallvms

and get this error:
Failed to login: Connection refused

I read somewhere that SSH has to be enabled in order for vim-cmd to work.  I'm actually working directly on the host's terminal, not by SSH, but just in case I enabled SSH, and the same error still occurred.
How can I get vim-cmd to work in the local management console?

A: check whether the 'vpxa' service is running, I had the same issue and figured out that the 'vpxa' service was stopped.
after starting the service everything worked well.
https://kb.vmware.com/s/article/1003490


text:
Q: how do I write an equation in terms of another variable, not in the original equation? For example, this problem is asking me to write the following equation in terms of $a$, where $a = x^2 + 4?$
The equation is as follows:$$(x^2 + 4)^2 + 32 = 12x^2 + 48.$$
I don't know how to solve this.

A: If $a = x^2 + 4$, then $x^2 = a - 4$, so:
$$
  a^2 + 32 = 12 (a - 4) + 48
$$
I'm sure you can take it from here.
Another way is to just expand the square:
$$
x^4 + 8 x^2 + 16 + 32 = 12 x^2 + 48
$$
This is biquadratic, but it is really a quadratic in $x^2$. In reality, the constant terms cancel:
$$
x^4 - 4 x^2 = 0 \\
x^2(x^2 - 4) = 0
$$
Roots are apparent.

A: You have to find a way to make the big equation look like a quadratic trinomial, the form of which will be
$ a^2 +  [(some-number)\times a]  +32 = 0$.
Note : the " some number " will be negative
In order to do this , you'll have to find a way to express the RHS of the equation as a product having variable $ a $ ( that is ($x^2+4$) ) as a factor. ( Notice that $48$ = $4\times$ something... )... and then move the RHS to the left.
Then , solve the quadratic for $a$ ( that is, find the possible values of $a$ that make the equation true, in the same way as you ordinarily solve a quadratic for $x$).
Then , use the value(s) you have found as to $a$ to solve for $x$.


text:
Q: Как задать рабочую папку при создании SCHTESKS через CMD? Доброго времени суток.
Подскажите пожалуйста, как можно через командную строку создать задание в планировщике задач с указанием рабочей папки?
Само задание создаю так SCHTASKS /Create /ru "SYSTEM" /SC DAILY /TN AllVision /TR "\"%appdata%\AllVision\start.VBS"" /ST 10:25:00
Задание создается, но что бы мой скрипт работал, нужно в самом задании указать рабочую папку. Делать это руками каждый раз нет возможности, нужно при создании задания через CMD каким-то образом передать адрес рабочей папки "%appdata%\AllVision\"
Заранее благодарен!
.

A: Отвечаю сам себе и другим, кто в будущем столкнется с этим.
Что бы задать рабочую папку во время создания задачи через CMD нужно передать ключ /v1. Почему именно его, я сам не до конца понял, если кто сможет объяснить, буду благодарен!
В итоге у меня получилось SCHTASKS /Create /ru "SYSTEM" /v1 /SC DAILY /TN AllVision /TR "\"%appdata%\AllVision\start.VBS"" /ST 10:25:00 и все заработало

A: У SCHTASKS есть такой ключ комстроки, как /XML XMLfile, который выполняет импорт параметров задачи из XML-файла. В котором вполне можно указать и каталог запуска. и любые другие параметры. Сам XML можно создавать в процессе выполнения, если команда выполняется из пакетного файла, или подготовить заранее.


text:
Q: how to drag and drop only using button not by whole row? I am making a demo in which user can drag and drop the row.In my demo user hold row anywhere (from whole width of row) and drop in another position.I need to prevent that it only drag and drop when user in the area of button .If user want to drag the row it should hold the button area and drop anywhere .
I am creating the row after click the button .Now I want to prevent the drag and drop from whole width only in button area.
Here is my fiddle
http://jsfiddle.net/FZQ8D/22/
$("#testCaseContainer").sortable({
          stop: function( event, ui ) {

          }
    }).disableSelection();

first create 2 or 3 row after clicking add button.
then it should drag and drop on button area.
Thanks

A: As @scragar given the perfect answer .
$("#testCaseContainer").sortable({
        handle: '.editButton',
          stop: function( event, ui ) {

                      var obj={};
        var len=$("#testCaseContainer > div").length;
    // alert("all Index");
        for(var i=0;i<len;i++){
           // var id=
      //alert($("#testCaseContainer > div").eq(i).find('li').attr('id'));
            obj[i]=$("#testCaseContainer > div").eq(i).find('li').attr('id');

          //  alert($("#testCaseContainer > div")[0].find('li').id);

        }
console.log(obj)

          }
    }).disableSelection();


text:
Q: Escalar un ajuste lognormal simple a una suma lognormal en python estoy tratando de ajustar unos datos que presentan una distribución lognormal. Puedo ajustar los datos para una sola población pero me pregunto cual es la manera correcta de ajustar multiples distribuciones lognormales. Por ejemplo, para 2 poblaciones con distribución normal la función que describe los datos es una suma de funciones gaussianas. Pero para una para mas de una distribución lognormal no entiendo cual es la manera de representar esta distribución. My codigo es el siguiente:
from scipy.optimize import curve_fit

# Primero genero 3 poblaciones con distribución lognormal:
import numpy as np

s1 = np.random.lognormal(2, 0.6, 1000)  #mu and sigma
s2 = np.random.lognormal(1.6, 0.3, 1000) #mu and sigma
s3 = np.random.lognormal(1.8, 0.5, 1000) #mu and sigma

mb = np.max([s1,s2,s3])
X = np.arange(1,mb,1)
 #histogram population 1
Y11, bins1 = np.histogram(s1, X)
Y1 = Y11/Y11.sum()
X1 = bins1[:-1]

 #histogram population 2
Y22, bins2 = np.histogram(s2, X)
Y2 = Y22/Y22.sum()
X2 = bins2[:-1]

 #histogram population 3
Y33, bins3 = np.histogram(s3, X)
Y3 = Y33/Y33.sum()
X3 = bins3[:-1]

 #Aqui presento la suma de las 3 distribuciones con distintos parámetros
S =  np.concatenate((s1, s2, s3), axis=None)

Yi, bins = np.histogram(S, X)
Y = Yi/Yi.sum()
X = bins[:-1]

def logN(x, mu, sigma):

    return  (np.exp(-(np.log(x) - mu)**2 / (2 * sigma **2)) / (x * sigma * np.sqrt(2 * np.pi)))  #lognormal function

params, pcov = curve_fit(logN, X,Y, method="lm")
print(params)
plt.plot(X1, Y1, 'o')
plt.plot(X2, Y2, 'o')
plt.plot(X3, Y3, 'o')
plt.plot(X, Y, 'r-o')
plt.plot(X, logN(X ,params[0], params[1]))

plt.show()

Mi objetivo es llegar a los parámetros 'mu' de las 3 poblaciones por separado. Los datos reales comienzan con datos como 'S'y mi función describe una distribución lognormal simple, pero no entiendo como poder llegar a los parámetros que componen esta distribución. Cualquier idea es bien recibida


text:
Q: How to filter "permalink" from stream table on my wall? I want to filter and get "permalink" from my wall. To get the permalink I use the following query:
SELECT permalink FROM stream where source_id = me() and type != 80 LIMIT 0, 100000

I want the posts of my friends on my wall alone except the photos; I mean I need only the status and comments of my friends over my wall. using the "type" like,
SELECT permalink FROM stream where source_id = me() WHERE type IN (8, 46, 56)

was not at all helped me. Please advice. Thanks in advance.


text:
Q: Where is tftp efi shell command? Cannot find tftp command in  shell.efi app from Tianocore.
When type tftp, got 'tftp' is not recognized as an internal or external command, operable program, or batch file. Help also doesn't know about it.
I looked at sources and found it is implemented in DynamicCommand directory. Maybe command must be loaded or activated somehow before using?
Edit: well, the only way i found to get tftp client working on Tianocore shell is building ShellPkg from sources. There is DynamicCommand/TftpDynamicCommand subdirectory contains tftp application. It will produce tftp.efi on package building finished. "Manual" can be found here. Still dont understand how to make shell with built-in tftp command and why Tianocore maintainers do not include procompiled tftp.efi in ShellBinPkg for example.

A: How to Run OVMF article contain information on how to get pre-built OVMF images:

Pre-built images are available at https://www.kraxel.org/repos/

*

*These images are automatically built and track the latest OVMF code in the EDK II tree.

*Some of these builds include a seabios CSM and can boot non-UEFI "legacy" operating systems. Note: seabios is GPLv3 licensed)

*If your OS doesn't work with RPM repositories, then you can manually download and decompress the RPM files under jenkins/edk2

You can find the latest OVMF RPM packages at kraxel repository. They contain the latest firmware and UefiShell.iso to boot. You will find tftp command you need and other cool stuff there.


text:
Q: How to check if the datatype of an object value is null (JS) Some values of my object are sometimes not in the domain and thus have a null value. How can I filter out the null values from this object when trying to iterate through it?
That's the code I wrote but it doesnt do anything.
function enLanguage(){
    let value1 = Object.values(dicEnglish);
    let key1 = Object.keys(dicEnglish);
    for (let y=0; y<50; y++){
      if ((typeof key1[y] === "object") || (typeof value1[y] ==="object")){
        continue;
      }else{
        let text1 = value1[y];
        document.getElementById(key1[y]).textContent = text1;
        key1[y].textContent=value1[y]}}}

A: A couple points to notice:

*

*In JS an object key cannot be another object.
So this typeof key1[y] === "object" is not going to work.

*You would probably want Object.entries function, example:

for (const [key, value] of Object.entries(dicEnglish)) {
    // Do something
}

*To check if a value is nullish you can use value == null (note 2 equal signs).
This returns true if a value is null or undefined.

Given said, you can rewrite your function as:
function enLanguage(){
    for (const [key, value] of Object.entries(dicEnglish)) {
        // Here you check for null
        if (value == null) {
            // Do something
        } else {
            // Do something else
        }

    }

A: strangely enough, the null datatype in JavaScript is also an object.
but we can filter it out through the ! operator.
for example:
console.log(!null) // true
console.log(!undefined) // true

const x = "Hello World!"
console.log(!x) // false

it returns true if the subsequent value is null, undefined or 0 (falsy values)
so in your code change the condition:
if (!key1[y] || !value1[y]) continue

this will now skip any falsy values

A: A compact way to check if a value is null is trwar using strict equality operators:
(value === null)  // true if value is of datatype NULL
(value !== null)  // true if value is not of datatype NULL

Non-strict operators provide a similar test but check if a value is null or undefined:
(value == null)  // true if value is of datatype NULL or UNDEFINED
(value != null)  // true if value is not of datatype NULL or UNDEFINED.

where "NULL" mean the data type of null and "UNDEFINED" means the data type of undefined.
The typeof operator returns "function" for function objects (of data type OBJECT) and "object" for the null primitive of type NULL. This dates back to the original design and implementation of JavaScript on PC's of the 1990s era, and is so entrenched it can't be changed.
TL;DR That typeof null returns "object" does not mean null is an object or has data type OBJECT. null is the singleton value of JavaScript data type NULL.


text:
Q: PHP scripting to use search engine I'm making a simple website with a form where a user enters a word and then I take that word and google it using a php script and displaying the results. How would I be able to do this? or where would I get a script to do this?

A: I'm fairly sure reusing their results as you want to do is against their Terms of Service.
Why not simply create a form that redirects to the Google result page? Here is a tutorial on  how.
Linking to Google Search Results

A: You would look for Google Site Search - http://www.google.com/sitesearch/

A: First, as quick solution, you should redirect your users to Google's result page.
When your sript receives the search term, it may

*

*change spaces to "+" sign,

*append it to the following URL: http://www.google.com/search?q=site%3Aexample.com+ (change example.com to your domain),

*redirect to it.

Example: http://www.google.com/search?site=&q=site%3Astackoverflow.com+banana


text:
Q: Why are dynamically added html table rows and cells not being added to a front end html table? I'm trying to populate a front-end html table using back-end c#, but none of the HtmlTableRows and HtmlTableCells are showing up in the table. I was able to successfully populate a front-end table dynamically in another asp page in the same project (Images.aspx), but it won't work in this one (Products.aspx).
The front-end tables look like this:
Images.aspx

Products.aspx

Here is the C# code from each page:
Page_Load in Images.aspx.cs (working)
List<Product> productList = DBL.GetProductList(); // Creates a list of products using a database table

foreach (Product product in productList)
{
    HtmlTableRow tRow = new HtmlTableRow();
    tblImages.Rows.Add(tRow);

    for (int i = 0; i <= 1; i++)
    {
        HtmlTableCell tCell = new HtmlTableCell();
        if (i == 0)
        {
            tCell.InnerText = product.Name;
        }
        else if (i == 1)
        {
            HtmlButton btn = new HtmlButton();
            btn.ID = product.ModelPath;
            btn.Attributes["class"] = "view";
            btn.Attributes["type"] = "button";
            btn.InnerText = "View Model";
            tCell.Controls.Add(btn);
        }
        tRow.Cells.Add(tCell);
    }
}

Page_Load in Products.aspx.cs (not working)
List<Product> productList = DBL.GetProductList(); // Creates a list of products using a database table

int column = 1; // keeps track of the column of the cell being populated
const int TOTAL_COLUMNS = 3; // number of columns in the table
HtmlTableRow tRow = new HtmlTableRow();
tblProducts.Rows.Add(tRow);
HtmlTableCell tCell = new HtmlTableCell();
tRow.Cells.Add(tCell);

tCell.Attributes["colspan"] = "3";
tCell.InnerText = "Products";

foreach (Product product in productList) // for every product in the list
{
    if (column == 1) // Create and add a new row if on the first column
    {
        tRow = new HtmlTableRow();
        tblProducts.Rows.Add(tRow);
    }

    // Create cell and populate it

    tCell = new HtmlTableCell();
    tRow.Cells.Add(tCell);
    tCell.InnerHtml += "
" + product.Name + "
" +
                       "

$" + product.Cost + "
" +
                       "
" + product.Description + "

";

    if (column == TOTAL_COLUMNS) // if the final column has been reached, reset column counter
    {
        column = 1;
    }
    else // Otherwise, increment column counter
    {
        column++;
    }
}

if (column != 0) // Adds empty cells if the end of the row wasn't reached in the foreach loop
{
    for (int i = column; i < TOTAL_COLUMNS; i++)
    {
        tCell = new HtmlTableCell();
        tRow.Cells.Add(tCell);
    }
}

I tried copying the C# code from Images.aspx.cs to Products.aspx.cs to see if it was something with the code in Products, but the table still wouldn't populate.