text:
Q: ASP.NET MVC Entity Framework Core how to create a separate table for each data subset I currently have a class called SingleSymbolData that contains all of the associated weekly stock data.
public class SingleSymbolData
{
    [Key]
    public int SingleSymbolKey { get; set; }

    public string SymbolName { get; set; }

    public virtual ICollection<WeeklyStockData> WeeklyStockDataCollection { get; set; } = new List<WeeklyStockData>();
}

The weekly stock data looks like this:
public class WeeklyStockData
{
    public WeeklyStockData()
    {
    }

    [Key]
    public int StockDataID { get; set; }

    public string Symbol { get; set; }
    public DateTime Time { get; set; }
    public float Volume { get; set; }
}

The problem is that all of the weekly stock data is being added to a single table called WeeklyStockData. Meanwhile I have another table called SingleSymbolData which contains a foreign key.
The problem is that the single WeeklyStockData table is starting to get very large, and will just get larger with the more weekly stock data I add.
I was wondering if there was some way I could create a table for each subset of weekly stock data so that the foreign key of the SingleSymbolData table would point to that separate table.
Here is what my db set stuff looks like:
public DbSet<SingleSymbolData> StockSymbols { get; set; }
public DbSet<WeeklyStockData> WeeklyStockData { get; set; }

I'm hoping this would be possible for performance reasons since queries are just getting slower on the individual table. Let me know if I'm going down the wrong path here. I'm open to other solutions as well, or changing my current entity setup. Please let me know if I should add more of my code or more information. Thanks for your help in advance.


text:
Q: Asp.Net CodeFirst How can i navigate between 3 models? I have 3 models in my project:

*

*Category

*Marka

*Product

And I need to fill the Category dropdown with Marka options, like when you click on TV category and TV brands show up.
Here is my controller:
public ActionResult LoadMarkas(int CategoryId)
{
    return (_Contex.Markas.Where(m =>m.Products.CategoryId == CategoryId));
}

Sorry for bad English

redpajama_set_name: RedPajamaStackExchange


text:
Q: expected value of two multiplying random variables I have two random variables, say $X$ and $Y$ which are not correlated.
then $$|E[XY]|$$is
greater, equal or less than $$E[|XY|]?$$

A: Jensen's inequality states that for any integrable random variable $Z$ the inequality $|E[Z]| \le E[|Z|]$ holds.


text:
Q: App Insights GetMetric("name").TrackValue doesn't aggregate when viewing in App Insights portal I am sending a custom metric to Application Insights (Azure Monitor?) using the following C# code in an Azure Function.
(it measures the elapsed time between Service Bus message enqueued and Function code execution)
this.TelemetryClient.GetMetric("QueueTriggerLagMs").TrackValue((now - serviceBusMessage.SystemProperties.EnqueuedTimeUtc).TotalMilliseconds);

I'd expect this to be aggregated by the SDK and shown as an aggregate in the portal but its summing it, I think.

Microsoft.ApplicationInsights.TelemetryClient.TrackMetric is not the preferred method for sending metrics. Metrics should always be pre-aggregated across a time period before being sent. Use one of the GetMetric(..) overloads to get a metric object for accessing SDK pre-aggregation capabilities. If you are implementing your own pre-aggregation logic, you can use the TrackMetric() method to send the resulting aggregates. If your application requires sending a separate telemetry item at every occasion without aggregation across time, you likely have a use case for event telemetry; see TelemetryClient.TrackEvent (Microsoft.ApplicationInsights.DataContracts.EventTelemetry).

Source https://learn.microsoft.com/en-gb/azure/azure-monitor/app/api-custom-events-metrics
It's funny, while typing this question out I re-read and noticed that the wording in that pullquote is confusing and that I need to do my own aggregation.

Use one of the GetMetric(..) overloads to get a metric object for accessing SDK pre-aggregation capabilities.

Makes it sound like by using that method instead of TrackMetric then it'll pre-aggregate but I don't think that's what they're saying.
I thought the built-in behaviour would be to aggregate for me, instead of forcing every developer to write the same code to aggregate over some batching time period that we don't know.
I'm completely lost.
Does anyone know what I'm supposed to do to track that lag time?

Relates to question.
Azure Function is not logging LogMetric telemetry to Application Insights

A: TrackValue sums up provided values and also tracks valueCount. It allows to get average during query time:

Metrics blade also allows to pick Aggregation:

A: Before getting to metric details...  The question implies that "sum" is not an "aggregate", but "aggregate" is a generic term for any value or process that represents many combined values in some manner.  In other words, a "sum" is just one type of aggregate; "average" is another, etc.  It's not clear exactly what you expect.
GetMetric() returns an object that automatically does local aggregation over 60 second intervals before sending details to the App Insight telemetry server, but it is special because although it aggregates some things like count, sums and averages it still allows alerts to be triggered from individual values (if configured).
The purpose of GetMetric() is to do the pre-aggregation for you to reduce traffic and telemetry storage and cost.  The alternative is to call telemetryClient.TrackMetric() which will record each and every value, but at increased cost.
See GetMetric() documentation for details.
Lastly, it could be that you're visualizing the data incorrectly in App Insights.  When tracking milliseconds (or any time value), I suggest looking at an Avg aggregation in a Scatter Plot graph.  Don't use the Line or Area plots since they do a poor job of interpolating between missing points and paint a wildly-fluctuating curve.
Probably don't use the Count aggregation either since that won't tell you anything about the custom "elapsed timing" values, rather it will only tell you about how often the metric was sent.  That might provide useful answers, but only for the right question.


text:
Q: SharePoint 2010 Dialog Missing Content I have customized a SharePoint 2010 master page, all is working except dialog boxes are displaying empty. For example, if I try to add users to a group the dialog comes up, but no content is in the box.
What could be the issue ?

A: use the developer tools and see if there is your custom css is blanking the form up. As you may know that you can remove css rules from the developer tool on the spot without changing the master page itself to see the effect (just to save you any hassle)


text:
Q: DatePicker crashing with NullPointerException Currently i applied a DatePicker into my application and when i click the Button, it crashed. Below is the logcat:
08-18 00:22:39.564: E/AndroidRuntime(793): FATAL EXCEPTION: main
08-18 00:22:39.564: E/AndroidRuntime(793): java.lang.RuntimeException: Unable to start activity  ComponentInfo{com.stts.sparetimetradingsystem/com.stts.sparetimetradingsystem.employer.EditEventActivity}:  java.lang.NullPointerException
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.os.Looper.loop(Looper.java:123)
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.app.ActivityThread.main(ActivityThread.java:4627)
08-18 00:22:39.564: E/AndroidRuntime(793):  at java.lang.reflect.Method.invokeNative(Native Method)
08-18 00:22:39.564: E/AndroidRuntime(793):  at java.lang.reflect.Method.invoke(Method.java:521)
08-18 00:22:39.564: E/AndroidRuntime(793):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-18 00:22:39.564: E/AndroidRuntime(793):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-18 00:22:39.564: E/AndroidRuntime(793):  at dalvik.system.NativeStart.main(Native Method)
08-18 00:22:39.564: E/AndroidRuntime(793): Caused by: java.lang.NullPointerException
08-18 00:22:39.564: E/AndroidRuntime(793):  at com.stts.sparetimetradingsystem.employer.EditEventActivity.updateDisplayFrom(EditEventActivity.java:532)
08-18 00:22:39.564: E/AndroidRuntime(793):  at com.stts.sparetimetradingsystem.employer.EditEventActivity.onCreate(EditEventActivity.java:236)
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-18 00:22:39.564: E/AndroidRuntime(793):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-18 00:22:39.564: E/AndroidRuntime(793):  ... 11 more

Sorry for not placing my code. Here is my code:
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_event);

    edit_eventSpinner = (Spinner) findViewById(R.id.edit_spinner);
    btnSaveEvent = (Button) findViewById(R.id.btnSaveEvent);
    btnDeleteEvent = (Button) findViewById(R.id.btnDeleteEvent);
    edit_error = (TextView) findViewById(R.id.edit_error);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.salary_array,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    edit_eventSpinner.setAdapter(adapter);
    edit_eventSpinner
            .setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent,
                        View view, int position, long id) {

                    if (position == 0) {
                        rate = "/hour";
                    } else if (position == 1) {
                        rate = "/day";
                    } else {
                        rate = "/month";
                    }
                }

                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

    // getting event details from intent
    Intent i = getIntent();

    // getting event id (EID) from intent
    eid = i.getStringExtra(TAG_EID);

    // Getting complete event details in background thread
    new GetEventDetails().execute();

    // save button click event
    btnSaveEvent.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // starting background task to update event
            String e = edit_eventName.getText().toString();
            String c = edit_eventCName.getText().toString();
            String s = edit_eventSalary.getText().toString();
            String f = edit_eventFrom.getText().toString();
            String t = edit_eventTo.getText().toString();
            String whf = edit_eventWHFrom.getText().toString();
            String wht = edit_eventWHTo.getText().toString();
    });

    // Delete button click event
    btnDeleteEvent.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // deleting event in background thread
            new DeleteEvent().execute();
        }
    });

    Button edit_pickDateFrom = (Button) findViewById(R.id.edit_pickDateFrom);

    edit_pickDateFrom.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }
    });

    updateDisplayFrom();
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {

    case DATE_DIALOG_ID:
        return new DatePickerDialog(this, mDateSetListenerFrom, mYear,
                mMonth, mDay);
    }
    return null;
}

protected void onPrepareDialog(int id, Dialog dialog) {
    switch (id) {

    case DATE_DIALOG_ID:
        ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
        break;
    }

}

// SET THE DATE FORMAT ALREADY USER SELECT FROM THE DATEPICKER
private void updateDisplayFrom() {
    edit_eventFrom.setText(new StringBuilder()
            // Month is 0 based so add 1
            .append(mDay).append("-").append(mMonth + 1).append("-")
            .append(mYear).append(""));
}

private DatePickerDialog.OnDateSetListener mDateSetListenerFrom = new DatePickerDialog.OnDateSetListener() {

    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;
        updateDisplayFrom();
    }
};

Below is the new error that i get after even though i initialized the edit_eventName etc.
08-18 01:09:56.764: E/AndroidRuntime(977): FATAL EXCEPTION: main
08-18 01:09:56.764: E/AndroidRuntime(977): java.lang.IllegalArgumentException: current should be >= start and <= end
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.widget.NumberPicker.setCurrent(NumberPicker.java:288)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.widget.DatePicker.updateDaySpinner(DatePicker.java:364)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.widget.DatePicker.updateSpinners(DatePicker.java:350)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.widget.DatePicker.init(DatePicker.java:346)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.app.DatePickerDialog.<init>(DatePickerDialog.java:124)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.app.DatePickerDialog.<init>(DatePickerDialog.java:83)
08-18 01:09:56.764: E/AndroidRuntime(977):  at com.stts.sparetimetradingsystem.employer.EditEventActivity.onCreateDialog(EditEventActivity.java:527)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.app.Activity.onCreateDialog(Activity.java:2472)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.app.Activity.createDialog(Activity.java:881)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.app.Activity.showDialog(Activity.java:2547)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.app.Activity.showDialog(Activity.java:2514)
08-18 01:09:56.764: E/AndroidRuntime(977):  at com.stts.sparetimetradingsystem.employer.EditEventActivity$5.onClick(EditEventActivity.java:245)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.view.View.performClick(View.java:2408)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.view.View$PerformClick.run(View.java:8816)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.os.Handler.handleCallback(Handler.java:587)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.os.Handler.dispatchMessage(Handler.java:92)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.os.Looper.loop(Looper.java:123)
08-18 01:09:56.764: E/AndroidRuntime(977):  at android.app.ActivityThread.main(ActivityThread.java:4627)
08-18 01:09:56.764: E/AndroidRuntime(977):  at java.lang.reflect.Method.invokeNative(Native Method)
08-18 01:09:56.764: E/AndroidRuntime(977):  at java.lang.reflect.Method.invoke(Method.java:521)
08-18 01:09:56.764: E/AndroidRuntime(977):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-18 01:09:56.764: E/AndroidRuntime(977):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-18 01:09:56.764: E/AndroidRuntime(977):  at dalvik.system.NativeStart.main(Native Method)

A: It seems as though you have not initialized edit_eventFrom anywhere in the code you posted.
You will need to inflate that View from your layout, like you did your other Views:
edit_eventSpinner = (Spinner) findViewById(R.id.edit_spinner);
btnSaveEvent = (Button) findViewById(R.id.btnSaveEvent);
btnDeleteEvent = (Button) findViewById(R.id.btnDeleteEvent);
edit_error = (TextView) findViewById(R.id.edit_error);

And as swayam mentioned, you will need to do this for any View you are wanting to use in your code.

swayam
Similarly, initialize all the following EditText views before using in your code

Second Error

IllegalArgumentException: current should be >= start and <= end

You need to initialize mYear, mDay and mMonth to some default or whatever value you want.
Reference for this solution.

A: You are missing the initialization of the EditText views with reference to your XML.
EditText edit_eventName = (EditText) findViewById(R.id.idOfThisEditTextInYourXML);
EditText edit_eventFrom = (EditText) findViewById(R.id.idOfThisEditTextInYourXML);

Similarly, initialize all the following EditText views before using in your code :
            edit_eventCName
            edit_eventSalary
            edit_eventFrom
            edit_eventTo
            edit_eventWHFrom
            edit_eventWHTo

You are also missing the initializations for mDay, mMonth and mYear. You need to assign some values(integers) to them.
private int mYear = 2012; // example value
private int mMonth = 7; // example value
private int mDay =17; // example value


text:
Q: OAuth2 for Exchange server 2013, 2016 and Office 365 Can anyone help me on how do I connect to Exchange server (need to connect to 2013, 2016 and Office 365 based on the user account) and get the emails of a User in that Exchange server via OAuth2?
I have gone through few articles describing it
Here are the list of them
1. https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/
2. https://msdn.microsoft.com/en-us/library/office/dn626019(v=exchg.150).aspx
But I'm bit confused, as those articles are implying different procedures to implement for Exchange 2013, 2016 and Office 365.
I needed a "Client Credential Flow" of OAuth2 to connect to them. But I wanted to have a Single server to server application which can talk to 2013, 2016 and Office 365
Thank you

A: As the 2nd article you linked to says, OAuth2 is only an option for Exchange Online (aka Office 365).


text:
Q: How can I detect when a draggable circle shape overlaps another circle shape with KineticJS? I have a draggable circle shape that the user drags to another circle shape [static, non-draggable]. When the draggable circle overlaps the static circle, I need to display a "Success" text. How can I do so ?

A: When the user drags the circle, you can handle the "dragmove" events.
In "dragmove": test whether the circles are colliding.  If so, then declare success!
Circle1.on("dragmove",function(){
    if(theyAreColliding(Circle1,Circle2)){
        // Success!
    }
});

The test for collision looks like this:
function theyAreColliding(c1,c2){
    var dx=c1.getX()-c2.getX();
    var dy=c1.getY()-c2.getY();
    var radiiSum=c1.getRadius()+c2.getRadius();
    console.log(dx+"/"+dy+": "+radiiSum);
    return((dx*dx+dy*dy)<radiiSum*radiiSum);
}

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/3dQpL/
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Prototype</title>


text:
Q: Stack Exchange Android app keeps replaying notifications Version of the app: 1.0.51. (It is up to date at the time of writing according to Google Play.)
This started happening after the network problem that happened earlier this morning. Both my tablet and my phone are popping up notifications for events (comments, and probably edits too) that happened prior to the network issue. I had received notifications for these events already and had already cleared them before the network issue happened.
The repeated notifications do not show up in the bar displayed at the top of the Stack Exchange sites. In other words, I get notified again in Android but do not get notified again on the SE web sites.

A: We had quite a lot of push notifications queued up for some users, our push notification service went down over the weekend when we were testing out a fail-over to our secondary data-center. This seems to have caused some duplicated push notifications to be sent out, sorry about that. All should be well now.

A: A possible workaround if you want to stop the flow of stale notifications but still keep notified about new stuff: an upgrade may stop the old notifications.
The version of the app on my phone was a bit behind. After I upgraded it, I stopped getting notifications about old events on my phone. I know the upgrade stopped the flow of stale notifications on my phone because my tablet kept getting the stale notifications.
My tablet was at the latest version. A force close did not fix the issue. I uninstalled and reinstalled. This did not fix the problem.


text:
Q: Confirmation: does "Cocoa-Touch framework" only support for iOS8 or later? Refer to the title, how about my app running in iOS7 if my deployment target is iOS7? Will it crash or throw some unexpected runtime error?
Currently I got the following error:
ld: embedded dylibs/frameworks are only supported on iOS 8.0 and later (@rpath/MyFramework.framework/MyFramework) for architecture x86_64


text:
Q: Date range by week number Golang With this simple function, I can get the week number. Now, with the number of the week, how can I get the date range, started on Sunday?
import (
    "fmt"
    "time"
)
func main() {
    Week(time.Now().UTC())
}

func Week(now time.Time) string {
    _, thisWeek := now.ISOWeek()
    return "S" + strconv.Itoa(thisWeek)
}

A: The following does the work of finding the first day of week for me, although not from week number but from time. If you add an extra parameter - for the hard-coded time.Monday - that can be any day of week, e.g. Sunday.
func weekStartDate(date time.Time) time.Time {
    offset := (int(time.Monday) - int(date.Weekday()) - 7) % 7
    result := date.Add(time.Duration(offset*24) * time.Hour)
    return result
}

Test:
    func TestWeekStartDate(t *testing.T) {
        date := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
        for i := 0; i < 2000; i++ {
            weekStart := weekStartDate(date)
            log.Printf("%s %s", date.Format("2006-01-02 Mon"), weekStart.Format("2006-01-02 Mon"))
            assert.NotNil(t, weekStart)
            assert.Equal(t, time.Monday, weekStart.Weekday())
            date = date.Add(24 * time.Hour)
        }
    }

Output:
...
2021/01/17 08:50:03 2020-12-15 Tue 2020-12-14 Mon
2021/01/17 08:50:03 2020-12-16 Wed 2020-12-14 Mon
2021/01/17 08:50:03 2020-12-17 Thu 2020-12-14 Mon
2021/01/17 08:50:03 2020-12-18 Fri 2020-12-14 Mon
2021/01/17 08:50:03 2020-12-19 Sat 2020-12-14 Mon
2021/01/17 08:50:03 2020-12-20 Sun 2020-12-14 Mon
2021/01/17 08:50:03 2020-12-21 Mon 2020-12-21 Mon
2021/01/17 08:50:03 2020-12-22 Tue 2020-12-21 Mon
2021/01/17 08:50:03 2020-12-23 Wed 2020-12-21 Mon
2021/01/17 08:50:03 2020-12-24 Thu 2020-12-21 Mon
2021/01/17 08:50:03 2020-12-25 Fri 2020-12-21 Mon
2021/01/17 08:50:03 2020-12-26 Sat 2020-12-21 Mon
2021/01/17 08:50:03 2020-12-27 Sun 2020-12-21 Mon
2021/01/17 08:50:03 2020-12-28 Mon 2020-12-28 Mon
2021/01/17 08:50:03 2020-12-29 Tue 2020-12-28 Mon
2021/01/17 08:50:03 2020-12-30 Wed 2020-12-28 Mon
2021/01/17 08:50:03 2020-12-31 Thu 2020-12-28 Mon
2021/01/17 08:50:03 2021-01-01 Fri 2020-12-28 Mon
2021/01/17 08:50:03 2021-01-02 Sat 2020-12-28 Mon
2021/01/17 08:50:03 2021-01-03 Sun 2020-12-28 Mon
2021/01/17 08:50:03 2021-01-04 Mon 2021-01-04 Mon
2021/01/17 08:50:03 2021-01-05 Tue 2021-01-04 Mon
2021/01/17 08:50:03 2021-01-06 Wed 2021-01-04 Mon
2021/01/17 08:50:03 2021-01-07 Thu 2021-01-04 Mon
2021/01/17 08:50:03 2021-01-08 Fri 2021-01-04 Mon
2021/01/17 08:50:03 2021-01-09 Sat 2021-01-04 Mon
2021/01/17 08:50:03 2021-01-10 Sun 2021-01-04 Mon
2021/01/17 08:50:03 2021-01-11 Mon 2021-01-11 Mon
2021/01/17 08:50:03 2021-01-12 Tue 2021-01-11 Mon
2021/01/17 08:50:03 2021-01-13 Wed 2021-01-11 Mon
2021/01/17 08:50:03 2021-01-14 Thu 2021-01-11 Mon
2021/01/17 08:50:03 2021-01-15 Fri 2021-01-11 Mon
2021/01/17 08:50:03 2021-01-16 Sat 2021-01-11 Mon
2021/01/17 08:50:03 2021-01-17 Sun 2021-01-11 Mon
2021/01/17 08:50:03 2021-01-18 Mon 2021-01-18 Mon
2021/01/17 08:50:03 2021-01-19 Tue 2021-01-18 Mon
2021/01/17 08:50:03 2021-01-20 Wed 2021-01-18 Mon
2021/01/17 08:50:03 2021-01-21 Thu 2021-01-18 Mon
2021/01/17 08:50:03 2021-01-22 Fri 2021-01-18 Mon
2021/01/17 08:50:03 2021-01-23 Sat 2021-01-18 Mon
2021/01/17 08:50:03 2021-01-24 Sun 2021-01-18 Mon
2021/01/17 08:50:03 2021-01-25 Mon 2021-01-25 Mon
2021/01/17 08:50:03 2021-01-26 Tue 2021-01-25 Mon
2021/01/17 08:50:03 2021-01-27 Wed 2021-01-25 Mon
2021/01/17 08:50:03 2021-01-28 Thu 2021-01-25 Mon
2021/01/17 08:50:03 2021-01-29 Fri 2021-01-25 Mon
2021/01/17 08:50:03 2021-01-30 Sat 2021-01-25 Mon
2021/01/17 08:50:03 2021-01-31 Sun 2021-01-25 Mon
2021/01/17 08:50:03 2021-02-01 Mon 2021-02-01 Mon
2021/01/17 08:50:03 2021-02-02 Tue 2021-02-01 Mon
2021/01/17 08:50:03 2021-02-03 Wed 2021-02-01 Mon
2021/01/17 08:50:03 2021-02-04 Thu 2021-02-01 Mon
2021/01/17 08:50:03 2021-02-05 Fri 2021-02-01 Mon
...

A: Thanks to @prajwal Singh, I've found more generic to find out the start and last day of the week w.r.t month, week, and year
func DateRange(week, month, year int) (startDate, endDate time.Time) {

    timeBenchmark := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)
    weekStartBenchmark := timeBenchmark.AddDate(0, 0, -(int(timeBenchmark.Weekday())+6)%7)

    startDate = weekStartBenchmark.AddDate(0, 0, (week-1)*7)
    endDate = startDate.AddDate(0, 0, 6)

    return startDate, endDate
}

A: Foreword: Time.ISOWeek() returns you the week number that starts on Monday, so I will answer your question that also handles weeks starting on Monday. Alter it to your needs if you want it to work with weeks starting on Sunday.
I released this utility in github.com/icza/gox, see timex.WeekStart().

The standard library does not provide a function that would return you the date range of a given week (year+week number). So we have to construct one ourselves.
And it's not that hard. We can start off from the middle of the year, align to the first day of the week (Monday), get the week of this time value, and corrigate: add as many days as the week difference multiplied by 7.
This is how it could look like:
func WeekStart(year, week int) time.Time {
    // Start from the middle of the year:
    t := time.Date(year, 7, 1, 0, 0, 0, 0, time.UTC)

    // Roll back to Monday:
    if wd := t.Weekday(); wd == time.Sunday {
        t = t.AddDate(0, 0, -6)
    } else {
        t = t.AddDate(0, 0, -int(wd)+1)
    }

    // Difference in weeks:
    _, w := t.ISOWeek()
    t = t.AddDate(0, 0, (week-w)*7)

    return t
}

Testing it:
fmt.Println(WeekStart(2018, 1))
fmt.Println(WeekStart(2018, 2))
fmt.Println(WeekStart(2019, 1))
fmt.Println(WeekStart(2019, 2))

Output (try it on the Go Playground):
2018-01-01 00:00:00 +0000 UTC
2018-01-08 00:00:00 +0000 UTC
2018-12-31 00:00:00 +0000 UTC
2019-01-07 00:00:00 +0000 UTC

One nice property of this WeekStart() implementation is that it handles out-of-range weeks nicely. That is, if you pass 0 for the week, it will be interpreted as the last week of the previous year. If you pass -1 for the week, it will designate the second to last week of the previous year. Similarly, if you pass max week of the year plus 1, it will be interpreted as the first week of the next year etc.
The above WeekStart() function only returns the given week's first day (Monday), because the last day of the week is always its first day + 6 days.
If we also need the last day:
func WeekRange(year, week int) (start, end time.Time) {
    start = WeekStart(year, week)
    end = start.AddDate(0, 0, 6)
    return
}

Testing it:
fmt.Println(WeekRange(2018, 1))
fmt.Println(WeekRange(2018, 2))
fmt.Println(WeekRange(2019, 1))
fmt.Println(WeekRange(2019, 2))

Output (try it on the Go Playground):
2018-01-01 00:00:00 +0000 UTC 2018-01-07 00:00:00 +0000 UTC
2018-01-08 00:00:00 +0000 UTC 2018-01-14 00:00:00 +0000 UTC
2018-12-31 00:00:00 +0000 UTC 2019-01-06 00:00:00 +0000 UTC
2019-01-07 00:00:00 +0000 UTC 2019-01-13 00:00:00 +0000 UTC

A: Thanks to @icza for the solution, found a way to simplify it even further in terms of logic:
func DateRange(week, year int) (startDate, endDate time.Time) {
    timeBenchmark := time.Date(year, 7, 1, 0, 0, 0, 0, time.UTC)
    weekStartBenchmark := timeBenchmark.AddDate(0, 0, -(int(timeBenchmark.Weekday())+6)%7)

    _, weekBenchmark := weekStartBenchmark.ISOWeek()
    startDate = weekStartBenchmark.AddDate(0, 0, (week-weekBenchmark)*7)
    endDate = startDate.AddDate(0, 0, 6)

    return startDate, endDate
}

Works fine as well.


text:
Q: Padding for WinForms TreeView In a WinForms application I have a custom button positioned on top of a TreeView. In certain scenarios the button will hide the bottom content from the TreeView:

I'm looking for a way to invisibly inflate the TreeView-height in the bottom in order to trigger the scroll bar earlier, and am open for other suggestions, too.

A: I have done a similar thing with buttons at the top:

I used a UserControl with a TreeView docked to fill and a Panel docked to the top. (In your case, dock the panel to the bottom.) I set TreeView.BorderStyle = None and used another Panel to look like a border with 1px padding all around, which hosts the button panel and tree. You can make the tree public or expose it via a property. With docking you can also hide the button panel as necessary, and the tree will automatically take up the remaining space. I also used a Label docked to the bottom inside the button panel to act as a visual separator.


text:
Q: nodejs jugglingdb belongsTo and hasMany relations with existing db objects jugglingdb exposes two functions to create relational dbs:
belongsTo
and
hasMany
i now aks myself how i might use this in daily development.
belongsTo and hasMany are adding functions to the objects,
but as it seems there is no way to create relations between existing objects?
see:
http://compoundjs.com/juggling.html#hasMany
for an example.
i would like to not create the object but instead create linkages between existing objects,
how will that work?
maybe i am just misinterpreting the functions?
have fun
jascha
ps:
would be great if someone with 1500+ rep could create the jugglingdb tag and add it to this question? i really cant say if its relevant enough though.

A: When you, i.e. want to add articles for an existing author, you can do it like the following:
User.find(uid, function(err, user) {
        var article = user.articles.build({articleName : 'Article Foo'});
        article.save();
});

That will automatically create a foreign key for user inside the new created article.


text:
Q: About test for diagonalizability. Question about $\operatorname{rank}(T-\lambda I)$
"Let T be a linear operator on an n-dimensional vector space V. Then T is diagonalizaable if and only if:
1).The characteristic polynomial T splits.
2). For each eigenvalue $\lambda$ of T, the multiplicity of $\lambda$ equals $n-\operatorname{rank}(T-\lambda I)$

Question: Is $\operatorname{rank}(T-\lambda I)$ the dimension of the eigenspace which makes up the eigenvectors? Why does $n-\operatorname{rank}(T-\lambda I)$ have to equal the multiplicity?

A: Represent $T$ by a matrix $A.$ Then $T- \lambda I$ is represented by $A- \lambda I$. For any $m \times n$ matrix $B$ the dimensiion of the solution space of $B$ is $n-\text {rank} (B)$. So all that the second condition is saying is that the algebraic multiplicity of the eigenvalue $\lambda$ equals the dimension of the corresponding eigenspace.


text:
Q: How should I configure grub for booting linux kernel from a USB hard drive? I have a laptop hard drive in an external enclosure which I use as a large pendrive. For an added twist, I have installed Linux on it, so I can boot any machine with my distribution of choice (e.g. for data recovery or repairing a b0rked system or just using a borrowed laptop without destroying the preinstalled Windows).
The problem is that, depending on the hardware configuration, the USB hard drive may be visible under different paths. For grub configuration, I just use (hda0,0) as it is relative to the device the grub was launched from. I have UUID entries in /etc/fstab. I also specify rootwait in the kernel parameters so that it waits for the USB subsystem to settle down before trying to mount the device.
What should I pass to the kernel as root=? Currently, boot from the pendrive once, check the debug messages to see what /dev/sdX device has been assigned to the USB drive by the kernel, then reboot and edit the grub configuration. I can't change anything on the PC besides enabling Boot from USB hard drive in BIOS and setting it to a higher priority than internal hard drives.
There are various initrd generating scripts that include support for UUID in root device path, unfortunately, the Gentoo native one (genkernel) does not support rootwait and I had no luck trying to use others.
The boot process goes like this (it is quite similar in Windows):

*

*The BIOS chooses the boot device and loads whatever is its MBR (which happens to be grub stage-1).

*Grub loads it's configuration and stage-2 files from the device it has set as root, using (hd0) for the device it was loaded from by BIOS.

*Grub loads and starts a kernel (still the same numbering, so I can use (hd0,0) again ).

*The kernel initializes all built-in devices (rootwait does it's magic now).

*The kernel mounts the partition it was passed as root (this is a kernel parameter, not grub parameter).

*init.d starts the userland booting process, including mounting things from /etc/fstab.

Part 5 is the one giving me problems.

A: I think the answer should be to use either root=LABEL=... or root=UUID=...
But you indicate that this doesn't work for you. I would suggest looking into if there is some problem with the actions of your initrd.

A: You can use:
set root='(hd0,msdos5)'

A: I could be mistaken or possibly just misunderstanding you, but isn't choice of boot device something that would be configured from the BIOS of the machine you're booting?
I would think it would be a matter of choosing the USB drive, which would have GRUB installed as its bootloader, and then choosing which distro you want to boot from the GRUB menu.


text:
Q: How does the platform default character encoding affect cross platform performance I have read that its bad idea to use platform default character encoding for example when reading a text file and importing the text into arrays etc. Could you explain how that could affect cross platform performance , and how to get past that problem ? Is there an encoding that should be used for cross-platform applications ? Thanks

A: It's not about performance, but about showing and reading properly encoded text. There are a number of ways to cope with the problem:

*

*set a JVM option -Dfile.encoding=utf-8

*always use the methods overloaded with a character encoding parameter. These are the ones of String, Reader, Writer and more.

I think the latter is a must. If you always set the jvm option, it will work, but if you forget to set it at some point, there will be unexpected failures at random places.
And the other question - stick to UTF-8.
See also this question.

A: Usually its no problem, if the read and written files are not exchanged between platforms. But if you have e.g. a configuration file created on windows (Win1252, similar to ISO8859-1 encoding), and then start your app on a recent linux (UTF-8 encoding), the config file will have problems with nearly all chars above 127 (like german Umlauts ä, ö, ü, or the € sign, or similar characters).
In this case just specify that you always use either encoding, and stick with it. If you only use plain ASCII (non latin extended!) files, you won't have problems so far.

A: The default encoding varies from OS to OS and even between users on the same machine in the case of some multilingual installs. This means that character data written by the application will vary and not be readable/appear corrupt if read using a different default encoding. The Euro character (€) will encode as the bytes 80 under windows-1252, A4 under ISO-8859-15 and E2 82 AC under UTF-8.
Legacy encodings can cause data loss since many of them only support a narrow range of code points.
The only supported way to change the default encoding is to change it in the operating system.
It is generally better to be explicit in choosing encodings and prefer a lossless Unicode encoding (usually UTF-8.) The decision to make "ANSI" encodings the default on Windows, for example, made more sense when when supporting Windows 95.


text:
Q: why is Socket.io is very slow on windows? I recently noticed that Socket.io has become really really slow on windows. I noticed this when I opened two tabs and tried emitting events. It took more than 15 seconds to receive a response from server. Server Coded on NodeJS.
Environment:
Windows 10 Pro
Electron Socket.io-Tester
Socket.io - Version 2.0.4

A: I'm having this exact problem.  Used to work fine on Windows (and still does on MacOS), now emits are just getting lost in lag, as much as 5 seconds.  This only happens when a 2nd or more connection has been made to the server - as I'm developing a multi player game this is pretty important.  The emit event works fine and you can see it in the frame, its just taking forever for the server to respond.
After much experimentation, I can safely conclude this is a problem with NodeJS LTS itself.  THIS IS WORKING IN v6.13.1, but not for later versions (not sure where it starts, and not going to bother incrementally upgrading Node).
Downgrade node to safely address this issue.  Fun.

A: In your code are there any proxies? That can sometimes muddle things up a bit.
If there are proxies I found a gist related to a "Socket is slow issue" that was due to proxies. This Gist was a "Fix" to the issue maybe it will help. This snippet is the proxy config.
    var server = http_m.createServer(function(req, res) {
    switch(req.headers.host) {
    case "ws.app.com":
        handle_ws(req, res);
        break;
    case "api.app.com":
        handle_api(req, res);
        break;
    default:
        handle_error(req, res);
        break;
    }
});

server.on("upgrade", handle_ws_upgrade);
server.listen(80);


text:
Q: Hostname appearing in email header I use Postfix as SMTP Server and I don't want my server hostname to appear in the email header, what changes should I do?
As you can see in the code bellow, here is the hostname: server1.example.com
Here is the full header:
Received: from server1.example.com (example.com [My Ip(111.11.111.11)])
Delivered-To: myemail@gmail.com
Received: by 10.150.95.9 with SMTP id s9cs39975ybb;
        Tue, 12 Oct 2010 10:04:11 -0700 (PDT)
Received: by 10.142.128.14 with SMTP id a14mr6566111wfd.384.1286903051027;
        Tue, 12 Oct 2010 10:04:11 -0700 (PDT)
Return-Path: <user@example.com>
Received: from server1.example.com (example.com [My Ip(111.11.111.11)])
        by mx.google.com with ESMTP id y15si19129610wfd.52.2010.10.12.10.04.10;
        Tue, 12 Oct 2010 10:04:11 -0700 (PDT)
Received-SPF: pass (google.com: domain of user@example.com designates 111.11.111.11 as permitted sender) client-ip=111.11.111.11;
Authentication-Results: mx.google.com; spf=pass (google.com: domain of user@example.com designates 111.11.111.11 as permitted sender) smtp.mail=user@example.com
Received: by server1.example.com (Postfix, from userid 2523)
 id D33A612980A1; Tue, 12 Oct 2010 17:04:09 +0000 (UTC)
subject: Hello
Message-Id: <20101012170409.D33A612980A1@server1.example.com>
Date: Tue, 12 Oct 2010 10:03:49 -0700 (PDT)
From: user@example.com
To: undisclosed-recipients:;

A: You could change the helo_name setting but, as noted by DandyPandy, receiving SMTP servers will still reverse look-up your MTA's IP address and make note of it.
http://www.manpagez.com/man/5/postconf/

A: You can't help that. All you can do is configure your server to advertise another name. Sometimes, please use white-label domains that give no clear indication of who they're coming from. That's the standard though and that part of the header is being put there by the receiving server (gmail).


text:
Q: Why am I getting a 400 error, as I try to deploy my app from netbeans? While trying to deploy my google app engine application from netbeans I get the following error :
com.google.appengine.tools.admin.HttpIoException: Error posting to URL: https://appengine.google.com/api/appversion/create?app_id=programworks&version=1&
400 Bad Request
Java 6 applications are prevented from being deployed to Google App Engine from any version of the SDK, including older ones. If you need to continue to deploy Java 6 applications for compatibility reasons, you can request that your application be whitelisted for Java 6 deployment by visiting http://goo.gl/ycffXq.

Unable to update app: Error posting to URL: https://appengine.google.com/api/appversion/create?app_id=programworks&version=1&
400 Bad Request
Java 6 applications are prevented from being deployed to Google App Engine from any version of the SDK, including older ones. If you need to continue to deploy Java 6 applications for compatibility reasons, you can request that your application be whitelisted for Java 6 deployment by visiting http://goo.gl/ycffXq.

What is this error all about ? I am using java 7 as my library.

A: Create a new small Java 7 project that deploys and runs successfully. Copy your existing application content into the new project. Rename the old project to use it as an archive. Rename the new project to use the original project name and application id. (originally this answer to this question).


text:
Q: delete request ajax jquery don't function I'm trying to do a DELETE request with Ajax, but it doesn't function,I receive an internal error, but i can't see the problem, can you help me?
this is the partial code of javascript:
$.ajax({
    url: 'http://localhost:8080/actors/remover',
    type: 'DELETE',
    data: JSON.stringify(movie),
    traditional:true,
    dataType: 'json',
    success: function(result) {...},
    error: function(result){...}
});

and here the code of my controller:
@RequestMapping(value = "/actors/remover", method = RequestMethod.DELETE)//TODO, elimina un attore dal db
public boolean remove(@PathVariable("movie") int movie) {
    System.out.println("Attori da cancellare");
    serv.deleteActors(movie);
    return true;
}//remove

A: Problems i see in your code:

*

*dataType:'json' is used if you get your response as a json object.

*At the backend you are not producing json at all but there is a boolean.

*You have to use contentType:'application/json'.

*And there is no need to use traditional:true.

So i suggest you to use this:
$.ajax({
    url: 'http://localhost:8080/actors/remover',
    type: 'DELETE',
    data: {movie:movie}, //<-----this should be an object.
    contentType:'application/json',  // <---add this
    dataType: 'text',                // <---update this
    success: function(result) {...},
    error: function(result){...}
});


text:
Q: background image missing in slides ionic rc 2 My intention is to have a slide with Background image but the Background image is missing in ion-slide.background image is working fine in other pages.the following is the code.......
typescript

import { Component } from '@angular/core';
import { ModalController, MenuController, NavController } from 'ionic- angular';
import { ViewController } from 'ionic-angular';
// import { RegistrationPage } from '../event-create/event-create';
import { LinkToRegistration } from '../about/about';
import { ModalPage } from '../modal/modal';
import { UserData } from '../../providers/user-data/user-data';
 // import * as moment from 'moment';
 // import * as firebase from 'firebase';
 declare var firebase: any;
 export interface Slide {
  title: string;
  description: string;
  //image: string;
 }
@Component({
templateUrl: 'tutorial.html'
})
export class TutorialPage {
slides: Slide[];
showSkip = true;
public time: any[] = [];
amp = "";
count = 0;
aseats = 0;
gathering = 0;
start = 0;
sfix ="";
date = 0;
constructor(public navCtrl: NavController, public menu: MenuController,
public modalCtrl: ModalController, public viewCtrl: ViewController, public    userData: UserData) {
  //   this.navCtrl = navCtrl;
  var db = firebase.database();
 // var ref = db.ref("dcuser");
  var time = db.ref("dcsession details");

// date and time==================
  time.on("child_added", (snap)=>{
// this.count++;
// var active = db.ref('dcsession details/'+session+'/UserGroup);
    console.log("added:", snap.key);
    if(snap.val().SessionStatus == "Active")
    {   var session = snap.key;
        var active = db.ref('dcsession details/'+session+'/UserGroup');
       // ===================================================testing

          active.on('child_added', (spsnapshot) => {
          if(spsnapshot.val().UserSessionStatus == "Active")
          {
               this.count++
          }
    }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
});
   // ==========================================================================testing
        console.log("sessionid:"+session);
        this.userData.setsession(session);
        this.time.push({date: snap.val().Date, start: snap.val().StartingTime, aseats: snap.val().AllottedSeats });
        this.aseats = snap.val().AllottedSeats;
        this.gathering = snap.val().GatheringCount;
        if(this.gathering == 1)
        {
          this.sfix = "st";
        }else if(this.gathering == 2)
        {
          this.sfix = "nd";
        }else if(this.gathering == 3)
        {
          this.sfix = "rd";
        }else
        {
          this.sfix = "th";
        }
        this.date = snap.val().Date;
        this.start = snap.val().StartingTime ;
      // var hours = this.start.getHours() % 12 || 12;  // 12h instead of 24h, with 12 instead of 0.
        this.amp = this.start >= 12 ? 'PM' : 'AM';
        console.log("hor"+this.start);
        console.log("Date"+this.date);
        console.log("ampm"+this.amp);
        console.log("asets"+this.aseats);
    }

    console.log("time:",JSON.stringify(this.time));
 });

//     ==============================

this.slides = [
{
  title: '',
  description: ' ',
  // image: 'assets/img/ica-slidebox-img-1.png',
}
];
 }
 presentModal() {
  let modal = this.modalCtrl.create(ModalPage);
modal.present();
}
 dismiss() {
 this.viewCtrl.dismiss();
}

startApp() {
  console.log("btton click detected");
  this.viewCtrl.dismiss();
  this.navCtrl.push(LinkToRegistration);
}
onSlideChangeStart(slider) {
  this.showSkip = !slider.isEnd;
}
ionViewDidEnter() {
// the root left menu should be disabled on the tutorial page
  this.menu.enable(false);
}

 ionViewWillLeave() {
 // enable the root left menu when leaving the tutorial page
  this.menu.enable(true);
}
}
// modal content

scss file===========================================
.tutorial-page {
  .toolbar-background {
    background: #4795e2;
    border-color: transparent;
  }

.dcslide-img1{
     //background: url('../../img/Slides_slide1_WOdots.svg');
     //  background-color: blue;
    background: url('../assets/img/Slides_slide1_WOdots.svg') no-repeat center center fixed;
       -webkit-background-size: cover;
       -moz-background-size: cover;
        background-size: cover;
  }
  .dcslide-img2{
    //background: url('assets/img/Slides_slide2_wWOdots.svg');
      background-color: blue;
   background: url('../assets/img/Slides_slide2_wWOdots.svg') no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      background-size: cover;
  }
  .dcslide-img3{
   // background: url('../../img/Slides_Slide3_WOdots.svg');
     background-color: blue;
     background: url('../assets/img/Slides_Slide3_WOdots.svg') no-repeat center center fixed;
       -webkit-background-size: cover;
      -moz-background-size: cover;
      background-size: cover;
  }
  .dcslide-header-title{
    font-size: 12px;
    color:#a8d4ff;//#2975c0;
    margin-top: 3px;
    padding: 10px;
    font-size: 14px;
    text-align: left;
  }
  .dcslide-aloava-value{
      font-size: 45px;
      color: #ffffff;//#044a8e;
      font-weight: bold;
  }
  .dcslide-aloava-text{
      font-size: 15px;
      color:#FFEB3B;//#2975c0;
      text-transform: lowercase;
  }
  .dc-name{
    text-align:center;
    font-weight:bold;
    margin-top: 40px;
    color:#ffffff
  }
  .dc-name-p{
    text-align:center;color:#003061;text-transform: lowercase;
  }
  .dcslide-badge{
    font-size: 18px;
  }
  .dcslide-heart-icon{
    color: #96ffa2;margin-right: 1px;margin-top: 5px; margin-bottom: 5px;
  }
  .dcslide-pepole-icon{
    color: #ff4848;
    margin-right: -1px;
    margin-top: 0px;
    margin-bottom: 2px;
    font-size: 18px !important;
  }
  .card-header{
    font-size: 18px;
    text-align: left;
    color: #fff;
  }

  .slide-zoom {
    height: 100%;
  }

  .dc-count-panel{
        background-color: #0A6BC8;//rgb(150, 203, 255);//rgba(255, 255, 255, 0.1);
  }
  .slide-title {
    margin-top: 2.8rem;
  }

  .slide-image {
    max-height: 50%;
    max-width: 60%;
    margin: 36px 0;
  }

    .image-holder {
        display:inline-block;
        position: relative;
    }
    .image-holder:after {
        content:'';
        top: 0;
        left: 0;
        z-index: 10;
        width: 100%;
        height: 100%;
        opacity: 0.7;
        display: block;
        position: absolute;

        background: linear-gradient(141deg, #0fb8ad 0%, #1fc8db 51%, #2cb5e8 75%);
    }
    .image-holder:hover:after {
        opacity: 0;
    }
  //slide 2
  .item-inner{
        border-bottom: 0px solid #dedede;
  }
  ion-badge{
        padding: 1px 5px !important;
        background-color: #0a6bc8 !important;
        color: #ffffff !important;
  }
  .hed-transparent{
   background: transparent !important;
  }
 .swiper-container-horizontal > .swiper-pagination{
    bottom: 50%;
    left: 3px;
    width: 0;
 }
 .join-monthly-btn{
   margin: 0;
   height: 5.6rem;
   font-size: 2rem;
   background-color: #044f78;
 }
 .dcslide-time{
   font-size: 55px;
   color: #ffffff;
 }
 .dcslide-ampm{
   color: #96cbff;
 }
 .dcslide-date{
   font-size: 18px;
   margin-left: -10px;
   color: #012548;
 }
  .fab-footer {
    z-index: 99;
  }
  .button-dark{
           color: #0a6bc8;
    background-color: rgba(255, 255, 255, 0.65);
    font-size: 1.4em;
  }
  .bar-footer {
    //background: url(../../img/footer-wireframe.png) repeat-x;
    height: 2px;

    position: absolute;
    right: 0;
    bottom: 44px;
    left: 0;
  }

  b {
    font-weight: 500;
  }

  p {
    padding: 0 40px;
    font-size: 14px;
    line-height: 1.5;
    color: #60646B;

    b {
      color: #000000;
    }
  }

}

Html file ================================
<ion-header no-shadow>
</ion-header>

<ion-content>
  <ion-slides [options]="{pager: true}" (ionWillChange)="onSlideChangeStart($event)">
     <ion-slide class="dcslide-img1">
      <ion-grid class="dc-count-panel">
        <ion-row>
          <ion-col width-26>

                 Creative's {{gathering}}{{sfix}} Monthly Gathering

          </ion-col>
          <ion-col width-35>

{{aseats}}

Allocated Seats

          </ion-col>
          <ion-col width-35>

{{ aseats-count }}

Available Seats

          </ion-col>
        </ion-row>
      </ion-grid>

CREATIVES /

         <ion-icon name="quote"></ion-icon>
            WAS ESTABLISHED TO SPREAD AWARENESS ABOUT VARIOUS ARTS AND RAISE THE CEILING OF CREATIVITY AMONG CREATIVES IN .
         <ion-icon name="quote"></ion-icon>

      <button ion-button icon-only fab dark fab-bottom fab-center class="fab-footer" (click)="presentModal()">
        <ion-icon name="finger-print" is-active="false"></ion-icon>
      </button>

    </ion-slide>
    <ion-slide class="dcslide-img2">
      <ion-item class="hed-transparent">
          <ion-badge item-right>
            <ion-icon name="people" class="dcslide-heart-icon" item-left></ion-icon>
           {{ aseats-count }}/{{aseats}} </ion-badge>
      </ion-item>
    </ion-slide>
    <ion-slide class="dcslide-img3">
     <ion-item class="hed-transparent">
          <ion-badge item-right>
            <ion-icon name="people" class="dcslide-heart-icon" item-left></ion-icon>
           {{ aseats-count }}/{{aseats}} </ion-badge>
      </ion-item>

{{start}}
        {{amp}}

{{date| date:'EEE, MMMM dd'}}

      <ion-footer>
        <button ion-button icon-right block (click)="startApp()" class="join-monthly-btn">

          Join monthly gathering
          <ion-icon name="arrow-forward"></ion-icon>
        </button>
      </ion-footer>
    </ion-slide>
  </ion-slides>
</ion-content>

A: Try to write the full img URL in CSS without any ../ , and check if that helps bring back the missing background image.
background: url('FULL URL');

A: Create a variable with the path for background image under variables.scss and use the variable in whatever file you wish to use.
Variables.scss
$bg : "../assets/img/Slides_slide2_wWOdots.svg";

Your Scss file
.dcslide-img1{
    background: url($bg) no-repeat center center fixed;
}


text:
Q: node-gyp serialport build error on Raspberry Pi 4 I have a nodejs electron app running on a Raspberry Pi 4.  The latest raspberry pi OS will not build the application (and older OS versions will not run on the latest hardware.)  I fairly sure this centers on the serialport package.  I have tried building a bare-bones electron app with just the serialport package and it does not work either.  Is this a system configuration issue or package version(s)?  I have tried Node 12, 14, & 16; serialport 9 & 10...?
I get the following error when doing npm i:
> usb@2.5.0 install /home/myapp/myapp/node_modules/usb
> node-gyp-build

> lzma-native@8.0.6 install /home/myapp/myapp/node_modules/lzma-native
> node-gyp-build

gyp ERR! configure error
gyp ERR! stack Error: Command failed: /usr/bin/python -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                       ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:308:12)
gyp ERR! stack     at ChildProcess.emit (events.js:314:20)
gyp ERR! stack     at maybeClose (internal/child_process.js:1022:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5)
gyp ERR! System Linux 5.15.56-v7l+
gyp ERR! command "/home/myapp/.config/nvm/versions/node/v12.22.12/bin/node" "/home/myapp/myapp/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/myapp/myapp/node_modules/lzma-native
gyp ERR! node -v v12.22.12
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN myapp-app@1.3.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: appdmg@0.4.5 (node_modules/appdmg):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for appdmg@0.4.5: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"arm"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! lzma-native@8.0.6 install: `node-gyp-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the lzma-native@8.0.6 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/myapp/.npm/_logs/2022-08-26T13_57_08_118Z-debug.log

The error message is some string interpolation in a python script printing version info...

A: After further investigating (using Node@16 & serialport@10), springing from this line:
node-gyp -v v3.8.0
I installed node-gyp locally:
npm i node-gyp@latest -D
...and that clears this install error.  Other packages depend on older versions of node-gyp which is causing runtime problems but this particular issue is cleared...


text:
Q: Swift4 JSONDecoderExpected to decode Dictionary but found an array instead I'm pretty newbie with this, but I've been attempting to work out how JSONDecoder works for a login function that needs to retrieve data from a MySQL database, as shown in my code below and am receiving this error.
Swift Code:
func testParseJson(){

                var request = URLRequest(url: URL(string: "https://test.php")!)
        request.httpMethod = "POST"

        let postString = ("Email=test&Password=test")
        print(postString)
        request.httpBody = postString.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data else { return }
            do {
                var responseString = String(data: data, encoding: .utf8)!
                print("new response string \(responseString)")
                let decoder = JSONDecoder()
                let newData = try decoder.decode(User.self, from: data)
                print(newData.Email)
                print(newData.UserType)
            } catch let err {
                print("Err", err)
            }
            }.resume()
    }

Temporary Struct I have been attempting to use:
struct User: Decodable {
 let U_ID: String
 let Email: String
 let Password: String
 let UserType: String

private enum CodingKeys: String, CodingKey {
    case U_ID
    case Email
    case Password
    case UserType
 }
}

And the JSON response string reads:
[{"U_ID":"1",
"Email":"test",
"Password":"test",
"UserType":"Teacher"}]

Any help would be massively appreciated.

A: Here, JSON data is Array of Objects.
change
try decoder.decode(User.self, from: data)

to
try decoder.decode(Array<User>.self, from: data)

Example:
var users = [User]()

let data = """
[{"U_ID":"1","Email":"test","Password":"test","UserType":"Teacher"}]
""".data(using: .utf8)

do{
    users = try JSONDecoder().decode(Array<User>.self, from: data!)
}catch{
    print(error.localizedDescription)
}

print(users.first?.Email)

Note: For better understanding, this is my video series about JSON parsing in swift 4


text:
Q: A proposed solution of projectile's height and range projectile

Point shoot by initial velocity $v_0=600m/s$ along the direction with the angle about horizontal plane $\alpha =45{}^{\circ}$. Solve for the maximum height and the range(assuming $g\approx 10m\left/s^2\right.$,without air resistance).
$v_x=v_0\text{Cos}[\alpha ]$
$S=v_xt=v_0\text{Cos}[\alpha ]t=600 \frac{\sqrt{2}}{2}t$
$h=v_y(t/2)-\frac{1}{2}g (t/2)^2$
$v_y=v_0\text{Sin}[\alpha ]=g t/2$
$t=2\left.v_y\right/g=2\times 600\left.\frac{\sqrt{2}}{2}\right/10=60\sqrt{2}$
$S=300\sqrt{2}60\sqrt{2}=36000$
$h=\left(600\frac{\sqrt{2}}{2}\left(30\sqrt{2}\right)-\frac{1}{2}10\left(30\sqrt{2}\right)^2\right)$=9000
So Range=36000m, Height=9000m

Any problems?
My steps may be not so clear, how to improve the writing?


text:
Q: Dismiss a VC and return to a countdown on previous VC How can I get a VC to dismiss while returning to the previous VC which still displays the state after the START button was pressed (ie buttons still visible and countdown still going on etc.) as in this snippet.
 -(IBAction)startPressed:(id)sender
 {
// hide start UI
self.startButton.hidden = YES;
self.promptLabel.hidden = YES;

// show running UI
self.timeLabel.hidden = NO;
self.distLabel.hidden = NO;
self.paceLabel.hidden = NO;
self.stopButton.hidden = NO;
self.progressImageView.hidden = NO;
self.mapView.hidden = NO;
self.cameraButton.hidden = NO;

self.seconds = 0;

// initialize the timer
self.timer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(eachSecond) userInfo:nil repeats:YES];

self.distance = 0;
self.locations = [NSMutableArray array];

[self startLocationUpdates];

}
Currently the previous VC returns to the initial state with all buttons hidden and the START button ready to press again.
What kind of segue to the second VC is necessary so the countdown on the first VC continues and the second simply appears over it and is then dismissed without interfering with the stuff going on on the first one?


text:
Q: Passing an argument to git alias not working I created the following alias on Windows 10 to issue a commit -am <commit message> command. I used the the $1 token to register an argument, but it is not working.
git config --global alias.cam 'commit -am $1'
Issuing the following command returns the error message below:
git cam "test commit"
Error Message:
fatal: paths 'test commit ...' with -a does not make sense
How do I make this work? I researched how to use arguments in git aliases, but none of the resources offers a simple solution to my problem. Thanks.

A: This is the rule for Git beginners: do not use git commit -a.
This is the rule for advanced Git users: do not use git commit -a unless:

*

*you would run git add -u before git commit, and

*you know that the repository is not using a badly written pre-commit script that will misbehave in the presence of git commit -a.

From your comment:

@jthill That works, but now it just displays the untracked files when I issue git cam "test commit". Nothing is staged or committed. If I issue the add and commit commands separately, it works fine. Why is that?

The problem here is that git commit -a is not like git add followed by git commit.  It's more like git add -u followed by git commit (but even then, still not exactly the same).  Specifically, git add -u will only update files that Git already knows about.  The u in -u stands for update, i.e., don't add any untracked files, but do update all tracked ones as appropriate.
You have an untracked file that you'd like to add.  You must use git add without the -u option to do this.  (Technically there are several other commands that could get you there, but git add is the one to use.)

A: One solution is to pass the aliased git command to a shell command. This way, the $1 argument will not be appended again to the end of the command, causing it to succeed.
git config --global alias.cam '!sh -c "git commit -am $1"'
Or simply leave out the $1 argument token:
git config --global alias.cam '!git commit -am'
But, keep in mind that commit -a only applies to tracked files that need their modifications staged. So a better approach would be:
git config --global alias.cam '!git add . && git commit -m'


text:
Q: Documenting preprocessor defines in Doxygen Is it possible to document preprocessor defines in Doxygen? I expected to be able to do it just like a variable or function, however the Doxygen output appears to have "lost" the documentation for the define, and does not contain the define itself either.
I tried the following
/**My Preprocessor Macro.*/
#define TEST_DEFINE(x) (x*x)

and
/**@def TEST_DEFINE

   My Preprocessor Macro.
*/
#define TEST_DEFINE(x) (x*x)

I also tried putting them within a group (tried defgroup, addtogroup and ingroup) rather than just at the "file scope" however that had no effect either (although other items in the group were documented as intended).
I looked through the various Doxygen options, but couldn't see anything that would enable (or prevent) the documentation of defines.

A: In my "C" files, I use a comment format and #define line like this:
/** @brief Number of milli-seconds to wait*/
#define kTimeoutMSec (2)

My html documents do end up containing documentation I specify. (I do have @file at the top of the file and EXTRACT_ALL=YES)

A: Yes, it is possible. The Doxygen documentation says:

To document global objects (functions, typedefs, enum, macros, etc),
  you must document the file in which they are defined. In other words,
  there must at least be a
/*! \file */
or a
/** @file */
line in this file.

You can use @defgroup, @addtogroup, and @ingroup to put related items into the same module, even if they appear in separate files (see documentation here for details). Here's a minimal example that works for me (using Doxygen 1.6.3):
Doxyfile:
# Empty file.

Test.h:
/** @file */

/**My Preprocessor Macro.*/
#define TEST_DEFINE(x) (x*x)

/**
 * @defgroup TEST_GROUP Test Group
 *
 * @{
 */

/** Test AAA documentation. */
#define TEST_AAA (1)
/** Test BBB documentation. */
#define TEST_BBB (2)
/** Test CCC documentation. */
#define TEST_CCC (3)
/** @} */

Foo.h:
/** @file */

/**
 * @addtogroup TEST_GROUP
 *
 * @{
 */

/** @brief My Class. */
class Foo {
    public:
        void method();
};

/** @} */

Bar.h:
/** @file */

/**
 * @ingroup TEST_GROUP
 * My Function.
 */
void Bar();

In this case, the TEST_DEFINE documentation appears in the Test.h entry under the Files tab in the HTML output, and the TEST_AAA etc. definitions appear under Test Group in the Modules tab together with class Foo and function Bar.
One thing to note is that if you put the file name after the @file command, e.g:
/** @file Test.h */

then this must match the actual name of the file. If it doesn't, documentation for items in the file won't be generated.
An alternative solution, if you don't want to add @file commands, is to set EXTRACT_ALL = YES in your Doxyfile.
I hope this helps!

A: Try setting EXTRACT_ALL option, I have that set in my project and it generates documentation for #defines. There might be a more elegant way of doing it without using EXTRACT_ALL so be sure to check the documentation
http://www.doxygen.nl/config.html#cfg_extract_all

A: Adding to the previous answers, it is also needed to have ENABLE_PREPROCESSING=YES on the Doxyfile.


text:
Q: A way to identify a record in Firebird without RDB$DB_KEY or a key Is there a way to identify any record in any table without using RDB$DB_KEY or a table's key?
Unfortunately RDB$DB_KEY can only be guaranteed for the current transaction and might be different outside of it and without another key in the table one would not be able to uniquely identify a record if a record is an exact duplicate of another.

A: Other than RDB$DB_KEY, a primary key, or a unique key, there is nothing else to uniquely identify a row.
It is possible to extend the lifetime of RDB$DB_KEY to the lifetime of a connection using DPB property isc_dpb_dbkey_scope. However, using that is a bad idea: it will start an internal transaction for the lifetime of your connection which will prevent garbage collection of old row versions. This can seriously affect the performance of your application.


text:
Q: Amazon Web Services - EC2 - Active Directory (Domain Controller) | Web Server (IIS) | DB Server (SQL Server) I would like to setup 3 Windows 2012R2 EC2 instances:

*

*AD Server (Domain Controller)

*Web Server (IIS)

*Database Server (SQL Server)

Setting up the servers individually is fine, but I would like to setup the AD Server so that it acts as a Domain Controller. I would just like the domain to run in the cloud, it is not necessary that the Domain be accessible from a remote office.
I have tried setting up the AD Server by installing the Windows feature. That part is working fine, however, when I try setting a static IP, then I lose complete access to the machine. Note when installing AD I have installed DHCP and DNS as well. The configuration is where I am getting stuck.
Can anyone advise / point me to a good tutorial on setting up an architecture like this in AWS EC2? I am developer who striving to better under dev ops.

A: Don't use a static IP on the domain controller, instead try allocating an Elastic IP for it. Amazon's docs include a guide to setting up a DC: http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ConfigWindowsHPC.html


text:
Q: Generate polynomial Given solutions of a n degree polynomial , how can we find the polynomial.
Eg. : I have solutions like :
For x = 3, answer = 2
x = 4, answer = 1.77778

x = 5, answer =  1.660800

A: Use the Lagrange interpolation formula. If you are given that $P(x_i) = y_i$ for $i \in \{1,\ldots,n\}$, then one solution is
$$
P(x) = \sum_{i=1}^n y_i \prod_{j \neq i} \frac{x - x_j}{x_i - x_j}.
$$
Compute $P(x_i)$ yourself to see why you get $y_i$.


text:
Q: Does Zurb Foundation return accurate rems using rem_calc()? Output seems off Does Zurb Foundation 5.2.3 return accurate rems using rem_calc()?
Using a base of 12px, Foundation's rem calculating function rem_calc() says that a font size of 148px should equal 9.25rem ... rem_calc(148) = 9.25rem;. The output is visually smaller than what Photoshop says should be 148px.
Pluging in the base font size and size to be calculated in Rem Calculator outputs 148px = 12.33rem. Manually defining a font size of 12.33rem matches Photoshop.
Where does the difference come from in Foundation? Am I using this function wrong?
Edit:
I am not using the wrong REM base, or if I am it's becuase foundation is not looking for it properly. As defined in very top of Foundation Settings.scss, before @import "foundation/functions"; is called...
 $base-font-size: 12px;
 $rem-base: $base-font-size;

A: You are using wrong base:
// $rem-base: 16px; // default base
@debug rem-calc(148); //2.25rem

$rem-base: 12px;
@debug rem-calc(148); //12.33333rem

@debug rem-calc(148, 16);// again 2.25rem with the 16 base

A: The answer to this question is that in Foundation 5.2.3 $rem-base must have a defined font pixel size, simply declaring $rem-base: $base-font-size; is not enough.


text:
Q: How to copy the terminal's output and paste them into input? Does anyone know the function that I have to use to copy the output in the terminal?
For example, in terminal, if I input "ls", it gives me a list of files. I want to copy some of the texts and paste them into the next command to do "cd ". Is shell script able to do that?

A: You sound quite unfamiliar with bash, so here are a few hints about selecting files with wildcards, and regexes.

List files beginning with a
ls a*

List files beginning with a or c:
ls [ac]*

List files beginning with a, b or c:
ls [a-c]*

List files beginning with a-l or n-z but  not those starting with m:
ls [a-ln-z]*

List all files except those starting with m or a capital letter:
ls [^mA-Z]*

List PNG or JPG images:
ls *{png,jpg}

List PNG images with exactly 3 character/digit names:
ls ???.png

Another tip... this is an alternative to copying and pasting. Practice selecting files with ls as above (because ls is harmless), and when you have the correct regex, you can use !$ in the next command to repeat it (the last word of the previous command) without re-typing. So, practice your regex till it looks good, e.g. select evenly numbered PNG images:
ls *{0,2,4,6,8}.png

Then, get a long listing of just those files:
ls -l !$

A: Use ls | pbcopy to get a list of the files (file names) copied to the clipboard (mac/unix).
To copy the contents of the text files, you can use cat:
cat filename.txt | pbcopy

Definition of the | character http://www.linfo.org/vertical_bar_character.html


text:
Q: Curl returning 'Resource id #2 ' as response why? I have the following curl which does a SOAP request
$soap_do = curl_init();
            curl_setopt($soap_do, CURLOPT_URL,"http://uat-api.gafoorkp.in/services/simulator");
            curl_setopt($soap_do, CURLOPT_RETURNTRANSFER,true);
            curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST,false);
            curl_setopt($soap_do, CURLOPT_POST,true);
            curl_setopt($soap_do, CURLOPT_POSTFIELDS,"<?xml version='1.1'?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:sas='http://uat-api.gafoorkp.in/services/simulator'><SOAP-ENV:Body><sas:Login><Username>demo</Username><Password>demo</Password></sas:Login></SOAP-ENV:Body></SOAP-ENV:Envelope>");
            // $report=curl_getinfo($soap_do);
            if(curl_exec($soap_do) === false)
            {
                $err = 'Curl error: ' . curl_error($soap_do);
                curl_close($soap_do);
                echo $err;
            }
            else
            {
                curl_close($soap_do);
                echo 'Operation completed without any errors';
                print_r($soap_do);
                // print_r($report);
            }

This code is giving me a response as 'Resource ID #2' in the browser where Im suppose to get an xml response.Why is this happening,is there something wrong with what im doing?
Also no curl error is returned


text:
Q: Find force of friction on an object under influence of tension by another object I conducted an experiment using video analyses software, and found the accleration of a box on a table being pulled by a string attached to a pulley on the edge of the table attached to the weight (bag of sand).

(the meter stick is used for the video analysis reference)
•The mass of the sand is 9.883Kg, and the mass of the box is .3636Kg
•I am using the value 9.8m/s^2 for the acceleration of gravity.
•The acceleration of the box was calculated to be 6.034m/s^2 using the software.
•I am trying to find the force of friction.
So I tried a few things, but I don't know if they are correct, and would appreciate any help with the problem.
I first calculated the force Gravity is pulling on the bag of sand. 9.8m/s^2 * 9.883 Kg = 96.8534 Newtons. I then calculated the Effective force on the sand, 6.034 m/s^2 * 9.883 Kg = 59.594 Newtons. That would mean 96.8N-59.495N = 39.259 Newtons of friction force on the sand.
But the box's mass has something to do with it too, correct? I did the same calculation for the wooden box, and got 3.563N from gravity, 2.193N Effective, and 1.37N of friction.
I am confused here, do I add the friction forces together? It would seem like there should only be one friction force from the box. Everything is held together by the string, so I would think it would have the same value throughout.
Thanks for any help, I really wish to have a better understanding of newtons laws and motion.

A: The tension pulls the box to the right, and friction to the left. The net result is horizontal acceleration
$$T - \mu \,m_{box} g = m_{box} a_{box}$$
The tension is found by the acceleration of the bag of sand
$$m_{bag} g - T = m_{bag} a_{bag}$$
Since they are connected with a rope $a_{bag} = a_{box}=6.034$. Now you have a system of equations
$$\begin{aligned} T - \mu\,(0.3636*9.8) & = (0.3636*6.034) \\
(9.833*9.8)-T &= (9.833*6.034) \end{aligned}$$
which you need to solve for $T$ and $\mu$.

A: I do apologize for being a little to artistic:

Force of Sandbag $F_s$, Normal Force $F_n$ (equal to Gravitational Force $F_g$), and Kinetic Friction $F_k$:
$$
F_s = 9.883 \cdot 9.8 \\
F_s = 96.8534\space N
$$
We also know the total accelaration which means we know the Net Force:
$$
\Sigma F = ma \\
\Sigma F = (0.3636 + 9.883) \cdot 6.034\\
\Sigma F = 61.8279844\space N\\
$$
Since we know the $F_s$ and the Net Force, we can easily calculate the kinetic force:
$$
F_k = F_s - \Sigma F \\
F_k = 96.8534-61.8279844 \\
F_k = 35.0254156\space N
$$
From here we can find the coefficient of kinetic friction:
$$
F_k = \mu F_n \\
F_n = \frac{F_k}{\mu} \\
3.56328 = \frac{35.0254156}{\mu} \\
\mu = \frac{35.0254156}{3.56328} \\
\mu \approx  9.83\\
$$
I included the mass of the sandbag in the Net Force. Honestly, I'm not positive I should have. However, I only calculated the Kinetic Frictional Force of the box.


text:
Q: Class Data Member Inaccessible I can't for the life of me figure this out.
int Warrior :: attack ()
{
  int hit;
  srand(time(0));

if (Warrior.weapon == 6)
    int hit = rand() % 5 + 1;
else if (Warrior.weapon == 7)
    int hit = rand() % 7 + 4;
else if (Warrior.weapon == 8)
    int hit = rand() % 7 + 9;
else if (Warrior.weapon == 9)
    int hit = rand() % 7 + 14;
else if (Warrior.weapon == 10)
    int hit = rand() % 7 + 19;

std::cout<< "You hit " << hit <<"!\n";

return hit;
}

I get this error: Error C2059: syntax error : '.'
(also I know I should use a switch statement instead of else if)
Thank You.

A: Warrior is the name of the class. If you are inside of a member function, you do not need to qualify data members with the name of the class. You should also declare hit before the chain of if-then-else:
int hit;
if (weapon == 6)
    hit = rand() % 5 + 1;
else if (weapon == 7)
    hit = rand() % 7 + 4;
else if (weapon == 8)
    hit = rand() % 7 + 9;
else if (weapon == 9)
    hit = rand() % 7 + 14;
else if (weapon == 10)
    hit = rand() % 7 + 19;

You would probably be better off with a switch statement, or even an array of pairs for % and + values.
int mod[] = {0,0,0,0,0,0,5,7,7,7,7};
int add[] = {0,0,0,0,0,0,1,4,9,14,19};
int hit = rand() % mod[weapon] + add[weapon];

In the arrays above, when weapon is, say, 8, the mod[weapon] is 7, and the add[weapon] is 9, matching the data from your if statement.


text:
Q: Client ssl using mbedtls using C I am getting error message during handshake

*

*mbedtls_ssl_read_record_layer() returned -29184 (-0x7200)

*mbedtls_ssl_read_record() returned -29184 (-0x7200)
Why this error..?

A: You can look up Mbed TLS error codes with the strerror utility available with the library's source code.
programs/util/strerror 29184
Last error was: -0x7200 - SSL - An invalid SSL record was received

There could be many reasons for receiving an invalid record. If this is on the first message received from a server, this probably indicates that the server isn't using the TLS protocol. At other times, it probably indicates that something is corrupting packets. This could also indicate that the peer is using some TLS protocol extension that your library doesn't support, although this would usually be detected during the handshake. With DTLS, it could be a stray packet remaining from a previous connection on the same ports.


text:
Q: htaccess - Redirect all URLs containing /THIS/something/ANDTHAT/ My CMS is running into a loop often, because impossible URLs are generated. Those URLs have the format
www.xy.com/STRING1/something/STRING2/something

or
www.xy.com/something/STRING1/somethingother/anything/STRING2/something

I want to deny or block all URLs that contain STRING1 and STRING2 as segments.
Thanks for any idea!

A: There are many issues with the accepted answer above, so I will post a correction...
RewriteEngine on
RewriteRule ^/?STRING1/.*/STRING2/ https://example.com/ [R=301]

Note: the L flag does not make any sense when you implement an external redirection. Also the matching is not really precise in the accepted answer...
In case you want to return an explicit http status (like 403) you can also do that:
RewriteEngine on
RewriteRule ^/?STRING1/.*/STRING2/ - [R=403]

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...
This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.
And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

A: You can do it with this rewriting:
RewriteRule STRING1\/.*\/STRING2.* https://www.xy.com/ [R=301,L]


text:
Q: VBA: Macro to divide range by a million I have a range in an Excel sheet with hardcoded values, in millions. How can I write a VBA macro to divide a selected range by a million?
Best regards

A: No macro needed.

*

*Write 1,000,000 in one cell

*Copy that cell

*Select the range with hard-coded values

*Paste Special and select Divide

*OK

A: No loop needed
Sub MyDivide
    Selection.Value = Selection.Parent.Evaluate("INDEX(" & Selection.address & "/1000000,)")
End Sub

Just select the cell you want and run the sub.

A: For something as simple as this, I would write a formula in an area near the range (underneath if a row, beside if a column, etc.) and copy/paste as values and replace the original area.
If you really want to make a macro for this, you can assign a range to a variable, including the selected range. From there, loop through each cell in the range and replace value with the desired value (something like this):
Dim cell as Object

For Each cell in Selection
    cell.value = cell.value / 1000000
Next cell

A: Use a custom number format to make cells look like they were divided by a million while retaining the true raw underlying values.
sub meh()
    selection.numberformat = "0,,\M"
end sub

I've added a M as a unit suffix.


text:
Q: Should be returning true but returns false instead? Code:
Bukkit.getServer().broadcastMessage("Check " + ChatColor.stripColor(i));
Bukkit.getServer().broadcastMessage("That it starts with " + ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&',      GUIShop.instance.getConfig().getString("Messages." + type + "Label"))));
Bukkit.getServer().broadcastMessage(ChatColor.stripColor(i).startsWith(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', GUIShop.instance.getConfig().getString("Messages." + type + "Label")))) + "");

And image of it returning false instead of true:

Could me being stupid.. Not sure
EDIT1: Ok so thanks to eckes he pointed out that I was being stupid.. How would I check if "Buy: 50.0" started with "Buy: Price". Like if up to %price%

A: False is correct, "Buy: 50.0" does not start with "Buy: %price%". And you should really not mix color logic with translation logic with business logic.
Make your code readable, it often helps to find the problem yourself.
If you want to remove %price% you could use:
String check = ChatColor.stripColor(i);
String pattern = ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&',
                   GUIShop.instance.getConfig().getString("Messages." + type + "Label")));
pattern = pattern.replace(" %price%", "");
boolean isBuy = check.startsWith(pattern);

I cant make it much more readable without more background details.


text:
Q: UrlSession closure code not called after receiving data I have a UrlSession that calls a web service, and should receive a users data, which is then processed. The data processing closure is never entered though. I have checked to make sure that the url created returns the expected data. Please see my code below:
import Foundation
import SwiftUI
import CoreLocation

struct DbCustomer: Codable, Identifiable
{
    var id: String
    var user_name: String
    var pass_word: String
    var fullname: String
}

class LunchboxViewModel: ObservableObject
{

    @AppStorage("loggedIn") var loggedIn: Bool = false
    @AppStorage("username") var username: String = ""
    @AppStorage("password") var password: String = ""
    @AppStorage("fullname") var fullname: String = ""
    @AppStorage("userid") var userId: String = ""

    func loginInUser(username: String) -> Bool
    {
        var urlComponents = URLComponents()
        urlComponents.scheme = "http"
        urlComponents.host = "www.venndor.co.uk"
        urlComponents.path = "/logindo.php"
        urlComponents.queryItems = [
            URLQueryItem(name: "username", value: username)
        ]
        guard let url = urlComponents.url else {
            fatalError("Invalid URL")
        }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        URLSession.shared.dataTask(with: request) { data, response, error in

        /* the code below is never executed*/

            guard let data = data else{ return}
            do{
                let decoder = JSONDecoder()
                decoder.dataDecodingStrategy = .base64
                let decodedData =  try decoder.decode([DbCustomer].self, from: data)
                self.username = decodedData[0].user_name
                self.password = decodedData[0].pass_word
                self.userId = decodedData[0].id
                self.fullname = decodedData[0].fullname
                self.loggedIn = true
            }catch let error{
                print(error)
            }
        }.resume()
    if self.loggedInUser != nil
    {
        return true
    }
    else
    {
        print("no data")
        return false
    }
    }
}

Here is where the code is used, and called:
Here's the code!:
import SwiftUI

struct SignUpSignIn: View {

    @State var signUpProgress: Int = 0
    @State var fullname: String = ""
    @State var username: String = ""
    @State var companyname: String = ""
    @State var companydescription: String = ""
    @StateObject var viewModel: LunchboxViewModel = LunchboxViewModel()

    @State var loginSignUpOption: String? = nil

    //Sign Up Progress States
    /*
        0:  Welcome
        1:  Username
        2:  Full name
        3:  Company name
        4:  Company description
        5:  Complete
     */

    let transition: AnyTransition = .asymmetric(insertion: .move(edge: .trailing), removal: .move(edge: .leading))

    var body: some View {
        NavigationLink("", tag: "logIn", selection: $loginSignUpOption){ LunchboxTabView() }

        ZStack()
        {
            ZStack
            {
                switch signUpProgress
                {
                case 0:
                    welcomeScreen
                        .transition(transition)
                case 1:
                    addUsernameScreen
                        .transition(transition)
                case 2:
                    addNameScreen
                        .transition(transition)
                case 3:
                    addCompanyNameScreen
                        .transition(transition)
                case 4:
                    addCompanyDescriptionScreen
                        .transition(transition)
                default:
                    Text("Default")
                }
            }
            VStack()
            {
                Spacer()
                bottomButton
            }
            .padding(30)
        }
        .environmentObject(viewModel)
    }
}

struct SignUpSignIn_Previews: PreviewProvider {
    static var previews: some View {
        SignUpSignIn()
            .background(.blue)
    }
}

// MARK: Components
extension SignUpSignIn
{
    var bottomButton: some View
    {
        Text(signUpProgress == 0 ? "Start": signUpProgress == 4 ? "Sign Up" : "Continue")
            .font(.headline)
            .foregroundColor(.blue)
            .frame(height: 60)
            .frame(maxWidth: .infinity)
            .background(.white)
            .cornerRadius(10)
            .onTapGesture {
                handleButtonPress()
            }
    }

    var welcomeScreen: some View
    {
        VStack(spacing: 40)
        {
            Spacer()
            Image(systemName: "tortoise")
                .resizable()
                .scaledToFit()
                .frame(width: 200, height: 200)
                .foregroundColor(.white)
            Text("Never miss them again!")
                .font(.title)
                .foregroundColor(.white)
                .fontWeight(.semibold)
            Text("With this app, you need never miss that sandwich lady, ice cream van, or other mobile vendor again!")
                .font(.headline)
                .foregroundColor(.white)
                .multilineTextAlignment(.center)
            Spacer()
            Spacer()
        }
    }

    var addUsernameScreen: some View
    {
        VStack(spacing: 40)
        {
            Spacer()
            Text("Please enter a username")
                .font(.title)
                .foregroundColor(.white)
                .fontWeight(.semibold)
            TextField("Enter your username...", text: $username)
                .font(.headline)
                .frame(height: 55)
                .padding(.horizontal)
                .background(.white)
                .cornerRadius(10)
            Text("Enter any name you like as your username! If you have used the app before, and you want to use your old account, enter that username, and we'll do the rest!")
                .font(.headline)
                .foregroundColor(.white)
                .multilineTextAlignment(.center)
            Spacer()
            Spacer()
        }
        .padding(30)
    }

    var addNameScreen: some View
    {
        VStack(spacing: 40)
        {
            Spacer()
            Text("Please enter your name")
                .font(.title)
                .foregroundColor(.white)
                .fontWeight(.semibold)
            TextField("Enter your name...", text: $fullname)
                .font(.headline)
                .frame(height: 55)
                .padding(.horizontal)
                .background(.white)
                .cornerRadius(10)
            Spacer()
            Spacer()
        }
        .padding(30)
    }

    var addCompanyNameScreen: some View
    {
        VStack(spacing: 40)
        {
            Spacer()
            Text("Do you have a company?")
                .font(.title)
                .foregroundColor(.white)
                .fontWeight(.semibold)
            TextField("Enter your company's name...", text: $companyname)
                .font(.headline)
                .frame(height: 55)
                .padding(.horizontal)
                .background(.white)
                .cornerRadius(10)
            Text("If you have a company, and you want to use this app to alert your customers to your presence, just enter a name here. Leave it blank if not, and we'll sign you up right away!")
                .font(.headline)
                .foregroundColor(.white)
                .multilineTextAlignment(.center)
            Spacer()
            Spacer()
        }
        .padding(30)
    }

    var addCompanyDescriptionScreen: some View
    {
        VStack(spacing: 40)
        {
            Spacer()
            Text("What does your company do?")
                .font(.title)
                .foregroundColor(.white)
                .fontWeight(.semibold)
            TextField("Enter a description of your company", text: $companydescription)
                .font(.headline)
                .lineLimit(10)
                .multilineTextAlignment(.leading)
                .frame(height: 200)
                .padding(.horizontal)
                .background(.white)
                .cornerRadius(10)
            Text("This is the last bit! Thank you for your patience! Just a quick check, and we'll have you signed up in no time!")
                .font(.headline)
                .foregroundColor(.white)
                .multilineTextAlignment(.center)
            Spacer()
            Spacer()
        }
        .padding(30)
    }

}

// MARK: Functions
extension SignUpSignIn
{
    func handleButtonPress()
    {
        if signUpProgress == 1
        {
            if viewModel.loginInUser(username: username)
            {
                loginSignUpOption = "logIn"
            }
        }
        if companyname == "" && signUpProgress > 2
        {
            let newUser = DbCustomer(id: "0", user_name: username, pass_word: "", fullname: fullname)
            viewModel.signUpUser(user: newUser)
            loginSignUpOption = "logIn"
            return
        }
        if signUpProgress == 5
        {
            let newUser = DbCustomer(id: "0", user_name: username, pass_word: "", fullname: fullname)
            let newCompany = DbVendor(id: "0", company_name: companyname, description: companydescription, customer_id: "0")
            viewModel.signUpUserWithCompany(user: newUser, company: newCompany)
            loginSignUpOption = "logIn"
            return
        }
        else
        {
            withAnimation(.spring())
            {
                signUpProgress += 1
            }
        }
    }
}

A: Probably data is nil.
Put a break point at line that you get guard let data = data else{ return} to debug value of data


text:
Q: How to show use Page.IsBusy in xamarin.froms? I binded property IsBusy="{Binding IsBusy} and label from my page to viewmodel property. I see value changed in label, by i can't see any busy indicator on page on android, is it right?

A: I think there is some confusion over the IsBusy property. On iOS it shows the indicator in the statusbar which is questionable because the indicator there, according to iOS guidelines is only to be shown for network activity.
On Android it doesn't seem to do anything (visually) at all. Also see this bug on Bugzilla where this discussion is ongoing on what you, as a developer, can expect it to do.
When we read the documentation page for the IsBusy property it says:

Marks the Page as busy. This will cause the platform specific global
  activity indicator to show a busy state.

So you should be able to see an activity indicator, also on Android. But in the bug mentioned earlier it is stated that it only appears if certain conditions are met or not at all when using AppCompat.
For now, if you have a requirement for this, I think it would be best to either skip over it for now until this is sorted out or implement your own visual aids.

A: The activity indicator on Android was removed as part of the transition to material design, as it was no longer inline with the design recommendations.


text:
Q: Printed Image generated in c# is too big for Zebra ZXP 3 I want to print image generated in C# via printer called -  Zebra ZXP 3.
This printer has 86mm x 54 mm card and printing in 300 DPI.
I generated image in this way (badge Height is get from database in mm and then converted in private method to pixel, so I write below value for this variables).
badgeWidth = 1016
badgeHeight = 638
 var bitmap = new Bitmap(badgeWidth, badgeHeight);

 bitmap.SetResolution(300, 300);
 SetBackgroundColor(badgeTemplateData, bitmap);

Then I have couple method to draw something on bitmap which looks like (some method generate picture, some text, some barcode etc.)
private void SetStringElement(string value, Bitmap bitmap, BadgeElement element)
    {
        var left = element.Coordinates.Left;
        var top = element.Coordinates.Top;

        var fontSize = element.ElementStyle.TextSize;

        var textColor = new SolidBrush(element.ElementStyle.TextColor);
        var font = new Font("Arial", fontSize);

        using (Graphics graphic = Graphics.FromImage(bitmap))
        {
            graphic.DrawString(value, font, textColor, left, top);
        }
    }

In the end I have method which convert this image to Base64:
//This is class which generate Image (look above):
var imageGenerator = new ImageGenerator(badgeTemplate);
var badgeTemplateBitmap = imageGenerator.MapBadgeTemplateToPng(badgeSide);

var memoryStream = new MemoryStream();

badgeTemplateBitmap.Save(memoryStream, ImageFormat.Png);

var byteImage = memoryStream.ToArray();

var badgeTemplateBase64 = Convert.ToBase64String(byteImage);

return badgeTemplateBase64;

The last step is send this picture to browser, so I calling Ajax which getting above base64:
$.ajax({
        url: "/Guests/PrintSingleFrontBadgeTemplate",
        type: "post",
        data: { guestTypeId: guestTypeId, guestId: guestId },
        success: function (response) {
            var popupWin = window.open('', '_blank', 'width=1200,height=800');
            popupWin.document.open();
            popupWin.document.write('');
            popupWin.document.close();
            popupWin.print();
            popupWin.close();
        }
    });

AND What Can I see? THE Huge image which takes 3 pages...
As I said my printer printing 86mm x 54mm in 300 dpi.
To print whole area I need image in 1016px x 638px.
Why my picture is 3 times bigger than I expected?
And the huge surprise is when I download this image and print from windows I have perfectly precision image on one page.


text:
Q: Custom equation curve fitting in Matlab I am trying to use Matlab to find the values of the coeffiecients of the following equation
y=ax/((c+bx)*(a+cx+b))

I have 7 data points for y and x . How can I do this using curve fitting toolbox

A: Use least squares fitting:
 f = fittype('a*x./((c+b*x).*(a+c*x+b))');
 [fit1,gof,fitinfo] = fit(x',y',f,'StartPoint',[1 1 1]);

Try multiple start points to warrant a global minimum is reached.


text:
Q: Vim: change label for specific tab Say I have a bunch of tabs open in Vim, with a tabline looks something like this:
1 v/file1.py   2 t/file.py   1 t/file.py 1 o/otherfile.py
See how two tabs both say "t/file.py"? Those are different files, they just get turned into the same tab label.
In my workflow the tab titles are often ambiguous (yay for Chef naming everything "default.rb") or unhelpful ("I know one of these 8 tabs with 4 buffers each has that file I'm looking for...").
I'd like to rename the tabs to indicate what they logically represent:
1 homepage_view  2 tests  1 homepage_template  1 o/otherfile.py
I'm fine with tabs defaulting to a filename-based label, as long as I'm free to change it once the tab is created.
How can I do this in Vim?

A: There's a nice little plugin called Taboo that makes this easy. Just install it and then you can change the tab title with:
:TabooRename My Tab Title

You can look at the source code for that plugin if you're interested in writing your own solution.

A: For gvim, see
:help 'guitablabel'
:help setting-guitablabel

Set the option to an expression that evaluates to t:mytablabel (a tab-local variable) if it exists, or else to an empty string (meaning to use the default):
:set guitablabel=%{exists('t:mytablabel')?t:mytablabel\ :''}

Maybe that is already too complicated, or maybe you want to get fancier.  In that case, define a function:
function! GuiTabLabel()
  return exists('t:mytablabel') ? t:mytablabel : ''
endfunction
:set guitablabel=%{GuiTabLabel()}
:set go+=e

Then, in any tab where you want to override the default, do something like
:let t:mytablabel = 'homepage_template'

If you are using vim in a terminal, not gvim, then you have to set the 'tabline' option instead of 'guitablable'.  This is a little more complicated, since you need a single expression that includes labels for all the open tabs.  There is a complete example under
:help setting-tabline