text:
Q: TabPage title alignment being wrong after drag'n'dropping I have the class that extends System.Windows.Forms.TabControl and had implemented drag'n'drop mechanism for its TabPages as following:
#region Overriden base methods

protected override void OnDragOver(DragEventArgs e)
{
    if (PointedTabPage == null) return;

    e.Effect = DragDropEffects.Move;

    var dragTab = e.Data.GetData(typeof (ManagedTabPage)) as ManagedTabPage;

    if (dragTab == null) return;

    int dropIndex = TabPages.IndexOf(PointedTabPage);
    int dragIndex = TabPages.IndexOf(dragTab);

    if (dragIndex == dropIndex) return;

    var modifiedTabPages = new List<ManagedTabPage>(from ManagedTabPage tabPage in TabPages
                                                    where TabPages.IndexOf(tabPage) != dragIndex
                                                    select TabPages[TabPages.IndexOf(tabPage)] as ManagedTabPage);

    modifiedTabPages.Insert(dropIndex, dragTab);

    for (byte i = 0; i < TabPages.Count; ++i)
    {
        var managedTabPage = TabPages[i] as ManagedTabPage;

        if (managedTabPage != null && managedTabPage.Uid == modifiedTabPages[i].Uid)
            continue;

        TabPages[i] = modifiedTabPages[i];
    }

    SelectedTab = dragTab;
}

protected override void OnMouseDown(MouseEventArgs e)
{
    try
    {
        switch (e.Button)
        {
            case MouseButtons.Left:
                DoDragDrop(PointedTabPage, DragDropEffects.Move);

                break;
            case MouseButtons.Middle:
                CloseTab(PointedTabPage);

                break;
        }
    }
    catch (InvalidOperationException)
    {
    }
    finally
    {
        TabPages.Insert(0, String.Empty);
        TabPages.RemoveAt(0);
    }
}

#endregion

Nota bene that in the finally clause of OnMouseDown method there are 2 lines for workarounding the
problem: for some reason w/o these lines after drag'n'dropping any of TabPages alignment of their titles is being wrong:

What should I do to correct this behavior without this smelly workaround? Maybe sending some Windows messages could do the trick?
Thanks a lot for any suggestions.
Edit 1. Code of ManagedTabPage is 100% unimportant (it's just extends TabPage with some specific properties).
PointedTabPage is unimportant too, but this is it:
return (from ManagedTabPage tabPage in TabPages
        let tabPageIndex = TabPages.IndexOf(tabPage)
        where GetTabRect(tabPageIndex).Contains(PointToClient(Cursor.Position))
        select TabPages[tabPageIndex]).Single() as ManagedTabPage;

I'm trying to achieve fully-centered alignment of labels. You see, labels on the screenshot didn't centered horizontally?

A: I can't do much with the posted code.  Let's take a completely different tack and create a tabcontrol that supports dragging a tabpage with the mouse.  Add a new class to your project and paste this code:
using System;
using System.Drawing;
using System.Windows.Forms;

class TabControlEx : TabControl {
    private Point downPos;
    private Form draggingHost;
    private Rectangle draggingBounds;
    private Point draggingPos;

    public TabControlEx() {
        this.SetStyle(ControlStyles.UserMouse, true);
    }
}

The usage of the variable becomes clear later.  First thing we need is to get mouse events from the TabControl so we can see the user trying to drag a tab.  That requires turning on the UserMouse control style, it is off by default for controls (like TabControl) that are built-in Windows controls and use their own mouse handling.
Use Build > Build and drag the new control from the top of the toolbox onto a form.  Everything still looks and acts like a regular TabControl, but do note that clicking tabs no longer changes the active tab.  A side-effect of turning the UserMouse style on.  Let's fix that first, paste:
protected override void OnMouseDown(MouseEventArgs e) {
    for (int ix = 0; ix < this.TabCount; ++ix) {
        if (this.GetTabRect(ix).Contains(e.Location)) {
            this.SelectedIndex = ix;
            break;
        }
    }
    downPos = e.Location;
    base.OnMouseDown(e);
}

We are storing the click location, that's needed later to detect the user dragging the tab.  That requires the MouseMove event, we need to start dragging when the user moved the mouse far enough away from the original click position:
protected override void OnMouseMove(MouseEventArgs e) {
    if (e.Button == MouseButtons.Left && this.TabCount > 1) {
        var delta = SystemInformation.DoubleClickSize;
        if (Math.Abs(e.X - downPos.X) >= delta.Width ||
            Math.Abs(e.Y - downPos.Y) >= delta.Height) {
            startDragging();
        }
    }
    base.OnMouseMove(e);
}

The startDragging method needs to create a toplevel window that can be moved around with the mouse, containing a facsimile of the tab we're dragging around.  We'll display it as an owned window, so it is always on top, that has the exact same size as the tab control:
private void startDragging() {
    draggingBounds = this.RectangleToScreen(new Rectangle(Point.Empty, this.Size));
    draggingHost = createDraggingHost(draggingBounds);
    draggingPos = Cursor.Position;
    draggingHost.Show(this.FindForm());
}

The createDraggingHost needs to do the heavy lifting and create a window that looks just like the tab.  A borderless form we'll move around with the mouse.  We'll use the TransparencyKey property to make it look similar to the dragged TabPage with a tab sticking out at the top.  And make it look the same by simply letting it display a screenshot of the tabpage:
private Form createDraggingHost(Rectangle bounds) {
    var host = new Form() { FormBorderStyle = FormBorderStyle.None, ControlBox = false, AutoScaleMode = AutoScaleMode.None, Bounds = this.draggingBounds, StartPosition = FormStartPosition.Manual };
    host.BackColor = host.TransparencyKey = Color.Fuchsia;
    var tabRect = this.GetTabRect(this.SelectedIndex);
    var tabImage = new Bitmap(bounds.Width, bounds.Height);
    using (var gr = Graphics.FromImage(tabImage)) {
        gr.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size);
        gr.FillRectangle(Brushes.Fuchsia, new Rectangle(0, 0, tabRect.Left, tabRect.Height));
        gr.FillRectangle(Brushes.Fuchsia, new Rectangle(tabRect.Right, 0, bounds.Width - tabRect.Right, tabRect.Height));
    }
    host.Capture = true;
    host.MouseCaptureChanged += host_MouseCaptureChanged;
    host.MouseUp += host_MouseCaptureChanged;
    host.MouseMove += host_MouseMove;
    host.Paint += (s, pe) => pe.Graphics.DrawImage(tabImage, 0, 0);
    host.Disposed += delegate { tabImage.Dispose(); };
    return host;
}

Note the use of the Capture property, that's how we detect that the user released the mouse button or interrupted the operation by any other means.  We'll use the MouseMove event to move the window around:
private void host_MouseMove(object sender, MouseEventArgs e) {
    draggingHost.Location = new Point(draggingBounds.Left + Cursor.Position.X - draggingPos.X,
                                      draggingBounds.Top + Cursor.Position.Y - draggingPos.Y);

}

And finally we need to handle the completion of the drag.  We'll swap tabs, inserting the dragged tab at the mouse position and destroy the window:
private void host_MouseCaptureChanged(object sender, EventArgs e) {
    if (draggingHost.Capture) return;
    var pos = this.PointToClient(Cursor.Position);
    for (int ix = 0; ix < this.TabCount; ++ix) {
        if (this.GetTabRect(ix).Contains(pos)) {
            if (ix != this.SelectedIndex) {
                var page = this.SelectedTab;
                this.TabPages.RemoveAt(this.SelectedIndex);
                this.TabPages.Insert(ix, page);
                this.SelectedIndex = ix;
            }
            break;
        }
    }
    draggingHost.Dispose();
    draggingHost = null;
}

Looks pretty good.

A: since you hasn't shared ManagedTabPage code, i used default TabPage control
changes are made in method OnDragOver
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Demo
{
    public class MyTabControl : TabControl
    {
        public MyTabControl()
        {
            SizeMode = TabSizeMode.Fixed;
            ItemSize = new Size(224, 20);
        }

        #region Overriden base methods

        protected override void OnDragOver(DragEventArgs e)
        {
            if (DesignMode)
                return;
            if (PointedTabPage == null) return;

            e.Effect = DragDropEffects.Move;

            var dragTab = e.Data.GetData(typeof(TabPage)) as TabPage;

            if (dragTab == null) return;

            int dropIndex = TabPages.IndexOf(PointedTabPage);
            int dragIndex = TabPages.IndexOf(dragTab);

            if (dragIndex == dropIndex) return;

            // change position of tab
            TabPages.Remove(dragTab);
            TabPages.Insert(dropIndex, dragTab);

            SelectedTab = dragTab;

            base.OnDragOver(e);
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (DesignMode)
                return;

            switch (e.Button)
            {
                case MouseButtons.Left:
                    DoDragDrop(PointedTabPage, DragDropEffects.Move);

                    break;
                case MouseButtons.Middle:
                    TabPages.Remove(PointedTabPage);
                    break;
            }
        }

        #endregion

        TabPage PointedTabPage
        {
            get
            {
                return TabPages.OfType<TabPage>()
                    .Where((p, tabPageIndex) => GetTabRect(tabPageIndex).Contains(PointToClient(Cursor.Position)))
                    .FirstOrDefault();
            }
        }
    }
}


text:
Q: Remove HTML tags in String How can I remove HTML tags from the following string?

In an
email sent just three days before the Deepwater Horizon exploded, the onshore
BP manager in charge of
the drilling rig warned his supervisor that last-minute procedural changes were
creating "chaos". April emails were given to government investigators by BP and reviewed by The Wall
Street Journal and are the most direct evidence yet that workers on the rig
were unhappy with the numerous changes, and had voiced their concerns to BP's operations managers in
Houston. This raises further questions about whether BP managers properly
considered the consequences of changes they ordered on the rig, an issue
investigators say contributed to the disaster.

I'm writing it to Asponse.PDF, but the HTML tags are shown in the PDF. How can I remove them?

A: Warning: This does not work for all cases and should not be used to process untrusted user input.
using System.Text.RegularExpressions;
...
const string HTML_TAG_PATTERN = "<.*?>";

static string StripHTML (string inputString)
{
   return Regex.Replace
     (inputString, HTML_TAG_PATTERN, string.Empty);
}

A: You should use the HTML Agility Pack:
HtmlDocument doc = ...
string text = doc.DocumentElement.InnerText;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best practices with class visibility Is it best practice to have all the classes public in a Java project? I have noticed that in all Java projects I have worked with, there have only been public classes.

A: It isn't a guideline, no.
The information hiding principle tells us to only exposed what is required, and nothing more, to minimize coupling.
So, for example, if a class lets you handle logic in a separate class easier, and is only used by that class, there's no reason to have it public, nor should you make it public.

A: The simple answer to your question is "no!"
The slightly more complicated one is that you should only make a class public if it needs to be used by other classes outside it's own package.  But if, like me, you break you project up into many packages for readability, then then if will often be the case that your classes will need to be public to be usable.
While your question is simple to ask, it is far from simple in its nature.  Much will depend upon the kind of code your writing.  It you're writing a library then use externally is probably high on your agenda.  In an application less so.
I have found that I prefer the public approach.  I try and design for reuse because it keeps my options open, causes me to think more carefully about my implementation because of the reuse issues, and that leads to better code.  But it really is horses for courses, you are the biggest variable in this equation.

A: It depends, For top level class's, If you want other class's in a different package to view your class you should mark it public. If you only want class's in the same package to view you class mark it default(no-modifier).

A: So, your question is really, should all top level classes be public? I think it boils down to the usage of the package access that you do in your project. This question was relevant to that, some time ago.

A: Usually most classes are indeed public but there are cases when you might want to use default or private scope as well.
A class using the default scope is only accessible to other classes in the same package. In case of helper classes for example it's often a good practice to limit their use this way as your code becomes more encapsulated. The private scope can often be used for inner classes for the same reason.

A: No it is not. There are lot of classes with other access specifiers or even anonymous. For an example, you can write private or anonymous classes that can be registered to listeners like
'ActionListener' and 'ItemListener'. Just like that, for various purposes, we do write lot of classes with no public specifier. It really helps to separate your work into pieces.
However, in Java, normally every source file contains a public class. That is because if your source file's name is 'Reader.java', you cannot have a private or other access specifier  for the class 'Reader' inside that source file. It must be public or default. Apart from that, no other class can have the access specifier 'public' instead of 'Reader' class.
Other thing is, private, protected and other types (except default) of classes cannot be written in a source file as "Independent classes". For an example, following is an error
Check.java
private class Check
{

}

A: It definitely is not best practice.  You are seeing it because most programmers don't know that a top-level class doesn't have to be public.
Ideally, a package isn't just a way to organize classes into groups.  There is no minimum or maximum number of classes that belong in a single package;  rather, subpackages should be created only when there is a need for package-level classes and/or members.  Java APIs do this a lot, and since the javadoc distributed from Sun/Oracle is generated for protected-level classes and members, some packages may appear to be sparse, even to the point of appearing nonsensically so.
For instance, the javax.swing.colorchooser package appears to have only four classes, but it actually has 17 (actual number may vary depending on the version of Java).  Four are public;  the rest are only for use with JColorChooser internals.
I've found that an inner class that is becoming too big to be easily maintained as an inner class is usually a good candidate for being a non-public top-level class.


text:
Q: 2 queries to 1 using 2 different WHERE SELECT qurum_id, qurum, COUNT(qurum1) AS I FROM `qurum` AS qur
JOIN (SELECT id, qurum1,input_date FROM DATA ) `aa` ON qur.qurum_id =
aa.qurum1
WHERE DATE_FORMAT(aa.input_date, '%Y') = $year AND DATE_FORMAT(aa.input_date, '%m') < 07

GROUP BY qurum_id
ORDER BY qurum_id

and
SELECT qurum_id, qurum, COUNT(qurum1) AS II FROM `qurum` AS qur2
JOIN (SELECT id, qurum1,input_date FROM DATA ) `bb` ON qur2.qurum_id =
bb.qurum1
WHERE DATE_FORMAT(bb.input_date, '%Y') = $year AND DATE_FORMAT(bb.input_date, '%m') BETWEEN 06 AND 12

GROUP BY qurum_id
ORDER BY qurum_id

How can I join these queries to 1? I need columns like this - qurum_id, qurum,  I, II.

A: You can use conditional aggregation.  The trick is to take a conditional count of records depending on the month condition, which is different for your two current queries.  Note that the WHERE condition for the year was left alone, because both queries share this condition.
SELECT
    qurum_id,
    SUM(CASE WHEN DATE_FORMAT(aa.input_date, '%m') < 07
               THEN 1 END) AS I,
    SUM(CASE WHEN DATE_FORMAT(aa.input_date, '%m') BETWEEN 06 AND 12
               THEN 1 END) AS II
FROM qurum AS qur
INNER JOIN (SELECT id, qurum1,input_date FROM DATA ) AS aa
    ON qur.qurum_id = aa.qurum1
WHERE DATE_FORMAT(aa.input_date, '%Y') = $year
GROUP BY qurum_id
ORDER BY qurum_id


text:
Q: Defining custom parameter types with JAX-RS to return data by identifier I am new to  Jersey, and I discovered that we can define our own parameter types to handle other types than string, as dates or boolean for instance.
I will work with an ORM to store the data in a database, so that I will be able to map an identifier to an instance of a class, let's say to a User.
Is it a good practise to define a param class which would handle the user id given in parameter (path or query for instance), and return the instance of User corresponding to the id?

A: If your param is directly mappable to a primitive type then there's no need to define your own. It sounds like you want to accept a user ID as a param, which is likely to be a long, int or String. All of these are automatically mapped.
For example;
@Path("/")
public class UserService {

  @GET
  @Produces(MediaType.APPLICATION_XML)
  @Path("/{id}")
  public User getUser(@PathParam("id") String id) {
    //Your implementation here
  }

}

A: Well, lets take some example:
stackoverflow.com/users/1235336/

Here we have the path with usedId in it. And if we proceed the link (execute a GET request), we will get the some user enity in response.
So defining a user id as a path parameter and returning some user instance is kind of normal practice.


text:
Q: How can I aggregate changes between rows in Pandas Dataframe? I have several columns that can be either 1 or -1
d = {'col1': [1, 1,-1,1], 'col2': [1,-1,1,1],'col3': [1,-1,1,1]}
df = pd.DataFrame(data=d)
print(df)

   col1  col2  col3
0     1     1     1
1     1    -1    -1
2    -1     1     1
3     1     1     1

I want to count the number of columns that have flipped sign on each row to give:
   NumFlipped
0           0
1           2
2           3
3           1

How do I do that?

A: Try comparing diff with 0, then sum:
df.diff().fillna(0).ne(0).sum(1)

Or we can compare df with its shift:
df.ne(df.shift().fillna(df)).sum(1)

Output:
0    0
1    2
2    3
3    1
dtype: int64


text: Q: Change color line under autocomplete editext (Android) I'm using an AutoCompleteEditText and some EditText. I have edited the color of the line under the EditText and it works but when I attempt to change the color of line under the AutoCompleteEditText, the color remains green. What can I do to solve this problem?


text:
Q: Add a key value pair to results from Laravel Model with pagination In my controller i am calling my invoices model which is doing a paginated selected. After i get the results i then need to loop through each result and add a key => value pair to the original results.
I have my laravel set up in config/database.php to get results as arrays:
'fetch' => PDO::FETCH_ASSOC,
My code in my controller is
    $invoices = Invoices::getInvoices($clientId);
    $total = 0;
    foreach($invoices as $key=>$inv) {

        $payments = Payments::getPaymentAmount($inv['InvoiceId']);

        foreach($payments as $pmt) {

                $total += $pmt['Pmt_Amount'];

        }

        $invoices[$key]['total'] = $total;
    }

My Invoices Model is:
public static function getInvoices($clientId)
{
   $invoices = DB::table('invoices')
    ->where('ClientId', '=', $clientId)
    ->paginate(25);
   return $invoices;
}

and my payments model
public static function getPaymentAmount($invoiceId)
{
    $payment = DB::table('payments')
        ->select('Pmt_Amount', 'PaymentStatusId')
        ->where('InvoiceId', $invoiceId)
        ->get();

    return $payment;
}

When i try to add 'total' to the invoices array i get the following error
Indirect modification of overloaded element of Illuminate\Pagination\LengthAwarePaginator has no effect

A: Your $invoices is object, try toArray() after your getInvoices() function :
$invoices = $invoices->toArray();


text:
Q: how to debug request.post in nodejs could some give me idea to debug the below snippet.
var request = require('request');

function sendINFO() {
    var jsonString = {
        reportType: 'customer',
        comment: customerDetails.cust_id,
        imageUrl: customerDetails.url1
    }
    console.log('json string', jsonString)
    request.post(
        'http://52.7.0.131/SendInfo/XC1K1AZ9', {
            json: jsonString
        },
        function(error, response, body) {
            console.log('response after adding report', response, 'error', error)
            if (!error && response.statusCode == 200) {
                console.log(body)
            }
        }
    );
}

i want to check whether it's working or not. and how to test this with postman api
many thanks for any help

A: in postman in URL section add 52.7.0.131/SendInfo/XC1K1AZ9 this url with method as POST then Navigate to body tag and then select raw radio button. Then in same row you will see [Text] combo box click on that and select JSON(application/json). Then paste only { reportType: 'customer', comment: customerDetails.cust_id, imageUrl: customerDetails.url1 }  this part of json below and click on Send button.


text:
Q: Android Calendar. I have a problem with adding entry to the Calendar.I tried a lot of tests but without success.
Source code:
 String calName;
        String calId = null;
        String[] projection = new String[] { "_id", "name" };

        Uri calendars = Uri.parse("content://com.android.calendar/calendars");
        Cursor managedCursor = managedQuery(calendars, projection, "selected=1", null, null);
        ContentValues event = new ContentValues();

        DateFormat date = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        long time = System.currentTimeMillis();
        String StartTime = date.format(time);
        String EndTime = "13/4/2011 15:30";

        Log.d(TAG, "Value of timeStr: " + StartTime);

        if (managedCursor.moveToFirst()) {

            int nameColumn = managedCursor.getColumnIndex("name");
            int idColumn = managedCursor.getColumnIndex("_id");

            do{
                calName = managedCursor.getString(nameColumn);
                calId = managedCursor.getString(idColumn);

                event.put("calendar_id", calId);
                event.put("title", "Event Title");
                event.put("description", "Description");
                event.put("eventLocation", "New York");
                event.put("dtstart", StartTime );
                event.put("dtend", EndTime);

                Uri eventsUri = Uri.parse("content://com.android.calendar/events");
                Uri calUri = getContentResolver().insert(eventsUri, event);
            }
            while (managedCursor.moveToNext());
            }
              }
}

Errors:
04-11 20:37:27.965: ERROR/ContentValues(262): Cannot parse Long value for 11/04/2011 08:37 at key dtstart
04-11 20:37:27.995: ERROR/DatabaseUtils(262): Writing exception to parcel
04-11 20:37:27.995: ERROR/DatabaseUtils(262): java.lang.NullPointerException
04-11 20:37:27.995: ERROR/DatabaseUtils(262):     at com.android.providers.calendar.CalendarProvider2.calculateLastDate(CalendarProvider2.java:2433)
04-11 20:37:27.995: ERROR/DatabaseUtils(262):     at com.android.providers.calendar.CalendarProvider2.updateLastDate(CalendarProvider2.java:2502)
04-11 20:37:27.995: ERROR/DatabaseUtils(262):     at com.android.providers.calendar.CalendarProvider2.insertInTransaction(CalendarProvider2.java:1792)
04-11 20:37:27.995: ERROR/DatabaseUtils(262):     at com.android.providers.calendar.SQLiteContentProvider.insert(SQLiteContentProvider.java:90)
04-11 20:37:27.995: ERROR/DatabaseUtils(262):     at android.content.ContentProvider$Transport.insert(ContentProvider.java:180)
04-11 20:37:27.995: ERROR/DatabaseUtils(262):     at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:175)
04-11 20:37:27.995: ERROR/DatabaseUtils(262):     at android.os.Binder.execTransact(Binder.java:288)
04-11 20:37:27.995: ERROR/DatabaseUtils(262):     at dalvik.system.NativeStart.run(Native Method)

A: Start and end time need to be longs and not strings:
event.put("dtstart", StartTime );
event.put("dtend", EndTime);

As you try to put in "11/04/2011", parsing this as long fails and you get the exception.
Try passing in longs:
long now = System.currentTimeMillis();
event.put("dtend",now);


text:
Q: Function for turning TimeStamps and Counter Values to a rate? Are there any libraries in R with a function to take something like:

   CounterDateTime CounterValue
1 2012-01-25 17:09:04        25052
2 2012-01-25 17:09:06        25054
3 2012-01-25 17:09:07        25054
4 2012-01-25 17:09:08        25055
5 2012-01-25 17:09:09        25055
6 2012-01-25 17:09:10        25055

And convert the CounterValue column to a per second rate? Ideally it will work with the irregular time in my example.


text:
Q: How to sort dollar number ranges in JavaScript I am trying to sort dollar ranges in JavaScript. The problem is that the response values are ordered like so
['$10,000 - $29,999', '$30,000 - $49,999', '$5,000 - $9,999', '$50,000+', 'Lower than $5,000']

needs to be sorted to

['Lower than $5,000', '$5,000 -$9,999', '$10,000 - $29,999', '$30,000 - $49,999', '$50,000+']

I would like to sort this in ascending order like so, but I would also want it to be robust in a sense that if the API ever changes the order it sends this data, it still maintains the same sorting:
Is there a way I can do this without hardcoding the sorting algorithm?

A: Well you could try this:

    let r = ['$10,000 - $29,999', '$30,000 - $49,999', '$5,000 - $9,999', '$50,000+', 'Lower than $5,000'];

    r.sort((a, b) => {
      return parseInt(a.match(/\$\d+,\d+/gi).pop().replace(/\D/gi, ""), 10) - parseInt(b.match(/\$\d+,\d+/gi).pop().replace(/\D/gi, ""), 10);
    });
    console.log(r);

Explanation:

*

*Removing every character that is not a digit

*Parse it into a number

*Compare it

Edit:
I've edited my code in response to comment (I know it's not the prettiest code but it works)

A: If your ranges will be preserved in the time, you can create an object to maintain a relation between the ranges and an assigned order. Then later you can use this object in the Array.sort() method:

const rangeOrder = {
  'Lower than $5,000': 0,
  '$5,000 - $9,999': 1,
  '$10,000 - $29,999': 2,
  '$30,000 - $49,999': 3,
  '$50,000+': 4,
}

let input =  ['$10,000 - $29,999', '$30,000 - $49,999', '$5,000 - $9,999', '$50,000+', 'Lower than $5,000'];

console.log(input.sort(
  (a, b) => rangeOrder[a] - rangeOrder[b]
));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Another solution, to avoid harcoding the ranges, can be using a custom function to match the maximun range value on every string.

let input =  ['$10,000 - $29,999', '$30,000 - $49,999', '$5,000 - $9,999', '$50,000+', 'Lower than $5,000'];

const matchValue = (str) =>
{
    let matches = str.match(/\d+,\d+/g);
    let maxVal = matches.length > 1 ? matches[1] : matches[0];
    return +(maxVal.replace(",", ""));
}

input.sort((a, b) => matchValue(a) - matchValue(b));
console.log(input);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


text:
Q: Spring data JPA consumes all the connection objects I have a scenario where in data is uploaded from excel sheet to mysql db. I am using spring data jpa. And the service calls the entities recursively after stuffing them with data taken from excel sheet to save in db. This creates "unable to acquire jdbc connections" after a certain load.
I tried with @Transactional to know advantage. Then I am thinking of using EntityManager manually in code and control transaction boundary so that all recursive save calls of entities happen within one transaction and thereby one connection object. I just wanted to check would it be a nice idea or is there any other approach I should take which is more performant. Needless to say anyhow I have to do it through entities.

A: My answer is completely based on the assumption that the way of implementing the requirement is faulty as there isn't any code shared in the question.
By your approach, yes you will run out of the connection as the entity population would surely be much faster than persisting that entity in the database and since you are doing it recursively your application will run out connections at one point of time if the amount of the data is very high, numbers are certainly a factor here.
The other approach I would prefer is that you can prepare your entities(Assuming all the data is for a common entity class) and store in a collection, once it is ready you can persist all of it in one transaction using saveAll() method.
If the data is not for common entities you can create multiple lists of different entities and initiate the DB operations after processing the excel sheet.


text:
Q: How to add Dark mode to Localstorage using Javascript Please house, I want to make local storage for my Dark mode.
Here ie my code. Please help add local storage to it:
HTML

Dark
<input class='tgl tgl-KaXTam' id='KaXTamNight' type='checkbox'/>

JS
$('#KaXTamNight').click(function(){
    if ($('#KaXTamNight').is(':checked')) {
    $("body").addClass('KaXTamNight');
    }else {
    $("body").removeClass('KaXTamNight');
    }
    });

My CSS is in place.
I only need the functionality of Localstorage added to the javascript.

A: Just add to local storage when you check/uncheck the box and while on page load retrieve it and set the class if it was saved earlier
Check in JSFiddle: https://jsfiddle.net/f7jqwmto/
$(() => {
  const theme = 'KaXTamNight';
  const darkMode = localStorage.getItem(theme);
  $('body').toggleClass(theme, darkMode === 'true');

  $('#' + theme).prop('checked', darkMode === 'true').click(function() {
    $("body").toggleClass(theme, $(this).is(':checked'));
    localStorage.setItem(theme, String($(this).is(':checked')));
  });
});

.KaXTamNight {
  background-color: #777;
}

Dark
  <input class='tgl tgl-KaXTam' id='KaXTamNight' type='checkbox' />


text:
Q: Apache 403 Error: You don't have permission to access this resource My site was working until I added certs and a config for virtualhost :443.
Since then ive been getting the "403: You don't have permission to access this resource" error when trying to visit my site.
I have been tinkering with the .conf file to try and fix this and tried a lot of different settings. Below are the current one which im sure need changed.
Any help would be appreciated, Thanks in advance.
<VirtualHost *:80>
        ServerName mysite.co.uk
        ServerAlias www.mysite.co.uk
        DocumentRoot /srv/www/wordpress
RewriteEngine on
RewriteCond %{SERVER_NAME} =www.mysite.co.uk [OR]
RewriteCond %{SERVER_NAME} =mysite.co.uk
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
<VirtualHost *:443>
        ServerName mysite.co.uk/
        ServerAlias www.mysite.co.uk/
        DocumentRoot /srv/www/wordpress

Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/mysite.co.uk/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/mysite.co.uk/privkey.pem
<Directory /srv/www/wordpress>
Options All
AllowOverride All
Require all granted
DirectoryIndex index.php
</Directory>
<Directory /srv/www/wordpress/wp-content>
Options All
AllowOverride All
Require all granted
</Directory>

</VirtualHost>

I have checked the apache log and I can see the following errors
AH01630: client denied by server configuration: /srv/www/wordpress/
[Mon Oct 10 00:54:05.714700 2022] [authz_core:error] [pid 5860] [client 86.14.65.155:62383] AH01630: client denied by server configuration: /srv/www/wordpress/
[Mon Oct 10 00:54:43.436074 2022] [mpm_prefork:notice] [pid 5856] AH00170: caught SIGWINCH, shutting down gracefully
[Mon Oct 10 00:54:43.614777 2022] [mpm_prefork:notice] [pid 5878] AH00163: Apache/2.4.52 (Ubuntu) OpenSSL/3.0.2 configured -- resuming normal operations
[Mon Oct 10 00:54:43.614826 2022] [core:notice] [pid 5878] AH00094: Command line: '/usr/sbin/apache2'
[Mon Oct 10 00:54:51.836567 2022] [authz_core:error] [pid 5880] [client 86.14.65.155:62391] AH01630: client denied by server configuration: /srv/www/wordpress/
[Mon Oct 10 00:54:52.888525 2022] [authz_core:error] [pid 5879] [client 86.14.65.155:62394] AH01630: client denied by server configuration: /srv/www/wordpress/
[Mon Oct 10 00:55:01.878786 2022] [authz_core:error] [pid 5885] [client 86.14.65.155:62397] AH01630: client denied by server configuration: /srv/www/wordpress/
[Mon Oct 10 00:55:02.264432 2022] [authz_core:error] [pid 5885] [client 86.14.65.155:62397] AH01630: client denied by server configuration: /srv/www/wordpress/
[Mon Oct 10 00:55:37.722738 2022] [authz_core:error] [pid 5888] [client 86.14.65.155:62401] AH01630: client denied by server configuration: /srv/www/wordpress/page14
[Mon Oct 10 00:56:41.274489 2022] [authz_core:error] [pid 5888] [client 206.189.106.73:41108] AH01630: client denied by server configuration: /srv/www/wordpress/ab2g
[Mon Oct 10 00:56:43.990252 2022] [authz_core:error] [pid 5880] [client 206.189.106.73:41540] AH01630: client denied by server configuration: /srv/www/wordpress/ab2h
[Mon Oct 10 00:56:51.892303 2022] [authz_core:error] [pid 5883] [client 206.189.106.73:51902] AH01630: client denied by server configuration: /srv/www/wordpress/
[Mon Oct 10 00:57:14.110706 2022] [mpm_prefork:notice] [pid 5878] AH00170: caught SIGWINCH, shutting down gracefully
[Mon Oct 10 00:57:14.247187 2022] [ssl:warn] [pid 5904] AH01909: ip-172-31-2-184.ec2.internal:443:0 server certificate does NOT include an ID which matches the server name
[Mon Oct 10 00:57:14.295372 2022] [ssl:warn] [pid 5905] AH01909: ip-172-31-2-184.ec2.internal:443:0 server certificate does NOT include an ID which matches the server name
[Mon Oct 10 00:57:14.303365 2022] [mpm_prefork:notice] [pid 5905] AH00163: Apache/2.4.52 (Ubuntu) OpenSSL/3.0.2 configured -- resuming normal operations

also i believe the permissions are set correctly on the directory the site resides
`enter code here`:/srv/www# ls -lrth
`enter code here`total 4.0K
`enter code here`drwxr-xr-x 5 www-data nogroup 4.0K Oct  9 13:10 wordpress


text:
Q: How do you trigger Riddler buttons that are mounted on the wall?
Possible Duplicate:
How to deal with riddler trophies

I've come across several Riddler puzzles that require pressing buttons that are mounted vertically against a wall.  I have tried several different methods for pressing them, including using the line launcher and tight rope walking to press my body into it, but nothing I have tried works.  What's the easiest technique for pressing these pads?

A: You want to glide into the wall on the button. Batman will activate it, and you can push off and glide elsewhere. You'll want to start on top of a building then glide down to it.
Buttons on walls tend to turn up in sets of three, all of which need to be pressed without touching anything that's not a button. Don't be surprised if it turns off when you land.


text:
Q: What is the default successURL in recurly transaction?
I have subscription plans in recurly, it also provides the successURL
  for every plan, which is going to be called after transaction is
  completed.
I have added that successURL into the javascript code as:

  Recurly.buildSubscriptionForm({
    target: '#recurly-subscribe',
    // Signature must be generated server-side with a utility method provided
    // in client libraries.
    signature: sign,
    successURL: 'http://domain_name/page_name',
    planCode: 'blablabla',... });

so my question is, is i need to provide that successURL in this
  javascript code for every subscription plan? or it will take automatically from recurly account?

A: Your successURL can be any page you want.  Most people would start with the successURL as just a redirect to your users dashboard, settings page, or a thank you page.  The URL can be relative as well:
...
successURL: '/page_name'.
...

If you need to do some additional processing (like saving subscription uuid) for the subscription on your end, a success token will be posted to your successURL which you can use to gather more information based on the type of Recurly.js form you used.
https://docs.recurly.com/api/recurlyjs/integration#results-overview


text:
Q: How to set knp_paginator 'limit per page' inside twig using symfony I am using KNP_PAGINATOR in my Symfony v.5 project running locally. So far, I've been able to get the paginator up and running with no issue. Now, I need to allow the users to be able to choose how many results they want to see per page in their browser. Obviously I already set that value within the controller but how can I change this value depending on user's interaction with the app?
What I was able to do so far: By getting a {{dump(pagination)}} inside twig, it shows that there is a parameter called: numItemsPerPage which is currently set to 2 (for testing purposes as I do not have many dummy data inside the DB). I can change that like so:
    {{ pagination.setParam('numItemsPerPage', 3) }}

or even like so:
{% do pagination.setParam('numItemsPerPage', 3) %}

Both of which will change the dump output to the new value for the said 'numItemsPerPage'. like so:
    Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination {#1074 ▼
  -route: "cat_products"
  -params: array:5 [▼
    "direction" => "desc"
    "sort" => "p.id"
    "page" => "1"
    "id" => "1"
    "numItemsPerPage" => 3
  ]
  -pageRange: 5
  -template: "@KnpPaginator/Pagination/twitter_bootstrap_v4_pagination.html.twig"
  -sortableTemplate: "@KnpPaginator/Pagination/sortable_link.html.twig"
  -filtrationTemplate: "@KnpPaginator/Pagination/filtration.html.twig"
  #currentPageNumber: 1
  #numItemsPerPage: 2
  #items: array:2 [▶]
  #totalCount: 5
  #paginatorOptions: array:6 [▶]
  #customParameters: array:3 [▶]
}

But it has no effect whatsoever on the actual number of items shown per page!
here is my repository:
/**
 * @param string|null $catId
 */
public function getPrdsViaCatId(?string $catId): QueryBuilder
{
    $qb = $this->createQueryBuilder('p') //product
    ->innerJoin('p.category', 'pc') // p=product, pc=product category, ps=product sub-category
    ->innerJoin('p.sub_category', 'ps')
    ->addSelect('pc')
    ->addSelect('ps');
    if ($catId) {
        $qb->andWhere('pc.id = :catId')
            ->andWhere('pc.is_active = :pctrue')
            ->andWhere('ps.is_active = :pstrue')
            ->andWhere('p.is_active = :ptrue')
            ->setParameter('catId', $catId)
            ->setParameter('pctrue', true)
            ->setParameter('pstrue', true)
            ->setParameter('ptrue', true)
        ;
    }
    return $qb
        // ->orderBy('pc.id', 'DESC')
    ;
}

The Controller:
//start of pagination processing
    $query = $prdRepo->getPrdsViaCatId($id);
    $pagination = $paginator->paginate(
        $query, /* query NOT result */
        $request->query->getInt('page', 1)/*page number*/,
        2/*limit per page*/
    );

and finally in twig:

                    <select>
                        <option value="10">Show 10 items</option>
                        <option value="20">Show 20 items</option>
                        <option value="30">Show 30 Items</option>
                    </select>

                    <select id="sortSelect">
                          <option value="">Sort results</option>
                        {{ knp_pagination_sortable(pagination, 'ID 0-9', 'p.id', {}, {'direction': 'asc'}) }}
                        {{ knp_pagination_sortable(pagination, 'ID 9-0', 'p.id', {}, {'direction': 'desc'}) }}
                        {{ knp_pagination_sortable(pagination, 'Name', 'p.name')|raw }}
                    </select>

                {% if pagination %}
                        {% for prd in pagination %}

                        {% endfor %}
                {% endif %}

                        {{ knp_pagination_render(pagination) }}

Many thanks in advance.


text:
Q: Subset being an Abelian group. There is a theorem that states:
Let $P(X)$ be the set of subsets of $X$ and let $$\Delta $$ be the symmetric difference defined by $$A\Delta B = (A \cup B)\text{$\backslash $(A $\cap $ B)}.$$ Then P(X) is an Abelian group and with each element being its own inverse.
Would someone be nice to simplify this theorem?

A: The "hard" part of this theorem is proving that $\Delta$ is associative. The empty set is easily seen to be an identity element:
$A \Delta \emptyset = (A \cup\emptyset)\setminus(A \cap\emptyset) = A\setminus\emptyset = A$.
and:
$A \Delta A = (A \cup A) \setminus (A \cap A) = A\setminus A = \emptyset$,
for any $A \in \mathcal{P}(X)$.


text:
Q: Slicing movie audio according to timings present in its .srt I have extracted audio track from a movie. I've its subtitle file in .srt format. I want to slice the audio in to speech files according to timings that are available in subtitle file so that I can get transcribed speech data. Please suggest any method to do this.

A: I've found a way to do the same. There is tool named FFmpeg where I can slice an audio by giving start point and duration as input. I stored start time and duration of speech of a movie in an excel file. By using a small python script I was able to automate the process.


text:
Q: Angularjs Init Service I'm working on AngularJs project which have top navigation items load from server using a service call
App.service('Menu', function($http){
   return {
       get:function(callback){
           $http.get('api/menu.json').success(function(menuData){
               callback(menuData);
           });
       }
   }
});

I'm using the same in my BaseController as mentioned below
App.controller('BaseCtrl', function($scope, Menu){
    $scope.menuData = {};
    Menu.get(function(menuData){
        $scope.menuData = menuData;
    });
});

My Menu looks blank for a while until the service call succeed and assign the value to the $scope.menuData is there any way to fetch the same before rendering the view.
Please let me know, I might have tried all possible ways to do this, but nothing worked :(
PS: I'm using AngularJS v1.2.9

A: Return a promise from your service, and use that in your controller's resolve:
app.service('Menu', function($http) {
    var menuData = null;

    var promise = $http.get('api/menu.json').success(function (data) {
      menuData = data;
    });

  return{
          getMenuPromise: promise,
          getMenuData:function(){
            return menuData;
          }
   };
});

and in your route definitions:
$routeProvider
    .when('/home',{controller:'BaseCtrl',
    templateUrl:'../homeTpl.html',
    resolve:{
      'menuData':function(Menu){
        return Menu.getMenuPromise;
     }
    }})

Now when BaseCtrl is instantiated the data is there:
app.controller('BaseCtrl', function($scope,Menu) {
  $scope.menuData = MyService.getMenuData();
});

A: The best way to make sure data is available before rendering a view is to use the resolve property on your route.
If it returns a promise it will resolve that promise before actually rendering your view.
.when('/blah', {
   templateUrl: '/path/to/view.html',
   controller: 'myController',
   resolve: {
      menuItems: function($http){
         return $http.get('api/menu.json');
      }
   }
});

That value will be passed in to your controller as a dependency:
angular.controller('myController', function(menuItems){
   $scope.menuData = menuItems;
});


text:
Q: Is there a way to make all derived classes friends of one another? And if so, in what situation might this be useful?
Or (and I imagine this is the case), why is it absolutely useless? (What other approach essentially covers the abilities afforded by such friendship, but in a safer and less-leaky way?)
I was in a situation where I almost thought I needed such a thing. I went after an entirely different design in the end, making all the class members static. I'm still curious though.

A:
Is there a way to make all derived classes friends of one another?

The language does not provide any mechanism to specify something like this in a base class. You'll have to provide the friend declarations in every class you inherit from the base class.
I am not able to suggest anything more positive since I don't know the problem you are trying to solve.
In a comment, you said:

In my case, I needed to access sibling methods, so if B and C derive from A, I needed to call B::foo() from C::foo(). In my case these classes encapsulate different algorithms (so the Strategy pattern comes to mind...) but sometimes one algorithm would use a substantial portion of another algorithm. Yet, it didn't seem correct to derive C from B, because C doesn't really have an "is-a" relationship with B.

If C doesn't have an "is-a" relationship with B, yet C::foo() somehow needs to call B::foo(), it indicates to me that B::foo() can only use data that is common to both B and C. In that case, it should be possible to factor out the code into a non-member function and then use it from B::foo() and C::foo().
Change the dependency from:
B::foo()
   ^
   |
C::foo()

to
 <some namespace>::foo()
          ^
          |
  +-------+---------+
  |                 |
B::foo()          C::foo()

A: C++ only gives you two ways to name friends:
friend class C; // a specific class

template <typename T>
friend class S; // friend the class template S

There's no way to stick in a metafunction in there, which would look hypothetically something like this:
template <typename T>
friend enable_if_t<std::is_base_of<Base, T>::value, T>;

But I guess if you're open to horrible hackery (this phrase should be interpreted as never do this ever please god no, but it's at least marginally amusing), you could simply implement all of your derived types as explicit specializations of some template.
struct Base { ... };

template <typename > class Derived;

struct A_tag { };

template <>
class Derived<A_tag> : Base {
    template <typename T>
    friend class Derived;

    ...
};

using A = Derived<A_tag>;

If we do similar thing for B, C, etc., then A, B, and C are mutually all friends - since under the hood they're really Derived<A_tag>, Derived<B_tag>, and Derived<C_tag> and thus the friend class template statement covers all of them.

A: Not friend exactly,  but you may be able to restrict access using some variant of the Passkey pattern
If you create a protected inner Passkey class in your base class. Any derived classes can then restrict access to siblings by requiring the Passkey as a parameter:
class A {
protected:
  class Passkey {};
};

class B : public A {
public:
  void someProtectedFunction(Passkey) {};
};

class C : public A {
public:
  void somePublicFunction() {
    B b;
    b.someProtectedFunction(A::Passkey{});
  }
};

int main() {
  C c;
  c.somePublicFunction();

  B b;
  //b.someProtectedFunction(A::Passkey{});  // error: `class A::Passkey` is protected
}


text:
Q: Is it possible to change core javascript function with extensions I am trying to change default javascript parameters. I want to create extension for prevent getting screen size of web sites. When websites would get clients screen size it will notify and prevent it. Is it possible to do that?

>> window.screen.width
1366
>> window.screen.width = 800
800
>> window.screen.width
1366

A: window.screen is a built-in getter/setter. If you want to notify when it's accessed, you can overwrite the property with your own getter:

Object.defineProperty(window, 'screen', {
  get() {
    console.log('Tried to get window.screen, preventing');
    throw new Error();
  },
  set() {
  }
});

console.log(window.screen.availHeight);

You might consider returning dummy data instead, though, so that the page's JS still has a chance of running, eg:

Object.defineProperty(window, 'screen', {
  get() {
    console.log('Tried to get window.screen, preventing and returning false data');
    return {
      availHeight: 800,
      availLeft: 0,
      availTop: 0,
      availWidth: 800,
      colorDepth: 24,
      height: 800,
      orientation: {angle: 0, type: "landscape-primary", onchange: null},
      pixelDepth: 24,
      width: 800,
    };
  },
  set() {
  }
});

console.log(window.screen.availHeight);


text:
Q: How do I set up a Spring Data Neo4j integration test with JUnit 5 (in Kotlin)? Most examples around the Web for doing Spring integration tests with Neo4j are still on JUnit 4, and use the Neo4jRule.
How do we create a setup for Neo4j + Spring + JUnit 5?

A: If you are testing on embedded, please use the Test Harness with a simple Spring Configuration.
Here are some examples:
https://medium.com/neo4j/testing-your-neo4j-based-java-application-34bef487cc3c
https://github.com/michael-simons/neo4j-sdn-ogm-tips/tree/master/examples/using-the-test-harness
https://github.com/michael-simons/neo4j-sdn-ogm-tips/tree/master/examples/using-testcontainers
https://github.com/neo4j/neo4j-java-driver-spring-boot-starter/tree/master/examples/testing-with-neo4j-harness
I would have an eye on the above ^^
This and test containers will be our way forward.
Note: The @Neo4jExtension is mostly used internally by the core team and not recommended for general use.


text:
Q: How to undo after copying a file in centos I wanted to copy contents of one file to another but by mistake i copied the new file to file having contents. So now file which had data is overwritten and is empty. Is there a way to revert this process back without backup. Any way?
centos 6.4

A: Unfortunately Linux doesn't provides undo feature, as far as data concern which tool do you use to take image based data backup.


text:
Q: How can i select particular currency from api in python? I want to select TRY currency from an api. When i print that request text, it shows dozens of currencies. How can i select only one currency (TRY)?
Code is below. This code gives the currency list.
import pandas as pd
from datetime import datetime

rsp = requests.get("https://openexchangerates.org/api/latest.json?app_id=KEY").json()

print(rsp)

A: import pandas as pd
import requests
from datetime import datetime

rsp = requests.get("https://openexchangerates.org/api/latest.json?app_id=c92e9bfec2584ff0848965f86681ec37").json()

print(rsp["rates"]["TRY"])

A: You can either use square brackets or .get() to access a key of the result you got from the api (as a dictionary)
import requests
rsp = requests.get("https://openexchangerates.org/api/latest.json?app_id=c92e9bfec2584ff0848965f86681ec37").json()

In your case TRY is listed inside rates. You can access it like this:
rsp.get("rates").get("TRY")


text:
Q: How to configure kile in texlive 2010? How to configure kile in texlive 2010?

A: put the .../texlive/bin/../ to your path and everything will be fine. A good idea is to create a file zzz-texlive.sh in /etc/profile.d/:
export PATH=/usr/local/texlive/2010/bin/`uname -i`-linux:$PATH
export MANPATH=/usr/local/texlive/2010/texmf/doc/man:$MANPATH
export INFOPATH=/usr/local/texlive/2010/texmf/doc/info:$INFOPATH
unset TEXINPUTS
unset TEXMFCONFIG

replace 2010 with your current texlive year or change the whole path if you have another location of texlive.

A: I just went through the painful process of getting TeXLive 2010 installed and getting it to work with Kile. Here are the steps I had to take:

*

*Uninstall Kile

*Uninstall all signs of texlive in synaptic

*Install TeXLive 2010 http://tug.org/texlive/quickinstall.html

*Reinstall Kile from source http://kile.sourceforge.net/download.php

*Make it so I can run kile easily from the command line
alias kile='KDEDIRS=$HOME/kile-install:$KDEDIRS $HOME/kile-install/bin/kile'

*And also change the path in /etc/environment (mine now reads:)

PATH="/usr/local/texlive/2010/bin/x86_64-linux:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

I also tried a few other things like changing paths and folder names in the process, but I don't think those affected it much.

A: *

*Edit the /etc/enviroment file as root and add the path directly,
like:
sudo gedit /etc/enviroment

*then add the path, it should look something like this (if you distribution is 32 bit)
PATH="/usr/local/texlive/2010/bin/i386-linux:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

*logout or reboot

*next puge kile out of you system
sudo apt-get purge kile kbibtex then

*add this PPA   https://launchpad.net/~koshi/+archive/ppa

*update and reinstall kile

P.S. Just one note, when you do a sudo tlmgr update --all it wont work. You just have to do a sudo su then  tlmgr update --all


text:
Q: How can I use the az --query command to list all of the json fields but not their values? eg. az account list --query  I'm looking for an 'az' --query syntax that just lists the json fields and not their values.
this will print a table:
az account list --query [*] -o --table

Name    State  IsDefault  TenantId    CloudName

----    -----  ---------  --------    ---------

bob     Enabled True       nnn        AzureCloud

but I don't want the values under the column names, I just want a list of the column names.

A: Context

*

*MSFT azure cloud shell console (as of 2019-11-17)

*azure cloud shell az commands with queries

Use-case

*

*User_broglock wants a query to return the field-names (and not field-values) from the output result of a cloud shell az account list command

Solution

*

*complete command

az account list --query '@|[0]|keys(@)|[*].{"FieldName":@}' --output table

*

*demo result

FieldName
-----------
id
name
state
user
isDefault
tenantId
cloudName

Explanation

*

*The Azure CLI uses the --query argument to execute a JMESPath query

*JMESPath supports the keys() function, which returns the names in a JSON name-value-pair object (aka dictionary) (aka associative array) (aka HashTable)

*After extracting with keys() we return the result as a list of name-value pairs: {"Fieldname":<CurrentItemFromList>} ... this essentially gives us a table with one column.

Diagram

See also

*

*https://learn.microsoft.com/en-us/cli/azure/query-azure-cli?view=azure-cli-latest


text:
Q: Python function return the same value for each row i want to pos-tagging a dataset of .csv file. I create a function which i hope can return the value of the pos-tagged words. But the value that return , instead give a value of the row , it return all of the value on every row. What do i miss? Is it because of the datatype or sum? anyway , here's the code that i wrote
def postagging(text):
pos_emotion = ct.tag_sents([df.emotion])
return pos_emotion

df['pos_emotion'] = df['emotion'].apply(postagging)
df

and here's the result

I'm sorry if i don't explain really clear, my english is not so good.

A: You are getting the same value because every time you are passing [df.emotion] that is entire column of the dataframe instead of text that will be the value you want to process.
if you want to do postagging for each row you should modify your function in the following way:
def postagging(text):
   pos_emotion = ct.tag_sents([text])
   return pos_emotion

hope it helps.


text:
Q: Get date from week number Please what's wrong with my code:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d, "%Y-W%W")
print(r)

Display "2013-01-01 00:00:00", Thanks.

A: import datetime
res = datetime.datetime.strptime("2018 W30 w1", "%Y %W w%w")
print res

Adding of 1 as week day will yield exact current week start. Adding of timedelta(days=6) will gives you the week end.
datetime.datetime(2018, 7, 23)

A: In Python 3.8 there is the handy datetime.date.fromisocalendar:
>>> from datetime import date
>>> date.fromisocalendar(2020, 1, 1)  # (year, week, day of week)
datetime.date(2019, 12, 30, 0, 0)

In older Python versions (3.7-) the calculation can use the information from  datetime.date.isocalendar to figure out the week ISO8601 compliant weeks:
from datetime import date, timedelta

def monday_of_calenderweek(year, week):
    first = date(year, 1, 1)
    base = 1 if first.isocalendar()[1] == 1 else 8
    return first + timedelta(days=base - first.isocalendar()[2] + 7 * (week - 1))

Both works also with datetime.datetime.

A: To complete the other answers - if you are using ISO week numbers, this string is appropriate (to get the Monday of a given ISO week number):
import datetime
d = '2013-W26'
r = datetime.datetime.strptime(d + '-1', '%G-W%V-%u')
print(r)

%G, %V, %u are ISO equivalents of %Y, %W, %w, so this outputs:
2013-06-24 00:00:00

Availabe in Python 3.6+; from docs.

A: If anyone is looking for a simple function that returns all working days (Mo-Fr) dates from a week number consider this (based on accepted answer)
import datetime

def weeknum_to_dates(weeknum):
    return [datetime.datetime.strptime("2021-W"+ str(weeknum) + str(x), "%Y-W%W-%w").strftime('%d.%m.%Y') for x in range(-5,0)]

weeknum_to_dates(37)

Output:
['17.09.2021', '16.09.2021', '15.09.2021', '14.09.2021', '13.09.2021']

A: A week number is not enough to generate a date; you need a day of the week as well. Add a default:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")
print(r)

The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:
2013-07-01 00:00:00

%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.
See the strftime() and strptime() behaviour section in the documentation, footnote 4:

When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.

Note, if your week number is a ISO week date, you'll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.

A: In case you have the yearly number of week, just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta

>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)

A: Another solution which worked for me that accepts series data as opposed to strptime only accepting single string values:
#fw_to_date
import datetime
import pandas as pd

# fw is input in format 'YYYY-WW'
# Add weekday number to string 1 = Monday
fw = fw + '-1'
# dt is output column
# Use %G-%V-%w if input is in ISO format
dt = pd.to_datetime(fw, format='%Y-%W-%w', errors='coerce')

A: Here's a handy function including the issue with zero-week.


text:
Q: How to perform a pipeline aggregation without returning all buckets in Elasticsearch I'm using Elasticsearch 2.3 and I'm trying to perform a two-step computation using a pipeline aggregation.
I'm only interested in the final result of my pipeline aggregation but Elasticsearch returns all the buckets information.
Since I have a huge number of buckets (tens or hundreds of millions), this is prohibitive. Unfortunately, I cannot find a way to tell Es not to return all this information.
Here is a toy example. I have an index test-index with a document type obj. obj has two fields, key and values.
curl -XPOST 'http://10.10.0.7:9200/test-index/obj' -d '{
  "value": 100,
  "key": "foo"
}'

curl -XPOST 'http://10.10.0.7:9200/test-index/obj' -d '{
  "value": 20,
  "key": "foo"
}'

curl -XPOST 'http://10.10.0.7:9200/test-index/obj' -d '{
  "value": 50,
  "key": "bar"
}'

curl -XPOST 'http://10.10.0.7:9200/test-index/obj' -d '{
  "value": 60,
  "key": "bar"
}'

curl -XPOST 'http://10.10.0.7:9200/test-index/obj' -d '{
  "value": 70,
  "key": "bar"
}'

I want to get the average value (over all keys ) of the minimum value of objs having the same keys.
An average of minima.
Elasticsearch allows me to do this:
curl -XPOST 'http://10.10.0.7:9200/test-index/obj/_search' -d '{
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggregations": {
    "key_aggregates": {
      "terms": {
        "field": "key",
        "size": 0
      },
      "aggs": {
        "min_value": {
          "min": {
            "field": "value"
          }
        }
      }
    },
    "avg_min_value": {
      "avg_bucket": {
        "buckets_path": "key_aggregates>min_value"
      }
    }
  }
}'

But this query returns the minimum for every bucket, although I don't need it:
{
  "took": 21,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 4,
    "max_score": 0,
    "hits": [

    ]
  },
  "aggregations": {
    "key_aggregates": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "bar",
          "doc_count": 2,
          "min_value": {
            "value": 50
          }
        },
        {
          "key": "foo",
          "doc_count": 2,
          "min_value": {
            "value": 20
          }
        }
      ]
    },
    "avg_min_value": {
      "value": 35
    }
  }
}

Is there a way to get rid of all the information inside "buckets": [...]? I'm only interested in avg_min_value.
This might not seem like a problem in this toy example, but when the number of different keys is not big (tens or hundreds of millions), the query response is prohibitively large, and I would like to prune it.
Is there a way to do this with Elasticsearch? Or am I modelling my data wrong?
NB: it is not acceptable to pre-aggregate my data per key, since the match_all part of my query might be replaced by complex and unknown filters.
NB2: changing size to a non-negative number in my terms aggregation is not acceptable because it would change the result.

A: I had the same issue and after doing quite a bit of research I found a solution and thought I'd share here.
You can use the Response Filtering feature to filter the part of the answer that you want to receive.
You should be able to achieve what you want by adding the query parameter filter_path=aggregations.avg_min_value to the search URL. In the example case, it should look similar to this:
curl -XPOST 'http://10.10.0.7:9200/test-index/obj/_search?filter_path=aggregations.avg_min_value' -d '{
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggregations": {
    "key_aggregates": {
      "terms": {
        "field": "key",
        "size": 0
      },
      "aggs": {
        "min_value": {
          "min": {
            "field": "value"
          }
        }
      }
    },
    "avg_min_value": {
      "avg_bucket": {
        "buckets_path": "key_aggregates>min_value"
      }
    }
  }
}'

PS: if you found another solution would you mind sharing it here? Thanks!


text:
Q: Unexpected behavior of Series I noticed something strange today. Consider the code
Series[x + x^2, {x, 0, 2}]

This of course outputs the usual series cut of at the second power of x. If I run instead
Series[x + x^2, {x, 0, 1}]

I get the series untill x, but if I run
Series[x + x^2, {x, 0, 0}]

I again get the series until the first power of x instead of 0, which is what I would have guessed I should obtain. How can I force this behavior?


text:
Q: Google SignIn CocoaPods deprecated How to implement Google SignIn in iOS app as now Google pod is deprecated?
Using the deprecated pod is giving
: Framework not found GoogleAppUtilities

A: New pod location is:-
 pod 'GoogleSignIn'

A: The pod install is indeed 'GoogleSignIn' . However this also means adjusting the bridging header to
#import <GoogleSignin/GoogleSignIn.h>

And instead of using :
GGLContext.sharedInstance().configureWithError(&configureError)

You need to use :
GIDSignIn.sharedInstance().clientID = kClientID

And replace kClientID with your client id (You can/need to remove some other lines also regarding the &configureError).
You can find the info here : Google Sign-In
The Pod install now follows the manually install method mentioned in the blue notes.


text:
Q: How to include pdfpage with subsection written on top? I am using pdfpages package and I have a 3 page document of pdf I want to insert into my main document. But the problem is I can't get the subsection heading to show on the top of the page before the pdf file is inserted ONLY ONCE. I used pagecommand but what that does is for everypage it writes out the subsection at the top. Here is the code im using
Here is the code I am using
\usepackage{pdfpages}
...
\includepdf[pages=-,pagecommand=\subsection{List of use cases}]{SE2.pdf}

What am i doing wrong?

A: You could use a command that inserts a section head then redefines itself to do nothing:
\def\mysect{%
\subsection{List of use cases}%
\gdef\mysect{}}

\includepdf[pages=-,pagecommand=\mysect]{SE2.pdf}


text:
Q: Roll back data before saving to mongoDB database java standalone application I'm new to mongoDB and trying to use mongo database for my desktop application which I use javaFX as frontend.The version of mongo-java-driver is 3.10.1 and up to now can add data to db successfully.I want to perform Roll Back if any of textfields are empty.isValidText boolean check whether textfields are empty.Do I really need to roll back?If so how can I perform roll back?
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("testDB");
        DBCollection coll = db.getCollection("test");

        BasicDBObject doc = new BasicDBObject("name", nameTxt.getText().toString())
                .append("type", typeTxt..getText().toString())
                .append("count", countText.getText().toString())
                .append("info", infoTxt.getText().toString());
                if (isValidText){
                    coll.insert(doc);
                }else{
                    System.out.println("Text Fields are empty");
                }


text:
Q: Performance of Ray Tracing I wonder whether we can formulate the performance of ray-tracing. In my primitive ray-tracer, performance depends on this formula mostly: width x height x number of sampler x (number of objects + number of lights)
So for example, in Pixar or any other big companies, do they follow such formula for performance evaluation. Isn't performance depends on triangle count of the objects? For example if I want to calculate roughly the maximum render time of the frame of 1000x1000 with average 500 objects that consists 5.000.000 triangles, would it be possible?

A: Ray tracers used for serious work use various acceleration methods that make them proportional to log(triangles), not number of triangles.  And sometimes sublinear with respect to the number of lights as well (excluding lights that can't affect parts of the scene, collectively sampling all lights at once, that sort of thing).
On the other hand, material changes (even with a fixed resolution and scene geometry) can make a big change as well.  For example, making things more or less reflective/refractive can have big changes in the average "ray depth" of the scene.
Generally speaking, for a given set of geometry, lights, and materials, time should be linearly proportional to the total number of rays (i.e. resolution and sampling rate), but that can be thrown off for really big scenes that are partially serialized on reading the scene input (which may be GB and GB of parsing) and reading of texture from disk or network (we routinely have scenes that reference >> 1 TB of texture).
So overall, you would expect time to be somewhat related to:
scene_I/O + xres * yres * samples * (shading_factor + texture_factor + log(triangles)) + texture_I/O
The I/O numbers and arbitrary shading and texture factors that have to do with your materials can make it all hard to predict accurately.

A: You can only have the upper boundary of the performance.
for example, the calculation would be very fast if all polygons (triangles or others) are not in the view.
But if you wish to calculate the upper boundary you need to define the algorithm specifics: are you using marching-cubes? do you remove back-face polygons, etc...
but for a specific algorithm, the calculation should be pretty straight forward.
p.s. the number of objects is irrelevant only the sum of all their polygons.


text:
Q: The group of $k$-automorphisms of $k[x_1,\ldots,x_n,x_1^{-1}]$ Let $k$ be a field (of characteristic zero).
For $k[x_1,\dotsc,x_n]$ it is known that the affine and triangular automorphisms generate $G_n$, the group of automorphisms of $k[x_1,\dotsc,x_n]$,
see, for example, van den Essen's book "Polynomial automorphisms and the Jacobian conjecture".
It is also known that $G_2$ is a free amalgamated group, see, for example, Dicks's paper "Automorphisms of the polynomial ring in two variables".
This question asks what is $\hat G_n$, the group of automorphisms of $k[x_1,\dotsc,x_n,x_1^{-1},\dotsc,x_n^{-1}]$.
Now, my question is:

What is $\tilde G_n$, the group of automorphisms of $k[x_1,\dotsc,x_n,x_1^{-1}]$? Namely, we only invert one variable, say $x_1$.

Thus far, what I was able to obtain is as follows:
(1) $k[x,x^{-1}]$: This case was already done in the answer to the above mentioned question.
(2) $k[x,x^{-1},y]$: If $f$ is an automorphism, then it is necessary that $f(x)$ is invertible in $k[x,x^{-1},y]$, so (if I am not wrong), $f(x)=\lambda x^d$, for some non-zero scalar $\lambda$ and some integer $d$. In order to be surjective, $d \in \{\pm1\}$. Then, unless I am missing something, $f(y)$ must be of the following form: $\varphi(y)= \mu y + \sum_{i=s}^{t}c_i x^{i}$, where $\mu$ is a non-zero scalar, $c_i$ are scalars, and $s \leq t$ are integers. So there are only 'a few' automorphisms,
which are similar to the usual triangulars (the difference is the existence of negative exponents for $x$).
(3) Perhaps the $n \neq 3$ is similar to the $n=2$ case.

A: I repeat my comment as an answer as suggested.
Your argument for $n=2$ generalises and shows that $x_1$ is always mapped to some $\lambda x_1^m$ for $\lambda\in k^\times$ and $m\in\{\pm1\}$. Therefore if you consider the subring $S:=k[x_1^{\pm1}]$, a general $k$-linear automorphism of $R:=k[x_1^{\pm 1},x_2,\ldots,x_n]$ is a composition of a $S$-linear automorphism of $S[x_2,...,x_n]$ and a $k$-linear automorphism of $S$ (acting on $S[x_2,...,x_n$] by acting on coefficients). Phrased slightly differently
$$Aut_k(R) = Aut_S(S[x_2,\ldots,x_n])\rtimes Aut_k(S) = Aut_S(S[x_2,\ldots,x_n]) \rtimes (k^\times \rtimes \{\pm1\})$$
But note that $Aut_S(S[x_2,\ldots,x_n])$ is not the group $G_{n-1}$, only a subgroup of it (and for a different field of coefficients: $k(x_1)$ instead of $k$), because $S$ is not a field. Nevertheless, this gives you a lot more information than you had before.


text:
Q: Element attribute value is null even if the attribute has specific value Below is the part of html of a modal pop up in our website
<div id="DeliveryDateModal" class="modal fade in" role="dialog" data-backdrop="static" data-keyboard="false" style="display: block; padding-right: 17px;" aria-hidden="false">

If the popup is displayed the attribute aria-hidden value is true and otherwise it is false.
When I am trying to read the attribute value using Selenium webdriver
String value driver.findElement(By.id("DeliveryDateModal")).getAttribute("aria-hidden");

the string 'value' is always null. Why is that it is null even though the attribute has a specific value

A: Try with java script.
String script = "return document.getElementById('DeliveryDateModal').getAttribute('aria-hidden');";
String value = ((JavascriptExecutor) driver).executeScript(script).toString();


text:
Q: Chinese remainder theorem induction I came across this somewhere,

An important consequence of the chinese remainder theorem is that when studying modular arithmetic in general, we can first study modular arithmetic a prime power and then appeal to the Chinese Remainder Theorem to generalize any results. For any integer $n$, we factorize $n$ into primes $n=p_{1}^{k_1}\dots p_{m}^{k_m},$ and then use the Chinese Remainder Theorem to get
$$ℤ_n=ℤ_{p_{1}^{k_1}}×\cdots ×ℤ_{p_{m}^{k_m}}$$
To prove statements in $ℤ_{{p}^{k}}$, one starts from $ℤ_{{p}}$, and inductively works up to $ℤ_{{p}^{k}}$. Thus the most important case to study is $ℤ_{{p}}$.

Can someone help me do the induction on this?

A: Suppose you want to find the last 2 digits of $2^{80}$
i.e. what is $2^{80} \pmod {100}$
The Chinese remainder theorem says to look at:
$2^{80} \pmod {2},2^{80} \pmod {5}, 2^{80} \pmod {4}, 2^{80} \pmod {25}$
$2^{80} 4^{40}\equiv 0 \pmod {4}$
$2^{4} \equiv 1\pmod {5}$ Fermat little theorem
$2^{20} \equiv 1\pmod {25}$
We need a number that equals $1$ when divided by $25$ and $0$ when divided by $4,$ and is less than $100.$
$76$

A: You need to show that if all primes $p_1$ to $p_m$ are distinct then the ideals $p_{i}^{a_i}\mathbb{Z}$ and $p_{j}^{a_j}\mathbb{Z}$ are comaximal, for all $i\neq j$, that is we can say $p_{i}^{a_i}\mathbb{Z}+p_{j}^{a_j}\mathbb{Z}=\mathbb{Z}$ (due to the fact there exist integers $a$, $b$ s.t. $p_ia+p_jb=1$). Then the map
$$\mathbb{Z}\rightarrow (\Bbb{Z}/p_1^{a_1}\Bbb{Z})\times (\Bbb{Z}/p_2^{a_2}\Bbb{Z})\times\dotsm\times(\Bbb{Z}/p_{m}^{a_m}\Bbb{Z})$$
is a surjection, with kernel
$$p_{1}^{a_1}\Bbb{Z}\cap p_{2}^{a_2}\Bbb{Z}\cap\dotsm \cap p_{m}^{a_m}\Bbb{Z}
=p_{1}^{a_1}\Bbb{Z}\cdot p_{2}^{a_2}\Bbb{Z}\dotsm  p_{m}^{a_m}\Bbb{Z}
$$
hence
\begin{align*}
\Bbb{Z}/(p_{1}^{a_1}\Bbb{Z} p_{2}^{a_2}\Bbb{Z} \dotsm p_{m}^{a_m}\Bbb{Z} )
&=\mathbb{Z}/(p_{1}^{a_1}\Bbb{Z} \cap p_{2}^{a_2}\Bbb{Z} \cap\dotsm\cap p_{m}^{a_m}\Bbb{Z} )\\
&\cong(\mathbb{Z}/p_{1}^{a_1}\Bbb{Z}) \times (\mathbb{Z}/p_{2}^{a_2}\Bbb{Z})\times\dotsm\times(\mathbb{Z}/p_{m}^{a_m}\Bbb{Z})
\end{align*}
First do this for two prime powers, $p_1^{a_1}$ and $p_2^{a_2}$. Consider the map
$$\sigma : \mathbb{Z}\longrightarrow(\mathbb{Z}/p_{1}^{a_1}\Bbb{Z}) \times (\mathbb{Z}/p_{2}^{a_2}\Bbb{Z})$$
defined by
$$\sigma(z)=(z\,\operatorname{mod}p_1^{a_1},\ z\,\operatorname{mod} p_2^{a_2})$$
with $z\pmod{p_1^{a_1}}$ meaning the class in $\mathbb{Z}/p_{1}^{a_1}\Bbb{Z}$ containing $z$. For brevity define $A=p_{1}^{a_1}\Bbb{Z}$ and $B=p_{2}^{a_2}\Bbb{Z}$. We have $\sigma$ is a ring homomorphism, projecting $\Bbb{Z}$ into the two components $\Bbb{Z}/A$ and $\Bbb{Z}/B$ of the direct product.
The kernel of the homomorphism are the elements $e\in\Bbb{Z}$ that are in both of the ideals $A$, and $B$: $\ker(\sigma)=A\cap B$.
Since the $\gcd(p_1,p_2)=1$, the ideals $A$ and $B$ are comaximal. Hence there are elements $x\in A$ and $y\in B$ s.t. $x+y=1$. Thus
$$\sigma(x)=(x\,\operatorname{mod}p_1^{a_1},\ 1-y\,\operatorname{mod}p_2^{a_2})=(0,1),$$
$$\sigma(y)=(1-x\,\operatorname{mod}p_1^{a_1},\ y\,\operatorname{mod}p_2^{a_2})=(1,0).$$
Now if $(z_1\,\operatorname{mod}p_1^{a_1},\ z_2\,\operatorname{mod}p_2^{a_2})$ is an arbitrary element of $\Bbb{Z}/A\times  \Bbb{Z}/B$, then the element $z_2x+z_1y$ maps under $\sigma$ to:
\begin{align*}
\sigma(z_2x+z_1y)&=\sigma(z_2)\,\sigma(x)+\sigma(z_1)\,\sigma(y)\\
&=(z_2\,\operatorname{mod}p_1^{a_1},\ z_2\,\operatorname{mod}p_2^{a_2})\,(0,1)+(z_1\,\operatorname{mod}p_1^{a_1},\ z_1\,\operatorname{mod}p_2^{a_2})\,(1,0)\\
&=(0,\ z_2\,\operatorname{mod}p_2^{a_2})+(z_1\,\operatorname{mod}p_1^{a_1},0)\\
&=(z_1\,\operatorname{mod}p_1^{a_1},\ z_2\,\operatorname{mod}p_2^{a_2})
\end{align*}
Hence $\sigma$ is surjective. We always have the ideal $AB\subseteq A\cap B$. Since $A$ and $B$ are comaximal we can show the reverse inclusion: let $x\in A$ and $y\in B$ s.t. $x+y=1$, then if $c\in A\cap B$, we have $c=cx+cy\in AB$, and $A\cap B\subseteq AB$. This proves the case for the two ideals $A$ and $B$.
Now for the induction, which follows from the case of two ideals: Let $A_1=p_{1}^{a_1}\Bbb{Z}$ and $A_2\dotsm A_m=p_{2}^{a_2}\Bbb{Z}\dotsm p_{m}^{a_m}\Bbb{Z}$. These are two ideals $A_1$ and $A_2\dotsm A_m$, which are comaximal. To see this let $x_i\in p_{1}^{a_1}\Bbb{Z}$ and $y_i\in p_{i}^{a_i}\Bbb{Z}$ s.t. $x_i+y_i=1$, $i\in\{2,3,\dotsc,m\}$, with $x_i+y_i\equiv y_i\pmod{p_1^{a_1}}$, and so $1=(x_2+y_2)(x_3+y_3)\dotsm(x_m+y_m)$ is an element in $p_{1}^{a_1}\Bbb{Z}+(p_{2}^{a_2}\Bbb{Z}\dotsm p_{m}^{a_m}\Bbb{Z})=\Bbb{Z}$.
Then if the prime factorisation of $n$ is $n=p_{1}^{a_1}p_{2}^{a_2}\dotsm p_{m}^{a_m}$, the factorisation of the ring $\Bbb{Z}/n\Bbb{Z}$ into a direct product of the rings of integers modulo the prime factors is the ring isomorpism:
$$\Bbb{Z}/n\Bbb{Z}\cong (\Bbb{Z}/p_1^{a_1}\Bbb{Z})\times (\Bbb{Z}/p_2^{a_2}\Bbb{Z})\times\dotsm\times(\Bbb{Z}/p_{m}^{a_m}\Bbb{Z})$$
As multiplicative groups we also have the isomorphism:
$$(\Bbb{Z}/n\Bbb{Z})^{\times}\cong (\Bbb{Z}/p_1^{a_1}\Bbb{Z})^{\times}\times (\Bbb{Z}/p_2^{a_2}\Bbb{Z})^{\times}\times\dotsm\times(\Bbb{Z}/p_{m}^{a_m}\Bbb{Z})^{\times}$$
whose order is given by:
$$\phi(n)=\phi(p_1^{a_1})\phi(p_2^{a_2})\dotsm\phi(p_m^{a_m})$$
where $\phi$ is the Euler totient function, and $\phi(p^a)=p^{a-1}(p-1)$.

A: It would be more accurate to say $ℤ_n \cong ℤ_{p_{1}^{k_1}}×\cdots ×ℤ_{p_{m}^{k_m}}$ as the left and right sides are isomorphic to each other, not equal.
By $``$inductively works up to $\mathbb Z_{p^k}"$, the author suggests that you first solve the problem for $\mathbb Z_p$, then for $\mathbb Z_{p^2}$, and so on until, eventually, you see a pattern which you can state as an hypothesis.  Then, hopefully, you can then prove that hypothesis using induction.
Exactly what the induction is will depend almost entirely on the problem you are trying to solve. So, without an actual problem, there is no way we can tell you how to do the induction.


text:
Q: clojure extend-type vs deftype and protocol implementation In the e-book about specter, there is this passage:

We need to define ALL's type like this:
(deftype AllType [])
Finally, we need to add the AllType
  implementation of select*
(extend-type AllType   Navigator   (select*
[this structure continuation]
    ...))

(If you're fluent with protocols, you may wonder why we don't define select* when we define the type:
(deftype AllType []
  Navigator
  (select* [this structure continuation]
    ...))

The reason is that the implementation-dependent lookup of specific protocol functions doesn't work for functions defined that way.)

I don't really get what the author is trying to say here. What is the difference between extend-type and deftype + in-place implementation?

A: I just finished reading the Clojure Polymorphism book which discusses this a bit in the last chapter.  You may wish to look there for more details.
The gist of it is that they seem the same conceptually, but they are not.
He describes a semantic "gotcha" since a Java class also defines a namespace. For example:
(ns my.ns)
(defprotocol Foo  (run [this]))

(ns your.ns)
(defprotocol Foo  (run [this]))

(ns user)
(defrecord FooAble [])
(extend-protocol my.ns/Foo
  FooAble
  (run [this] (println "Foo Me")))
(extend-protocol your.ns/Foo
  FooAble
  (run [this] (println "Foo You")))

(println 1 (->FooAble))
(def some-foo (->FooAble))

(my.ns/run   some-foo)  => Foo Me
(your.ns/run some-foo)  => Foo You

In Java you would try to say
someFoo.run()  =>  Which `run` method...?

So in Clojure I can have 2 run methods with the same name & signature on a single object iff I use extend-protocol. If I try to define inline it crashes:
(defrecord BeerAble []
  my.ns/Beer
  (run [this] (println "Beer Me"))
  your.ns/Beer
  (run [this] (println "Beer You")))

(println 2 (->BeerAble))
(def some-beer (->BeerAble))

(my.ns/run   some-beer)
(your.ns/run some-beer)

;=>  CompilerException java.lang.ClassFormatError: Duplicate method name&signature in class file user/BeerAble,

So the inline definnition is like trying to hava a Java interface with two void run() methods. To make it work you would have to change the method names to be myRun and yourRun which is kludgy at best and impossible if two external libs have already chosen the function name run and are now clashing.

Having not read the Spectre book I can't say if this directly answers the original question, but you may wish to experiment a bit. Unless you have the clashing namespace/function problem it seems you should get the same results either way. You could also profile your program to determine if one or the other speeds up your program.
Looking at the text more closely now, I can't see that it should make any difference for the use-case he cites. You could experiment to verify the answer.


text:
Q: WiFi Problem for Atheros Based Card in Toshiba My laptop is Toshiba C50-A628. The WIFI card in the laptop is Qualcomm Atheros ath9k. I am unable to turn on and see wifi networks through the laptop.

A: Check to see if the wireless hardware switch is turned off( assuming it has one) and turn it on. It's usually located near the wireless indicator light.


text:
Q: Debugging Entity Framework Model Building Exception I'm hitting the error

Sequence contains more than one matching element

after upgrading EF from 6.1.0-beta1 to the latest 6.1.3 in my ASP.NET MVC project.
Stack trace is included below, and since it shows the exception is thrown during model building, I assume there's an issue with my model that was OK in the previous EF version (my model hasn't changed), but since my model is rather extensive I've been searching high and low for a way to get any information about the specific table/class where the problem occurs.
I've tried enabling debugging .NET framework code in VS to see if I could reach the exception in the debugger, but it fails to download the debug symbols for Entity Framework. I've tried downloading the source, and building it to point to the .pdb file, but it wouldn't accept it.
I've even tried changing the references to my own build of EF, but got an error because it wasn't signed.
How can I find out which entity/class/table has the problem?
UPDATE: Through trial and error, it turns out the error appears when updating from Entity Framework version 6.1.0 to 6.1.1.

[InvalidOperationException: Sequence contains more than one matching element]
  System.Linq.Enumerable.SingleOrDefault(IEnumerable'1 source, Func'2 predicate) +4380333
  System.Data.Entity.ModelConfiguration.Configuration.Mapping.<>c__DisplayClass4a.b__47(ForeignKeyBuilder fk) +178
  System.Data.Entity.Utilities.IEnumerableExtensions.Each(IEnumerable'1 ts, Action'1 action) +130
  System.Data.Entity.ModelConfiguration.Configuration.Mapping.ForeignKeyPrimitiveOperations.RemoveAllForeignKeyConstraintsForColumn(EntityType table, EdmProperty column, DbDatabaseMapping databaseMapping) +155
  System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingConfiguration.CleanupUnmappedArtifacts(DbDatabaseMapping databaseMapping, EntityType table) +1312
  System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingConfiguration.Configure(DbDatabaseMapping databaseMapping, ICollection'1 entitySets, DbProviderManifest providerManifest, EntityType entityType, EntityTypeMapping& entityTypeMapping, Boolean isMappingAnyInheritedProperty, Int32 configurationIndex, Int32 configurationCount, IDictionary'2 commonAnnotations) +1719
  System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureTablesAndConditions(EntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, ICollection'1 entitySets, DbProviderManifest providerManifest) +155
  System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection'1 entitySets, DbProviderManifest providerManifest) +105
  System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest) +361
  System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) +434
  System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +55
  System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
  System.Data.Entity.Internal.RetryLazy'2.GetValue(TInput input) +123
  System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +627
  System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
  System.Data.Entity.Internal.Linq.InternalSet'1.Initialize() +53
  System.Data.Entity.Internal.Linq.InternalSet'1.GetEnumerator() +15
  System.Data.Entity.Infrastructure.DbQuery'1.System.Collections.Generic.IEnumerable.GetEnumerator() +53
  System.Collections.Generic.List'1..ctor(IEnumerable'1 collection) +375
  System.Linq.Enumerable.ToList(IEnumerable'1 source) +58
  Scanboat2014.Repositories.ScanboatAdRepository..ctor() in C:\Users\Martin\Source\Repos\Scanboat\Scanboat2014\Repositories\ScanboatAdRepository.cs:26
  Scanboat2014.Controllers.HomeController..ctor() in C:\Users\Martin\Source\Repos\Scanboat\Scanboat2014\Controllers\HomeController.cs:18


text:
Q: Ignite client node does not put data though server nodes to DB (with writeThrough only on server, without writeBehind) Could you please help me with following question:
I have the following configuration of partitioned cache cluster:

*

*server nodes with writeThrough enabled. They are able to write data to DB by cacheStoreFactory=HibernateCacheStoreFactory

*client nodes without writeThrough configuration but with clientMode=true
I perform put on client node, then I see, that this data is sent to server node, but server node performs put only to cache, but does not invoke cacheStoreFactory (writeThrough behaviour). So, data is only cached in cluster, but is not written to DB.
If I add writeThrough configuration to client nodes, writeThrough is invoked of course, but I would like to remove any dependencies on Hibernate from client nodes.
Also, if I enable writeBehind configuration on server side, then writeThrough functionality is invoked and server node, writes data from client node to DB asynchronously. But it does not satisfy my requirements, because I'd like to perform puts from client node in one transaction.
Is it possible to perform puts from client node to store data by server nodes with writeThrough in transaction without writeBehind?

A: Transactional cache writes to the persistence store from the node that initiated the transaction (in your case it's a client node). This is done because a transaction can potentially include entries that are stored on different nodes, and if the store will be also updated from different nodes, it would be impossible to maintain transactional consistency between cache and the database.
If you don't have access to the database on the client, you can send a closure to one of the servers and start a transaction there, like this:
Ignition.ignite().compute().run(new IgniteRunnable() {
    @IgniteInstanceResource
    private Ignite ignite;

    @Override public void run() {
        try (Transaction tx = ignite.transactions().txStart()) {
            // Cache operations go here...

            tx.commit();
        }
    }
});


text:
Q: Почему не подключается класс? Почему у меня все работает в файле public/index.php:
use Controller\ClientsController;
$myControl = new ClientsController();
$myControl->hello();

а если я подключу вместо этой иницилизации вспомогательный файл all.php , в который вставлю эти же самые строки объявления класса:
use Controller\ClientsController;
require "../src/routes/all.php";

То в нем класс ClientsController не находится? По сути код файл all.php вставляется в index.php и при этом все должно работать нормально, неужели путь влияет на это? В чем подвох?
Структура проекта:
`-classes
--ClientsController.php
-public/
--index.php
-src/
--routes/
---all.php
`

A: Пропишите абсолютный путь, вместо 2 точек
require "../src/routes/all.php";


text:
Q: Describe the desired features of a "Mathematics Colloquium"? I'm now a member of my department's colloquium committee.  Our task is to make a great colloquium series. I thought that the first step would be to come up with an appropriate definition of "Mathematics Colloquium." Standard dictionaries are not too much help:
Colloquium: n.
 1. A usually academic meeting at which specialists deliver
    addresses on a topic or related topics and then answer questions relating to them.
 2. A conference at which scholars or other experts present papers on, analyze,
    and discuss a specific topic.

So here's my question: What is the ideal definition of a mathematics colloquium?  Of course I know a bunch of things that make for bad colloquium talks, so I'm interested in knowing the definition of a good or great mathematics colloquium.

A: A great mathematics colloquium is one which satisfies many if not all of its goals, and may have additional benefits which make it great.
A list of potential goals/benefits:

*

*accessibility: many if not all attendees can understand a talk

*entertainment: attendees enjoy or find the presentation enjoyable

*breadth: the collection of topics covers a wide range of interests

*thematic: there is a common thread or other connection which relates the
different talks and draws connections

*stimulating: encourages audience members to discuss and extend the subject matter
outside the colloquium

*durable:  the recording made is archive quality and can be shared with others

*effective: members of the audience can take some of the main ideas and recapitulate them for others who were not at the colloquium, and make the others understand the ideas.

Of the list above, I value being effective more highly than the other items.
Gerhard "What Are Your Colloquium Goals?" Paseman, 2015.06.07

A: Some suggestions:

*

*Let all faculty members in turn choose speakers to invite.
This ensures that everybody gets involved, and that the interests
of all faculty members are represented.

*Choose a room / building in which people feel well
(this is underestimated sometimes!), and choose a time where people
have time to attend and do not need to rush to their lectures
once the talk is over.

*After the colloquium talks, always have a joint lunch / coffee / supper
(depending on the time of the day) in some pub / restaurant etc..
This fosters discussion among faculty members working on different
fields, and with the speakers. Try to choose a different location for this
every time.

*As others have already said, tell speakers to give talks
which all faculty members can understand -- and not only
specialists in the respective field.


text:
Q: Where does Plink command look out for the private keys? I am trying to connect a Linux machine from Windows using passwordless SSH connection. I generated the keys using PuTTYgen in the Windows machine and copied the keys to the Linux machine appropriately.
From the command prompt of windows I could access passwordless using the below command:
ssh user@ipaddress

When I use Plink, if I issue the below command the passwordless connection is going through:
plink user@ipaddress -i <path to private ppk>

My question here is: in case I use plink -batch option, where does the private key file will be picked from if I don't mention -i option?
In other words, which is the default location of ppk file which Plink is looking for?
For example:
plink -batch user@ipaddress

A: Plink does not have any default location for private keys.
What you should do instead, is load the private key into Pageant (PuTTY authentication agent).


text:
Q: for loop is only looping once in Laravel 8 I have a loop that is only looping once.
Below is the code, I do not know why it is doing such.
I want the code to loop according to the number of students below is the code.
What could be the reason the script is only looping once?
$combined = [];

            // dd($students);

            foreach ($students as $key => $val) {

                $combined[] = ['student_id'=>$val, 'result'=>$result[$key], 'present_class'=>$present_class[$key]];

                $student=$combined[$key]['student_id'];
                $final_status=$combined[$key]['result'];
                $current_class=$combined[$key]['present_class'];

                $class_map_exists=ClassSequence::where('origin', $current_class)->exists();
                $class_map_doesnt_exist=ClassSequence::where('origin', $current_class)->doesntexist();

                if ($class_map_exists) {
                    //if class-map exists for that class
                    //get the next class
                    $next_class=ClassSequence::where('origin', $current_class)->first();
                    $destination=$next_class->destination;

                    if ($final_status=='Proceed' or $final_status=='Promoted') {

                        $create_new_entry=StudentClass::updateOrCreate(
                            ['student_id' => $student, 'grade_id' => $destination, 'academic_session' => $to_session, 'active'=>1],
                            ['student_id' => $student, 'grade_id' => $destination, 'academic_session' => $to_session, 'active'=>1]
                        );
                    }

                    if ($final_status=='Repeat') {
                        $create_new_entry=StudentClass::updateOrCreate(
                            ['student_id' => $student, 'grade_id' => $current_class, 'academic_session' => $to_session, 'active'=>1],
                            ['student_id' => $student, 'grade_id' => $current_class, 'academic_session' => $to_session, 'active'=>1]
                        );
                    }

                    if ($final_status=='Try Another School') {

                        User::find($student)->update(['active']);
                    }

                    flash()->overlay(''.' Congratulations. You have successfully migrated students to the next class', 'Migration Process Notice');
                    return Redirect::back();
                } else {
                    // if($class_map_doesnt_exist){
                    //else if it does not exist

                    flash()->overlay(''.' Sorry. Class Mapping does not exist. Please map classes first, to do so, please click '.' here', 'Migration Process Notice');
                    return Redirect::back();
                }
            }
        }


text:
Q: how to configure rsyslog to receive log from specic IP addresses? I want to configure rsyslog on a server so that receive logs from specific IP addresses and drop the others.is it possible?

A: Block it with your UFW (assuming 1.1.1.1 is the device generating syslogs and 2.2.2.2 is your server)
sudo ufw enable
sudo ufw allow from 1.1.1.1 to 2.2.2.2 port 514/udp
check with
sudo ufw status


text:
Q: ExPex example numbers do not align to top of TikZ pictures or tabular I'm submitting to a journal with a provided LaTeX template. They require examples to be done using ExPex. Many of my examples are in the form of TikzPicture "matrix of nodes" diagrams and tables. The default alignment for ExPex example numbers is at the top of the example (see #1 in the example below). The journal's stylesheet examples all have the example number aligned this way.
However, when I use tabular, the example number is aligned with the middle of the table (see #2). Worse yet, TikZ pictures appear entirely above the example number. I usually use [row sep=5mm], and thought that that might be affecting ExPex's alignment, however the same alignment appears with (#3) and without (#4) the custom row separation.
Is there any way to tell ExPex to align example numbers to the top of TikZ pictures and tabular environments? Another question provided a way to change the alignment of example numbers in ExPex globally (link), but unless I've misread the thread, I don't think it addresses the discrepancy between example numbering in different environments.
\documentclass{article}
\usepackage{expex}
\usepackage{tikz}
\usetikzlibrary{backgrounds,matrix,cd}
\tikzset{showall/.style={framed, every node/.style=draw}}
\begin{document}
\ex
 A multi-line \\ example.
\xe
\ex
\begin{tabular}{cccl}
    a & b & c \\
    d & e & f \\
    g & h & i
    \end{tabular}
\xe
\ex
\begin{tikzpicture}
 \matrix (m) [matrix of nodes, row sep=5mm] {
  a & b & c \\
  d & e & f \\
  g & h & i \\
  };
\end{tikzpicture}
\xe
\ex
\begin{tikzpicture}
 \matrix (m) [matrix of nodes] {
  a & b & c \\
  d & e & f \\
  g & h & i \\
  };
\end{tikzpicture}
\xe
\end{document}

A: For tikzpicture you can use the baseline option. Fix it to any coordinate you want to use as reference. Following code shows one option. tikzpicture's background rectangle and matrix border are shown for reference.
For general alignment problems you can use adjustbox package.
\documentclass{article}
\usepackage{expex}
\usepackage{tikz}
\usetikzlibrary{backgrounds,matrix,cd}
\tikzset{showall/.style={framed, every node/.style=draw}}
\begin{document}
\ex
 A multi-line \\ example.
\xe
\ex
\begin{tabular}{cccl}
    a & b & c \\
    d & e & f \\
    g & h & i
    \end{tabular}
\xe
\ex
\begin{tikzpicture}[baseline={([yshift=-3mm]current bounding box.north)}, show background rectangle]
 \matrix (m) [matrix of nodes, draw=red, row sep=5mm] {
  a & b & c \\
  d & e & f \\
  g & h & i \\
  };
\end{tikzpicture}
\xe
\ex
\begin{tikzpicture}
 \matrix (m) [matrix of nodes] {
  a & b & c \\
  d & e & f \\
  g & h & i \\
  };
 \end{tikzpicture}
 \xe
 \end{document}