text:
Q: Listing permutations of two dice with one loop As part of a coding challenge for myself, I've been trying to write code for simple problems in one line. Currently, I'm trying to print out all permutations possible for two dice. So far, I have a simple algorithm utilizing two for loops:
for(int i = 1; i <= 6; i++)
    for(int j = i; j <= 6; j++)
        printf("%d %d", i, j);

Which can be easily turned into one line:
for(int i = 1; i <= 6; i++) for(int j = i; j <= 6; j++) printf("%d %d", i, j);

Both programs output the permutations in the desired order:
1 1
1 2
1 3
1 4
1 5
1 6
2 2
2 3
2 4
2 5
2 6
3 3
3 4
3 5
3 6
4 4
4 5
4 6
5 5
5 6
6 6

In order to make this challenge harder, I'm trying to print out the permutations in the same order as the output above, using only one loop. I'm sure I'll need to use division and modulo in order to accomplish this, but I'm stuck and unsure how to achieve this.

A: The 2 loop version is the most readable. But since you asked, here are some 1 loop versions:
int main()
{
    int n = 6;
    for (int i = 1, j = 1; i < n; ++j)
    {
        if (j > n)
        {
            ++i;
            j = i;
        }
        std::cout << i << " " << j << '\n';
    }

    std::cout << std::flush;
}

int main()
{
    int n = 6;
    int i = 1;
    int j = 1;
    while (true)
    {
        if (j > n)
        {
            ++i;
            j = i;
        }
        if (i > n)
        {
            break;
        }
        std::cout << i << " " << j << '\n';
        ++j;
    }
    std::cout << std::flush;
}

As a side note:
for(int i = 1; i <= 6; i++) for(int j = i; j <= 6; j++) printf("%d %d", i, j);

This is horrible. Don't ever write code like this. The artificial goal of writing code in one line is completely and utterly pointless. You can take any code and put it on one line like that without any effort so it has absolutely not benefit, teaching or otherwise.
There is the concept of writing one-liners but that is not just replacing new lines in source code with spaces. It's about e.g. replacing loops with function calls or chain calls.
And don't forget, first and foremost write correct, clean and readable code.


text:
Q: Custom create method to prevent duplicates I would like to add some logic to my serializer.py.
Currently it creates duplicate tags (giving a new ID to the item, but often it will match a tag name already).
In plain english
if exists:
   # Find the PK that matches the "name" field
   # "link" the key with Movie Class item
else:
   # Create the "name" inside of Tag class
   # "link" the key with Movie Class item

The data being posted looks like this:
{
  "title": "Test",
  "tag": [
    {
      "name": "a",
      "taglevel": 1
    }
  ],
  "info": [

  ]
}

Models.py
class Tag(models.Model):
    name = models.CharField("Name", max_length=5000, blank=True)
    taglevel = models.IntegerField("Tag level", blank=True)
    def __str__(self):
        return self.name

class Movie(models.Model):
    title = models.CharField("Whats happening?", max_length=100, blank=True)
    tag = models.ManyToManyField('Tag', blank=True)
    def __str__(self):
        return self.title

Serializers
class MovieSerializer(serializers.ModelSerializer):
    tag = TagSerializer(many=True, read_only=False)
    class Meta:
        model = Movie
        fields = ('title', 'tag', 'info')

    def create(self, validated_data):
        tags_data = validated_data.pop('tag')
        movie = Movie.objects.create(**validated_data)
        for tag_data in tags_data:
            movie.tag.create(**tag_data)
        return movie

A: This will probably solve your issue:
tag = Tag.objects.get_or_create(**tag_data)[0]
movie.tag.add(tag)

get_or_create function returns tuple (instance, created), so you have to get instance with [0].
So the full code is:
def create(self, validated_data):
    tags_data = validated_data.pop('tag')
    movie = Movie.objects.create(**validated_data)
    for tag_data in tags_data:
        tag = Tag.objects.get_or_create(**tag_data)[0]
        movie.tag.add(tag)
    return movie

To make function case insensitive, you have to do "get or create" manually (the main part is to use __iexact in filter):
tag_qs = Tag.objects.filter(name__iexact=tag_data['name'])
if tag_qs.exists():
    tag = tag_qs.first()
else:
    tag = Tag.objects.create(**tag_data)
movie.tag.add(tag)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tesseract OCR for .net not detecting text when white text is written on black rectangle and the border of black rectangle is white? I am trying to extract a text from a png using tesseract. Tesseract doesn't extract text in case of following png.
The black rectangle in the image has white border(which is not visible because of website background).But, in case, I remove white border off the rectangle then Tesseract is able to detect the text.Is there any work around for this issue?
Also, if the decrease the border size then it does extract some text as:

I (31.04 I

Here is the code that I am using:
 using (TesseractEngine ocr = new TesseractEngine(dataPath, "eng", EngineMode.TesseractOnly))
            {
                using (Pix p = Pix.LoadFromFile(filePath))
                {
                    using (Pix img = p.Scale(2,3))
                    {

                        using (var page = ocr.Process(img))
                        {

                            string text = page.GetText();
                            Console.WriteLine(text);
                        }
                    }
                }

            }

By scaling I am able to extract following text:

I G1.04 I

However, if I increase the border size then even scaling the image has no effect.

A: using AForge.Imaging;
Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
Bitmap grImage = grayFilter.Apply(image);
grImage.Save("./grey_image.png");

Pass this image path to your TesseractEngine.


text:
Q: Django model - can't do aggregate sum with thousand comma separator and decimal points I have the following model:
class Example(models.Model):
    project_id = models.IntegerField(
        null=False,
        blank=False,
        default=0,
    )
    field1 = models.CharField(
        max_length=250,
        null=True,
        blank=True,
    )
    field2 = models.CharField(
        max_length=250,
        null=True,
        blank=True,
    )
    total = models.CharField(
        max_length=250,
        null=True,
        blank=True,
    )

Example data:

project_id
field1
field2
total

1
1,323
4,234.55
5,557.55

2
1,000
2
1,002

3
1.23
3
4.23

total = field1 + field2
I would like to sum all total values.
This is what I've tried views.py:
context['total'] = Example.objects.filter(project_id=pid).aggregate(Sum('total'))

Current output:
{'total': 10.23}

Expected output:
{'total': 6,563.78}

Or, if that's not possible at least: 6563.78 so that I can format the numbers later.
Since the project requires thousand comma separator and decimal points, I can not change or alter the model fields and use FloatField.
Any help would be much appreciated

A: Since you say you can't change the data type on the fields themselves, you can achieve this by using the Replace and Cast database functions (of course, this isn't ideal - it would be better to fix the data types in the model itself).
This should work - at least it does on a production-grade database like PostgreSQL (I am not sure it will work on SQLite - if you are using that in production then you really have problems):
from django.db.models import FloatField, Value
from django.db.models.functions import Cast, Replace

context['total'] = Example.objects.annotate(
    cleaned_total=Replace('total', Value(','), Value(''))
).annotate(
    float_total=Cast('cleaned_total', FloatField())
).aggregate(Sum('float_total'))

What this is doing is:

*

*Performing a replace on the field to remove commas.

*Passing that cleaned value to a cast function that casts the cleaned strings as floats.

*Performing a sum on the result.

A: Here are alternatives that you could look at in case solarissmoke's answer is not what you're looking for:

*

*Since aggregation/annotation needs real database fields, you could give up on aggregation/database functions and loop through the query set in python and convert the values to required numeric types (prehaps with a model method?) and sum them up.
This does come with noticeably worse performance.

*You could create additional numeric model fields that populate automatically after save (possibly by overriding the deffault save behaviour or using signals ). And then use aggregation and Sum on those numeric fields. You have to be careful about the possible conflicts with the original CharFields that would cause your results to be incorrect (i.e. missed updates, some other custom dehaviour).


text:
Q: How to use a text file's contents in HTML as text I am making a website template and I though of a cool new trick to save time when changing large text files. I want to have a separate plain text document that when the page loads, it contents will be transferred to my paragraph.
Example:
The text document:
Introducing the new red glasses.

The paragraph's text will be loaded and be the same as the text documents like so:
<p> Introducing the new red glasses. </p>

So how can I do something like this? Is it even possible? I am willing to use HTML, CSS, jQuery and Javascript.

A: You could use AJAX:
$.get( "mytext.txt", function( txt ) {
    $( "#myParagraph" ).text( txt );
});

You will need to host your HTML from a server, or otherwise it won't work


text:
Q: Question Regarding Office 365 Refresh Token starts with M.R3_BAY I get a refresh token starts with M.R3_BAY.  When I use this to get access_token and send email, it throws the following error
{"error":{"code":"InvalidAuthenticationToken","message":"CompactToken parsing failed with error code: 80049217","innerError":

From reading other posts I understand that this kind of refresh_token starting with M.R3_BAY... belongs to a  personal account. Is this due to client_id (belongs to a domain) and a personal account conflict?


text:
Q: Send byte from PC to USB communication port using java Can I send a byte from PC to usb communication port via java program?
if yes .Is there any sample code that can help in this issue??
I'm looking for sample codes or good tutorials

A: If you are using a USB-to-serial converter (which is what it sounds like) then the OS driver software presents a serial interface to applications.
I think what you need to look at is the JavaComms API - http://www.oracle.com/technetwork/java/index-jsp-141752.html.
Does this page help at all - http://alumni.media.mit.edu/~benres/simpleserial/ ?

A: When using a USB-Serial adapter the USB part can (usually) be ignored and instead you should just focus on the serial part. The USB adapter drivers will give you a virtual serial port to use as any other serial port.
For using a serial port with Java see Java Communications API or Serialio

A: You have not specified what kind of USB communication you want, so this is going to be a bit generic.
If your device identifies itself as a USB CDC you system probably already loads a driver and enables you to access it as a serial port. Similar is true if the dice identifies itself as a HID (Human Interaction Device) keyboard, mouse etc.
If you have your own type of device, then you can use javax.usb from linux (might be a port for windows). You need to identify your device from the vendor/device id, possibly configure your endpoints, device if you want control, bulk or isochronous data, create the packet, populate it with your byte(s) and then transfer it. Javax.usb has some example code.
For simplicity I'd recommend your device to be a CDC (code available, check google) and it will identify itself as a serial port and you do not need to handle any of the complexity of USB when communicating.


text:
Q: Extension of local diffeomorphism Let $(X,d)$ be a metric space where $X$ is a manifold and $\widetilde{X}$ its metric completion. Further let $X\xrightarrow{f}Y$ be a local diffeomorphism.
Can $f$ be extended to $\widetilde{X}\xrightarrow{\widetilde{f}}Y$, and if so do we have fruther information (e.g. uniqueness, structure)?
Edit
In my case, $Y$ is a Riemannian manifold $(Y,g)$ and the distance $d$ on $X$ is the one induced by the pullback metric $f^*g$.
It appears that $f$ can be extended if and only if $f$ is Cauchy-continuous. I believe this should give me the existence and uniqueness of the extension.


text:
Q: Как настроить замену с помощью регулярки Нужна замена в notepad++:
Найти все выражения находящиеся в скобках [], но только те скобки искать в которых есть одно и тоже слово в выражении, например "ЖАБА".
Заменить на пусто.
Спасибо
A: Думаю, где то такое регулярное выражение нужно
\[[^\[\]]*WORD[^\[\]]*\]

разбор по кусочкам
\[ - в начале должна быть скобка. Ее  нужно заекранировать, так ка это спецсимвол
[^\[\]]* - это нужно читать так. любой символ кроме (`^`) квадратных скобок 0 или более
WORD - собственно слово
[^\[\]]* - ещё раз
\] -  скобка в конце

А в поле "заменить на" нужно просто оставить пустоту.
A: before[r3242dexamplefswe]after -> \[.+example.+\] = beforeafter

Вводите свое повторяющие слово, а вот само чтоб искало совпадение и потом стирала, одной регулярным выражением хм ...


text:
Q: get Extra from different Intents I have an MainActivity which has different Buttons which opens the same PopUpActivty.
I am sending the tag with an Intent Extra from each Button in a Method. This Extra should help me to know which button is clicked in the MainActivity. Whit this information I want to open with one button in the PopupWindow diffrent Avtivities, depens on which button is on the MainActvity clicked.
My Problem:
I used getIntent in the PopUpWindow to get the Extra, but the Problem is, I am getting all tags from each buttons instead of just the clicked button.
 public void startPopUpActivity (View view) {

        String tag = view.getTag().toString();

        Intent startKarteikartenActivity = new Intent (this, popUpWindow.class );
        startKarteikartenActivity.putExtra("Activity", tag);
        startActivity(startKarteikartenActivity);
    }

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

public class popUpWindow extends Activity {

    public void startActicity (View view) {
        Intent getIntent = getIntent();

        String activity = getIntent.getStringExtra("Activity");

        switch  (activity){

            case "1":
                Intent intentKarteikarte = new Intent(getApplicationContext(), Karteikarten.class);
                startActivity(intentKarteikarte);
            case "2":
                Intent intentAusbildungsmethoden = new Intent(getApplicationContext(), Ausbildungsmethoden.class);
                startActivity(intentAusbildungsmethoden);
            case "3":
                Intent intentFallbearbeitung = new Intent(getApplicationContext(), Fallbearbeitung.class);
                startActivity(intentFallbearbeitung);
            case "4":
                Intent intentBonus = new Intent(getApplicationContext(), Bonus.class);
                startActivity(intentBonus);
            case "5":
                Intent intentGeneralprobe = new Intent(getApplicationContext(), Generalprobe.class);
                startActivity(intentGeneralprobe);

        }

    }

    public void openPremiumversion (View view) {

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
        startActivity(browserIntent);

    }

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

        DisplayMetrics displayMetrics = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;

        getWindow().setLayout((int) (width * 0.8), (int) (height * 0.5));
    }
}`

A: Your method startActvity you forgot add break in switch
      switch  (activity){

            case "1":
                Intent intentKarteikarte = new Intent(getApplicationContext(), Karteikarten.class);
                startActivity(intentKarteikarte);
                break;
            case "2":
                Intent intentAusbildungsmethoden = new Intent(getApplicationContext(), Ausbildungsmethoden.class);
                startActivity(intentAusbildungsmethoden);
                break;
            case "3":
                Intent intentFallbearbeitung = new Intent(getApplicationContext(), Fallbearbeitung.class);
                startActivity(intentFallbearbeitung);
                break;
            case "4":
                Intent intentBonus = new Intent(getApplicationContext(), Bonus.class);
                startActivity(intentBonus);
                break;
            case "5":
                Intent intentGeneralprobe = new Intent(getApplicationContext(), Generalprobe.class);
                startActivity(intentGeneralprobe);
                break;
        }

A: You are missing the break in your switch case,Also you could use single Intent variable
public void startActicity (View view) {
        Intent getIntent = getIntent();

        String activity = getIntent.getStringExtra("Activity");

        Intent intent;
        switch  (activity){

            case "1":
                intent = new Intent(getApplicationContext(), Karteikarten.class);
                break;
            case "2":
                intent = new Intent(getApplicationContext(), Ausbildungsmethoden.class);
                break;
            case "3":
                intent = new Intent(getApplicationContext(), Fallbearbeitung.class);
                break;
            case "4":
                intent = new Intent(getApplicationContext(), Bonus.class);
                break;
            case "5":
                intent = new Intent(getApplicationContext(), Generalprobe.class);
                break;

        }
       startActivity(intent);

    }


text:
Q: all elements that belong to at least one of the sets Ak <Introduction to Real Analysis.P.3)
For a finite collection of sets {A1, A2, . • • , An}, their union is the set A consisting of all elements that belong to at least one of the sets Ak, and their intersection consists of all elements that belong to all of the sets Ak.
So my question is: what does it mean all elements that belong to at least one of the sets Ak? For example, all elements that belong to two of the sets? three of the sets? Wouldn't this be the intersection of the these sets?


text:
Q: Not be able to fetch data based on custom dimensions Custom dimension
`public class GetUsersData {
private static final String APPLICATION_NAME = "Wtr-web";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String KEY_FILE_LOCATION = "D:\\ga3\\credentials.json";

//  private static final String USER_VIEW_ID = "281667139"; // userIdView
private static final String CLIENT_VIEW_ID = "281540591"; // all page
//  private static Map<String, String> convertedUserMap = new LinkedHashMap<>();
public UsersData getUsersData() throws Exception {

    // Create the DateRange object.
    DateRange dateRange = new DateRange();
    dateRange.setStartDate("30DaysAgo");
    dateRange.setEndDate("today");

    return getStatistics(initializeAnalyticsReporting(), dateRange, CLIENT_VIEW_ID);

}

private AnalyticsReporting initializeAnalyticsReporting() throws GeneralSecurityException, Exception {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(KEY_FILE_LOCATION))
            .createScoped(Collections.singletonList(AnalyticsReportingScopes.ANALYTICS_READONLY));

    // Construct the Analytics Reporting service object.
    return new AnalyticsReporting.Builder(httpTransport, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME).build();

}

private UsersData getStatistics(AnalyticsReporting service, DateRange dateRange, String userViewId) {

    // Create the Metrics object.
    Metric visits = new Metric().setExpression("ga:visits");

    Dimension UserId = new Dimension().setName("ga:UserID");

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest().setViewId(userViewId).setDateRanges(Arrays.asList(dateRange))
            .setMetrics(Arrays.asList(visits))
            .setDimensions(Arrays.asList(UserId));

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest().setReportRequests(Arrays.asList(request));
    GetReportsResponse response = null;
    try {
        response = service.reports().batchGet(getReport).execute();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(" data not found");
    }

    if (response != null) {
        for (Report report : response.getReports()) {
            ColumnHeader columnHeader = report.getColumnHeader();
            ClassInfo classInfo = report.getClassInfo();

            List<ReportRow> rows = report.getData().getRows();

            if (rows == null) {
                System.out.println("No data found for the request.");
            }

            for (ReportRow row : rows) {
                List<String> dimensions = row.getDimensions();

                List<DateRangeValues> metrics = row.getMetrics();

            }

        }

    }
    return new UsersData();
}

}`
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
POST https://analyticsreporting.googleapis.com/v4/reports:batchGet
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Unknown dimension(s): ga:UserID\nFor details see https://developers.google.com/analytics/devguides/reporting/core/dimsmets.",
"reason" : "badRequest"
} ],
"message" : "Unknown dimension(s): ga:UserID\nFor details see https://developers.google.com/analytics/devguides/reporting/core/dimsmets.",
"status" : "INVALID_ARGUMENT"
}
UserID is my custom dimension. how can i resolve this issue.


text:
Q: How to add a point and drag it into position in a 3D plot? I have some plotted points and I would like to add new points and be able to drag a pre-existing or added point using my mouse. After I am satisfied with the new plot, I would like to extract the coordinates of the points. Adding new points is not as important as being able to drag points already present.
Any ideas?.
pt = List @@@ ColorData["ThermometerColors"] /@ Subdivide[50];
Show[ListPointPlot3D[pt, BoxRatios -> {1, 1, 1}, ImageSize -> Medium,
   PlotStyle -> {Red, PointSize[0.015]},
   AxesLabel -> {"Red", "Green", "Blue"}] /.
  Point[x_] :> {Tooltip[Point[#], #] & /@ x}, Graphics3D@Line@pt]

Points are taken from

I have edited points manually and I have got this plot which is more or less what I want, but I would prefer a smoother curve.

My ultimate goal is to get more blue and red at the end points and keep middle as  "ThermometerColors"

A: This is not a complete answer (nor a robust one, likely), but here's one option (basic method stolen from @Heike's answer here).
Some notes on adding new points:

*

*For adding points, I used a right-click event so as not to interfere with the built-in pan/zoom/rotate for Graphics3D (I'm sure there's an obvious "nicer" way to do this, but this works for now).

*As @b3m2a1 noted, it's not really an easy thing to pick out a particular point in the 3D space with the mouse position.
MousePosition["Graphics3DBoxIntercepts"] can give us the endpoints of the line of points a single mouse click could potentially map to (as shown in this answer), but one would still have to give the program the desired "depth" somehow. However, since we are able to move the points after the fact, we can simply choose the "front" coordinate of MousePosition["Graphics3DBoxIntercepts"] and adjust as necessary. (Again, probably not optimal, but the best I can think of at the moment.)

*The points can only be added to the ends of the curve at the moment (the Setter at the bottom determines which end).

initpts = List @@@ ColorData["ThermometerColors"] /@ Subdivide[50];

DynamicModule[
 {pts = initpts,
  current,
  icurrent,
  prepending = False,
  newpt
  },

 Column[{
   EventHandler[
    Graphics3D[{
      EventHandler[
       Dynamic@{
         {PointSize[0.015],
          Red,
          Tooltip[Point[#], #] & /@ pts},
         Line[pts]
         },
       {
        "MouseDown" :> (

          current =
           Nearest[pts, MousePosition["Graphics3DBoxIntercepts"]][[1,
             1]];
          icurrent = First@Flatten@Position[pts, current]),
        "MouseDragged" :> (

          pts[[icurrent]] = (#[[2]] +
               Projection[
                current - #[[2]], #[[1]] - #[[2]]]) &@(MousePosition[
              "Graphics3DBoxIntercepts"])
          )
        }
       ]
      },
     ImageSize -> {400, Automatic},
     Axes -> True,
     AxesLabel -> {"Red", "Green", "Blue"}
     ],
    {{"MouseClicked", 2} :> (
       newpt = First@MousePosition["Graphics3DBoxIntercepts"];
       If[
        prepending,
        PrependTo[pts, newpt],
        AppendTo[pts, newpt]
        ]
       )}
    ],
   Row@{Setter[Dynamic[prepending], True, "Prepend new points"],
     Setter[Dynamic[prepending], False, "Append new points"]},
   OpenerView[{"Current Points", Dynamic@pts}]
   }]
 ]

A: Here's a way to make a locator pane that allows you to move your points in the plane of the current ViewMatrix:
pt = List @@@ ColorData["ThermometerColors"] /@ Subdivide[50];
transf =
  {{1.1`, 0.4`, 0.`, -0.8`}, {-0.2`, 0.5`, 1.`, -0.7`}, {-0.4`,
    1.`, -0.5`, 3.4`}, {0.`, 0.`, 0.`, 1.`}};
proj =
  {{2.2`, 0.`, 0.5`, 0.`}, {0.`, 2.2`, 0.5`, 0.`}, {0.`, 0.`,
    4.3`, -13.8`}, {0.`, 0.`, 1.`, 0.`}};

Column@{
  Graphics3D[
   {
    {Red, Point[Dynamic[pt]]},
    Line@Dynamic[pt]
    },
   ViewMatrix -> Dynamic[{transf, proj}],
   ImageSize -> Large
   ],
  Dynamic[
   With[{tf = transf[[;; 3, ;; 3]],
     inv = Inverse[transf[[;; 3, ;; 3]]]},
    Graphics[
     {
      Line[Dynamic[Transpose[tf.Transpose[pt]][[All, ;; 2]]]],
      {Red,
       Point[Dynamic[Transpose[tf.Transpose[pt]][[All, ;; 2]]]]},
      Table[
       With[{i = i},
        Locator[
         Dynamic[
          Dot[tf, pt[[i]]][[;; 2]],
          Function[pt[[i]] = inv.Append[#, 0]]
          ],
         None
         ]
        ],
       {i, Length@pt}
       ]
      }
     ]
    ]
   ]
  }

It really emphasizes how tricky the concept of a 2D motion in a 3D space can be.

These 2D motions appear one way, but rotation of the 3D object shows that the true motion can be very different from the apparent one.
If your points define a plane, simply find the transformation that rotates this plane to the xy plane and have your locators live there. Then, obviously, when setting values apply the inverse of this transformation.


text:
Q: Helm library chart returning can't evaluate field Values in type []interface {} I'm following the Helm Library chart example in the Helm docs here.
The original example has a common ConfigMap in the library chart defined as follows:
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name | printf "%s-%s" .Chart.Name }}
data: {}
{{- end -}}
{{- define "mylibchart.configmap" -}}
{{- include "mylibchart.util.merge" (append . "mylibchart.configmap.tpl") -}}
{{- end -}}

I'm working on a chart that requires me to have an if statement to enable or disable a particular resource. In this  example, it's a configmap, but it could be an HPA or a deployment in a blue / green chart.
When I add the If statement as follows:
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name | printf "%s-%s" .Chart.Name }}
data: {}
{{- end -}}
{{- define "mylibchart.configmap" -}}
{{- if .Values.configMapEnabled }}
{{- include "mylibchart.util.merge" (append . "mylibchart.configmap.tpl") -}}
{{- end -}}
{{- end -}}

where .Values.configMapEnabled exists in the values.yaml file, and is set to true.
Everything else stays the same as described in the documentation i.e. I use a simple chart to include the library chart as a dependency, and I run:
helm install mydemo mychart/ --debug --dry-run
I am receiving the following error:
helm.go:84: [debug] template: mychart/templates/configmap.yaml:1:4: executing "mychart/templates/configmap.yaml" at <include "mylibchart.configmap" (list . "mychart.configmap")>: error calling include: template: mychart/charts/mylibchart/templates/_configmap.yaml:9:14: executing "mylibchart.configmap" at <.Values.configMapEnabled>: can't evaluate field Values in type []interface {}

Why isn't the Values field not being evaluated? It seems like a scoping issue, but I'm not able to resolve it.

A: I have tested it on my own setup and it looks like you didn't define ConfigMap in lib Chart.
Place it on the beginning of the file:
{{- define "mylibchart.configmap.tpl" -}}

Also in your case lib Chart doesn't know anything about Values - it is defined by app Chart side.
Also  all conditions should be placed in app Chart not lib Chart.
Schema:
parent/child chart -  chart dependencies, with global switches on/off

See section: dependnecies -> condition: (optional).
In your case:
$ helm install mydemo mychart/ --debug --dry-run --set configmap.enabled=false


text:
Q: Ansible run concurrently a set of tasks using n servers I m attempting to use together the strategy free and run_once = true so I can run concurrently several tasks on multiple hosts. Ansible shows a warning during execution it is not yet supported. Any suggestions on how to achieve that?

A: Have you considered using the default strategy with async tasks?
Fire each task off and check for them later.
https://docs.ansible.com/ansible/latest/user_guide/playbooks_async.html#concurrent-tasks-poll-0


text:
Q: How to render Mandelbulb-style 3D fractals I'm interested in experimenting with equations for 3D fractals (a la Mandelbulb).  Does anyone know of a framework that will allow me to supply a 3-coordinate, Mandelbrot-style function, identifying a point as being contained or not contained within a set, and render the surface form of the resulting set in 3D?
Obviously, a solution that can use the GPU to do the processing would be better.

A: The 3D Mandelbulb Ray Tracer by subblue has been getting impressive results.  It uses the GPU.  It was used to produce this fly through.  Maybe not as programmable as you'd like.
According to documentation, this project on Github may fit the bill: http://github.com/vain/GPUTracer.  You can find more by Googling "mandelbulb raytracer github"


text:
Q: Berkeley mathematics department colloquium by S.Mochizuki On the website of the Berkeley mathematics department there is mention (see this) of a colloquium  held on november 5, 2020 (by Zoom) whose speaker was Shinichi Mochizuki, with a talk titled "Classical Roots of Inter-universal Teichmüller Theory". The corresponding slides seem to be online (see this). Here are my factual questions:

*

*did this event really occur ?

*if yes to 1, how was the speaker introduced ?

*if yes to 1, do the slides reflect all that was said, or were there other comments, and if so what ?

A: *

*Yes it really occurred.

*He was introduced in the normal way, something like "Today we have Shinichi Mochizuki..." that mentioned his name, maybe his talk title and the institution he's from (can't remember exactly.)

*He annotated those slides with a magnificent glitter-rainbow-colored pen, adding clarificatory details here and there. But yes, (to my understanding) those notes describe the content of what was said.


text:
Q: Interceptors not allowing field error to be displayed in struts2 Here I have included one interceptor class for login purposes .but after mentioning it in the struts.xml ,field errors are not visible on my struts form when i click on register button on my registration page.
Below is my struts.xml. please correct where i should put that LoginInterceptors class of interceptors. Below is my struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <package name="myPack" extends="struts-default">
        <interceptors>
            <interceptor name="cache" class="org.entity.CacheInterceptor" />
            <interceptor name="cacheone" class="org.entity.LoginInterceptors"></interceptor>
            <interceptor-stack name="cacheStack">
                <interceptor-ref name="cache" />
                <interceptor-ref name="cacheone"></interceptor-ref>
                <interceptor-ref name="defaultStack" />
            </interceptor-stack>
            </interceptors>
        <default-interceptor-ref name="cacheStack" />
        <action name="registration" class="org.entity.RegistrationAction">
            <result name="input">BloodBankSection.jsp</result>
            <result name="success">success.jsp</result>
            <result name="error">BloodCampError.jsp</result>
        </action>
        <action name="AdminAction" class="org.entity.AdminAction">
            <result name="input">Admin.jsp</result>
            <result name="success">AdminLoginSucess.jsp</result>
            <result name="error">Admin.jsp</result>
        </action>
        <action name="feedback" class="org.entity.FeedbackAction">
            <result name="input">Feedback.jsp</result>
            <result name="success">/feedbacksuccess.jsp</result>
            <result name="error">/Feedback.jsp</result>
        </action>
        <action name="UpdateStockAction" class="org.entity.UpdateStockAction">
            <interceptor-ref name="cacheone"></interceptor-ref>
            <result name="input">UpdateStock.jsp</result>
            <result name="success">updatesuccess.jsp</result>
            <result name="error">UpdateStock.jsp</result>
        </action>
        <action name="LoginAction" class="org.entity.LoginAction">
            <result name="input">BloodBankSection.jsp</result>
            <result name="success">UpdateStock.jsp</result>
            <result name="error">bloodloginerror.jsp</result>
        </action>
        <action name="delete" class="org.entity.DeleteAction">
            <result name="success">AdminLoginSucess.jsp</result>
            <result name="error">BloodBankSection.jsp</result>
        </action>
        <action name="DonorAction" class="org.entity.DonorAction">
            <result name="input">DonorSection.jsp</result>
            <result name="success">dsuccess.jsp</result>
            <result name="error">DonorSection.jsp</result>
        </action>
        <action name="DonorLoginAction" class="org.entity.DonorLoginAction">
            <result name="input">DonorSection.jsp</result>
            <result name="success">DonorLoginSuccess.jsp</result>
            <result name="error">donorloginerror.jsp</result>
        </action>
        <action name="SearchOneAction" class="org.entity.SearchOneAction">
            <result name="input">DonorLoginSuccess.jsp</result>
            <result name="success">DonorLoginSuccess.jsp</result>
            <result name="error">errorsearch.jsp</result>
        </action>
        <action name="SearchTwoAction" class="org.entity.SearchTwoAction">
            <result name="input">DonorLoginSuccess.jsp</result>
            <result name="success">DonorLoginSuccess.jsp</result>
            <result name="error">errorsearch.jsp</result>
        </action>
        <action name="SearchThreeAction" class="org.entity.SearchThreeAction">
            <result name="input">DonorLoginSuccess.jsp</result>
            <result name="success">DonorLoginSuccess.jsp</result>
            <result name="error">errorsearch.jsp</result>
        </action>

        <action name="DonorInfoAction" class="org.entity.DonorInfoForBloodBank">
            <result name="input">donorbloodsection.jsp</result>
            <result name="success">donorbloodsection.jsp</result>
            <result name="error">feedbacksuccess.jsp</result>
        </action>
        <action name="FPA" class="org.entity.ForgotAction">
            <result name="input">ForgotPassword.jsp</result>
            <result name="success">ForgotPasswordSuccess.jsp</result>
            <result name="error">errorpassword.jsp</result>
        </action>
        <action name="DonorForgotAction" class="org.entity.DonorForgotAction">
            <result name="input">DonorForgot.jsp</result>
            <result name="success">DonorForgotSuccess.jsp</result>
            <result name="error">errorpassword2.jsp</result>
        </action>

        <action name="BloodCampAction" class="org.entity.BloodCampAction">
            <result name="input">BloodCampInfoReg.jsp</result>
            <result name="success">BloodCampSuccess.jsp</result>
            <result name="error">BloodCampError.jsp</result>
        </action>

        <action name="BloodBankEditAction" class="org.entity.BloodBankEditAction">
            <result name="input">BloodUpdateProfile.jsp</result>
            <result name="success">UpdateStock.jsp</result>
            <result name="error">BloodUpdateProfile.jsp</result>
        </action>
        <action name="DonorEditAction" class="org.entity.DonorEditAction">
            <result name="input">DonorUpdateProfile.jsp</result>
            <result name="success">DonorLoginSuccess.jsp</result>
            <result name="error">DonorUpdateProfile.jsp</result>
        </action>
        <action name="logout" class="org.entity.LoginAction" method="logout">
            <result type="redirect">BloodBankSection.jsp</result>
        </action>
        <action name="logout2" class="org.entity.DonorLoginAction" method="logout">
            <result type="redirect">DonorSection.jsp</result>
        </action>
        <action name="LastDonatedDateAction" class="org.entity.LastDonatedDateAction">
            <result name="input">DonorLoginSuccess.jsp</result>
            <result name="success">LastDonatedSuccess.jsp</result>
            <result name="error">LastDonatedError.jsp</result>
        </action>

    </package>
</struts>

Below is my LoginInterceptors class.
package org.entity;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginInterceptors implements Interceptor
{

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void init() {
        // TODO Auto-generated method stub

    }

    @Override
    public String intercept(ActionInvocation action) throws Exception {
        HttpSession session=ServletActionContext.getRequest().getSession(false);
        if(session==null || session.getAttribute("login")==null)
        {
            ServletActionContext.getResponse().sendRedirect("BloodBankSection.jsp");
            System.out.println("First Inter");
        }

        return action.invoke();

    }

}

As interceptors is always executed first,form field errors are not visible and also not redirected to intended page.  Output is "first inter" followed by remaining testing lines.

A: First, remove the login interceptor from the interceptor stack of the actual login action. It prevents the action from being executed since you are not logged in yet.
Second, an interceptor shouldn't redirect directly. It creates a new request, which also means that validation errors are lost. Let it return a result value.
@Override
public String intercept(ActionInvocation action) throws Exception {
    HttpSession session=ServletActionContext.getRequest().getSession(false);
    if(session==null || session.getAttribute("login")==null)
    {
        System.out.println("First Inter");
        return "login";
    }
    return action.invoke();
}

Then you can create a <global-results> entry for it. Which should (normally) not be a redirect.
<struts>
    <package name="myPack" extends="struts-default">

         <global-results>
             <result name="login">BloodBankSection.jsp</result>
         </global-results>

</struts>


text:
Q: frame width return slarge number I have a slider whose width and height is 200 x 10
CGRect frame = CGRectMake(0.0, 0.0, 200.0, 10.0);

UISlider *slider = [[UISlider alloc] initWithFrame:frame];

When I log
NSLog(@"WIDTH: %d", slider.frame.size.width);

I get back
WIDTH: 396044417

which is a large number and seems incorrect. Is this normal?

A: %d is for printing integers, for floating point values you have to use %f. You can also limit the number of decimal digits using %.2f.
The best solution though is logging the whole frame:
NSLog(@"Frame: %@", NSStringFromCGRect(slider.frame));


text:
Q: JS Regex: Remove anything (ONLY) after a word I want to remove all of the symbols (The symbol depends on what I select at the time) after each word, without knowing what the word could be. But leave them in before each word.
A couple of examples:
!!hello! my! !!name!!! is !!bob!! should return...
!!hello my !!name is !!bob ; for !
and
$remove$ the$ targetted$@ $$symbol$$@ only $after$ a $word$ should return...
$remove the targetted@ $$symbol@ only $after a $word ; for $

A: You need to use capture groups and replace:
"!!hello! my! !!name!!! is !!bob!!".replace(/([a-zA-Z]+)(!+)/g, '$1');

Which works for your test string. To work for any generic character or group of characters:
var stripTrailing = trail => {
  let regex = new RegExp(`([a-zA-Z0-9]+)(${trail}+)`, 'g');
  return str => str.replace(regex, '$1');
};

Note that this fails on any characters that have meaning in a regular expression: []{}+*^$. etc. Escaping those programmatically is left as an exercise for the reader.
UPDATE
Per your comment I thought an explanation might help you, so:
First, there's no way in this case to replace only part of a match, you have to replace the entire match. So we need to find a pattern that matches, split it into the part we want to keep and the part we don't, and replace the whole match with the part of it we want to keep. So let's break up my regex above into multiple lines to see what's going on:
First we want to match any number of sequential alphanumeric characters, that would be the 'word' to strip the trailing symbol from:
(       // denotes capturing group for the 'word'
  [     // [] means 'match any character listed inside brackets'
    a-z // list of alpha character a-z
    A-Z // same as above but capitalized
    0-9 // list of digits 0 to 9
  ]+    // plus means one or more times
)

The capturing group means we want to have access to just that part of the match.
Then we have another group
(
  ! // I used ES6's string interpolation to insert the arg here
  + // match that exclamation (or whatever) one or more times
)

Then we add the g flag so the replace will happen for every match in the target string, without the flag it returns after the first match. JavaScript provides a convenient shorthand for accessing the capturing groups in the form of automatically interpolated symbols, the '$1' above means 'insert contents of the first capture group here in this string'.
So, in the above, if you replaced '$1' with '$1$2' you'd see the same string you started with, if you did 'foo$2' you'd see foo in place of every word trailed by one or more !, etc.


text:
Q: Creating a histogram with .txt file using Python? Here's the code I tried. It gave me a syntax error highlighting 'data'. Any help? The .txt file has 4 columns if that's of any help.
def file():
  file = open('hsp.txt', 'r')
  col = [] data = file.readlines()
  for i in range(1,len(data)-1):
    col.append(int(float(data[i].split(',')[5])))
  return col

def hist(col):
  handspan = []
  for i in range(11):
    handspan.append(0)
  for i in (col):
    handspan[i] += 1
  return handspan

col = file()
handspan = hist(col)
print(col)
print(handspan)

A: It is because your line
col = [] data = file.readlines()

should be on two separate lines:
col = []
data = file.readlines()

A: You can try this, it worked for me.
Hence it is a histogram it yields a dictionary.
Better answers are welcome!
import string
def list_from_file(filename):
    myfile = open(filename, 'r')
    data = myfile.read().split()
    col = []
    for word in data:
        col.append(word)
    return col

def myhist(col):
    hist = {}
    for word in col:
        word = word.lower()
        word = word.strip(string.punctuation + string.whitespace)
        hist[word] = hist.get(word, 0)+1
    return hist

col = list_from_file('em.txt')
colf = myhist(col)
print(colf)


text:
Q: How to Launch a compiled MATLAB program from C Project using MATLAb Engine Using: Windows 10, Matlab R2019b and VS2012.
I am currently using the Matlab Engine calling: engOpen(), in a compiled C program to launch a Matlab Command Window.   Once this command window is opened I am using functions like: engEvalString() and engPutVariable() to pass data and process this data in MATLAB.  This all works well on my MATLAB development PC but in the long run I would like to deploy on a non-development PC, meaning MATLAB would not be installed but rather a compiled MATLAB program is installed.  So it it possible to use the MATLAB Engine COM methodology from a C program to open and communicate to a compiled MATLAB program?  If so can you suggest reference material or provide an example?
Thank You!


text:
Q: Django dynamically form I have the following
My models:
# База товаров / Base products
class Products(models.Model):
    name = models.CharField(max_length=150, verbose_name='Название')

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)
        verbose_name = 'База товаров'
        verbose_name_plural = 'База товаров'

# Закупили / Base purchases
class Purchases_item(models.Model):
    product = models.ForeignKey(Products, on_delete=models.CASCADE, verbose_name='Товар')
    quantity = models.PositiveIntegerField(default=0, verbose_name='Кол-во')
    untils = models.ForeignKey(Untils, on_delete=models.CASCADE, verbose_name='Ед. измерения')
    price = models.DecimalField(max_digits=150, default=0, decimal_places=0, verbose_name='Цена себестоимости')
    total_price = models.DecimalField(max_digits=150, default=0, decimal_places=0, verbose_name='Общая сумма')

    def __str__(self):
        return str(self.product)

    def save(self, *args, **kwargs):
        super(Purchases_item, self).save(*args, **kwargs)
        val = self.price * self.quantity
        if self.total_price != val:
            self.total_price = self.price * self.quantity
            self.save()

    class Meta:
        ordering = ('product', 'price', 'total_price')
        verbose_name = 'Покупка по позициям'
        verbose_name_plural = 'Покупки по позициям'

# Список который мы закупили записываем на склад / Purchases List
# По факту это склад списком
class Purchases(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField(auto_now_add=True, verbose_name='Дата') # переделать на defaul и отключить auto now add
    company = models.CharField(max_length=150, verbose_name='Компания', null=True, blank=True, default=None)
    product = models.ManyToManyField(Purchases_item, verbose_name='Товар(ы)')
    total_price = models.DecimalField(max_digits=150, decimal_places=0, verbose_name='Общая сумма', default=0)

    def __str__(self):
        return self.company

    def save(self, *args, **kwargs):
        super(Purchases, self).save(*args, **kwargs)
        if self.total_price != sum(product.total_price for product in self.product.all()):
            self.total_price = sum(product.total_price for product in self.product.all())
            self.save()

    class Meta:
        ordering = ('date', 'company', 'total_price')
        verbose_name = 'Покупка список'
        verbose_name_plural = 'Покупки список'

My Forms:
class ProductForm(ModelForm):
    class Meta:
        model = Products
        fields = ['name', 'category']

class PurchasesForm(ModelForm):
    class Meta:
        model = Purchases
        fields = ['user', 'company']
        widgets = {
            'user': Select(attrs={
                'class': "form-select",
                'placeholder': 'Название товара'
            }),
            'company': TextInput(attrs={
                'class': "form-select",
                'placeholder': 'Поставщик'
            }),
        }

class PurchasesItemForm(ModelForm):
    class Meta:
        model = Purchases_item
        fields = ['product', 'quantity', 'untils', 'price']
        widgets = {
            'product': Select(attrs={
                'class': "form-select",
                'placeholder': 'Название товара'
            }),
            'quantity': NumberInput(attrs={
                'class': "form-control",
                'placeholder': 'Кол-во'
            }),
            'untils': Select(attrs={
                'class': "form-select",
                'placeholder': 'Ед. измерения'
            }),
        }

PurchasesItemFormSet = modelformset_factory(
    Purchases_item,
    fields = ("product", "quantity", "untils", "price", "total_price"),
    widgets= {
        'product': Select(attrs={
            'class': "form-control form-select",
            'placeholder': 'Название товара'
        }),
        'quantity': NumberInput(attrs={
            'class': "form-control",
            'placeholder': 'Кол-во'
        }),
        'untils': Select(attrs={
            'class': "form-select",
            'placeholder': 'Ед. измерения'
        }),
        'price': NumberInput(attrs={
            'class': "form-control",
            'placeholder': 'Кол-во'
        }),
        'total_price': NumberInput(attrs={
            'class': "form-control",
            'placeholder': 'Кол-во'
        }),
    },
    extra = 1
)

My View:
# Создать закупку
class PurchasesCreate(View):
    model = Purchases

    context = {}

    def get(self, request, *args, **kwargs):
        self.context['form'] = PurchasesForm()
        self.context['formset'] = PurchasesItemFormSet(queryset = Purchases_item.objects.none())

        # self.context['product'] = Products.objects.all()
        # self.context['purchases_item'] = Purchases_item.objects.all()

        if self.request.user.is_authenticated == False:
            return redirect('login')
        else:
            return render(request, 'erp/purchases_create.html', self.context)

    def post(self, request, pk, *args, **kwargs):

        formset = PurchasesItemFormSet(data = self.request.POST)

        if formset.is_valid():
            formset.save()
            return redirect('/')

        self.context['user'] = Purchases.objects.get(id=pk)

        if self.request.user.is_authenticated == False:
            return redirect('login')
        else:
            return render(request, 'erp/purchases_create.html', self.context)

The essence of the problem is that I have "Many to many" in the Purchases model, the line "Row", and I need it all to be saved and dynamic so that I can select
Example in the photo
Example
How can I make it dynamic and have the received data saved in "purchases" and "item purchases" models?


text:
Q: 2nd order Differential equation(right side) Hello I have the differntial equation (2nd order), I solved the homogenic part but the other (right side)not. Can anybody help me?
$$x''-2x'+3x=4e^t\cos(\sqrt{2}t)$$
$$x(\text{Homogenic})=e^t(c_1\cos(\sqrt{2}t) + c_2\sin(\sqrt{2}t))    $$
Now I need the other part but I don't know how to start. Thanks Ciwan

A: rewriting, $$(D^2 - 2D + 3)x = 4e^tcos(\sqrt2 t)$$ where $D = \frac{d}{dt}$. Then, $$x = \frac{1}{(D^2 - 2D + 3)}.4e^tcos(\sqrt2 t)$$
$$x = 4e^t\frac{1}{(D+1)^2 - 2(D+1) + 3}.cos(\sqrt2 t)$$
$$x = 4e^t\frac{1}{D^2 + 2}.cos(\sqrt2 t)$$
$$x = 4e^t\frac{t}{2\sqrt2}sin(\sqrt2t)$$
$$x = t\sqrt2e^tsin(\sqrt2t)$$
is the particular solution

A: Firstly, you should find the complementary solution which is
$$x''-2x'+3x=0$$
$$r^2-2r+3=0$$
$$r=1\pm \sqrt{2}i$$
$$y_c=e^x(C_1\cos\sqrt{2}t+C_2\sin\sqrt{2}t)$$
The particular solution is
$$y_p=e^x(A\cos\sqrt{2}t+B\sin\sqrt{2}t)\rightarrow e^x(At\cos\sqrt{2}t+Bt\sin\sqrt{2}t)$$
then complete the solution to find the value of $A$ and $B$

A: Here the differential equation is $$x''-2x'+3x=4e^t\cos(\sqrt{2}t)\implies(D^2-2D+3)x=4e^t\cos(\sqrt{2}t)$$ where $D\equiv \frac{d}{dt}$

For the Particular Integral (i.e., P.I.) there are some general rules
$1.$ $\frac{1}{D + a} \phi (x) = e^{-ax}\int e^{ax}\phi(x)$
$2.$ $\frac{1}{f(D)} e^{ax} \phi(x) = e^{ax}\frac{1}{f(D+a)} \phi(x)$
$3.$ $\frac{1}{f(D)} x^{n} \sin ax  = $Imaginary part of $e^{iax}\frac{1}{f(D+ia)} x^n$
$4.$ $\frac{1}{f(D)} x^{n} \cos ax  = $Real part of $e^{iax}\frac{1}{f(D+ia)} x^n$
$5.$ $\frac{1}{f(D)} x^{n} (\cos ax + i\sin ax)  = \frac{1}{f(D)} x^n e^{iax}=e^{iax}\frac{1}{f(D+ia)} x^n$

To find the P.I. we use the Rule$- 2$
Here $f(D)=D^2-2D+3, \phi(t)=4\cos(\sqrt{2}t)$ and $a=1$
So P.I. $= \frac{1}{D^2-2D+3}4e^t\cos(\sqrt{2}t)$
$=4e^t\frac{1}{(D+1)^2-2(D+1)+3}\cos(\sqrt{2}t)$
$=4e^t\frac{1}{D^2+2}\cos(\sqrt{2}t)$
$=4e^t\sin(\sqrt{2}t)\frac{t}{2\sqrt 2}$
$=\sqrt 2 e^t\sin(\sqrt{2}t)$

For the Particular Integral (i.e., P.I.) of trigonometric functions  you have to follow the following rules:

If $f(D)$ can be expressed as $\phi(D^2)$ and $\phi(-a^2)\neq 0$, then
$1.$ $\frac{1}{f(D)} \sin ax=\frac{1}{\phi(D^2)} \sin ax = \frac{1}{\phi(-a^2)} \sin ax$
$2.$ $\frac{1}{f(D)} \cos ax=\frac{1}{\phi(D^2)} \cos ax = \frac{1}{\phi(-a^2)} \cos ax$
Note: If $f(D)$ can be expressed as $\phi(D^2)=D^2+a^2$, then $\phi(-a^2)= 0$.
$1.$ $\frac{1}{f(D)} \sin ax =\frac{1}{\phi(D^2)} \sin ax=x\frac{1}{\phi'(D^2)} \sin ax= x \frac{1}{2D} \sin ax= -\frac{x}{2a} \cos ax$.
$2.$ $\frac{1}{f(D)} \cos ax =\frac{1}{\phi(D^2)} \cos ax=x\frac{1}{\phi'(D^2)} \cos ax=  x \frac{1}{2D} \cos ax= \frac{x}{2a} \sin ax$.
where $\phi'(D^2)\equiv\frac{d}{dD}\phi(D^2)$


text:
Q: Select the value for each first day of the month I have the below table

I want to select the value of [UsedSpace(MB)] for each first day of the month.
For example 1/5/2015 the value of [UsedSpace(MB)] should be 10.
I tried the below query, but without success.
Select Cast(DATEADD(mm,DATEDIFF(mm,0,ExecuteTime),0) AS DATE) AS [Monthly],
       [UsedSpace(MB)]
from tbl_Test
group by DATEADD(mm,DATEDIFF(mm,0,ExecuteTime),0), [UsedSpace(MB)]
Order by DATEADD(mm,DATEDIFF(mm,0,ExecuteTime),0)

Please any suggestions.

A: If you know that you will always have a single record for each date then you could limit the results in the WHERE statement. If there may be multiple records on the same date or no record on a date then you should use a MIN function.
SELECT
    CAST(ExecuteTime as Date) AS Date,
    UsedSpace
FROM tbl_Test
WHERE Day(ExecuteTime) = 1

A: For the sample data provided, you can simply make a where clause for the first day of the month. If you need a more generic solution, you need to get the lowest date for each month, and then join this with the original table.
WITH cte AS
(
  SELECT MIN(ExecuteTime) AS Monthly
  FROM tbl_Test
  GROUP BY DATEADD(m, DATEDIFF(m, 0, ExecuteTime), 0)
)
SELECT t.ExecuteTime, t.[UsedSpace(MB)]
FROM tbl_Test AS t
JOIN cte AS m
ON t.ExecuteTime = m.Monthly
ORDER BY t.ExecuteTime


text:
Q: Running tests inside Pycharm while working in virtualenv Using PyCharm 2018.3
I am working in a conda virtualenv.  I have a file add.py and test_add.py which has unittest class to test the add.py module.
From a plain terminal (away from pycharm), with the virtualenv activated, I can run python test_add.py and the tests run perfectly fine.
From inside pycharm, where I've set the interpreter to use the same virtualenv,  I can run the add.py file, and it works.
However, from inside pycharm, if I try to run 'test_add.py`   it fails with a long stacktrace ending in a DLL import error:
Testing started at 9:23 PM ...
C:\ProgramData\Anaconda3\envs\nambu\python.exe "C:\Program Files\JetBrains\PyCharm 2018.3.6\helpers\pycharm\_jb_pytest_runner.py" --path C:/Users/kanugu/code/morsel/test_add.py
Launching pytest with arguments C:/Users/kanugu/code/morsel/test_add.py in C:\Users\kanugu\code\morsel

Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm 2018.3.6\helpers\pycharm\_jb_pytest_runner.py", line 31, in <module>
pytest.main(args, plugins_to_load)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\_pytest\config\__init__.py", line 60, in main
config = _prepareconfig(args, plugins)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\_pytest\config\__init__.py", line 195, in _prepareconfig
pluginmanager=pluginmanager, args=args
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pluggy\hooks.py", line 289, in __call__
return self._hookexec(self, self.get_hookimpls(), kwargs)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pluggy\manager.py", line 68, in _hookexec
return self._inner_hookexec(hook, methods, kwargs)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pluggy\manager.py", line 62, in <lambda>
firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pluggy\callers.py", line 203, in _multicall
gen.send(outcome)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\_pytest\helpconfig.py", line 93, in pytest_cmdline_parse
config = outcome.get_result()
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pluggy\callers.py", line 80, in get_result
raise ex[1].with_traceback(ex[2])
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pluggy\callers.py", line 187, in _multicall
res = hook_impl.function(*args)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\_pytest\config\__init__.py", line 654, in pytest_cmdline_parse
self.parse(args)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\_pytest\config\__init__.py", line 871, in parse
self._preparse(args, addopts=addopts)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\_pytest\config\__init__.py", line 816, in _preparse
self.pluginmanager.load_setuptools_entrypoints("pytest11")
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pluggy\manager.py", line 274, in load_setuptools_entrypoints
plugin = ep.load()
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pkg_resources\__init__.py", line 2411, in load
return self.resolve()
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pkg_resources\__init__.py", line 2417, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\_pytest\assertion\rewrite.py", line 296, in load_module
six.exec_(co, mod.__dict__)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pytest_doctestplus\plugin.py", line 18, in <module>
from .output_checker import OutputChecker, FIX
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\_pytest\assertion\rewrite.py", line 296, in load_module
six.exec_(co, mod.__dict__)
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\pytest_doctestplus\output_checker.py", line 10, in <module>
import numpy as np
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\numpy\__init__.py", line 140, in <module>
from . import _distributor_init
File "C:\ProgramData\Anaconda3\envs\nambu\lib\site-packages\numpy\_distributor_init.py", line 34, in <module>
from . import _mklinit
ImportError: DLL load failed: The specified module could not be found.

Process finished with exit code 1

Not sure why the test_add.py has an import problem when all the other combinations work fine.

A: Try 2019.1.3 RC build. The problem should be addressed there.


text:
Q: Determining if the element is the last child of its parent Using jQuery, is there a quick way of knowing if an element is its parent's last child?
Example:

$('#b').isLastChild(); //should return FALSE
$('#c').isLastChild(); //should return TRUE

A: You can use .is() with :last-child like this:
$('#b').is(":last-child"); //false
$('#c').is(":last-child"); //true

You can test it here.  Another alternative is to check .next().length, if it's 0 it's the last element.

A: Use :last-child selector together with .is()
$('#c').is(':last-child')

A: if($('#b').is(":last-child")){

}


text:
Q: Separating Command Buttons and VBA code in Excel I have an Excel worksheet with over 100 rows of data.  When the user completes filling in the information in their row, there is a command button at the end of the row that automatically sends an email to a specific email account with information from the row.
I've inserted several command buttons with the VB code to send the email and it works great!.  The problem I'm having is that I can't separate the command buttons, i.e., each button's code should be specific to the row it is on; when I change the code with the cell location that contains the information for that command button, it changes all of the command buttons to that information.
I know the answer must be really simple, but I've drawn a complete blank.I appreciate any help!
Here is the code I have:
Option Explicit

Private Sub CommandButton2_Click()

On Error GoTo ErrHandler

    ' SET Outlook APPLICATION OBJECT.
    Dim objOutlook As Object
    Set objOutlook = CreateObject("Outlook.Application")

    ' CREATE EMAIL OBJECT.
    Dim objEmail As Object
    Set objEmail = objOutlook.CreateItem(olMailItem)

    With objEmail
        .to = "[email address].com"
        .Subject = Range("A3")
        .Body = "[Message]"
        .Send        ' SEND THE MESSAGE.
    End With

    ' CLEAR.
    Set objEmail = Nothing:    Set objOutlook = Nothing

ErrHandler:
    '
End Sub

Each row should have this same command with only the CommandButton number changing and the .Subject = Range  entry changing.
I'm doing something wrong though because that doesn't work.

A: I said in a comment, it's probably easier to simply color cells to look like buttons and have the users click on a cell to send the emails - then you can simply use the offset for the particular row, but if you insist on using command buttons, it's quite simple.
Take your current code and put it in a new subroutine that accepts a range parameter.
Then, add your buttons, and link each one to its own code with a different range.
Option Explicit

Private Sub CommandButton3_Click()
SendEmail Range("A3")
End Sub

Private Sub CommandButton4_Click()
SendEmail Range("A4")
End Sub

Private Sub CommandButton5_Click()
SendEmail Range("A5")
End Sub

`...

Sub SendEmail(TheRange as Range)
    On Error GoTo ErrHandler
    ' SET Outlook APPLICATION OBJECT.
    Dim objOutlook As Object
    Set objOutlook = CreateObject("Outlook.Application")
    ' CREATE EMAIL OBJECT.
    Dim objEmail As Object
    Set objEmail = objOutlook.CreateItem(olMailItem)
    With objEmail
        .to = "[email address].com"
        .Subject = TheRange 'Change this line
        .Body = "[Message]"
        .Send        ' SEND THE MESSAGE.
    End With
    ' CLEAR.
    Set objEmail = Nothing:    Set objOutlook = Nothing
ErrHandler:
End Sub

If you prefer instead to use the SelectionChanged event, you can do it like this.
Then, you can just update [C4:C8] if you want to add any more "buttons"
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, [C4:C8]) Is Nothing Then
    SendEmail Range("A" & Target.Row)
    'Optionally select the subject we sent so we can re-click
    'You can choose any other cell not in our event range
    Range("A" & Target.Row).Select
End If
End Sub


text:
Q: Save while loop results as numpy array in python? Fairly new at coding, Im using python to do a monte carlo simulation. Not really sure how I would go about this, the end result would be to graph out the results from the steadystate function.
import random
import numpy as np

def steadystate():
    p=0.88
    Cout=4700000000
    LambdaAER=0.72
    Vol=44.5
    Depo=0.42
    Uptime=0.1
    Effic=0.38
    Recirc=4.3
    x = random.randint(86900000,2230000000000)
    conc = ((p*Cout*LambdaAER)+(x/Vol))/(LambdaAER+Depo+(Uptime*Effic*Recirc))
    return conc

x = 0
while x < 10000:
    result = steadystate()
    print(result)
    x+=1

Right now I just want to save the results from the while loop as an array so I can graph it. Ive tried appending it but it wouldnt print anything.

A: The simplest way to achieve what you need would be to generate your random integers as an array to start with, e.g.:
size = 10000

# generate 10000 (size) random integers as a numpy array
x = np.random.randint(86900000, 2230000000000, size=size)

p = 0.88
Cout = 4700000000
LambdaAER = 0.72
Vol = 44.5
Depo = 0.42
Uptime = 0.1
Effic = 0.38
Recirc = 4.3

result = ((p*Cout*LambdaAER)+(x/Vol))/(LambdaAER+Depo+(Uptime*Effic*Recirc))

The result object will also be a numpy array of the same size as x.


text:
Q: Is it possible to set vb.net datagridview cell alignment without modifying whole column? I am trying to set the alignment of a specific cell in a row/column to be right aligned. However I do not want to set the whole row, or whole column to right aligned. Is it possible to set the cell only? From what I've seen online I'm starting to think it isn't possible.

A: You would need to hook up to the RowDataBound event. This fires as each row is databound. Check that the row is a data row (as opposed to a header or footer). Then check the value in the column you are interested in. If the value meets your criteria for right justification then apply that to the column in question.
Note if you are using AlternateItemTemplate then check both Item rows and AlternateItem rows.
I've used this method to say change the backround colour of values that fall outside a range.


text:
Q: extract object by property prefix I tried to loop through a huge list of properties in object, but failed to extract properties that has the same prefix, I can't use object deletefunction because the list is huge, where is my mistake?
const a = {
  obj_abc: true,
  obj_def: false,
  hello_123: true,
  hello_456: 'another value'
};

let b = {};

for(k in a){
    const [key] = k.split('_');
    if(key === 'hello') {
      b = {...b[key], [key]:a[k]} //the problem is here, it gave me only hello_456: 'another value'

    }
}

console.log(b);

A: Try using bracket notation

const a = {
  obj_abc: true,
  obj_def: false,
  hello_123: true,
  hello_456: 'another value'
};

let b = {};

for (k in a) {
  const [key] = k.split('_');
  if (key === 'hello') {
    b[k] = a[k];
  }
}

console.log(b);

Using startsWith()

const a = {
  obj_abc: true,
  obj_def: false,
  hello_123: true,
  hello_456: 'another value'
};

let b = {};

for (k in a) {
  if (k.startsWith('hello_')) {
    b[k] = a[k];
  }
}

console.log(b);

A: Your key is hello for both hello_123 and hello_456, hence its overriding the old entry for hello key. you need unique keys. eg below.

const a = {
  obj_abc: true,
  obj_def: false,
  hello_123: true,
  hello_456: 'another value'
};

let b = {};

for(k in a){
    const [key] = k.split('_');
    if(key === 'hello') {
    //key is hello for both hello_123 and hello_456, hence its overriding
      b[k] = a[k] //the problem is here, it gave me only hello_456: 'another value'

    }
}

console.log(b);

A: Try this

const a = {
  obj_abc: 123,
  obj_def: 456,
  hello_123: 123,
  hello_456: 456
};

// filter out the keys that start with hello
var keys = Object.keys(a).filter(function(k) {
  return k.indexOf("hello") === 0;
});

//to convert an array of filtered keys into an object of key-value pairs
var res = keys.reduce(function(matched, k) {
  matched[k] = a[k];
  return matched;
}, {});

console.log(res);

A: You can use entries, reduce for clean code. Same time you can create map of all key, later good to extract. See the example 2.

// Example 1
const a = {
    obj_abc: true,
    obj_def: false,
    hello_123: true,
    hello_456: 'another value'
};

const result = Object.entries(a).reduce((map, [key, value]) => {
    if (key.indexOf("hello_") === 0) map[key] = value
    return map
}, {})

console.log(result);

// To collect all in once
// Example 2
const result2 = Object.entries(a).reduce((map, [key, value]) => {
    const [k] = key.split("_")
    if(!map[k]) map[k] = {}
    map[k][key] = value
    return map
}, {})

console.log(result2); // { obj: { obj_abc: true, obj_def: false }, hello: { hello_123: true, hello_456: 'another value' } }
console.log(result2["hello"]); // { hello_123: true, hello_456: 'another value' }
console.log(result2["obj"]); // { obj_abc: true, obj_def: false }

A: Please find my answer.

const a = {
  obj_abc: true,
  obj_def: false,
  hello_123: true,
  hello_456: "another value"
};

let b = {};

for (key in a) {
  let [text] = key.split("_");

  if (!(text in b)) {
    b[text] = { [key]: a[key] };
  }
 else {
    Object.assign(b[text], { [key]: a[key] });
  }
}

console.log(b);

OUTPUT
{
  "obj": {
    "obj_abc": true,
    "obj_def": false
  },
  "hello": {
    "hello_123": true,
    "hello_456": "another value"
  }
}


text:
Q: terraform cert-manager upgrade error: rendered manifests contain a new resource that already exists I'm trying to upgrade cert-manager from version v0.12.0 to v1.4.2 with terraform helm.
I've modified the k8s-cert-manager file as shown below in the picture and also added the following annotations and labels to all relevant manifests:
  annotations:
    meta.helm.sh/release-name: cert-manager
    meta.helm.sh/release-namespace: commons
  labels:
    app.kubernetes.io/managed-by: Helm

However, I keep getting this error from terraform apply:


text:
Q: How to design a floated button like in the attached image I am trying to create an app and I have a design already as an image, but I can not clone the exact shape of the button which is above the tabs
I expect the same design in this image: below
Note:
0 and 0.00EGP should be variables

A: Create a XML file bottom_corner.xml for background
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#0091fa"/>
    <stroke android:width="1dp"
        android:color="#0091fa" />

    <corners android:radius="10dp"/>
    <padding android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp" />
</shape>

Now create layout floated_button.xml and use this background here in the layout:
<RelativeLayout android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_marginRight="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginBottom="5dp"
    android:background="@drawable/bottom_corner"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/tv_total_value"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="0"
        android:textSize="18dp"
        android:gravity="center"
        android:layout_centerVertical="true"
        android:textColor="#fff"/>

    <TextView
        android:id="@+id/tv_egp_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0.00 EGP"
        android:textSize="22dp"
        android:gravity="center"
        android:paddingRight="15dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:textColor="#fff"/>

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#fff"
        android:layout_toRightOf="@+id/tv_total_value"/>

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Charge"
        android:textSize="22dp"
        android:gravity="center"
        android:paddingRight="15dp"
        android:paddingLeft="15dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/tv_total_value"
        android:textColor="#fff"/>

</RelativeLayout>

A: For your specific problem, you can move forward like this:

First of all, you have to create a drawable file of round background.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#000000" />
    <corners android:radius="15dp" />
</shape>

Then, you can add the tag of image and place it, on the corner of the image where you want to place it. Then use drawable as background then adjust the TextView on it.

<ImageView
    android:id="@+id/ivLauncher"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:src="@mipmap/ic_launcher"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ImageView
    android:id="@+id/ivBg"
    android:layout_width="15dp"
    android:layout_height="15dp"
    android:src="@drawable/round_text_bg"
    app:layout_constraintTop_toBottomOf="@id/ivLauncher"
    app:layout_constraintBottom_toBottomOf="@id/ivLauncher"
    app:layout_constraintLeft_toRightOf="@id/ivLauncher"
    app:layout_constraintRight_toRightOf="@id/ivLauncher"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="1"
    android:textColor="#FFFFFF"
    android:textSize="10dp"
    app:layout_constraintTop_toTopOf="@id/ivBg"
    app:layout_constraintBottom_toBottomOf="@id/ivBg"
    app:layout_constraintLeft_toLeftOf="@id/ivBg"
    app:layout_constraintRight_toRightOf="@id/ivBg"/>

Here is the result:
Flotted Button design on image corner


text:
Q: What is the area formed by the loop of the curve $x^3 - y^3= xy$? I know how to find area of elementary functions by integration. The only loop questions that I know how to solve are the ones that are of the petal type, which can be converted into polar form and then integrated using polar coordinates. In this question conversion into polar form was not much of a help.
I plotted the function on Desmos (Online Graphing Calculator) to see how it precisely looks. I have no idea how to proceed.
I am trying to isolate y to form a piece wise function, but I am not able to it yet. Please help me with this, I would be grateful.

A: Suggestion / partial answer:
If you swap to polar coordinates, you get $r = \frac{\sin\theta\cos\theta}{\cos^3\theta - \sin^3\theta}$. This means that the area is
$$
\int_{\pi/2}^\pi \left(\int_0^{\frac{\sin\theta\cos\theta}{\cos^3\theta - \sin^3\theta}}r\,dr\right)d\theta = \frac12\int_{\pi/2}^\pi\left(\frac{\sin\theta\cos\theta}{\cos^3\theta - \sin^3\theta}\right)^2\,d\theta
$$
That's not an integral I like. I am sure there are trigonometric identities that can be used and simplifications that can be done, but I know of none that jump out to me as immediately convenient to use. Or it can be put into a computer to get...$\frac16$.

A: Here's how to do the integral $:= I$ from the answer of Arthur:
Dividing numerator and denominator by $\cos^6(x)$, we get
\begin{align}
I
= \int \frac{\frac{\sin(x)}{\cos^5(x)}}{(\cos^3(x) - \sin^3(x))^2\sec^6(x)} dx
= \int \frac{\tan^2(x) \sec^2(x)}{(\tan^3(x) - 1)^2} dx
\end{align}
Now, using the substitution $u = \tan(x)$ and $du = \sec^2(x) dx$
we get
\begin{align}
I = \int \frac{u^2}{(u^3 - 1)^2} du
\end{align}
This you can evaluate easily with a second substitution: $v = u^3 - 1$.


text:
Q: How can I prevent re-rendering of my component in React Navigation version 5.x using createStackNavigator? In my React Native app I use a StackNavigator, more or less as follows:
// React navigation
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

// Create stack navigator
const Stack = createStackNavigator();

export default function App() {
    return (
        <NavigationContainer>
            <Stack.Navigator detachInactiveScreens={false} screenOptions={{ header: () => null }}>
                <Stack.Screen name="master" component={MasterView} />
                <Stack.Screen name="detail" component={DetailView} />
            </Stack.Navigator>
        </NavigationContainer>
    )
}

While the user uses the app he/she switches back and forth between MasterView and DetailView. The DetailView is reinstantiated
anytime the user navigates to it. However I need to prevent the DetailView to be reinstantiated upon navigation. I was hoping
to use the property detachInactiveScreens to accomplish this behavior as described here:
https://reactnavigation.org/docs/stack-navigator/#detachinactivescreens
I also included the invocation of enableScreens as follows in App.tsx
// Import react-native-screens
import { enableScreens } from 'react-native-screens';
enableScreens();

However I still see my DetailView being reinstantiated anytime the user navigates to it. Am I following the wrong approach? Is there
an alternative way to accomplish this behavior?
Thanks in advance


text:
Q: ¿Cómo poner publicidad de adMob en mi app con android studio? Estoy poniendo publicidad a mi aplicación. He optado por el tipo banner.
Es mi primera vez, así que he seguido un tutorial que me encontré por la red y finalmente he logrado que el "banner" cargue una publicidad de prueba cuyo id: ads:adUnitId="ca-app-pub-3940256099942544/6300978111".  Pero al reemplazar el id de prueba por el de mi bloque de anuncios, no me sale ningún error, ni aparece la publicidad en la app.
¿Qué cambios más debo hacer para que aparezca la publicidad?

A: Lo pongo como respuesta ya que seguramente sea lo que te está ocurriendo, ademas agregare un ejemplo.
Cuando creas una app y le colocas adMob, dese hace unas actualizaciones atrás, solamente la publicidad seria visible en dispositivos reales, y no en el emulador propio de Android Studio. Ademas de esto, a la hora de cargar la publicidad en tu código, puedes especificar id de prueba para que la publicidad no sea visible en dicho terminal.
Esto se debe a que no se pueden hacer click en los anuncios propios, siendo penalizado por Google adMob.
Así que para ver si realmente la publicidad esta siendo mostrada, instala la aplicacion en un dispositivo real.
Código para colocar los anuncios tipo banner:
En tu layout
<com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
    </com.google.android.gms.ads.AdView>

En tu archivo de manifiesto:
<activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent" />

Por ultimo en tu actividad:
AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);

Edito:
Si en tu aplicacion tienes tanto un id de prueba adRequest.addTestDevice("ID"), como si estas usando un emulador, lo que verias seria algo asi:

A:
Pero al reemplazar el id de prueba por el de mi bloque de anuncios, no
  me sale ningún error, ni aparece la publicidad en la app.

Revisa que el adUnitId sea valido para tu paquete de aplicación.

Es importante revises el LogCat ahí se mostraría el posible problema que puede ser:

*

*Tu aplicación no tiene permisos para conexión a internet. Asegura agregar el permiso

<uses-permission android:name="android.permission.INTERNET" />

dentro de tu AndroidManifest.

*

*El adUnitId no es valido, asegura que el anuncio este activo
.

*El espacio para mostrar el anuncio no es suficiente. Por ejemplo:

W/Ads: Not enough space to show ad. Needs 683x50 dp, but only has
  651x307 dp.

*

*Necesitas definir el id de un dispositivo de prueba.

Ads: Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test
  ads on this device.

*

*Asegura definir correctamente el tamaño deseado, en este caso:

ads:adSize="BANNER"

Si aseguras lo anterior puedes desplegar tu anuncio sin problema:

Revisa esta pregunta similar:
¿Como crear Banners con Admob?


text:
Q: QT QML - Changing Mapbox font size I'm using QT 5.12.4 with the MapboxGl plugin and I'm trying to figure out how to make the street names display in a larger font but I'm very confused about how to specify a text size.  I need to change the size dynamically so using a predefined style is not going to meet the requirements.
The two confusing aspects are that Mapbox's documentation has to be translated into "MapParameters" for QML and I'm clueless as to what exactly is needed to change the text size.  Between reading through the documentation and playing with the mapbox studio it seems like I need to modify the "road-label" layer. If anyone has some sample code of how to change the text size I would really appreciate it if you could share.
https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-text-size
  MapParameter
  {
      type: "layout"

      property var layer: "road-label"
      property var textSize: 20
  }

A: What you did looks correct. You need to define a MapParameter with the type layout because the text-size is a layout property in the Mapbox Style Specification. We cannot use - on QML variable names, so we camelCase it to textSize. After that you can bind textSize to anything you want.
You need to make sure that the layer road-label exists on the style at the moment the MapParameter is added.

A: I solved the problem and the key was getting the JSON for the predefined style that I was using (navigation-preview-day-v2).  This post showed me how to get the pre-defined sytle:
URL for Mapbox style sheet JSON
For the navigation-preview-day-v2 style, the URL would be:
https://api.mapbox.com/styles/v1/mapbox/navigation-preview-day-v2?access_token=(your token here)
Run the JSON through a formatter so you can read it and find the layer(s) where the street names are rendered.  In this case, there are four layers:

*

*road-label-small

*road-label-medium

*road-label-large

*road-label-extra-large

Here is an example of how to form the MapParameter in QML for the font size:

MapParameter
{
    type: "layout"
    property var layer: "road-label-large"
    property var textSize:
    {
       "base": 1,
       "stops":
       [
          [9, 10],
          [20, 16]
       ]
    }
}

You can also import the JSON into Mapbox Studio to review or manipulate the style.  In my case I wanted to dynamically scale the font size so in my QML I added a scale factor and the resulting MapParameter is:

MapParameter
{
    type: "layout"
    property var layer: "road-label-large"
    property var textSize:
    {
       "base": 1,
       "stops":
       [
          [9, Math.floor(10 * fontScaleFactor)],
          [20, Math.floor(16 * fontScaleFactor)]
       ]
    }
}


text:
Q: Cheerio just shows the first item instead of the list of children in div I'm trying to get all items in a specific div that is already addressed.
But after using children() it only shows the first item instead of a list of whole children.
Here is the source:

And here is my code:
> const html = res.data;
> const $ = cheerio.load(html);
> const data = $('div[id="thepics"]');
> console.log(data);

And its result:
LoadedCheerio {
  '0': <ref *1> Node {
    type: 'tag',
    name: 'div',
    namespace: 'http://www.w3.org/1999/xhtml',
    attribs: [Object: null prototype] {
      style: 'margin:-5px 0px 10px 0px',
      id: 'thepics'
    },
    'x-attribsNamespace': [Object: null prototype] { style: undefined, id: undefined },
    'x-attribsPrefix': [Object: null prototype] { style: undefined, id: undefined },
    children: [ [Node] ],
    parent: Node {
      type: 'tag',
      name: 'div',
      namespace: 'http://www.w3.org/1999/xhtml',
      attribs: [Object: null prototype],
      'x-attribsNamespace': [Object: null prototype],
      'x-attribsPrefix': [Object: null prototype],
      children: [Array],
      parent: [Node],
      prev: [Node],
      next: [Node]
    },
    prev: Node {
      type: 'tag',
      name: 'div',
      namespace: 'http://www.w3.org/1999/xhtml',
      attribs: [Object: null prototype],
      'x-attribsNamespace': [Object: null prototype],
      'x-attribsPrefix': [Object: null prototype],
      children: [],
      parent: [Node],
      prev: [Node],
      next: [Circular *1]
    },
    next: Node {
      type: 'tag',
      name: 'div',
      namespace: 'http://www.w3.org/1999/xhtml',
      attribs: [Object: null prototype],
      'x-attribsNamespace': [Object: null prototype],
      'x-attribsPrefix': [Object: null prototype],
      children: [Array],
      parent: [Node],
      prev: [Circular *1],
      next: [Node]
    }
  },
  length: 1,
  options: { xml: false, decodeEntities: true },
  _root: <ref *2> LoadedCheerio {
    '0': Node {
      type: 'root',
      name: 'root',
      parent: null,
      prev: null,
      next: null,
      children: [Array],
      'x-mode': 'no-quirks'
    },
    length: 1,
    options: { xml: false, decodeEntities: true },
    _root: [Circular *2]
  },
  prevObject: <ref *2> LoadedCheerio {
    '0': Node {
      type: 'root',
      name: 'root',
      parent: null,
      prev: null,
      next: null,
      children: [Array],
      'x-mode': 'no-quirks'
    },
    length: 1,
    options: { xml: false, decodeEntities: true },
    _root: [Circular *2]
  }
}

And after try to log data.children() the result is:
LoadedCheerio {
  '0': Node {
    type: 'script',
    name: 'script',
    namespace: 'http://www.w3.org/1999/xhtml',
    attribs: [Object: null prototype] {},
    'x-attribsNamespace': [Object: null prototype] {},
    'x-attribsPrefix': [Object: null prototype] {},
    children: [ [Node] ],
    parent: Node {
      type: 'tag',
      name: 'div',
      namespace: 'http://www.w3.org/1999/xhtml',
      attribs: [Object: null prototype],
      'x-attribsNamespace': [Object: null prototype],
      'x-attribsPrefix': [Object: null prototype],
      children: [Array],
      parent: [Node],
      prev: [Node],
      next: [Node]
    },
    prev: null,
    next: null
  },
  length: 1,
  options: { xml: false, decodeEntities: true },
  _root: <ref *1> LoadedCheerio {
    '0': Node {
      type: 'root',
      name: 'root',
      parent: null,
      prev: null,
      next: null,
      children: [Array],
      'x-mode': 'no-quirks'
    },
    length: 1,
    options: { xml: false, decodeEntities: true },
    _root: [Circular *1]
  },
  prevObject: LoadedCheerio {
    '0': Node {
      type: 'tag',
      name: 'div',
      namespace: 'http://www.w3.org/1999/xhtml',
      attribs: [Object: null prototype],
      'x-attribsNamespace': [Object: null prototype],
      'x-attribsPrefix': [Object: null prototype],
      children: [Array],
      parent: [Node],
      prev: [Node],
      next: [Node]
    },
    length: 1,
    options: { xml: false, decodeEntities: true },
    _root: <ref *1> LoadedCheerio {
      '0': [Node],
      length: 1,
      options: [Object],
      _root: [Circular *1]
    },
    prevObject: <ref *1> LoadedCheerio {
      '0': [Node],
      length: 1,
      options: [Object],
      _root: [Circular *1]
    }
  }
}


text:
Q: Steadily accumulating number formula This is quite likely a super simple question, but I lack the descriptive power to be able to find the answer on Google!
Consider the following two number sequences:
00, 10, 20, 30, 40, 50, 60, 70, 80, 90
45, 45, 45, 45, 45, 45, 45, 45, 45, 45

Both sequences have a total value of 450, but one accumulates steadily in multiples of 10, whilst the second remains constant at 45.
The second is easy to ascertain, divide the total value by the number of instances in the list. But the first sequence I'm stuck on - can anyone help me understand the formula for ascertaining the accumulation value (in this instance 10) from 0?
My goal is to be able to take any number and divide it x number of times, with the first number in the sequence being 0 and steadily increasing - apportioning greater and greater values to those later in the sequence.

A: It's an arithmetic sequence (i. e. every next element is created from the previous with adding the same number)  with the well-known formula for its  sum
$$a_1 + a_2 + \cdots + a_n = {n \over 2}(a_1+a_n)$$
So, as $a_1= 0,\ n = 10,\ $ and $\ a_{10} = 90$ you will obtain
$$00 + 10 +20 + \cdots + 90 = {10\over2}(0 + 90)= 5\cdot 90 = 450$$

Addendum:
If you know the first element ($a_1$), number of elements ($n$) and their sum ($s$), you may obtain the last element ($a_n$) by substituting the known values into the formula, and then isolate $a_n$:
$$a_n = {2s\over n}-a_1$$
You may then compute the difference $d$ between adjacent members as
$$d = {a_n-a_1\over n-1}$$
to consecutively obtain members between $a_1$ and $a_n$:
\begin{aligned}
a_2 &= a_1+d\\a_3 &= a_2+d\\
&\cdots
\end{aligned}
(To the question in your comment.)

A: $$\sum\limits_{i=0}^9 10 i = 10 \sum\limits_{i=0}^9 i = 10 \left[ \frac{(9+0)(9+1)}{2} \right] =450$$


text:
Q: android cocos2dx integration with scoreloop I am integrating scoreloop in Android with cocos2dx framework.
 i have download source from [https://github.com/ursine-paw/upSL][1]
[1]: https://github.com/ursine-paw/upSL, where i have put jni_scoreloop.ccp and Scoreloop.h file in classes folder and added using namespace cocos2x in jni_scoreloop.ccp.
but still there is error in submitScore
in jni_scoreloop
 void ScoreController::SubmitScore(ScoreController* self, double result, double minor_result, unsigned int level, unsigned int mode, std::map<std::string, std::string>* context==NULL)

Anyone have any idea about it then please help me.
and in Scorelopp.h file
template argument 3 is invalid

and show error


text:
Q: How can a node with complete log can be elected if another becomes a candidate first? I've been watching Raft Algorithm video at https://youtu.be/vYp4LYbnnW8?t=3244, but am not clear about one circumstance.

In leader election for term 4, if node s1 broadcasts RequestVote before s3 does then node s2, s4 and s5 would vote for it, while s3 doesn't.  And then node s3 broadcasts RequestVote to others, how can it get the vote of others?
One possible way to handle the situation I can figure out is:

*

*if node s1 receives the rejection from s3, and found out s3's log is newer than itself, and do not set itself as leader even though it receives majority of votes

*As to other nodes, they remember the leader information they voted, if a new vote request comes (with bigger <lastTerm, lastIndex>), they vote for the node with bigger <lastTerm, lastIndex>.

In both scenarios, eventually node s3 gets all others' votes, and sets itself as leader. I'm not sure if my guess is correct.

A: (Before I comment, be aware that there is NO possible way for entry #9 to be committed. There is no indication of which log entries are committed, but this discussion works with any of #s 1-8 as being committed.)
In short, s3 does not become the leader, s1 does because it gets a majority of the votes. If your concern is that entry #9 will be lost, that is true, but it wasn't committed anyway.
From §5.3:

In Raft, the leader handles inconsistencies by forcing
  the followers' logs to duplicate its own. This means that
  conflicting entries in follower logs will be overwritten
  with entries from the leader's log.

To comment on your handling of the situation.

1, if node s1 receives the rejection from s3, and found out s3's log is newer than itself, and do not set itself as leader even though it receives majority of votes

It could do this, but it will make failover take longer because s3 would have to try again with a different timeout, and you come into a race condition where s1 always broadcasts RequestVote before s3 does. But again, it is always safe to delete the excess entries that s3 has.
The last paragraph of §5.3 talks about how this easy, timeout-based election process was used instead of ranking the nodes and selecting the best. I agree with the outcome. Simpler protocols are more robust.

2, As to other nodes, they remember the leader information they voted, if a new vote request comes (with bigger <lastTerm, lastIndex>), they vote for the node with bigger <lastTerm, lastIndex>.

This is strictly forbidden because it destroys leader election. That is, if you have this in place you will very often elect multiple leaders. This is bad. I cannot stress enough how bad this is. Bad, bad, bad.