text:
Q: Semantic Issues when using STHTTPRequest I've imported STHTTPRequest by adding it to my project and including "STHTTPRequest.h" in my app delegate, as the instructions on the github page say to. However, I'm getting the following errors and warnings:
(Warning) Semantic Issue: STHTTPRequest.m:805:68: Undeclared selector 'backgroundSessionConfigurationWithIdentifier:'
(Error) ARC Semantic Issue: STHTTPRequest.m:807:63: No known class method for selector 'backgroundSessionConfigurationWithIdentifier:'
(Error) Semantic Issue: STHTTPRequest.m:819:26: Property 'sharedContainerIdentifier' not found on object of type 'NSURLSessionConfiguration *'
Is there something I'm doing wrong?


text:
Q: How to extract PrototypeJS(?) vars: possibilities, techniques, permalinks, etc On some sites users have account numbers, on others nicknames; one can represent the other and vise-versa.  Or not.  On some sites when the username is changed, all the links in their uploads, posts, and comments break completely.  KAT.CR is one of those sites.  Which is weird because there is a corresponding alphanumeric hash, it just isn't tied to the nickname.  This may be leftover from when changes to ones name led to an update, not a "broken user link." In fact this question was asked there first snd a staff member responded that the functionality was withdrawn.  No reason was given.  This is just an example, there are lots of sites that do this, or make other changes that cause links to break.
Rather than linking to static destination, I would like to write a script that
1. queries a database or subdomain for a pre-specified user id
2. returns the current username,
3. runs a redirect script to the updated profile page for the current user.
If it was my site and I wished to link to my profile here, for example, I would just manually update the url.  I used this example because uploads include links in their torrents that cant be updated.
Below is one of several javascripts that appears at the top of every page when logged in a KAT.  I am not certain which, if any of the values are a permanent fixture of the account or how/where such a script would search in order to perform the task I described... I would just like to know if the concept is viable.
<script type="text/javascript">
    +function(S,p,a,r,e,C,l,i,c,k)
    { S[r]=S[r]||[];S[e]||(S[e]=function(){
    S[r].push(Array.prototype.slice.call(arguments)) });
    i=p.createElement(a);c=p.getElementsByTagName(a)[0];
    i.src=C;i.async=true;c.parentNode.insertBefore(i,c)}
    (window,document,'script','_scq','sc', '//a.kickass.to/sc-8cce154.js');

    sc('setHost', 'a.kickass.to');
    sc('setAccount', '32 digit alphanumeric');
        var kat = {
        release_id: '8cce154',
        detect_lang: 0,
        spare_click: 1,
        mobile: false
    };
    var katUser = {
        idhash: '28digitalphanumeric',
        channel: 'another28digitalphanumeric',
        nickname: 'username',
        avatar: '//yuq.me/userpics/10/100/userpic.png',
        acl: 1,
        disable_sounds: 0,
        disable_animated_upics: 0        };
</script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compute $\int_{0}^{\infty}e^{-tz}(z+d)^{n-1}dz$ as a function of $\Gamma(n)$ Is it possible to compute this integral $$\int_{0}^{\infty}e^{-tz}(z+d)^{n-1}dz$$ as a function of complete gamma  $\Gamma(n)$. If possible, I'm looking for a closed form solution.
Thanks!

A: No, it is not possible to compute the integral as a function of $\Gamma(n)$
The integral is an Incomplete Gamma function. Change the variable $Z=t(z+d)$ and the integral definition of the Incomplete Gamma appears.
$\int_{0}^{\infty}e^{-tz}(z+d)^{n-1}dz = e^{td}t^{-n}\int_{td}^{\infty}e^{-Z}Z^{n-1}dZ = e^{td}t^{-n}\Gamma(n,td)$

A: A related technique. Here is a closed form for $n\in \mathbb{N}$. Recalling the binomial theorem and making the change of variables $u=tz$ we have
$$I= \int_{0}^{\infty}e^{-tz}(z+d)^{n-1}dz = \int_{0}^{\infty}e^{-u}(u/t+d)^{n-1}\frac{du}{t} $$
$$ = \sum_{k=0}^{n-1} {n-1\choose k} \frac{d^{n-1-k}}{t^k} \int_{0}^{\infty}u^{k}e^{-u}du $$

$$ \implies  I= d^{n-1}\sum_{k=0}^{n-1} {n-1\choose k} \frac{1}{(td)^k}\Gamma(k+1) $$

Added: If $n$ is not a natural number then you can consider Newton's generalised binomial theorem as stated in the comment by Cameron Williams.


text:
Q: Get text keeping any text-decoration styling Currently using Cheerio I can get the text I need but I would also like to retain strikethrough text. (if easier I can just wrap around the ~~ characters as the text will end up in a discord embed)
My Current Code is as follows:
const cheerio = require('cheerio');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

async function scrapeInformation() {
  const response = await fetch('https://scp-wiki.wikidot.com/personnel-and-character-dossier');
  const body = await response.text();

  const $ = cheerio.load(body);
  const titleList = [];

  const wikiTab = $('#wiki-tab-0-6 > p');

  wikiTab.each((i, title) => {
      const titleNode = $(title);
      console.log(titleNode.find("span").attr("style"));
      const titleText = titleNode.text();

      titleList.push(titleText);
  });
}

scrapeInformation();

What I expect for the text with strikethrough is:
Anartist musician, co-founder of the "House of Spades" rock band, partially responsible for the creation of SCP-952. In custody following two failed suicide attempts, designated D-952. Missing, presumed deceased.
Website for reference: https://scp-wiki.wikidot.com/personnel-and-character-dossier (D-Class Tab)
Some HTML from the website:

      D-952 (formerly Veronica Fitzroy): Anartist musician, co-founder of the "House of Spades"rock band, partially responsible for the creation of In custody following two failed suicide attempts, designated D-952. Missing, presumed deceased.

Any documentation or articles that could further my knowledge would be appreciated.

A: After some changes and testing I have created the solution below:
wikiTab.each((i, title) => {
   const titleNode = $(title);
   let titleText = titleNode.text();

   if (titleNode.find("span").attr("style")) {
      const span = $(titleNode.find("span"));
      const node = $(span);

      const replace = "~~" + node.text() + "~~";
      titleText = titleText.replace(node.text(), replace);
   }

   titleList.push(titleText);
});

What I have done is checked if the titleNode had a span element with the style attribute then did some stuff I honestly don't understand then replaced part of the already obtained text with text that would be strikethrough compatible with discord.
Any comments that could provide advice, articles and documentation would still be greatly appreciated so I can understand what I am actually doing.


text:
Q: Fix the header of html table at top I have fixed the columns of html table as given in this fiddle. Same way I am trying to fix only the header row of table as,
var $table = $('.table');
var $fixedColumn = $table.clone().insertBefore($table).addClass('fixed-column');

$fixedColumn.find('tbody').remove();

$fixedColumn.find('thead th').each(function (i, elem) {
    $(this).width($table.find('tbody tr:first td:eq(' + i + ')').width());
});

which is given in this fiddle. But the header didn't fixed. What is missing?

A: How about this??
DEMO

       #
       Table heading
       Table heading
       Table heading
       Table heading
       Table heading
       Table heading

css
.fixed
{
    position:fixed;
    background:gray;

}

You can try this EXAMPLE too if you are much more interested!!


text:
Q: how to push views iphone? i'm new to iphone development and i need some guidance in pushing views. I have the following application scenario "press on button ->switch view (contains a table)->press on table cell ->switch view".
To switch when i press the button i use the following code :
MapView *screen = [[MapView alloc] initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:screen animated:YES];
[screen release];

Then to push another view i want to use this code (but it does not work - and im asking why?)
Newclass *nextController = [[Newclass alloc] initWithItem:theItem];
    [self.navigationController pushViewController:nextController animated:YES];
    [nextController release];

A: You want to push this view from your MapView? Looks like you don't have a UINavigationController which is needed to push view controllers like that.
Update the first part of your code to put the MapView inside UINavigationController, than you can push other views onto it with that second part of code you have.
MapView *screen = [[MapView alloc] initWithNibName:nil bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:screen]; // this puts the MapView onto navigation controller
navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; // you will present the navController instead of screen so change it's modalTransitionStyle
[self presentModalViewController:navController animated:YES]; // present it
[screen release];
[navController release]; // don't forget to release


text:
Q: How to compute the integral $\int_{-\infty}^\infty e^{-x^2/2}\,dx$? Yes, I know that this is very similar to  $\int_{-\infty}^\infty e^{-x^2}\,dx$, which has been answered a million times, but I still don't know how to apply the technique from that integration to mine.
I don't want to do this using polar coordinates, or "erf". I'd like to use the Gamma function (which I assume is possible..).
Is this correct? :
$$\int_{-\infty}^\infty e^{-x^2/2}\,dx=2\int_{0}^\infty e^{-x^2/2}\,dx$$
Let $u = x^2/2  \implies x = \sqrt{2u}$, $du = x \, dx \implies dx = (2u)^{-1/2}$
So,
$$=2\int_{0}^\infty (2u)^{-1/2}e^{-u}\,dx=\sqrt{2}\int_0^\infty (u)^{-1/2}e^{-u}\,dx=\sqrt{2} \Gamma(1/2)= \sqrt{2\pi}$$

A: Actually, you can use sum expression for $e^{-x^2}$. Then you can get which function you want in this way and then you can integrate.

A: $$
=2\int_{0}^\infty (2u)^{-1/2}e^{-u}\underbrace{\,dx\,}_{\text{error}}=\sqrt{2}\int_0^\infty (u)^{-1/2}e^{-u}\,dx=\sqrt{2} \Gamma(1/2)= \sqrt{2\pi}
$$
If you put $du$ where $dx$ is, then its correct.  Where you wrote $dx = (2u)^{-1/2}$, you need $dx=(2u)^{-1/2}\,du$.
If you're only trying to reduce the integral $\displaystyle\int_{-\infty}^\infty e^{-x^2/2}\, dx$ to the integral $\displaystyle\int_{-\infty}^\infty e^{-x^2}\,dx$, it can be done as follows:
\begin{align}
u & = \frac x {\sqrt{2}} \\[8pt]
u^2 & = \frac{x^2}2 \\[8pt]
du & = \frac{dx}{\sqrt{2}} \\[8pt]
\sqrt{2}\,du & = dx \\[8pt]
\int e^{-x^2/2}\,dx & = \int e^{-u^2}\sqrt 2\,du = \sqrt 2\int e^{-u^2}\,du.
\end{align}
Then notice that as $x$ goes from $-\infty$ to $+\infty$, so does $u$, since $1/\sqrt 2$ is positive.  You get
$$
\int_{-\infty}^\infty e^{-x^2/2}\,dx = \sqrt 2 \int_{-\infty} e^{-x^2}\,dx = \sqrt 2\sqrt \pi.
$$


text:
Q: How to solve Auth guard [web] is not defined problem I make 2 guards 1. For admin and 2. for student. Now when i click on my button to show the login form i always caught that error that Auth guard [web] is not defined.Now how i solve this.
here is my config/auth.php
 'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
 'guards' => [
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'student' => [
            'driver' => 'session',
            'provider' => 'student',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],
    'providers' => [
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
        'students' => [
            'driver' => 'eloquent',
            'model' => App\Student::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

I am trying login the admin using admin guard.Please help me to solve that and i dont use default User.php model.

A: That's because you're removing web guard from the application.
Just change your default guard from web to your new guard.
'defaults' => [
    'guard' => 'admins',
    'passwords' => 'users',
],


text:
Q: Passing coordinates from one class to another I'm trying to make an app which gets user location, and guides the user to a certain place on the map. I've got two classes:
package com.pizzeria.uno;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class ComoLlegar extends MapActivity {

private MapView mapView;
private MyLocationOverlay myLocationOverlay;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // main.xml contains a MapView
    setContentView(R.layout.llegar);

    // extract MapView from layout
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);

    // create an overlay that shows our current location
    myLocationOverlay = new FixedMyLocationOverlay(this, mapView);

    // add this overlay to the MapView and refresh it
    mapView.getOverlays().add(myLocationOverlay);
    mapView.postInvalidate();
    mapView.setSatellite(true);

     GeoPoint point1 = new GeoPoint(43467604,-3833841);

     double lat1 = (point1.getLatitudeE6()/ 1E6);
     double lng1 = (point1.getLongitudeE6()/ 1E6);

     GeoPoint point2 = new GeoPoint(39639538,-4921875);

     double lat2 = (point2.getLatitudeE6()/ 1E6);
     double lng2 = (point2.getLongitudeE6()/ 1E6);

     final Intent intent = new Intent(Intent.ACTION_VIEW,

           Uri.parse(
                    "http://maps.google.com/maps?" +
                    "saddr=" + lat2 + "," + lng2 +
                    "&daddr=" + lat1 + "," + lng1 ));
           startActivity(intent);

     myLocationOverlay.disableMyLocation();

    // call convenience method that zooms map on our location
    zoomToMyLocation();
}

@Override
protected void onResume() {
    super.onResume();
    // when our activity resumes, we want to register for location updates
    myLocationOverlay.enableMyLocation();
}

@Override
protected void onPause() {
    super.onPause();
    // when our activity pauses, we want to remove listening for location updates
    myLocationOverlay.disableMyLocation();
}

/**
 * This method zooms to the user's location with a zoom level of 10.
 */
private void zoomToMyLocation() {

    double lat=43.467604;
    double lng=-3.833841;
    GeoPoint myLocationGeoPoint = new GeoPoint((int)(lat * 1E6), (int)(lng * 1E6));
    if(myLocationGeoPoint != null) {
        mapView.getController().animateTo(myLocationGeoPoint);
        mapView.getController().setZoom(13);
    }
    else {
        Toast.makeText(this, "Cannot determine location", Toast.LENGTH_SHORT).show();
    }
}

@Override
protected boolean isRouteDisplayed() {
    return false;
}
}

What I need is to change this "GeoPoint point2 = new GeoPoint(39639538,-4921875);" for the coordinates which I get from this class:
package com.pizzeria.uno;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.location.Location;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Projection;

public class FixedMyLocationOverlay extends MyLocationOverlay {

private boolean bugged = false;

private Drawable drawable;
private Paint accuracyPaint;
private Point center;
private Point left;
private int width;
private int height;

public FixedMyLocationOverlay(Context context, MapView mapView) {
    super(context, mapView);
}

@Override
protected void drawMyLocation(Canvas canvas, MapView mapView,
        Location lastFix, GeoPoint myLocation, long when) {
    if(!bugged) {
        try {
            super.drawMyLocation(canvas, mapView, lastFix, myLocation, when);
        } catch (Exception e) {
            // we found a buggy phone, draw the location icons ourselves
            bugged = true;
        }
    }

    if(bugged) {
        if(drawable == null) {

            accuracyPaint = new Paint();
            accuracyPaint.setAntiAlias(true);
            accuracyPaint.setStrokeWidth(2.0f);

            drawable = mapView.getContext().getResources().getDrawable(R.drawable.icon);
            width = drawable.getIntrinsicWidth();
            height = drawable.getIntrinsicHeight();
            center = new Point();
            left = new Point();
        }

        Projection projection = mapView.getProjection();
        double latitude = lastFix.getLatitude();
        double longitude = lastFix.getLongitude();
        float accuracy = lastFix.getAccuracy();

        float[] result = new float[1];

        Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
        float longitudeLineDistance = result[0];

        GeoPoint leftGeo = new GeoPoint((int)(latitude*1e6), (int)((longitude-accuracy/longitudeLineDistance)*1e6));
        projection.toPixels(leftGeo, left);
        projection.toPixels(myLocation, center);
        int radius = center.x - left.x;

        accuracyPaint.setColor(0xff6666ff);
        accuracyPaint.setStyle(Style.STROKE);
        canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

        accuracyPaint.setColor(0x186666ff);
        accuracyPaint.setStyle(Style.FILL);
        canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

        drawable.setBounds(center.x - width/2, center.y - height/2, center.x + width/2, center.y + height/2);
        drawable.draw(canvas);
    }
}
}

The problem is that I'm not able to get the coordinates from the second class to the first class.

A: For this problem, Create SINGLETON class for the ComoLlegar.class and make a reference to FixedMyLocationOverlay.class. Now you can access all the objects and you can send values to the First class.
Reference:
Write this code in ComoLlegar.class:
public static MapActivity getMapObject() {

    if (mapObject != null) {
        return mapObject;
    }
    return mapObject;

}

Write this code in Second.class
((ComoLlegar.class) object).method_name(arguments);

Now it works :):)

A: You can try
Intent i = new Intent();
i.putExtra("points", geoPoints);

in your second class call
Intent i = getIntent();
i.getExtra("points");

A: If your second activity only serves to calculate a coordinate and then return that data, then you should call that activity through startActivityForResult, see this. It let's you "prompt" an activity for a result.


text:
Q: OneLogin - OpenID Connect - Unable to use custom URL scheme? Ionic/Cordova How can I send the OpenID redirect to a custom url endpoint with OneLogin?  I'm trying to embed our OneLogin in our mobile apps and it's not letting me redirect to a custom url prefix. like myapp://token.  This is the way to use chrome tabs or the inappbrowser in a cordova app.  It seems to work for other OpenID ID providers.

A: Right now the supported protocol is HTTPS. (or http://localhost permitted for development purposes).
You will need to add your callback url to the list of approved Redirect URIs for your OneLogin OIDC app via the Admin portal.
See step 5 of https://developers.onelogin.com/openid-connect/connect-to-onelogin).

A: This capability is currently in beta at OneLogin and will be GA within a few weeks.


text: Q: Is there any way to Download plotly excel sheet with the chart image pasted into it? I want to export the Plotly chart image . Downloading it separately is fine, but I want to download it as an excel sheet with the chart's image already pasted into it.


text:
Q: Python // Lambda: invalid syntax I'm trying to iterate on a dataframe. I want to replace a few characters by anothers, unless the item I'm iterating is null/nan/NaN/etc.
For that I'm trying to use this line below:
lista['ultima_receita'] = lista['ultima_receita'].apply(lambda rstr: float(rstr.replace('.','').replace(',','.')[3:]) if pd.isnull(rstr) == False)

However it keeps getting me a invalid synthax error:
    lista['ultima_receita'] = lista['ultima_receita'].apply(lambda rstr: float(rstr.replace('.','').replace(',','.')[3:]) if pd.isnull(rstr) == False)
                                                                                ^
SyntaxError: invalid syntax

I've tried everything I could and didn't find out the reason why the synthax is wrong. Can someone help?

A: Try making your question simpler.  The lambda is indeed the issue, so this has nothing to do with pandas here.
>>> lambda rstr: float(rstr.replace('.','').replace(',','.')[3:]) if pd.isnull(rstr) == False
SyntaxError: invalid syntax  # At the end of 'False' above

or even simpler:
>>> lambda x: "foo" if "bar" == False
SyntaxError: invalid syntax

This is because python needs an else for the A if B else C construction.  If you want to do a conditional modification you could make this else rstr, or use other pandas / numpy logic to do different logic.
>>> func = lambda x: "foo" if "bar" in x else x
>>> func("isobaric"), func("agnostic")
('foo', 'agnostic')


text:
Q: How do I convert a NSString into TIS-620 encoded string In the apple document, I can see that there's a way to convert from UTF8 string to ASCII string like this
NSData *asciiData = [theString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *asciiString = [[NSString alloc] initWithData:asciiData encoding:NSASCIIStringEncoding];

But my app requires a TIS-620 string to post to a site so I try to do the same thing
NSData *asciiData = [newPost.header dataUsingEncoding:kCFStringEncodingMacThai allowLossyConversion:YES];
NSString *asciiString = [[NSString alloc] initWithData:asciiData encoding:kCFStringEncodingMacThai];
NSLog(@"%@", asciiString);

The output I got is like this ???????????.
Does anyone know how to convert the NSString to TIS-620 properly?
Thanks so much.

A: Firstly, TIS-620 is a subset of ISO-8859-11, so you should use the string encoding kCFStringEncodingISOLatinThai instead of kCFStringEncodingMacThai.
Also, a CF encoding cannot be directly used to decode an NSString. You need to convert the CF encoding into NS encoding first.
NSStringEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatinThai);
NSData *asciiData = [newPost.header dataUsingEncoding:enc allowLossyConversion:YES];


text:
Q: convert year or month into days, PHP So I have used this method to get the difference between 2 dates.
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

Now, lets say that I want to convert the years and months into days. How do I do that?

A: Using DateTime this is a piece of cake:
$date1 = new DateTime($date1);
$date2 = new DateTime($date2);

$diff = $date1->diff($date2, true);

echo $diff->format('%a') . ' days';

A: $currentDate = date("d-m-Y");
$date1 = date_create("".$joining_date."");
$date2 = date_create("".$currentDate."");
$diff12 = date_diff($date2, $date1);
$hub_days = $diff12->days;
$months = $diff12->m;
$years = $diff12->y;


text:
Q: TortoiseGit Commit window make none selected as default In the commit window of TortoiseGit , all files are selected by default. I would like to have "none" or no file selected by default.
Is there any setting to do this?

A: Go to TortoiseGit settings -> Dialogs 2 and remove the check for "Select items automatically".

A: After upgrading to TG 2.13, I had the opposite issue (no items selected by default, undesired behavior for me), even though Select items automatically was checked.
Uncheck it, click "Apply". Check it back, click "Apply". It fixed it for me.
Full path to this option:
TG Settings → General → Dialogs2


text:
Q: Passing created object instance to mapper I have one problem with some SharePoint Library. I would like to map my 'Model' object to 'ListItem' object. Unfortunately the 'ListItem' object doesn't have any constructor and I need to initialize it with function which are inside SharePoint Library. Is it possible to give (before mapping) an instance of mapped object?
    public void AddToList(Model model)
    {
        // 'new ListItem()' is fobbiden. 'CreateListItemInstance()'
        // creates 'instance' using client context, list name which aren't
        // inside 'model' object.
        ListItem instance = this.CreateListItemInstance();

        // (Model -> ListItem) It throws exception, because automapper
        // try to create instance of ListItem.
        ListItem parsedItem = Mapper.Map<ListItem>(model);

        // I would like to have something like below:
        // Mapper.Map<ListItem>(model).UseInstance(instance);

        this.SharePointListItemRepository.Insert(parsedItem);
        this.SharePointListItemRepository.Save();
    }

Update (12/22/2017)
I used ResolutionContext to pass instance to mapper and I used this instance in ConstructUsing method to replace constructor with instance.
        ListItem instance = this.CreateListItemInstance();

        ListItem parsed = mapper.Map<ListItem>(model, opts =>
        opts.Items["instance"] = instance);  //passing instance to ResolutioContext

        this.SharePointListItemRepository.Insert(parsed);
        this.Save();

Inside map profile:
            CreateMap<Model, ListItem>()
            //Using 'ConstructUsing' method to use instance of Model
            //(from resolutionContext) as constructor.
            .ConstructUsing((source, resolutionContext) =>
            (resolutionContext.Items["instance"] as ListItem))
            //Mappings...
            .AfterMap((source, destination) =>
            {
                destination["Title"] = source.Title;
            });

A: Check out this article:

Because we only supplied the type of the custom resolver to AutoMapper, the mapping engine will use reflection to create an instance of the value resolver.
If we don't want AutoMapper to use reflection to create the instance, we can supply it directly:
Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>()
    .ForMember(dest => dest.Total,
        opt => opt.ResolveUsing(new CustomResolver())
    );

In place of
opt.ResolveUsing(new CustomResolver())

there may be:
opt.ResolveUsing(CreateListItemInstance())


text:
Q: If it possible to submit form form Ajax with Flask? I have an application using Flask and JavaScript. I have a function in JavaScript when the user click the button and the data are send to Flask. This function create a marker on the map and set the data from function in Flask to marker popup. I use form in popup because I want to get the name form this popup. I want to submit this form from popup and get the name but when I do it print("Name :",nazwa_event) it return me None. I create a input with hidden tag in html and I set input value to the name from form  $('input[id=nameOF]').val(nazwa.value);. It is possible to do that or I can't submit form from Ajax ?
HTML code:
<input type="text" id="name_of_event"  class="form-control mb-2" name="name_event" placeholder="Nazwa wydarzenia">
                    <input name="nameOfEvent" type="hidden" value="" id="nameOF">

                    <button id="search-button_event" type='submit' name="event_form" class="btn btn-primary">Szukaj</button>

JS code:
$("#search-button_event").click(function () { // make ajax request on btn click
        $.ajax({
            type: "POST",
            url: "/mapaa", // url to the function
            data: {
                nameevent: $("#name_of_event").val(), // value of the form
            },
            success: function (response) {

                 nazwa = (response['name']);

                let marker_event = L.marker(array[0]).bindPopup()
                marker_event._popup.setContent(
                                                                '<form method="POST" action="/mapaa"'+
                                                                '
Nazwa: '+nazwa+'
'+
                                                                '<button type="submit" id="form-submit" name="form-submit"  class="btn btn-warning btn-block">Dołącz do wydarzenia</button>'+
                                                                '</form>')

                marker_event.addTo(mymap)

                polyline_event = L.polyline(array,{color: 'red'})
                marker_event.on('click',function(){
                    polyline_event.addTo(mymap)
                })
                marker_event.getPopup().on('remove', function() {
                    polyline_event.remove()
                })

                $('input[id=nameOF]').val(nazwa.value);
                mymap.setView(array[0],14)
            },
        });
    });

FLASK code:
@app.route('/mapaa',methods=['GET','POST'])
def mapa():
    user_id = current_user.get_id()
    slownik = {}

    if request.method == "POST":

        if request.is_json:
            req = request.get_json()
            nazwa = req['name']
            data_pocz = req['data_start']
            data_kon = req['data_end']
            typ = req['type']
            dlugosc = req['len_route']
            coord = req['coordinates']
            event_database = Event(date_start=data_pocz, date_end=data_kon, type=typ, name=nazwa, len_route=dlugosc,admin=user_id, route=coord)
            db.session.add(event_database)
            db.session.commit()
            print('Dodano wydarzenie')

        if 'form-submit' in request.form:
            nazwa_event = request.form.get('nameOfEvent')
            print("Id ev:",nazwa_event)

        else:
            name_ev = request.form.get('nameevent')
            all_data = Event.query.filter_by(name=name_ev).all()
            for row in all_data:
                date_st_string = str(row.date_start)
                date_end_string = str(row.date_end)
                slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
            return jsonify(slownik)
    return render_template('mapaa.html', title='Mapa')

A: I can't test it but as for me you have hidden <input> in wrong place - it has to be inside form inside popup. And you can set value directly in HTML without using jQuery
marker_event._popup.setContent(
    '<form method="POST" action="/mapaa"' +

    '<input name="nameOfEvent" type="hidden" value="' + nazwa.value + '" id="nameOF">' +

    '
Nazwa: ' + nazwa + '
' +
    '<button type="submit" id="form-submit" name="form-submit"  class="btn btn-warning btn-block">Dołącz do wydarzenia</button>' +
    '</form>'
)

I'm not sure if it should be nazwa.value or only nazwa like in '
Nazwa: ' + nazwa + '
'


text:
Q: Kafka - Spark direct stream fail over We have a simple spark streaming application, streaming events from kafka through spark and persisting this into redis.
Initially we use the Receiver-based Approach, which replicates the batches into HDFS and starts processing afterwards. This approach wasn't as stable as we whished (lot of traffic on our hadoop machines) so we switched to the Direct Approach (No Receivers) within spark streaming.
What confuses me is the auto.offset.reset parameter that is mentioned in the documentation. When a job failed or the sparkmaster went down, we would see the streaming jobs catching up by processing a large amount of events and then stabilizing overtime.
With the second approach we don't see this behaviour anymore and we are not sure if spark-streaming is really catching up or just starting at auto.offset.reset latest.
Is latest a sensible default for failover and does a streaming job really catches up correctly on restart/master-failure?
Thanks,
Muki

A:
What to do when there is no initial offset in Zookeeper or if an
offset is out of range:

*

*smallest : automatically reset the offset to the smallest offset

*largest : automatically reset the offset to the largest offset

*anything else: throw exception to the consumer. If this is set to largest, the consumer may lose some messages when the number of
partitions, for the topics it subscribes to, changes on the broker. To
prevent data loss during partition addition, set auto.offset.reset to
smallest

This option takes place only when you run your job first time
or when some messages expire and the last committed offset in your consumer no longer exists.
So smallest is preferable if you do not want to lose data. If you restart job within the data expiry time this option doesn't affect your failover/restart


text:
Q: Rails MS SQL query starting at the end I have a rails app querying a MS SQL DB, it is checking to see if one column is false, but I realistically only need to check in the last 1000 records (there are just over 900,000 records).
It takes a long time to check over everything every time, so is there a way to limit it to only check the last 1000 for this column? I've tried using @object.find_each, but that checks 1000 at a time, but goes through the whole table.

A: It's rather easy; all you have to do is to use YourModel.order('id desc').limit(1000).where('your_column = false'), which would generate the query to search through your last thousand rows.


text:
Q: How to implement Flutter Cards with Previous and Next button I have 4 different Cards with Radio button. I want to implement  Previous and next button at the end of every cards. At the end of the last Card I want a Submit button that will submit the whole form.
Can anyone tell me how can I implement this logic??


text:
Q: End of the Ext functors Let $R$ be a ring, and consider the hom functor $\hom\colon Mod(R)^\text{op}\times Mod(R)\to Mod(R)$; the end of $\hom$ is well-known to be the set of endomorphisms (endonatural transformations) of the identity functor $1\colon Mod(R)\to Mod(R)$, i.e. the kernel
$$
\int_M \hom(M,M)\cong \ker\left(\prod_{M\in Mod(R)} \hom(M,M)\xrightarrow{(-)\circ \phi - \phi\circ(-)}
\prod_{\phi\colon M\to N}\hom(M,N)\right)
$$
Now, what should the end of the derived functors $Ext^n\colon Mod(R)^\text{op}\times Mod(R)\to Mod(R)$ be?


text:
Q: поиск слов цельных слов Не понимаю, почему захватило abea? ведь по идеи должно находить только цельное слово
echo preg_replace('#(ab)+#', '!', 'ab abab abab abababab abea');

должно было вывести только ! ! ! ! abea
а выводит ! ! ! ! !ea

A: Чтобы найти целое слово, состоящее из ab, используйте границы слова \b:
echo preg_replace('#\b(?:ab)+\b#', '!', 'ab abab abab abababab abea');
                    ^^       ^^

// => ! ! ! ! abea

См. PHP-демо
Подробности

*

*\b - начальная граница слова (перед текущей позицией может быть начало строки или цифра/буква/знак подчёркивания)

*(?:ab)+ - одно или более повторений последовательности букв ab ((?:...) — незахватывающая группа, используемая только для группирования символов/шаблонов)

*\b - конечная граница слова (после текущей позиции может быть конец строки или цифра/буква/знак подчёркивания)

A: Используйте опережающую отрицательную проверку:
echo preg_replace('~(ab)+(?!ea)~', '!', 'ab abab abab abababab abea');
// Вывод : ! ! ! ! abea


text:
Q: Constant unexplained disk activity The screenshot below is from a Windows Server machine that is acting very strange lately. Every few minutes the HDD's go spinning like crazy without any reason I can explain.

*

*RAM Checked, OK

*HDD surface check, OK

*HDD SMART Monitor, No Errors

*Disk defragmented on schedule, no errors

No new hardware or software has been installed except Sophos AV which I actually suspect being the cause of everything.
I have also checked for hidden Bitcoin-Mining processes that are usually fired when the PC is idle but I found none.
What might be the cause of this problem?

A: The hard drive activity shown in your Resource Monitor screen shot doesn't inherently indicate anything out of the ordinary.  Your hard drive is operating at nearly 100% capacity as indicated by the blue line in the Disk graph. That could be perfectly normal for your computer, especially if you're running a mechanical hard drive as they are frequently the first of the four primary system resources (CPU, RAM, I/O, Network) to become bottle-necked.
But without knowing your system, that's just a guess.
The best way to know if you're experiencing unusual system activity (and troubleshoot it) is to have a performance baseline. This is simply a record of system resource use created during known-"normal" system operation.  This can be as simple as keeping Resource Monitor open while using your system normally to get a "feel" for the graphs and other data during normal activities.  Or you can take a more professional approach and use something like Windows Performance Monitor to make a detailed record of exact counter values (The excellent TechNet blog How to create a "black box" performance counter data collector is a good place to start).
With a good idea in hand what is normal for your system you can more effectively troubleshoot suspected "unusual" behavior.  In your case you suspect your antivirus, so you might record some system activity with the software installed, then remove it and have a look at the reported activity again.  If the antivirus software is to blame it should be clear from a comparison of the monitored activity.


text:
Q: Configure fails on `PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.12.3)' I am attempting to create a fairly simple BitBake recipe that uses autotools, which you can see here:
SUMMARY = "an example autotools recipe"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
inherit autotools
SRC_URI = "file://${TOPDIR}/piu/geo_utilities"
S = "${TOPDIR}/piu/geo_utilities"

After starting a BitBake build with this recipe's default package included,   do_configure fails with the following:
configure: line 12851: syntax error near unexpected token `GLIB,'
configure: line 12851: `PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.12.3)'

When I run ldd --version, I get this: ldd (GNU libc) 2.17.
I've found several sites like this Google Groups post and this GitHub issue which suggest that the problem can be solved by updating pkg-config. I'm running Red Hat, so I've run sudo yum install pkgconfig which returns that pkgconfig-0.27.1-4.el7.x86_64 already installed and latest version.
(this question followed after this question was solved by the answerer)

A: The proper fix is to inherit pkgconfig.  Specifically you need pkgconfig-native built.

A: I believe that this error was due to the do_configure step of my custom recipe being ran before the glib for my target machine was generated. I was able to resolve this error by adding this line to the recipe:
DEPENDS += " glib-2.0 pkgconfig "


text:
Q: eclipse: turn off automatically reloading of class files eclipse has  a very nice feature. that is when you debug, it reloads changes to your source files when you save the file.
what is the name of this feature?
is it possible to turn it off?
thanks!

A: I think you mean Hot Code Replace, you can disable this feature by disabling (uncheck) Build Automatically from the Project menu.


text:
Q: I have a NSDate, how do i show a stopwatch that auto updates showing a timer? I have a NSDate variable. From that variable, how I can show a stopwatch that continuously updates in the view?
I've tried [NSTimer scheduledTimerWithTimeInterval] but can't get it working but also doubt that is the ideal way to do that.

A: What's the problem with NSTimer?
- (void)startTimer {
    [NSTimer scheduledTimerWithTimeInterval:1/30.0f
                                     target:self
                                   selector:@selector(timerFired:)
                                   userInfo:[NSDate date]
                                    repeats:YES];
}

- (void)timerFired:(NSTimer *)timer {
    NSDate *startDate = timer.userInfo;
    NSTimeInterval secondsPassed = -[startDate timeIntervalSinceNow];
    // Update your label here.
}

A: Try this
- (void)updateTimer
{
    static NSInteger counter = 0;
    [stopWatchLabel setText:[NSString stringWithFormat:@"Counter: %i", counter++]];
}

- (IBAction)onStartPressed:(id)sender {
    startDate = [[NSDate date]retain];

    // Create the stop watch timer that fires every 10 ms
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
                                                      target:self
                                                    selector:@selector(updateTimer)
                                                    userInfo:nil
                                                     repeats:YES];
}

You have to connect the IBAction to a button, and the stopWatchLabel to a UILabel in the interface builder.
Found on: http://www.apptite.be/tutorial_ios_stopwatch.php

A: I ve tried this, its working
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];

-(void)timerCallback{
    NSDate *date=[NSDate date];
    NSLog(@"%@",date);
}

update timeInterval argument to what you want, and display it in view(I have just printed log);
I got this log:
2012-09-12 18:04:11.252 S[19550:f803] 2012-09-12 12:34:11 +0000
2012-09-12 18:04:12.170 S[19550:f803] 2012-09-12 12:34:12 +0000
2012-09-12 18:04:13.170 S[19550:f803] 2012-09-12 12:34:13 +0000
2012-09-12 18:04:14.170 S[19550:f803] 2012-09-12 12:34:14 +0000
2012-09-12 18:04:15.170 S[19550:f803] 2012-09-12 12:34:15 +0000
2012-09-12 18:04:16.170 S[19550:f803] 2012-09-12 12:34:16 +0000
2012-09-12 18:04:17.170 S[19550:f803] 2012-09-12 12:34:17 +0000
2012-09-12 18:04:18.170 S[19550:f803] 2012-09-12 12:34:18 +0000
2012-09-12 18:04:19.171 S[19550:f803] 2012-09-12 12:34:19 +0000
2012-09-12 18:04:20.170 S[19550:f803] 2012-09-12 12:34:20 +0000
2012-09-12 18:04:21.170 S[19550:f803] 2012-09-12 12:34:21 +0000


text:
Q: Spring PagingAndSortingRepository very slow on large database? I have a large database (30 mio rows).
And now discovered that using PagingAndSortingRepository with Pageable to limit the query has a very bad performance. But why?
interface MyRepo extends PagingAndSortingRepository<MyEntity, Long> {

    @Query(value = "SELECT * FROM mytable ORDER BY id limit 10",
            nativeQuery = true)
    List<Object> findAllLimited();

    @Query(value = "SELECT * FROM mytable",
            countQuery = "SELECT count(*) FROM mytable ORDER BY id",
            nativeQuery = true)
    Page<Object> findAllPageable(Pageable pageable);
}

Usage:
dao.findAllLimited(); //10ms
dao.findAllPageable(PageRequest.of(0, 10)); //20000ms

Why is a Page request through PagingAndSortingRepository that slow? It does not matter here if I use native or normal query. As soon as I try to apply pagination/limit by a Pageable, the performance collapses.
Any idea why this could be the case? The native LIMIT 10 approach proves that the db in general is able to serve the results just in time.
The table is defined like:
CREATE TABLE mytable (
 id bigint NOT NULL AUTO_INCREMENT,
  ...
 PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

A: Slice<Object> findBy(Pageable pageable) solved the problem! So the comments above are correct: the bottleneck is the count query that is executed for each page additionally by Spring.
If anybody has a solution for this that could retain the Page with it's total elements count, but without having to execute the count on each page request, please comment.
Apart from that, the slice solution works, except that one does not know how many pages are yet to come.


text:
Q: pages not indexed by Google My company have Google Search running on our sites indexing all pages, as far as I know. I've developed a document system that is also being indexed by Google. The pages in the system are dynamically generated, so I have www.mysite.com/doc.aspx?id=234, www.mysite.com/doc.aspx?id=236, etc which are indexed. The thing is that some random pages (say, www.mysite.com/doc.aspx?id=235) are not indexed for some unknown reason. Where do I look to have this resolved? Any ideas?

A: here is a short and very simpliefied outline on how google processes your site(s)
discovery -> crawling -> indexing -> ranking (->feedback)

discovery:
is the process of google discovering the pages of your site(s), this can either be done via links in html or via an sitemap.xml (and urls in onpage javascript, rss or atom feeds, ... basically any url google can find somewhere)
crawling:
the process of google fetching the content of a discovered url (and pushing newly found URLs into the discovery queue)
indexing:
storing the discovered and crawled content into their database and making it searchable
ranking:
matching the indexed content with a user query and - if it is important enough - return it as a visible SERP listing to the user.
feedback
based on the click/no-click behavior and data collected from other sources (presumed ISDN data and google toolbar, chrome browser reports, ...) google gathers feedback about the user behavior on it's serp (and after the click).

*

*between each and every step are a lot
of quality metrics (the last step is
just a quality metric collection
step).

*each and every step reports back to
the previous steps.

so basically even if you communicate all your urls to google (i.e. via sitemap.xml) google will not necessarily crawl all of your urls or index or rank them visible.
ok, so what are the low hanging fruites to get more pages into the index (where they at least have a chance to rank for something)?

*

*communicate exactly one URL per page (use http 301 redirects, canonical tag and clean up all links on the web)

*make your site faster (huge impact)

*make it lighter KB wise (nice impact, mostly because it's faster, too)

*put more unique content on your pages.

*prevent duplicate content

*external (from other websites) links to your pages (not the total number is important, but a steady growth over time)

p.s.: just as a side-note - the crawling step is optional. even uncrawled urls (i.e. if they were blocked via robots.txt) can get indexed (and rank) - but well that's not very common

A: Afaik, pages are not indexed, if they are not linked to from other pages. Maybe not a single page links to the non-indexed pages?

A: I agree with Daniel. You need a page with a links list. Or a page with pagination listing links.
But dinamyc urls are bad for SEO, the best way is friendly url. Take a look to ISAPIRewrite or Routing.
I hope this help you.

A: Not all pages are indexed, the index engine simply deems some pages to be uninterresting. On our site about 80% of the pages are indexed, and that is considered to be very good for that type of site, very few sites have a higher rate.
As Daniel mentioned, having links to the page is crucial, otherwise it won't be found at all. Then the page have to have some information that is unique for that page, and preferrably a unique title, or it may be classified as a duplicate.


text:
Q: Using meteor HTTP to connect to ethereum node I am trying to copy the following curl command using meteor HTTP
curl -X POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}' http://localhost:8545
The command is from here
This is what I tried:
HTTP.call('POST',"http://localhost:8545",{data:{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}},function(res,error){console.log(res)})
but it returns null. The curl command gives {"jsonrpc":"2.0","id":83,"result":"(the blocknumber)"}

A: You have to swap error and res params.
HTTP.call('POST',"http://localhost:8545",{data:{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}},function(error, res){console.log(res)})


text:
Q: How to implement "Go To Definition" extension in VSCode Which method in vscode-languageserver::IConnection has to be implemented to provide functionality "Go To Definition" over multiple files?
I was studying Language Server Node Example and vscode "API documentation", but I didn't find any info.

A: The following code snippet illustrates how to implement "Go To Definition" using vscode-languageserver:
connection.onInitialize((params): InitializeResult => {
  ...
  return {
    capabilities: {
      definitionProvider: true,
      ...
    }
  }
});

connection.onDefinition((textDocumentIdentifier: TextDocumentIdentifier): Definition => {
  return Location.create(textDocumentIdentifier.uri, {
    start: { line: 2, character: 5 },
    end: { line: 2, character: 6 }
  });
});

A: I think you have to create a class implementing the DefinitionProvider  and then register it using registerDefinitionProvider.
Take a look here and here for an example.


text:
Q: Ansible hostvars has no attribute 'ansible_nodename' We have several playbooks that use hostvars[item]['ansible_nodename'] where item is a host alias. It usually works. But sometimes does not, giving the following error:
'dict object' has no attribute 'ansible_nodename`

I printed the contents of hostvars and did not see this attribute there.
I could not find the documentation of hostvars to be able to see what we can safely use instead ansible_nodename. So, the questions are:

*

*Can I safely replace ansible_nodename with ansible_host?

*Where can I find a description of the contents of hostvars and algorithm of its creation?

A:
But sometimes does not, giving the following error...

This can be because facts for those hosts are not gathered at that moment in time.
You may want to add empty play to gather facts for all hosts at the very top of your playbook:
- name: gather facts
  hosts: all

- name: balancer configuration
  hosts: balancer
  tasks:
    - name: generate configs
      template:
        src: conf.j2
        dest: "/conf/{{ hostvars[item]['ansible_nodename'] }}.conf"
      with_hostnames: nodes

Without 'gather facts' play, configuration task for balancer will fail because ansible_nodename is not gathered.


text:
Q: Как написать разные заголовки в одной строке html Мне нужно сделать что-то на подобии этого
Вот что,я сделал,я не знаю как писать новый текст по центру

body
{
 font-family: 'Archivo Narrow', sans-serif;

}
.border{
    border: 1px solid black;
    padding: 10px;

}

strong{
 font-size: 50px;
}

h2 {
    font-size: 150%; /* Размер шрифта */
    border-bottom: 2px solid grey; /* Параметры линии под текстом */
    font-weight: normal; /* Убираем жирное начертание */
    padding-bottom: 5px; /* Расстояние от текста до линии */
   left:10%;
            width:10%;

   }
   .graficlogo{

 height: 5%;
 width: 5%;

 justify-content: left;

}
<!DOCTYPE HTML>

 <title>Заголовок документа</title>

  <link rel="stylesheet" type="text/css" href="style/style.css">
 <link href="https://fonts.googleapis.com/css?family=Archivo+Narrow" rel="stylesheet">
  <meta http-equiv="content-type" content="text/HTML; charset=utf-8" />

Резюме

ФИО

Инфо

Birthday: 2001-05-05

Phone: 380630

Email: yuranov8@gmail.com

Навики

English

use PC

Photoshop

C++

Microsoft Ofiice

MySQL

HTML

A: Вот пример

body {
  margin: 0;
  padding: 0ж
}

.card {
  min-height: 100vh;
  background-color: white;
  position: relative;
  display: flex;
}

.card-content,
.card-assets {
  padding: 80px 10px 10px 10px;
}

.card-title {
  font-size: 20px;
  padding: 1rem;
  background-color: white;
  width: 300px;
  position: absolute;
  top: 15px;
  left: 80px;
  border: 1px solid black;
  text-align: center
}

.card-assets {
  flex: 0 0 150px;
  background-color: #e2e2e2;
}

.accent {
  border-bottom: 1px solid black;
  text-transform: uppercase;
  font-weight: bold;
  font-size: .8rem;
  margin-bottom: .5rem
}

.text{
  margin-bottom: 1rem
}

Фамилия Имя

навыки:

Lorem ipsum

навыки:

Lorem ipsum

навыки:

Lorem ipsum

навыки:

Lorem ipsum

Описание:

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Soluta, odit.

навыки:

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Soluta, odit.

навыки:

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Soluta, odit.

навыки:

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Soluta, odit.

навыки:

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Soluta, odit.


text:
Q: Jenkins RejectedAccessException in whitelisted method In Jenkins 2.46.3 I'm trying to get the cause of the build (ie whether it was started by a git trigger or a human clicking "build now").  In an answer to another SO question it is suggested that ${currentBuild.buildCauses} has that information, and that the method is whitelisted.  But when I try it, i get a RejectedAccessException :
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getBuildCauses
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:113)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:16)
at WorkflowScript.run(WorkflowScript:7)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:57)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:109)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixName(FunctionCallBlock.java:77)
at sun.reflect.GeneratedMethodAccessor150.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:163)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:324)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:78)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:236)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:224)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:63)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)


text:
Q: How do I update the element inside the arraylist? public class billing{
                private int id;
                //File f=new File("C:/Users/Bingus/Documents/Projects/accounts.txt");
                private String bc;
                private String bd;
                private String customerName;
                private String customerAddress;
                private String customerNumber;
                private String periodT;
                private String periodF;
                private double presentR;
                private double previousR;
                private double previousB;
                private double dueTotal;
                private static ArrayList<Account> accountList = new ArrayList<>();

            public billing(int id,String bc,String bd,String customerName,String customerAddress,String customerNumber,String periodT,String periodF,double presentR,double previousR,double previousB,double dueTotal){
                this.id = id;
                this.bc = bc;
                this.bd = bd;
                this.customerName = customerName;
                this.customerAddress = customerAddress;
                this.customerNumber = customerNumber;
                this.periodT = periodT;
                this.periodF = periodF;
                this.presentR = presentR;
                this.previousR = previousR;
                this.previousB = previousB;
                this.dueTotal = dueTotal;
                }

            public int getId(){
                return id;
            }
            public String getBc(){
                return bc;
            }
            public String getBd(){
                return bd;
            }
            public String getCustomerName(){
                return customerName;
            }
            public String getCustomerAddress(){
                return customerAddress;
            }
            public String getCustomerNumber(){
                return customerNumber;
            }
            public String getPeriodT(){
                return periodT;
            }
            public String getPeriodF(){
                return periodF;
            }
            public double getPresentR(){
                return presentR;
            }
            public double getPreviousR(){
                return previousR;
            }
            public double getPreviousB(){
                return previousB;
            }
            public double getDue(){
                return dueTotal;
            }
                public static void main(String[] args){

                Scanner scanner = new Scanner (System.in);
                Scanner kb = new Scanner (System.in);
                int user_choice;
                int x = 0;

                do{
                        System.out.println();
                        System.out.println("1) New Billing");
                        System.out.println("2) Add Existing Billing");
                        System.out.println("3) View Billing Account ID");
                        System.out.println("4) View By Date");
                        System.out.println("5) Update Existing Billing");
                        System.out.println("6) Delete Billing Account");
                        System.out.println("7) Display All Account");
                        System.out.println("8) Exit");
                        System.out.println();
                        System.out.print("Enter choice [1-8]: ");
                        user_choice = scanner.nextInt();

                        switch (user_choice){

                            case 1:
                            int min = 1000;
                            int max = 9999;
                            int randomStr = (int)(Math.random() * (max - min + 1) + min);
                            int id = randomStr;
                            System.out.println("Your Account Number is : " + id);
                            System.out.print("Enter Billing Code: ");
                            String bc = scanner.next();
                            System.out.print("Enter Billing Date(dd/mm/yyyy): ");
                            String bd = scanner.next();
                            System.out.print("Enter Customer Name: ");
                            String customerName = kb.nextLine();
                            System.out.print("Enter Customer Address: ");
                            String customerAddress = kb.nextLine();
                            System.out.print("Enter Customer Number: ");
                            String customerNumber = scanner.next();
                            System.out.print("Enter Period To: ");
                            String periodT = scanner.next();
                            System.out.print("Enter Period From: ");
                            String periodF = scanner.next();
                            System.out.print("Enter Present Reading: ");
                            double presentR = scanner.nextDouble();
                            System.out.print("Enter Previous Reading: ");
                            double previousR = scanner.nextDouble();
                            System.out.print("Enter Previous Balance: ");
                            double previousB = scanner.nextDouble();
                            double dueTotal = getTotalDue(presentR,previousR,previousB);
                            Account user = new Account(id,bc,bd,customerName,customerAddress,customerNumber,periodT,periodF,presentR,previousR,previousB,dueTotal);
                            accountList.add(user);
                            break;

                            case 2:

                            case 3:
                            System.out.print("Enter Account Number: ");
                                 int a = scanner.nextInt();
                                 for(int i = 0; i<accountList.size();i++){
                                    if(a == accountList.get(i).getId()){
                                System.out.println("Account ID: " + accountList.get(i).getId());
                                System.out.println("Customer Name: " +accountList.get(i).getCustomerName());
                                System.out.println("Customer Address: " + accountList.get(i).getCustomerAddress());
                                System.out.print("Customer Number: " + accountList.get(i).getCustomerNumber());
                                }
                            }
                            System.out.println("\nBilling Code\t\tBilling Date\t\tAmount Due");
                                 for(int i = 0; i<accountList.size();i++){
                                     if(a == accountList.get(i).getId())
                                    {
                                     System.out.println(accountList.get(i).getBc()+"\t\t\t"+accountList.get(i).getBd()+"\t\t\t"+accountList.get(i).getDue());
                                   }
                                }
                                break;
                            case 4:

                            case 5:
                              System.out.print("Enter Account Number: ");
                               a = scanner.nextInt();
                              for(int i = 0; i<accountList.size();i++){
                              if(a == accountList.get(i).getId())
                                    {
                                        System.out.println("Your Account Number is : " + accountList.get(i).getId());
                                        System.out.print("Enter Billing Code: ");
                                        String bCode = scanner.next();
                                        String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
                                        int index = accountList.indexOf(c);
                                        accountList.set(index, bCode);

                                    }
                                }
                            break;

                            case 6:
                            System.out.print("Enter Account Number: ");
                            a = scanner.nextInt();
                            System.out.print("Enter Billing Code: ");
                            String b = scanner.next();
                            for(int i = 0; i<accountList.size();i++){
                                if(a == accountList.get(i).getId()){
                                          if(b.equals(accountList.get(i).getBc())){
                                            accountList.remove(i);
                                            System.out.print("\nAccount Removed\n");

                                          }else{
                                            System.out.print("Invalid Billing Code\n");
                                          }

                                }else if(a != accountList.get(i).getId()){
                                        System.out.print("Invalid Account Number or Number not in the database.\n");
                                }else{
                                    System.out.print("Try Again\n");
                                }
                            }

                            break;

                            case 7:
                            System.out.println("Account ID\t\tBilling Code\t\tAccount Name\t\tTotal Due\t\tPresent R\t\tPrevious R");
                            Collections.sort(accountList,Collections.reverseOrder());
                            for(int i=0; i<accountList.size();i++){
                                System.out.println(accountList.get(i).getId() + "\t\t\t"+accountList.get(i).getBc()+ "\t\t\t"+accountList.get(i).getCustomerName()+ "\t\t\t"+accountList.get(i).getDue()+"\t\t\t"+accountList.get(i).getPresentR()+ "\t\t\t"+accountList.get(i).getPreviousR());
                            }
                            break;
                        }

            }while(user_choice!=8);
          }

I'm new to programming in Java and I'm still learning towards it. I'm making my billing system which calcualtes the payment. My problem for this is how can I change or update the value which is already in the arraylist, I've tried the set() but I cannot make it work. using arraylist is a big jump for me and I haven't yet got a hang of it. I've watched youtube vids but they seem to show non user input arry lists
Any help?

  [1]: https://i.stack.imgur.com/HhF33.png

A: Your code:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);

If you want to update billing code in an account then get the account object and update the user entered bCode on the object. Also, you don't have to put the account back in the list:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
Account existing = accountList.get(i);
//create new account with same data except bCode
Account updated = new Account(existing.getId(),bCode, existing.getBd(),/*do same for rest of the fields */);
int index = accountList.indexOf(existing);
accountList.set(index, updated);

A: There are two ways to do it.
First Option is Loop the list and reach the object you want to change, update its attributes. Since the object is accessed by reference, whatever values you will change it will effect.
Second option is remove the object at that index, create a new object and insert at that position.
public void testArrayList ()
{

    class MyData
    {
        String Id = "";
        String Name = "";

        public MyData () {}
        public MyData (String id, String name) {
            Id= id;
            Name = name;
        }
        public String toString ()
        {
            return " Id=" + Id + " Name=" + Name;
        }
    }

    ArrayList myDList = new ArrayList ();
    myDList.add(new MyData("1", "John"));
    myDList.add(new MyData("2", "Mike"));
    myDList.add(new MyData("3", "Tom"));
    System.err.println ("Org List                         " + myDList);

    MyData tmp = (MyData) myDList.get(1);
    tmp.Id = "22";
    tmp.Name = tmp.Name + " Changed";

    System.err.println ("Mod List (Observe second Object ) " + myDList);
}

A: You need to set the value in ArrayList to be an object of type Account.
1.You need to get an object of type Account and use settter method to update bcode

2. Set that Account object back to ArrayList

A: Code TL:DR. Do you have a set method in your Account class?
//set method example
public void setBc(String newBc){ //can also use other data types as parameters
  this.bc = newBc;
}

If so you can just
accountList.get(i).setBc("This New BCODE"); //The parameter can also be a variable of string type

A: You have to change this part in Your program
…
Billing billing = accountList.get(i);
//String c = billing.getBc();   // this is the part in which I am having a hard time to fix, I've used
                                // the set but still I cannot change the element inside.
billing.setBc( yourNewBc );
//int index = accountList.indexOf(c);
//accountList.set(index, billing);
…

class names are capitalized in Java

A: Here in this example we have iterated over the list and modified the values of the object.
Please make a setter to the values you want to modify and follow something like this.
    public class Arr {
    public static void main(String args[]){
        ArrayList<Person> array = new ArrayList();
        Scanner sc=new Scanner(System.in);
        while (true){
            System.out.println("1.add 2. modify 3.view list ; anything else to to quit");
            int choice = sc.nextInt();
            if (choice==1){
                System.out.println("Enter ID then salary");
                int id = sc.nextInt();
                int salary = sc.nextInt();
                Person p = new Person(id,salary);
                array.add(p);
                System.out.println("Done");
            }
            else if (choice==2){
                System.out.println("Enter ID");
                int id = sc.nextInt();
                for (int i = 0; i < array.size(); i++){
                    Person p = array.get(i);
                    if (p.getId()==id){
                        System.out.println("value exits. Enter salary to be modified:");
                        int salary = sc.nextInt();
                        p.setSalary(salary);
                    }
                }
                System.out.println("Done");
            }
            else if (choice==3){
                for (int i = 0; i < array.size(); i++)
                    System.out.print(" " + array.get(i).getId() + " " + array.get(i).getSalary());
            }
            else
                break;
        }
    }
   }

    public class Person {
        int id;
        int salary;

        public Person(int id, int salary) {
            this.id = id;
            this.salary = salary;
        }

        public int getId() {
            return id;
        }

        public int getSalary() {
            return salary;
        }

        public void setSalary(int salary) {
            this.salary = salary;
        }
    }


text:
Q: Rollback rake assets:precompile I operate Rails 3.2.13 and I ran a
rake assets:precompile

In order to activate some CoffeeScript that wouldn't fire otherwise,
and it completely ruined my pages layout, which was fine until then.
The menu of my application is now vertical instead of horizontal and the rest of the pages is subsequently invisible.
I use Bootstrap and I suspect this has been updated, for some reason, but it's too much work to change it, if I only knew why it has changed and what has changed anyway...
I would like to go back to the former state of my layout.
Is there any way to roll back ?

A: remove public/assets
explanation:
the precompile task compiles your assets, usually in app/assets, and places them in your public folder/assets folder.
If you want to go back to the state prior to the precompile, just remove public/assets
rm -fr public/assets.

A: I had this problem too. In addition to removing the precompiled assets under the public folder, I also had to clear the tmp/cache folder.

A: ok, this should be the problem: you changed your bootstrap version from 2.1 to 3.1 and the syntax you're using is not suitable for 3.1.
That's not a question of compiling assets, just that from version 2 to version 3, there's a totally new syntax.
Have a look here:
http://getbootstrap.com/migration/
Then set your bootstrap gem version to 2.1 in your gemfile and run bundle install. Everything should go back to the right place.


text:
Q: Open movie app with precise video on iOS I would like to open the iPad movie player from my app to play a video.
The video will already be on the device, and the app is destined to ad-hoc distribution on pre-configured device, thus we can say the video will always be here.
My problem is that I can't figure out how to open the video app! I've searched a lot of things, including UTI, or embedded video, but that doesn't meet my needs.
Is there any way to simply open the player with the specified file ?

A: Do you need to open the video app per se? Or do you just need to play local video file from your app? In the latter case, you can just use MPMoviePlayerController (or the wrapping MPMoviePlayerViewController for iOS > 3.2).
Something like this works for me.
NSURL * url = [[NSBundle mainBundle] URLForResource:@"yourvideo" withExtension:@"mov"];
player = [[MPMoviePlayerController alloc] initWithContentURL:url];
player.view.frame = self.view.bounds;
player.movieSourceType = MPMovieSourceTypeFile;

[self.view addSubview:player.view];

player.shouldAutoplay = NO;
player.fullscreen = YES;
[player prepareToPlay];


text:
Q: User's can't login after changing session id cookie domain I've changed my session ID cookie domain so my sessions can be used on subdomains as per Allow php sessions to carry over to subdomains.
However now my users can't login. I think the old cookie is still being sent and read by my PHP session_start().
Should I try and remove the old cookie? Or is something else going on here?
Also, it would be good if a solution didn't require me to rename my session id cookie.


text:
Q: Nodejs console.log as callback in forEach I was having a hard time debugging the output of:
content.forEach(console.log);

content is an array of Strings. The problem was it seemed to log out the entire content variable once for every element in the array.
When I finally changed it to
content.forEach(function(a){ console.log(a) });

It began working. What devilry is this?

A: Array.forEach passes the callback three values:
currentValue: The current element being processed in the array.
index: The index of the current element being processed in the array.
array: The array that forEach is being applied to.
Console.log prints out all of the parameters, not just the first one.


text:
Q: AWS - EBS Snapshots is exceeding free tier 2 months ago I started using AWS and now I am having an issue with the Free Tier.
I installed a system with the elastic beanstalk tool (1 EC2 and 1 RDS).
Now I am seeing in Management Dashboard that I will be exceeding my monthly limit for EBS Snapshots. The forecast is 194.94% and I am just starting the month.
I reviewed all the settings and I couldn't find anything strange.
EC2
1 Running instances
1 volumes
2 Key Pairs
1 Elastic Ips
1 Snapshots

By looking the volume menu in AWS, the Snapshot id in the only volume that I have is not the same as the snapshot that I have. This is strange.
volume information:
Volume ID   --> vol-0cff610c
Size        --> 8 Gib
Volume type --> gp2
IOPS        --> 100 / 3000
Snapshot    --> snap-04786
State       --> in-use

And in the snapshot menu, the volume id is not the same as the volume that I have in the other view.
Snapshot Information
Snapshot ID --> snap-0d2988
Size        --> 8Gib
Volume      --> vol-05f5fee
Status      --> completed

Does anybody have an idea of what is causing this problem with the EBS?
Thanks!

A: Firstly, don't panic. EBS Snapshots are 5c/GB/month. Worst case, 8GB = 40c/month.
Secondly, if you don't want a snapshot, just delete it. Especially if you don't remember making it, and don't need to keep it.

A: Elastic Beanstalk can create AWS resources and terminate them automatically for you, depending on your workload.
If your server was under heavy workload at some point, Elastic Beanstalk could have provisioned auto scaling group with Elastic Load Balancer, and the number of EC2 instances can increase to cater for the increased workload.
As the workload drops, it can terminate the instances for you as well. Resulting in left-over snapshots, especially if you code writes to the local EC2 hdd.
Elastic Beanstalk is the "one-click" solution for deploying scalable clusters of servers.
Similar services are as follow :

*

*Elastic Beanstalk (easiest)

*OpsWorks

*Cloud Formation (hardest)

LightSail is not included here as it doesn't really scale automatically. Lambda is serverless so it is fundamentally different.

A: today I reviewed again the information and AWS console.
My problem was that I have an unused AMI and the snapshot was related to that AMI.
I thought that the only AMI I had was being used by the instance. But I was wrong, the AMI used in the instance was a different one. Probably because I started my instance with elastic beanstalk.
So the solution was to deregister this unused AMI, then delete the Snapshot.
Thanks to all


text:
Q: Unable to align two div's vertically in one line I am having two divs. One text box and another a button. I am unable to align both divs vertically. I need the text box and button to be of equal height and vertically aligned in same line. What is wrong?

.inputHolder{
  border:1px solid #FFF;
 vertical-align:middle;
}
.input{
 margin-top:150px;
 width:100px;
 height:50px;
 border:1px solid black;
 font-size:1.2em;
 padding:5px;
 display:inline-block;
}
.input:focus{
 outline:0;
}
.goBtn{
 height:50px;
 width:200px;
 border:1px solid black;
 display:inline-block;
}

   <input type="text" class="input">
   <input type="submit" value="Go" class="goBtn">

A: Display flex on the parent will make them the same height and side-by-side

.inputHolder {
  border: 1px solid #FFF;
  display: flex;
  justify-content: center;
}

.input {
  width: 100px;
  border: 1px solid black;
  font-size: 1.2em;
  padding: 5px;
}

.input:focus {
  outline: 0;
}

.goBtn {
  width: 200px;
  border: 1px solid black;
}

  <input type="text" class="input">
  <input type="submit" value="Go" class="goBtn">

A: Is it this that you want sample form?
CSS
 .inputHolder {
  border: 1px solid #FFF;
  vertical-align: middle;
}

.input {
  margin-top: 150px;
  width: 100px;
  height: 50px;
  border: 1px solid black;
  /* font-size: 1.2em; */
  padding: 0 5px;
  display: inline-block;
}

.input:focus {
  outline: 0;
}

.goBtn {
  height: 52px;
  width: 200px;
  border: 1px solid black;
  display: inline-block;
}

HTML

  <input type="text" class="input">
  <input type="submit" value="Go" class="goBtn">

A: Do you want to do this?
https://jsfiddle.net/pm3kpgL7/1/
If you want vertical-align elements, that property need to be placed to that element, not to his parent, so i just moved the vertical align to the inputs and it works using vertical-align: sub
.inputHolder{
  border:1px solid #FFF;
  text-align:center;
}
.input{
    margin-top:150px;
    width:100px;
    height:50px;
    border:1px solid black;
    font-size:1.2em;
    padding:5px;
    display:inline-block;
    vertical-align:sub;
}
.input:focus{
    outline:0;
}
.goBtn{
    height:50px;
    width:200px;
    border:1px solid black;
    display:inline-block;
}


text:
Q: objective-c : Is it dangerous cast to (NSInteger)self? Is it dangerous to cast "(NSInteger)self"?
I need to distinguish two views, not using tag value.
If It is dangerous, any ideas?

A: You mean you have two UIView pointers and you want to know if they are pointing to the same object?  Just use ==.  No need to cast them.  If you mean something else, you'll need to provide more details on what you mean by "distinguishing two views".

A: Ignoring what convulsions ARC may go through, it's not dangerous to cast self (or any other pointer) to integer.  It is exceedingly dangerous, however, to cast the other direction.
And Objective-C has enough odd corners and dark hallways that it's difficult to say with great confidence that self cast to an integer will be reproducible in a useful way.

A: The NSObject protocol declares an isEqual: method for comparing objects. A class can override this to define its instances as equal if their contents are equal; otherwise two instances will compare as unequal.
This is what you should really use to distinguish objects from each other, rather than comparing their pointer values directly. That is, however, safe to do.


text:
Q: C++ if statements: first condition superseding the second - UB or well defined? Being a moderate time coder, I saw things like the following many times:
if (a != nullptr && a->data != nullptr) {
  // do something good with a and a->data
}

However, I never really referred to documentation regarding such a simple case.

To my mind, the following is happening:

*

*First, a != nullptr is checked

*Second, a->data != nullptr is checked

The thing now here is: if a != nullptr returns false and we have a conjunction via && then there's no point to check the second statement a->data != nullptr being true or false:
since the first statement results in a false expression, the code inside the if-statement will not be executed, we don't need to check the second expression

But recently I have returned to the question yet again:
Is if safe to have a construction like this: if (a != nullptr && a->data != nullptr) {}? Can it happen so that both* statements are checked and what I get is the nullptr dereference?
*- no multi-threading involved

What I'm asking is: is the above situation has a well defined behavior (and where can I find documentation for that) or this is generally UB that must be avoided? Is the behavior any different depending on the operating system (say, Windows vs. Linux-based)?

A: This is safe
It's actually one of the few cases in which C++ guarantees the evaluation order; first the left-side is evaluated and then (and only if the left side is true) the second side is evaluated.


text:
Q: Question about homoscedasticity test one of the reviewer of a paper of mine suggested to perform a homoscedasticity test between the results of two experiments, testing the same thing in two conditions. The experiments consisted in ratings along a 7 points Likert-scale.
One of the experiment results were distributed on a large range of values, while the other showed a tendency towards the center of the Likert-scale range (i.e. 3.5). The reviewer argued that the latter behaviour could be due to the fact that participants answered more randomly, and he suggested that to verify this possibility, an homoscedasticity test should be performed comparing the two conditions.
Now, I would like to understand this comment. In relation to my case, what does it mean that the variances of the two conditions are significantly different?
What instead if they are equal?
Secondly and more importantly, which test for homoscedasticity do you suggest I perform?
I use R. Can you suggest the function more suitable for my case? I saw that there are many.

A: I think this question has been addressed a few times before although not in the context of your paper.  Even though the likert scale is ordinal, some people here argue that average scores can be looke at as numerical (interval).  Ascribing to that theory the variance of the averages has some meaning. Also a Likert scale even though it is discrete the individual scores could be thought of as interval if you believe that respondents think the change from 2 to 3 is the same as from 3 to 4 etc.  This may be a stretch.  Of course if the raw data were normally distributed you could use the F test for comparing two normally distributed variables.  Unless the sample size is large it is difficult to reject homoscedasticity. it has also been pointed out that the F test is not robust to depatures from normality.  So it is safer to use a robust test.  Levene's test is one of the most common ones  and there are modifications to it that have been proposed. Still you may be uncomfortable treating ordinal data as though it was were interval.  So maybe a nonparametric test based only on ranking the data or on permutations would be suitable.  then you really are asking if the distributions have different scales.
There are apparently three well-known nonparametric tests for equality of scale in two distributions with well-known properties and some new one appearing in the literature. A Google search using "nonparametric tests of scale" turns up a lot of interesting links.  There is even one that discuss whether or not Likert scales should be viewed parametrically or nonparametrically with a paper like yours instigating the discussion.  Do the search.
But to help out here are links to a few papers.  Full pdfs are not available

*

*Mathur

*Klotz

*Penfield.

A: According to the comments above reported I found that the solution is to use mood.test().
The result is
> mood.test(scrd_non_interactive$Response,scrd_interactive$Response)

Mood two-sample test of scale

data:  scrd_non_interactive$Response and scrd_interactive$Response
Z = 0.3895, p-value = 0.6969
alternative hypothesis: two.sided

From this I conclude that the variance of the two groups is not statistically different.


text:
Q: Can we use the distance to nearest prime to approximate large integers? Let's say we have two oracles, NearestPrime and IndexOfPrime, defined as follows:

Given some integer x, NearestPrime yields the prime number nearest to x that is not greater than x.

Examples:
    \begin{aligned}
NearestPrime(3) &= 3 \\
NearestPrime(25) &= 23 \\
NearestPrime(28) &= 23 \\
NearestPrime(102) &= 101
\end{aligned}

Given some prime p, IndexOfPrime yields the index of that prime in the sequence of all primes.

Examples:
    \begin{aligned}
IndexOfPrime(2) &= 1 \\
IndexOfPrime(5) &= 3 \\
IndexOfPrime(29) &= 10
\end{aligned}

If both the number of primes and prime gaps increase as a natural log of the integers, then couldn't we specify an integer n by the the following tuple:
$$
\left(IndexOfPrime(NearestPrime(n)), \\
n \bmod NearestPrime(n)\right)
$$
And, further, because both parameters are in log-space, wouldn't this be an space-efficient encoding for large integers?


text:
Q: How to determine if Window was launching as a modal using ShowDialog I have a WPF Window created. I have some cases where i want to display it using ShowDialog() and others just using Show().
For the ShowDialog() i want to set the DialogResult which all works fine, however if the window is launched using Show() and i set the DialogResult i get the exception
DialogResult can be set only after Window is created and shown as dialog.

How to i determine how the window was launched so i can place a condition on setting the DialogResult?

A: There could be multiple solutions, one of them could be override the ShowDialog() and show() method so you can send an parameter to determine in which way it was call. Or just set up an boolean flag on the class.

A: Check the Owner property on the child dialog. If Show() was used the child window Owner won't be set automatically but it should be when you use ShowDialog().


text:
Q: Electron / Blazor App: Electron Window won't open I have incorporated electron into my Blazor Server App. Here is my Program.cs file that should run the electron window.
using AutoHarp3_Server.Data;
using AutoHarp3_Server.Data.Classes;
using AutoHarp3_Server.Shared;
**using ElectronNET.API;**
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using System.Net.NetworkInformation;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddScoped<pCharStat>();
**builder.Services.AddElectron();
builder.WebHost.UseElectron(args);**
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

//Task.Run(async () => await Electron.WindowManager.CreateBrowserViewAsync());
//Task.Run(async () => await Electron.WindowManager.CreateWindowAsync());
//if (HybridSupport.IsElectronActive)
//{
    **Task.Run(async () =>
    {
        var window = await Electron.WindowManager.CreateWindowAsync();
        window.OnClosed += () =>
        {
            Electron.App.Quit();
        };
    });**
//}

//app.Run();

When I run Electron from Visual Studio I get the following from the command window but I do not get the actual electron window to open with the app. If I go to the http://localhost:port I do see it there.
Start Electron Desktop Application...
Arguments:

dotnet publish -r win-x64 -c "Debug" --output "D:\VisualStudio2022\BlazorApp\AutoHarp3\AutoHarp3_Server\obj\Host\bin" /p:PublishReadyToRun=true /p:PublishSingleFile=true --no-self-contained
MSBuild version 17.3.0+92e077650 for .NET
  Determining projects to restore...
  Restored D:\VisualStudio2022\BlazorApp\AutoHarp3\AutoHarp3_Server\AutoHarp3_Server.csproj (in 952 ms).
  AutoHarp3_Server -> D:\VisualStudio2022\BlazorApp\AutoHarp3\AutoHarp3_Server\bin\Debug\net6.0\win-x64\AutoHarp3_Server.dll
  AutoHarp3_Server -> D:\VisualStudio2022\BlazorApp\AutoHarp3\AutoHarp3_Server\obj\Host\bin\

node_modules missing in: D:\VisualStudio2022\BlazorApp\AutoHarp3\AutoHarp3_Server\obj\Host\node_modules
Start npm install...
npm install
up to date in 2.07s

14 packages are looking for funding
  run `npm fund` for details

ElectronHostHook handling started...
Invoke electron.cmd - in dir: D:\VisualStudio2022\BlazorApp\AutoHarp3\AutoHarp3_Server\obj\Host\node_modules\.bin
electron.cmd "..\..\main.js"

Electron Socket IO Port: 8000
Electron Socket started on port 8000 at 127.0.0.1
ASP.NET Core Port: 8001
stdout: Use Electron Port: 8000

I'm running NET6 with Visual Studio 2022.
I can guess the best way to recreate this and test is to create a new
Blazor server app in visual studio 2022.
Install electron into the project using the nuget manager.
Use the command line to install electron cli into the project and to initialize electron into the project.
Add the code for electron into the program.cs. I put asterixis around the code that I had to add for the project.
You should be able to build from Visual Studio.
I really didn't do anything beyond this.


text:
Q: Best way to query entire MongoDB collection for ETL We want to query an entire live production MongoDB collection (v2.6, around 500GB of data on around 70M documents).
We're wondering what's the best approach for this:

*

*A single query with no filtering to open a cursor and get documents in batches of 5/6k

*Iterate with pagination, using a logic of find().limit(5000).skip(currentIteration * 5000)

We're unsure what's the best practice and will yield the best results with minimum impact on performance.

A: I would go with 1. & 2. mixed if possible: Iterate over your huge dataset in pages but access those pages by querying instead of skipping over them as this may be costly as also pointed out by the docs.

The cursor.skip() method is often expensive because it requires the
  server to walk from the beginning of the collection or index to get
  the offset or skip position before beginning to return results. As the
  offset (e.g. pageNumber above) increases, cursor.skip() will become
  slower and more CPU intensive. With larger collections, cursor.skip()
  may become IO bound.

So if possible build your pages on an indexed field and process those batches of data with an according query range.

A: The brutal way
Generally speaking, most drivers load batches of documents anyway. So your languages equivalent of
var docs = db.yourcoll.find()
docs.forEach(
  function(doc){
    //whatever
  }
)

will actually just create a cursor initially, and will then, when the current batch is close to exhaustion, load a new batch transparently. So doing this pagination manually while planning to access every document in the collection will have little to no advantage, but hold the overhead of multiple queries.
As for ETL, manually iterating over the documents to modify and then store them in a new instance does under most circumstances not seem reasonable to me, as you basically reinvent the wheel.
Alternate approach
Generally speaking, there is no one-size-fits all "best" way. The best way is the one that best fits your functional and non-functional requirements.
When doing ETL from MongoDB to MongoDB, I usually proceed as follows:
ET…
Unless you have very complicated transformations, MongoDB's aggregation framework is a surprisingly capable ETL tool. I use it regularly for that purpose and have yet to find a problem not solvable with the aggregation framework for in-MongoDB ETL. Given the fact that in general each document is processed one by one, the impact on your production environment should be minimal, if noticeable at all. After you did your transformation, simply use the $out stage to save the results in a new collection.
Even collection spanning transformations can be achieved, using the $lookup stage.
…L
After you did the extract and transform on the old instance, for loading the data to the new MongoDB instance, you have several possibilities:

*

*Create a temporary replica set, consisting of the old instance, the new instance and an arbiter. Make sure your old instance becomes primary, do the ET part, have the primary step down so your new instance becomes primary and remove the old instance and the arbiter from the replica set. The advantage is that you facilitate MongoDB's replication mechanics to get the data from your old instance to your new instance, without the need to worry about partially executed transfers and such. And you can use it the other way around: Transfer the data first, make the new instance the primary, remove the other members from the replica set perform your transformations and remove the "old" data, then.

*Use db.CloneCollection(). The advantage here is that you only transfer the collections you need, at the expense of more manual work.

*Use db.cloneDatabase() to copy over the entire DB. Unless you have multiple databases on the original instance, this method has little to now advantage over the replica set method.

As written, without knowing your exact use cases, transformations and constraints, it is hard to tell which approach makes the most sense for you.

A: MongoDB 3.4 support Parallel Collection Scan. I never tried this myself yet. But looks interesting to me.
This will not work on sharded clusters. If we have parallel processing setup this will speed up the scanning for sure.
Please see the documentation here: https://docs.mongodb.com/manual/reference/command/parallelCollectionScan/


text:
Q: Configure Shiro context factory to connect to AD using Windows integrated security I would like to avoid having a plain text password in the .ini file. I guess it should use Kerberos authentication, but I couldn't find how to do that.

A: I don't believe that Shiro has any capability to support Windows Kerberos authentication nor does it appear to have any "out of the box" capability to support encrypted passwords in the [main] section of the shiro.ini file.
Looking at this message (http://shiro-user.582556.n2.nabble.com/How-to-secure-database-password-in-shiro-ini-td7578763.html) on the Shiro mailing list it suggests the best solution is to create your own password factory which will return the password when needed. The mailing list talks about using this for database passwords but the same principle should apply to Active Directory.
This link (https://issues.apache.org/jira/browse/SHIRO-445) contains a patch which should give you some pointers on how to do this.


text:
Q: my android studio can`t find compile method(com.android.support.constraint:constraint-layout:1.0.0-beta4) i have this problem in Android Studio and i added this in build.gradle file but i have that problem.

Error:(13, 0) Could not find method compile() for arguments [com.android.support.constraint:constraint-layout:1.0.0-beta4] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {

     repositories {
        google()
        jcenter()

     }
     dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        compile'com.android.support.constraint:constraint-layout:1.0.0-beta4'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
     }
    }

    allprojects {
     repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.google.com'
        }
     }
    }

    task clean(type: Delete) {
      delete rootProject.buildDir
    }

A: Beta 4 is an old version. Try using 1.0.2 instead:
compile 'com.android.support.constraint:constraint-layout:1.0.2'

A: Remove this line:
compile'com.android.support.constraint:constraint-layout:1.0.0-beta4'

You can't add the dependencies in the top-level file also you can not use this dependency in the buildscript block.


text:
Q: how differentiate symbolic function has a variable name matlab please,
I want matlab to generate dynamic variable name as many as specified number
ex,
generate F1,F2,...
but the problem that I want to differienate the unspeceified number
I use
for k = 1:number

   eval(diff(['F', num2str(k)]))

end

so what's wrong?

A: You should start your code with:
f=sym('f',[1,number])

this creates symbolic variables f1... organised in an array.
for k = 1:number

   diff(f(k))

end

Avoid eval whenever possible. For reasons read doc eval.