Why my service for locations bugs when GPS is off?

Question: I am building an app where I am using service for locations. I am starting that service in onCreate on MainActivity, but if GPS is off my service will not look for latitude and longitude. Even if I turn on GPS after that, my service will not looking lat and long. Only when I turn on GPS before starting service(and MainActivity)  then service will work fine and it will look for locations. What Should I change to set that my service don't bug when I turn on GPS after some time that I spent in app?
This is my location service:
public class LocationUpdateService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
protected static final String TAG = "LocationUpdateService";
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public static Boolean mRequestingLocationUpdates;
protected String mLastUpdateTime;
protected String timeWhenStartLocationUpdates;
protected String timeWhenStopLocationUpdates;
protected String timeWhenServiceDestroyed;
protected String connectionFailed;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected String timeWhenGetInGetLatLong;
protected String report_time;
protected String timeFromElse;
public static boolean isEnded = false;
Calendar calendar;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    startLocationUpdates();
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Connection suspended==");
    mGoogleApiClient.connect();
}

@Override
public void onLocationChanged(Location location) {
    mCurrentLocation = location;
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
    Log.d("mCurrentLocation", "Location is: " + location);
    getLatLong();
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("TimeWhenCameToOnLocationChanged", mLastUpdateTime);
    editor.apply();
    Log.d("onLocationchanged", "OnLocationChangedInServiceLocation");
    Log.d("Time ", "Time of lat and long from Service: " + mLastUpdateTime);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    connectionFailed = DateFormat.getTimeInstance().format(new Date());
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("connectionFailed", connectionFailed);
    editor.apply();
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("LOC", "Service init...");
    return Service.START_STICKY;
}

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient===");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    createLocationRequest();
}

public void getLatLong() {
    timeWhenGetInGetLatLong = DateFormat.getTimeInstance().format(new Date());

    if (mCurrentLocation != null && mLastUpdateTime != null) {

        String lat = String.valueOf(mCurrentLocation.getLatitude());
        String lng = String.valueOf(mCurrentLocation.getLongitude());
        calendar = Calendar.getInstance();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        report_time = simpleDateFormat.format(calendar.getTime());
        Log.d("preferences", "Time stored in preferences: " + mLastUpdateTime);
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("user_latitude", lat);
        editor.putString("user_longitude", lng);
        editor.putString("getLatLongIf", "ok");
        editor.putString("report_time_for_location_response", report_time);
        editor.putString("time_when_comes_to_getLatLong", timeWhenGetInGetLatLong);
        editor.apply();
    }else{
        timeFromElse = DateFormat.getTimeInstance().format(new Date());
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("getLatLongElse", timeFromElse);
        editor.apply();
    }
}

protected void createLocationRequest() {
    mGoogleApiClient.connect();
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

protected void startLocationUpdates() {
    timeWhenStartLocationUpdates = DateFormat.getTimeInstance().format(new Date());
    if (!mRequestingLocationUpdates) {
        mRequestingLocationUpdates = true;
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
       SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("startLocationUpdates", timeWhenStartLocationUpdates);
        editor.apply();
        Log.i("startUpdates", " startLocationUpdates===" + timeWhenStartLocationUpdates);
        isEnded = true;
    }
}
protected void stopLocationUpdates() {
    if (mRequestingLocationUpdates) {
        mRequestingLocationUpdates = false;
        timeWhenStopLocationUpdates = DateFormat.getTimeInstance().format(new Date());
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("stopLocationUpdates", timeWhenStopLocationUpdates);
        editor.apply();
        Log.d("stopUpdates", "stopLocationUpdates();==" + timeWhenStopLocationUpdates);
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    timeWhenServiceDestroyed = DateFormat.getTimeInstance().format(new Date());
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("onDestroyService", timeWhenServiceDestroyed);
    editor.apply();
    stopLocationUpdates();
    Log.d("onDestroyService", "onDestroy: + " + timeWhenServiceDestroyed);
}

@Override
public void onCreate() {
    super.onCreate();

    isEnded = false;
    mRequestingLocationUpdates = false;
    mLastUpdateTime = "";
    buildGoogleApiClient();
    Log.d("onCreateService", "onCreateService");
}

Again, I am starting my service in onCreate on Main activity...
Could anyone helps me? Thanks in advance.
Comment: I think your service is call only first time. Please check your service. It is running multiple time or not.
Comment: can you try my way how i'm doing http://stackoverflow.com/questions/39314901/getting-latitude-and-longitude-in-30-seconds
Comment: Yes, my service is running multiple times.
Comment: @Saveen Thanks for answer, but I would not like to completely changing my code..would you be kind just to tell me what should I add into this mine code?
Comment: @Bansal So, You think that I put logic from onCreate to onStartCommand or not?
Comment: Your service is not working permanently
Answer: Please check how i have changed service to your code.
Step 1. Make this class
GoogleLocationService.java
public class GoogleLocationService {
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();
LocationUpdateListener locationUpdateListener;
Context activity;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;

public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;

public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {
    this.locationUpdateListener = locationUpdateListener;
    this.activity = activity;
    buildGoogleApiClient();
}

protected synchronized void buildGoogleApiClient() {
    //Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(activity)
            .addConnectionCallbacks(callbacks)
            .addOnConnectionFailedListener(callbacks)
            .addApi(LocationServices.API)
            .build();
    createLocationRequest();
    mGoogleApiClient.connect();
}

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

}

private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
            Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();
               String connectionFailed = DateFormat.getTimeInstance().format(new Date());
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("connectionFailed", connectionFailed);
editor.apply();
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());

        }
        locationUpdateListener.cannotReceiveLocationUpdates();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location.hasAccuracy()) {
            if (location.getAccuracy() < 30) {
                locationUpdateListener.updateLocation(location);
            }
        }
    }
}

private static boolean locationEnabled(Context context) {
    boolean gps_enabled = false;
    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return gps_enabled;
}

private boolean servicesConnected(Context context) {
    return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context);
}

private boolean isPackageInstalled(String packagename, Context context) {
    PackageManager pm = context.getPackageManager();
    try {
        pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}

public void startUpdates() {
    /*
     * Connect the client. Don't re-start any requests here; instead, wait
     * for onResume()
     */
    if (servicesConnected(activity)) {
        if (locationEnabled(activity)) {
            locationUpdateListener.canReceiveLocationUpdates();
            startLocationUpdates();
        } else {
            locationUpdateListener.cannotReceiveLocationUpdates();
            Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();
        }
    } else {
        locationUpdateListener.cannotReceiveLocationUpdates();
        Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();
    }
}

//stop location updates
public void stopUpdates() {
    stopLocationUpdates();
}

//start location updates
private void startLocationUpdates() {

    if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks);
        String timeWhenStartLocationUpdates = DateFormat.getTimeInstance().format(new Date());
         SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
   SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("startLocationUpdates", timeWhenStartLocationUpdates);
    editor.apply();
    }
}

public void stopLocationUpdates() {
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks);
         String timeWhenStopLocationUpdates = DateFormat.getTimeInstance().format(new Date());
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("stopLocationUpdates", timeWhenStopLocationUpdates);
    editor.apply();
    }
}

public void startGoogleApi() {
    mGoogleApiClient.connect();
}

public void closeGoogleApi() {
    mGoogleApiClient.disconnect();
}

 }

Step2. Make this interface
LocationUpdateListener.java
 public interface LocationUpdateListener {

/**
 * Called immediately the service starts if the service can obtain location
 */
void canReceiveLocationUpdates();

/**
 * Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and
 */
void cannotReceiveLocationUpdates();

/**
 * Called whenever the location has changed (at least non-trivially)
 * @param location
 */
void updateLocation(Location location);

/**
 * Called when GoogleLocationServices detects that the device has moved to a new location.
 * @param localityName The name of the locality (somewhere below street but above area).
 */
void updateLocationName(String localityName, Location location);
}

Step 3. Make this Location service class
LocationUpdateService.java
 public class LocationUpdateService extends Service {

 protected String mLastUpdateTime;
 protected String timeWhenServiceDestroyed;
 protected String timeWhenGetInGetLatLong;
 protected String report_time;
 protected String timeFromElse;
 Calendar calendar;

 private GoogleLocationService googleLocationService;
 IBinder mBinder = new LocalBinder();

 public class LocalBinder extends Binder {
 public LocationUpdateService getServerInstance() {
    return LocationUpdateService.this;
}
}

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("LOC", "Service init...");
return Service.START_STICKY;
}

protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient===");
mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addApi(LocationServices.API)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();
createLocationRequest();
  }

  public void getLatLong() {
timeWhenGetInGetLatLong = DateFormat.getTimeInstance().format(new Date());

  if (mCurrentLocation != null && mLastUpdateTime != null) {

    String lat = String.valueOf(mCurrentLocation.getLatitude());
    String lng = String.valueOf(mCurrentLocation.getLongitude());
    calendar = Calendar.getInstance();
    @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    report_time = simpleDateFormat.format(calendar.getTime());
    Log.d("preferences", "Time stored in preferences: " + mLastUpdateTime);
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("user_latitude", lat);
    editor.putString("user_longitude", lng);
    editor.putString("getLatLongIf", "ok");
    editor.putString("report_time_for_location_response", report_time);
    editor.putString("time_when_comes_to_getLatLong", timeWhenGetInGetLatLong);
    editor.apply();
}else{
    timeFromElse = DateFormat.getTimeInstance().format(new Date());
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("getLatLongElse", timeFromElse);
    editor.apply();
 }
 }

@Override
public void onDestroy() {
super.onDestroy();
timeWhenServiceDestroyed = DateFormat.getTimeInstance().format(new Date());
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("onDestroyService", timeWhenServiceDestroyed);
editor.apply();
  if (googleLocationService != null) {
    googleLocationService.stopLocationUpdates();
  }
  Log.d("onDestroyService", "onDestroy: + " + timeWhenServiceDestroyed);
 }

 @Override
 public void onCreate() {
 super.onCreate();

 mLastUpdateTime = "";

Log.d("onCreateService", "onCreateService");

 googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
    @Override
    public void canReceiveLocationUpdates() {
    }

    @Override
    public void cannotReceiveLocationUpdates() {
    }

    //update location to our servers for tracking purpose
    @Override
    public void updateLocation(Location location) {
        if (location != null ) {
           mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.d("mCurrentLocation", "Location is: " + location);
getLatLong();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("user_location", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("TimeWhenCameToOnLocationChanged", mLastUpdateTime);
editor.apply();
Log.d("onLocationchanged", "OnLocationChangedInServiceLocation");
Log.d("Time ", "Time of lat and long from Service: " + mLastUpdateTime);

        }
    }

    @Override
    public void updateLocationName(String localityName, Location location) {

        googleLocationService.stopLocationUpdates();
    }
});
googleLocationService.startUpdates();

}

Try this, hope this help you. Remember you will get updated latitude and longitude on updateLocation.
Comment: Thanks mate, but where you saw that my service isn't working permanently?
Comment: Later I saw their is start sticky present in your service
Comment: Try it my way if still you get any problem then let me know
Comment: Okay, so just tu try this part of code that you write me for now, not that whole your function from another question?
Comment: I tried this but its the same problem..when I go into app and then I turn on location it doesn't appera icon of location in notification bar..but when I again go into app that icon is hsowed in the bar....so that means that my location don't work when I go first time into app.
Comment: I have  updated my answe and please check why you are not getting  location on location changed or update ? First time your method get location is not working because location start updating after call of this method.


Cannot find module `@ericblade/quagga2`

Question: I'm having an issue with my typescript serverless CDK lambda dependencies. Simply running npm install and routing to the file where I'm importing the @ericblade/quagga2 module, I can command click and route to the module.
However, when running the command sam local invoke --event s3-event.json I get an error that the module could not be found. ( other modules like aws-sdk were found )
I'm thinking this is a typescript problem, but I'm not sure how to fix it. I'm unfamiliar with any custom d.ts file hack that would solve this problem.
import statement : const Quagga = require('@ericblade/quagga2').default
tsconfig.json:
{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "esModuleInterop": true,
    "lib": [
      "es2018",
      "dom"
    ],
    "declaration": true,
    "moduleResolution": "node",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "exclude": [
    "cdk.out"
  ]
}

I've tried messing around with different configurations in the tsconfig, but I'm not really sure what I'm doing.
Answer: This problem was because I didn't have a package.json at the lambda level directory for lambda dependencies. The library aws-sdk was working at not throwing a module not found error because it is baked into the SAM testing image.

Cannot find module `@ericblade/quagga2`


'No matching constructor for initialization' when returning a C++ object

Question: I have a simple object, and I want to return an object in a method. I know the constructor used is valid since it's used somewhere else.
return Color(red, blue, green);

This codes returns the following error : No matching constructor for initialization of 'transitLib::Color'
However, just adding *new make the thing work :
return *new Color(red, blue, green); //Valid, apparently.

Any idea why this would produce this error?
Attached is the full code of the class
.h
class Color {

    float red;
    float blue;
    float green;

public:
    Color(float red, float blue, float green);
    Color(Color &color);

    Color colorByInterpolating(Color const& destinationColor, float fraction);

    bool operator==(const Color &other) const;
    bool operator!=(const Color &other) const;
    Color operator=(const Color &other);

    float getRed();
    float getBlue();
    float getGreen();
};

.cpp
transitLib::Color::Color(float red, float blue, float green):red(red),blue(blue),green(green){}
transitLib::Color::Color(Color &color):red(color.red),blue(color.blue),green(color.green){}

Color transitLib::Color::colorByInterpolating(Color const& destinationColor, float fraction) {
    return Color(red + fraction * (destinationColor.red - red), blue + fraction * (destinationColor.blue - blue), green + fraction * (destinationColor.green - green));
}

bool Color::operator==(const Color &other) const {
    return other.red == red && other.blue == blue && other.green == green;
}

bool Color::operator!=(const Color &other) const {
    return !(other == *this);
}

Color Color::operator=(const Color &other) {
    red = other.red;
    blue = other.blue;
    green = other.green;

    return *this;
}

float transitLib::Color::getRed() {
    return red;
}

float transitLib::Color::getBlue() {
    return blue;
}

float transitLib::Color::getGreen() {
    return green;
}

Answer: When you return by value, a copy is being made (using the copy constructor). You're attempting to return a temporary, which can't bind to a non-const reference (which is your copy constructor takes as a parameter).
Change
Color(Color &color);

to
Color(const Color &color);

Comment: This was indeed it, I knew it was a simple answer. Thanks.
Comment: @gcamp also note that `operator =` should return `*this` by reference (that's the idiomatic way)
Comment: Similar error brought me to this post.  In my case I had the following (reformatted to match this post's code)

explicit Color(const Color &rhs)

I had to remove the explicit directive but don't understand why the explicit keyword was causing me to get same error message


Accessing link in email body using gmail API

Question: I am using gmail api and python to access my gmail inbox. My email is stored in mime_msg. I want to access 'http://example.com/newpasswordid=exampleid12345' as seen below. How can I do that?
msg_str = base64.urlsafe_b64decode(full_message['raw'].encode('ASCII'))
mime_msg = email.message_from_bytes(msg_str)
print(mime_msg)

Link1

.

=A92020 For more info please visit=
 Link2

Comment: Do you just have a string containing the HTML you show, and you want to extract the first URL from the string?
Comment: @Steve I want to extract 'http://example.com/newpasswordid=exampleid12345' from the variable mime_msg
Comment: So like my answer?  Do you really not want the `http://` part? Tell me in comments on the answer if you are looking for something different
Answer: If you have that text in the string mime_msg, and you just want to extract the URL, that's pretty simple.  If you know your format is always going to be such that you want what's in the first pair of single quotes, you can use this code:
import re

mime_msg = """
Link1

.

=A92020 For more info please visit=
 Link2

 """

exp = re.compile(r"'(.*?)'")
mime_msg = re.sub(r"[\n\r]+", '', mime_msg)
m = exp.search(mime_msg)
print(m.group(1))

Result:
http://example.com/newpasswordid=exampleid12345

If you wanted to be able to deal with more complex mail bodies, you could make the regular expression more complex.
Comment: Thank you for the response. The variable mime_msg contains my email body. I've tried your example above, and I get the error

  File "C:\Users\test\Desktop\test.py", line 66, in main
    print(m.group(1))
AttributeError: 'NoneType' object has no attribute 'group'
Comment: That means the regular expression isn't matching the text.  But it does for me.  I wonder what happened?  Something probably changed in the copy/paste.  Did the quotes maybe change to "funny quotes"?  Are you printing the text just before my code, like you show in your example?  You should do that to make sure your message is really there.
Comment: I checked and it is the same as how you did it other than m = exp.search(str(mime_msg)). Not sure what's wrong.
Comment: You could try a different expression: `exp = re.compile(r"(http.*?).>")`
Comment: I've tried the new expression, and it returns me the second link.
Comment: That's quite bizarre.  I can't think what is happening.  That expression says to grab the first `http` and everything after it up to a `>`.  That should match the first URL as well as the second, and so should return the first one since it will match that one first.
Comment: I think the issue could be because the first link is not recognized as a url
Comment: all that matters is that it matches what I said...`http` + some number of chars + `>`.  Doesn't the first one match that pattern too from what you can see?
Comment: Strange.  This one line prints the URL for me as well: `print(mime_msg.split("'")[1])`
Comment: It can't recognize the first URL because in the email body, the url is split into 2 lines. So instead of http://example.com/newpasswordid=exampleid12345, it is http://example.com/newpasswordi and d=exampleid12345 on another line. Thanks anyway for your response!
Comment: Oh.  Well, we can deal with that! - why didn't that show up in your question?
Comment: Sorry, had to change up the url and forgot about it
Comment: I just added a line of code to the answer.  Try that version.
Comment: Cool!  Learn all about regular expressions when you can.  You can do amazing things with them.


Como quebrar linhas de acordo com um valor

Question: Como faço para quebrar linhas de acordo com o valor ? Por exemplo
a = 8. Ai eu tenho uma variável "d" q recebe uma string. var d = "obra escrita considerada na sua redação original". Se eu colocar um If = a; ela percorre a string contando sempre q for 8 caracteres ela quebra a linha. Quem poder me ajudar agradeço, já tentei algumas ideias mas não tive sucesso.
Comment: Mas o `b` e o `c` fazem o que ?
Comment: @Isac Tentei simplificar a minha pergunta, estava meio confusa mesmo. A ideia é ....Eu tenho uma string e quero fazer quebra de linha sempre q chegar no oitavo carácter.
Answer: Pode solucionar esse problema com uma expressão regular simples na forma de:
/.{1,8}/g

Explicação:
/     - Inicio da expressão regular
.     - Qualquer caratere
{1,8} - Entre 1 a 8 vezes, sempre apanhando o máximo possível.
/     - Fim da expressão regular
g     - Aplicado globalmente na string

Se este numero nunca muda pode simplificar e utilizar diretamente na função match que lhe devolve um array como resultado:

let texto = "obra escrita considerada na sua redação original";
let blocosTexto = texto.match(/.{1,8}/g);
let textoQuebrado = blocosTexto.join("\n");

console.log(textoQuebrado);

Como o valor obtido é um array, para construir um texto com quebras de linha para cada valor do array basta utilizar o método join de array passando o \n com parâmetro. Se por acaso o resultado for para mostrar em html então deve utilizar "
" no join para ter as quebras de linhas apropriadas.
Se o valor que indica a quantidade de careteres para quebrar poder mudar, ou se for lido/construido com base no input do usuário então já precisa de utilizar RegExp para construir a expressão regular:

let texto = "obra escrita considerada na sua redação original";
let quebra = 8;
let regex = new RegExp(`.{1,${quebra}}`, 'g');
let blocosTexto = texto.match(regex);
let textoQuebrado = blocosTexto.join("\n");

console.log(textoQuebrado);
Comment: muitoooo obrigadoooo....Vou ler e etestar o q vc escreveu. Valeu mesmo cara.


Inline Entity Form - How to Theme the referenced form edit screen with a tpl.php file?

Question: Inline entity form (IEF) is a module that lets you create other nodes/entity inside of a node edit form (or reference them).
I would like to theme the form edit screen using a tpl.php file. (By form edit screen, I mean the place where the inline form is displayed for the user to input data and not the display that shows the finished form (e.g. so the 'edit' part and not the 'view' part),
This thread explains how to change values of the fields of the IEF creation screen. But it doesn't show how to use a tpl.php.file.
This tutorial and this tutorial explain how to theme forms. However, their knowledge doesn't seem to apply to Inline Entity forms (mainly because IEF forms don't use a form element).
Answer: I found the following answer here: http://site-machines.ru/blog/temizaciya-inline-entity-form-v-drupal
===========================
When using Inline entityform time to time it is necessary to make it more beautiful, more than matching the concept of the site. There are several ways to implement this, segodyan I will talk about one of the - the use of theming template.
As   Inline entityform is the usual form, so it has a minima must be some hook_alter. See the documentation that is the way to be in the module - inline_entity_form.api.php. The documentation found the right hook - hook_inline_entity_form_entity_form_alter.
At the entrance is just fed our inline form.
The next step is adding theming function
/ **
  * hook_inline_entity_form_entity_form_alter
  * /
 function sm_inline_entity_form_entity_form_alter (& $ entity_form, & $ form_state) {
   // Added theme function
   $ Entity_form [ '# theme'] [] = 'inline_entity_form_entity_form_'.  $ Entity_form [ '# bundle'];
   dpm ($ entity_form);
 }
I almost forgot to say the magic is done in our template.php form.
I told him what happened, what we've done in the previous paragraph? We've added a feature to our temizaitsii inline form, not just for one but for all. devel dpm () function module will help us to examine the insides of our Inline form
The next step in our magic, it template.php create hook_theme and declare it a template for our inline form
/ **
  * Implements hook_theme ().
  * /
 function sm_theme ($ existing, $ type, $ theme, $ path) {
   $ Items [ 'inline_entity_form_entity_form_shoes'] = array (
     'Render element' => 'form',
     'Template' => 'inline-entity-form-entity-form-shoes',
     // This will set to module / theme path by default:
     'Path' => drupal_get_path ( 'theme', 'sm').  '/ Templates / inline_form',
   );
   return $ items;
 }
Just be sure to create our template file and we put him on the scullery indicated in the 'path' hook_theme.
Then I inserted the following code template
<-! Start inline-entity-form-entity-form-shoes.tpl.php ->
<-! @ See sm_theme adn template.php ->

Then we look at what we will give dpm (), continue using drupal_render output fields in the required manner


Is SSL adequate enough to keep a website safe?

Question: I've been looking into programming a website for a company (no data or information other than forms are on it) I've been looking at BlueHost as a hosting and the SSL secure feature for security, I don't know any other securing or encrypting myself, will BlueHosts SSL be enough?
Comment: SSL doesn't keep your site safe. It just keeps information being transmistted between your users and yourself safe.
Comment: If you think safety and security are just a matter of checking some boxes, then your approach is severely flawed and you should get some help with your project.
Comment: I want to take the opportunity to point you to [Let's Encrypt](https://letsencrypt.org/).
Comment: BTW: SSL does not exist anymore, it became *TLS* in 1999 (ok, you can still implement the old version, but that does not make any sense).
Answer: No.  SSL only protects data in transit from interception by a 3rd party-- and there are many factors to consider on how SSL is implemented required to decide if it even does that satisfactorily.
There are many countless facets of security that you must consider beyond how to make sure that data doesn't get read by someone else while it is being transmitted between a browser and a server over SSL.  Too many to elaborate on in a stackoverflow answer.  To put it in perspective, when I deploy a system that contains any sensitive data (I work for a payment processing company, but "sensitive" covers a lot more than just credit card numbers), I have to answer around 800 questions on a security audit.  Only about 30 of those questions relate to SSL and making sure SSL is implemented properly.  Then a team of experts have to review the implementation of such a system, deliberate, and vote unanimously that it meets requirements. Even after all that, routine security audits find potential vulnerabilities that were overlooked and must be mitigated.
No.  SSL by itself is not enough to consider a system "secure".  If it has data that needs SSL, it almost certainly has more needs than just SSL.
Comment: Agreed completely, but that last line sort of implies that HTTPS isn't necessary for general use cases.  It's important to point out that a major reason for HTTPS is ensuring that the data coming back is coming from a server authorized to send data for that domain... that it wasn't tampered with or replaced along the way.  Public WiFi installations very commonly inject their own scripts into pages to serve and replace ads.  If that isn't bad enough, these scripts are often insecure themselves and can have their own vulnerabilities that then get applied to all sites visited on that WiFi.
Comment: How about SiteLock security and CodeGuard with domain privacy protection? These are what I was wanting
Answer: First of all, you should have SSL. With that said, no, that is not enough.
So, what do you need? While it is true that there is a lot to cover, you clearly need to be pointed to the right direction...
As far as hosting provider goes, there are other features that you could be interested in:

Backups (although, you probably can roll a solution yourself)
Antimalware (although, if your site will not allow to upload files, it is less relevant)
DDoS mitigations.

I want to remind you that information security is not only confidentiality, it is also availability and integrity (and traceability).

Please set up a test enviroment, on a local server, make sure it works. You can do security audits on that before they go the production enviroment. Remember that the sooner you discover the bugs, the cheaper it will be to fix them... thus, you do not want to discover them in production.
Yeah, it is ok to not have HTTPS on the test enviroment. There is plenty to do besides that. And yeah, you should review the security in production too.
Ideally there will be team doing test, and among those tests they might look for potential vulnerabilities. There are also security scanners that can help with that.
However, you should be writing secure code to begin with. Right?

I have to tell you, the server-side is more relevant than the tagged HTML and jQuery. The golden rule is to not trust the client. Remember that request might not be coming from an actual browser (despite what the user agent might say). You must do validation on the server. Even though it is also a good idea to validate in the client (for a better user experience and to safe network capacity), client-side validations are virtally irelvant for security.
That is not the same to say that there are not things that can improve the security that can be done client-side. For example, figerprinting a client can be useful to detect when the client is coming from an unusual source for a given user, rising a red flag (a partial fingerprint is possible server-side). Also you can do mitigations for screen-recorders/keyloggers/shoulder-surfing.
There are also very specific cases where doing cryptography on the client makes sense. That is not the usual case. You probably do not need to do that. And in the odd case you do, please hire an expert.

Anyway, these are some things that developers often overlook (this is by no means a complete list):

Do not trust the client.
Validate all input.
Sanitize all output (considering where it is going to).
Use prepared statements on database access.
Specify character charsets (for HTML, server-side string manipulation, and both database storage and connections).
Do proper authentication and access control.
Store credentials properly.
Stay up to date with browser security features.
Use Cross-Origin Resource Sharing correctly.
Use HttPOnly cookies when possible.
Use a Service Worker and Web Cache properly.
Log errors instead of showing them to the client.
Have traceability for all modifications.

Also, consider two factor authentication.
You might also be interested in OWASP Top Ten project and OWASP Cheat Sheet Series. Note: These are not a security check list, and are not a replacement for a security audit. They aren't gospel either, however if you are not to follow them, let it not be because you are unaware.
Finally let me point you to Information Security Stack Exchange, a Q&A site dedicated to information security (hence the name) sister to this one.

Addendum: If you are not developing a web application, but setting up a content management system instead, then you must keep it up to date. Also, research and apply security hardening for whatever it is you are using.


GIF not appearing correctly on JDialog

Question: Well, I developed a wait screen with a JDialog, but it only works when isolated.
Here is my code:
/**
 *
 * @author krisnamourtscf
 */
public class TelaDeProcessamento extends Thread {

    private String titulo;
    private String mensagem;
    private JDialog dialog;

    public TelaDeProcessamento(String titulo, String mensagem) {
        this.titulo = titulo;
        this.mensagem = mensagem;
        dialog = new JDialog(new JFrame(), true);
    }

     public static TelaDeProcessamento iniciaTela(String titulo, String mensagem) {
        TelaDeProcessamento tela = new TelaDeProcessamento(titulo, mensagem);

        tela.start();
        return tela;
    }

    @Override
    public void run() {
        try {

            dialog.setTitle(titulo);
            dialog.getContentPane().setBackground(Color.WHITE);
            dialog.setSize(new Dimension(300, 150));
            dialog.getContentPane().setLayout(new BorderLayout());

            ImageIcon ii = new ImageIcon(getClass().getResource("/imagens/4.gif"));
            JLabel imageLabel = new JLabel();
            imageLabel.setLocation(70, 0);
            imageLabel.setText("         " + mensagem);
            imageLabel.setIcon(ii);

            dialog.getContentPane().add(imageLabel, java.awt.BorderLayout.CENTER);

            dialog.setLocationRelativeTo(null);
            dialog.validate();
            dialog.setVisible(true);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void paraTela() {
        dialog.dispose();
    }

    public static void main(String[] args) {
        TelaDeProcessamento tela=TelaDeProcessamento.iniciaTela("Aguarde....", "isso é um teste");
        try {
            Thread.sleep(5000);
        } catch (Exception ex) {

        }
        tela.paraTela();

    }

}

And this is the result:

Although, when I call it from another class, the GIF doesn't appear
Called from another JDialog class example
this.setTitle(title);
        this.setModal(true);
        this.setLocationRelativeTo(null);
        TelaDeProcessamento tela = TelaDeProcessamento.iniciaTela("Aguarde", "carregando dados");
        this.initiateScreenComponets();
        tela.paraTela();
        JTableUtil.addEventosSelecaoBusca(this);
        this.setVisible(true);

result:

What am I doing wrong?
Comment: I suspect this is because you are performing your actions outside of the AWT event dispatch thread.  Nearly all Swing and AWT methods must be run only in that thread, not in other threads.  Violating this rule will lead to strange and unpredictable behavior.  See https://docs.oracle.com/javase/tutorial/uiswing/concurrency/.
Comment: thanks @VGR I solved the problem with SwingWorker
Answer: You may have a problem finding the gif in the path... verify that!!
after trying your code I can confirm that your code must work!
Comment: It's not a path problem
Comment: Read the comment above, it's probably a Theading issue @Krismorte
Comment: I've tried both and is working... IT must be something related to the path
Answer: I don't neet to change my Class just the calling method
the old call
@Override
            public void initiate(String title) {
    this.setTitle(title);
    this.setModal(true);
    this.setLocationRelativeTo(null);
    TelaDeProcessamento tela = TelaDeProcessamento.iniciaTela("Aguarde", "carregando dados");
    this.initiateScreenComponets();
    tela.paraTela();
    JTableUtil.addEventosSelecaoBusca(this);
    this.setVisible(true);
}

the new call
       @Override
        public void initiate(String title) {
            this.setTitle(title);
            this.setModal(true);
            this.setLocationRelativeTo(null);
            procedimentoDeEspera();
        }

  private void procedimentoDeEspera() {
        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                TelaDeProcessamento.iniciaTela("Aguarde", "carregando dados");
                initiateScreenComponets();
                return null;
            }

            @Override
            protected void done() {
                TelaDeProcessamento.paraTela();
                finalizaTela();
            }

        };

        worker.execute();
    }

this link helped me
https://www.javacodegeeks.com/2012/12/multi-threading-in-java-swing-with-swingworker.html

GIF not appearing correctly on JDialog


Comparing two documents and writing output to a third [Python?]

Question: I am seeking some advice whether it be in terms of a script (possibly python?) that I could use to do the following.
I basically have two documents, taken from a DB:
document one contains :
hash / related username.

example:
fb4aa888c283428482370   username1
fb4aa888c283328862370   username2
fb4aa888c283422482370   username3
fb4aa885djsjsfjsdf370   username4
fb4aa888c283466662370   username5

document two contains:
hash : plaintext

example:
fb4aa888c283428482370:plaintext
fb4aa888c283328862370:plaintext2
fb4aa888c283422482370:plaintext4
fb4aa885djsjsfjsdf370:plaintextetc
fb4aa888c283466662370:plaintextetc

can anyone think of an easy way for me to match up the hashes in document two with the relevant username from document one into a new document (say document three) and add the plain so it would look like the following...
Hash : Relevant Username : plaintext

This would save me a lot of time having to cross reference two files, find the relevant hash manually and the user it belongs to.
I've never actually used python before, so some examples would be great!
Thanks in advance
Comment: It is customary that if you were given an answer to your question, you mark it as such....or follow up to get the answer that you need.
Answer: I don't have any code for you but a very basic way to do this would be to whip up a script that does the following:

Read the first doc into a dictionary with the hashes as keys.
Read the second doc into a dictionary with the hashes as keys.
Iterate through both dictionaries, by key, in the same loop, writing out the info you want into the third doc.
Answer: You didn't really specify how you wanted the output, but this should get you close enough to modify to your liking. There are guys out there good enough to shorten this into a fey lines of code - but I think the readability of keeping it long may be helpful to you just getting started.
Btw, I would probably avoid this altogether and to the join in SQL before creating the file -- but that wasn't really your question : )
usernames = dict()
plaintext = dict()
result = dict()

with open('username.txt') as un:
    for line in un:
        arry = line.split() #Turns the line into an array of two parts
        hash, user = arry[0], arry[1]
        usernames[hash] = user.rsplit()[0] # add to dictionary

with open('plaintext.txt') as un:
    for line in un:
        arry = line.split(':')
        hash, txt = arry[0], arry[1]
        plaintext[hash] = txt.rsplit()[0]

for key, val in usernames.items():
    hash = key
    txt = plaintext[hash]
    result[val] = txt

with open("dict.txt", "w") as w:
    for name, txt in result.items():
        w.write('{0} = {1}\n'.format(name, txt))

print(usernames)  #{'fb4aa888c283466662370': 'username5', 'fb4aa888c283422482370': 'username3' ...................
print(plaintext) #{'fb4aa888c283466662370': 'plaintextetc', 'fb4aa888c283422482370': 'plaintext4' ................
print(result) #{'username1': 'plaintext', 'username3': 'plaintext4', .....................


i need help to plot this data with Highcharts

Question: well , i don't know much about javascript
i have some data that i want to plot using Highcharts , right now i'm following this tuto :
http://blueflame-software.com/blog/using-highcharts-with-php-and-mysql/
i managed to do that example , but i have different data like this :
<code>    date        : temp
</code>
2013-05-08 20:17:26  :  -22
2013-05-08 20:18:26  :  -21
2013-05-08 20:24:26  :  -22
2013-05-08 20:37:26  :  -20
2013-05-08 20:40:26  :  -22
2013-05-08 20:47:26  :  -21
2013-05-08 20:52:26  :  -20
2013-05-08 20:53:26  :  -19
how to plot this with date in x axis and temp in y axis
Answer: To plot dates/times on the xaxis, use the xaxis type to specify datetime.
<code>      xAxis: {
        type: 'datetime'
      }
</code>
Next you'll need to format your xvalues in the time format Highcharts understands; the number of milliseconds from midnight of January 1, 1970.  You have two options:

Parse the date string as in your example link:
<code>line = line.split(/\t/);
date = Date.parse(line[0] +' UTC'); // change timezone accordingly
</code>
Have PHP/MySQL return milliseconds instead of a string from the database:
<code>$result = mysql_query("SELECT UNIX_TIMESTAMP(timespan) * 1000, visits FROM highcharts_php");
</code>
Comment: You can use formatter (http://api.highcharts.com/highcharts#tooltip.formatter) and extract data by point.options.nameofcustomparameter
Comment: Hey , thank you for your reply Mark , it's working very good :)
i have an other question if you don't mind :
i already have 'temperature' in the Y-axis and 'Date' in the x-axis , how can i add more data and retrieve them in tool-tip ?


Finding the Equation of the Circle with a given line and tangent x axis

Question: So my Professor ask us to solve a problem finding the equation of the circle with only a given
"Tangent to the x-axis with center on x + 4y = 5"
I'm confused in the part how do I find the center point in a line without a given endpoints of the line?
What I think about the problem is that the center would be along the given line and the x intercept would be the point where the circle touches
Edit:
after analyzing how it could be done. I found out that it really isn't a unique circle, the center and the x axis can be adjusted to match the given.
This is the first graph of equation
This is another one that was adjusted
My problem now is how do I create an differential equation of family of circles that would only satisfy the given problem.
Sorry I'm new, thank you for everyone's kind response
Comment: Welcome to MSE. Could you please be more specific, in the sense that, do you want a full solution or a hint? Also, could you please be more specific as to what you are confused about.
Comment: Thank you sorry I'm new. If possible I want a full solution so I could understand why and how to use the solution to apply it other similar problems. I don't know how to be specific in this problem our professor asked to find the equation of circle using the given "Tangent to the x-axis with center on x +4y = 5"
Comment: I have tried to give you some hint, seeing your difficulty. Please use it fully.
Comment: @Narasimham maybe delete this comment until you fix your now deleted answer.
Comment: There are a family of such circles, not just one. Start with any center point on the line other than where the line meets the $x$ axis, then drop a perpendicular from that point to the $x$ axis to get the radius.
Comment: @coffeemath Thank you I would try this. Is there a chance that I would not find a unique circle?
Comment: You will not find a unique circle, because as I noted the center can be at any of the (infinitely many) points on the given line other than where the line crosses the x axis. [And two circles with different centers are different circles.] Perhaps you omitted some other condition of your professor's problem which would make it unique. On the other hand maybe your professor wants you to find them all, or even satisfied if you find one of them.
Comment: @coffeemath Thank you. I was really confused and in doubt at first because every problems that I encountered so far were unique circles but this one is different. I realize that there's no constant given so I think you're right.
Comment: If you solved it, then this site encourages users to "answer" their own questions.
Comment: I'd like to see that graph. Because once you have one case that works, one can imagine moving the center along the line, at the same time changing the radius, so as to keep the circle tangent to the x axis.
Comment: I noticed you deleted your comment about having graphed it and getting a unique circle. Please don't delete comments that someone responds to--- it makes the response unmotivated.
Comment: Oh sorry, I meant to edit not delete. How do I send the graph here? It seems that there's a unique circle for the given.
Comment: Sorry I don't know how to put a graph here. But you can add to your question the information about where the center of your circle is (coordinates) and what its radius is.
Comment: Your two graphs you have inserted in the question are both satisfying requirements, and they show what I mean about the family of equations. Your question still doesn't mention  you need a differential equation for the family of circles. That information should be put in the question if it was what your professor wanted you to find.
Comment: @coffeemath yeah that too is a problem, I don't know what does my professor want us to do. I'm guessing anything goes as long the question can be answered.
Comment: @Confundo I highly suggest you ask your professor what he wants you to do. Are you taking a differential equations course from the professor? If so and you ask the professor and get an answer what you are to find, and if it is a differential equation for the circles, I have a way which i can answer. But I don't want to go to the trouble of doing so unless that's definitely what your professor wants you to do.
Answer: There are obviously not a unique one but multiple ( an infinite set) circle solutions.

They can be set by a variable center point given on the given parametrized straight line
$$ (x_C,y_C)=(t, \frac{5-t}{4})$$
You can find them all
$$ (x-x_C)^2+(y-y_C)^2= y_C^2.$$
Find the equation of Circle in the question misleads.
Comment: Thanks for pointing out my graphing error. Hope now it all stands corrected .
Comment: Is the blue line supposed to be $x+4y=5$? [It doen't look like your blue line has that equation.]


Error installing R (3.1.0) package caret on Ubuntu 14.04.1 LTS

Question: Trying to install package "caret" on R 3.1.0 (Ubuntu 14.04.01 LTS) and running into a build error.
<code>> install.packages('caret')
</code>
[...]
<code>* installing *source* package 'BradleyTerry2' ...
** package 'BradleyTerry2' successfully unpacked and MD5 sums checked
** R
** data
*** moving datasets to lazyload DB
** inst
** preparing package for lazy loading
Error : object 'brglm' is not exported by 'namespace:brglm'
ERROR: lazy loading failed for package 'BradleyTerry2'
* removing '/home/br00t/R/x86_64-pc-linux-gnu-library/3.1/BradleyTerry2'
Warning in install.packages :
  installation of package 'BradleyTerry2' had non-zero exit status
ERROR: dependency 'BradleyTerry2' is not available for package 'caret'
* removing '/home/br00t/R/x86_64-pc-linux-gnu-library/3.1/caret'
Warning in install.packages :
  installation of package 'caret' had non-zero exit status

The downloaded source packages are in
    '/tmp/Rtmp7pWmvr/downloaded_packages'
> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C               LC_TIME=en_CA.UTF-8        LC_COLLATE=en_CA.UTF-8
 [5] LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8    LC_PAPER=en_CA.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] sp_1.0-16

loaded via a namespace (and not attached):
[1] grid_3.1.0      lattice_0.20-29 tools_3.1.0
</code>
Wasn't able to find anything helpful on the interwebs. Not sure if this is an issue with the BradleyTerry2 package or brglm... help?
Thanks,
br00t
Comment: Never mind was able to resolve the issue by manually installing brglm and BradletTerry2 packges then reattempting install of caret and it worked... could have sworn that didn't work last night but hey, I'll take it!
Comment: I was wrong, the package built, but will not load, still complaining that "Error : object 'brglm' is not exported by 'namespace:brglm'"
Answer: If you are running a version of the brglm package greater than 0.5-9, uninstall and install brglm package version 0.5-9
Answer: I was able to get over the issue too by installing the dependencies. You may want to select your answer as the right one.
Comment: Unfortunately, just installing the dependencies did not fully resolve the issue for me. I realized that the BradleyTerry2 package attempts to import brglm from the brglm package. This function is exported in version 0.5-9 of brglm, but does not appear to be from version 0.6-1 onwards. In order to get caret to build AND load, I had to install version 0.5-9 of brglm
Comment: Good to know eventually it did work for you. And thanks for sharing the right answer.


Create and use a custom Account Email Template

Question: I am trying to create a new Email Template for the Account object using hook_form_alter. Here is how I create the template:
function my_module_form_user_admin_settings_alter(&$form, &$form_state, $form_id) {
    // Adds the Course Link email template to the Account Settings form
    $form['email_course_link'] = [
        '#type' => 'details',
        '#title' => t('Course link'),
        '#description' => t('Edit the course link e-mail messages sent to mobile app users.'),
        '#group' => 'email',
    ];
    $form['email_course_link']['user_mail_course_link_subject'] = [
        '#type' => 'textfield',
        '#title' => t('Subject'),
        '#maxlength' => 180,
    ];
    $form['email_course_link']['user_mail_course_link_body'] = [
        '#type' => 'textarea',
        '#title' => t('Body'),
        '#rows' => 15,
    ];
}

This adds the email template to my Account Settings form, but I am having two issues:

When I go to edit the template and hit save configurations, nothing gets saved. The subject and body edits I made are wiped out and they no longer exist.

When I go to use the template via _user_mail_notify('email_course_link', $user) I get NULL as the response and there are zero errors to be found and I never get the email...

What else am I missing here?
Answer: Specifically, your code is modifying the AccountSettingsForm, which is part of the core Drupal "user" module.
If you look at the source code for that form, you will see that like all forms in Drupal, it has both a buildForm() method and a submitForm() method. The problem with your code is that you've added form elements to the form array created by default in buildForm(), but you HAVEN'T added any code to process those new form elements and save the entered data, which is normally done in submitForm(). If you create new form elements in an existing form, you are responsible for processing the input and saving the entered values. Your custom module is the only thing that knows about those new elements, and your custom module is responsible for storing that data.
Let's look at one of the other elements defined in AccountSettingsForm, for example the email_admin_created details element which contains a user_mail_register_admin_created_subject and a user_mail_register_admin_created_body. It looks like you copied this code and changed the names for your own purpose, which is a good way to approach this. But if you search AccountSettingsForm, you will see that those form elements are also processed and saved in submitForm(), and you haven't added any new equivalent code for your new form elements.
The key then is to write your own function to execute on form submit, and in that function you need to save the values entered into your custom form elements. The way to tell Drupal about your custom submit function is to add the following at the end of your hook_form_alter():
$form['actions']['submit']['#submit'][] = 'my_module_email_course_link_submit';

Then add your function to my_module.module:
/**
 * Submit callback to  process and save email_course_link form elements.
 */
function my_module_email_course_link_submit(array $form, FormStateInterface $form_state) {
  $entered_body_value = $form_state->getValue('user_mail_course_link_body');
  $entered_subject_value = $form_state->getValue('user_mail_course_link_subject');

  // Save $entered_body_value and $entered_subject_value somewhere.
  // For example, in a database table created by your module, or
  // in a config object created by your module.
  // Where and how you save it is up to you.
}

You will also have to add use Drupal\Core\Form\FormStateInterface; at the top of my_module.module.
When you look at AccountSettingsForm you will see the user module saves form elements in the user.settings and user.mail configs. DON'T use those configs to store your custom data - define your own custom config if you want to store your own custom data in a configuration object.


Prove that $\triangle ABC$ is equilateral, If $(a+b-c)^{a}\cdot (b+c-a)^{b}\cdot (c+a-b)^{c}\geq a^a\cdot b^b\cdot c^c$

Question:
If $a,b,c$ are the sides of a $\triangle ABC\;,$ such that $$\left(1+\frac{b-c}{a}\right)^{a}\left(1+\frac{c-a}{b}\right)^{b}\left(1+\frac{a-b}{c}\right)^{c}\geq 1,$$
then proving $\triangle$ is equilateral.

$\bf{My\; Try::}$ We can write it as $$\left(1+\frac{b-c}{a}\right)^{a}\left(1+\frac{c-a}{b}\right)^{b}\left(1+\frac{a-b}{c}\right)^{c}\geq 1$$
So $$\left(\frac{a+b-c}{a}\right)^{a}\cdot \left(\frac{b+c-a}{b}\right)^{b}\cdot \left(\frac{c+a-b}{c}\right)^{c}\geq 1$$
So $$(a+b-c)^{a}\cdot (b+c-a)^{b}\cdot (c+a-b)^{c}\geq a^a\cdot b^b\cdot c^c$$
Now how can i solve after that, Help required, Thanks
Comment: Did you mean inequality hold if and only if equilateral?
Comment: Yes Chug Tak....
Answer: The title's inequality is wrong. I'll prove a reversed inequality.
Let $a=y+z$, $b=x+z$ and $c=x+y$.
Since our inequality does not changed after substitution $a\rightarrow ka$...,
we can assume that $x+y+z=3$.
And we need to prove that $\sum\limits_{cyc}(3-x)\ln\frac{2x}{3-x}\leq0$ or
$\sum\limits_{cyc}\left(3(x-1)-(3-x)\ln\frac{2x}{3-x}\right)\geq0$, which is true because
$3(x-1)-(3-x)\ln\frac{2x}{3-x}\geq0$ is true for all $x\in(0,3)$.
The equality occurs for $x=y=z=1$.
Thus, $a=b=c$ and we are done!
Maybe you mean the following problem.

If $a,b,c$ are the sides of a $\triangle ABC\;,$ such that $$\left(1+\frac{b-c}{a}\right)^{a}\left(1+\frac{c-a}{b}\right)^{b}\left(1+\frac{a-b}{c}\right)^{c}\geq 1,$$
then proving $\triangle$ is equilateral.

Let $a+b+c=1$.
Hence, by Jensen $a\ln\left(1+\frac{b-c}{a}\right)\leq\ln\sum\limits_{cyc}(a+b-c)=1$.
Thus, $\left(1+\frac{b-c}{a}\right)^{a}\left(1+\frac{c-a}{b}\right)^{b}\left(1+\frac{a-b}{c}\right)^{c}\leq 1$ and with the given we obtain $a=b=c$.
Answer: I will prove $a^a\cdot b^b\cdot c^c \geq (a+b-c)^{c}\cdot (b+c-a)^{b}\cdot (c+a-b)^{b}$
Let $a+b-c=2z,\ b+c-a=2x,\ a+c-b=2y$. Without losing generality, assume $x \geq y \geq z$. Now, we need prove
$$\prod \left(x+y\right)^{(x+y)} \geq \prod \left(2z\right)^{(x+y)}$$
$$\prod \left(\frac{x+y}{2z}\right)^{(x+y)} \geq 1$$
$$\prod \left(\frac{x+y}{y}\right)^x \left(\frac{x+y}{x}\right)^y \geq 4^{x+y+z}$$
$$\prod \left(\frac{y+x}{2y}\right)^x \left(\frac{x+y}{2x}\right)^y \geq 1$$
Applying Cauchy theorem for left side,
$$\prod \left(\frac{y+x}{2y}\right)^x \left(\frac{x+y}{2x}\right)^y \geq \prod \left(\frac{x}{y}\right)^{x/2} \left(\frac{y}{x}\right)^{y/2} = A$$
After simplifying $A$, we get
$$A = \left(\frac{x}{y}\right)^{\frac{x-y}{2}} \left(\frac{y}{z}\right)^{\frac{y-z}{2}} \left(\frac{x}{z}\right)^{\frac{x-z}{2}} \geq 1$$
Hence the given inequality holds iff $a=b=c$.
Comment: Where the first product $\prod \left(\frac{x+y}{2z}\right)^{(x+y) }$ come from?
Comment: Thanks Alex Silva, I hope the fixed version will be better :D
Answer: Another solution:
Prove: $$\left ( a+ b- c \right )^{a}\left ( b+ c- a \right )^{b}\left ( c+ a- b \right )^{c}\leq a^{a}b^{b}c^{c}$$
By weight power mean:
$$\sqrt[a+ b+ c]{\left ( \frac{a+ b- c}{a} \right )^{a}\left ( \frac{b+ c- a}{b} \right )^{b}\left ( \frac{c+ a- b}{c} \right )^{c}}\leq  \frac{1}{a+ b+ c}\left ( a. \frac{a+ b- c}{a}+ b. \frac{b+ c- a}{b}+ c. \frac{c+ a- b}{c} \right )= 1$$
i.e.


Reference request: general Turan density upper bounds

Question: One problem I have encountered while doing research is that I find it difficult to find papers that were published decades ago. In particular, I am interested in
"Extension of a theorem of Moon and Moser on complete subgraphs" - de Caen, 1983
and the proof of the result that the Turan density upper bound for complete r-graphs is $1 - \frac{1}{r}$. I believe this result was also proved by Sidorenko (and I vaguely remember seeing somewhere that two Japanese mathematicians had also proven this result, all of them around the early 1980s).
Over time, many results in Turan density upper bounds have referenced this but I cannot find it online. I should mention that I am a college student (in case it helps any with finding this paper).
Answer: Some papers you may find of interest regarding upper and lower bounds of Turán Densities of complete k-uniform hypergraphs:
Sidorenko A. (1995), "What we know and what we do not know about Turán numbers", Graphs and Combinatorics, 11 (2): 179–199, doi:10.1007/BF01929486
Sidorenko A. (1997), Upper Bounds for Turán Numbers, journal of combinatorial theory, Series A 77, 134-147
Some more recent results:
An excellent and comprehensive survey on the subject:
Keevash P. (2011), Hypergraph Turán problems, Surveys in combinatorics 392: 83-140.
New upper bound on the Turan density of the 4-uniform K_5:
Markström K. (2009), Extremal hypergraphs and bounds for the Turan density of the 4-uniform K-5,  Discrete Mathematics, Vol. 309, no 16, p. 5231-5234, DOI: 10.1016/J.Disc.2009.03.035
New lower bound on the Turan density of the 4-uniform K_6:
Montecalvo F. (2014), Asymptotic Bounds for General Covering Designs, J. Combin. Designs 23: 18–44, DOI 10.1002/jcd.21401


reLoad External Page onLinkClick via ajax and jquery

Question: This is the link
Reload

I want to click it and load an external file via ajax and jquery. In my page header, i have following javascript code.

I want to reload captcha.php on click of that link. Onpageload the file captcha.php is loading in id #captcha - but on that link click its not reloading.
captcha.php code
<?php
$capt = generate_captcha();
echo '<input type="hidden" name="captchacode" id="captchacode" value="'.$capt.'" />';

function generate_captcha()
    {
        $number= rand(11111, 99999);
        $width = 110;
        $height= 35;
        //create image using imagecreate php function
        $img = imagecreate($width, $height);
            $backcolor = imagecolorallocatealpha(
                      $img,
                      hexdec( substr( 'FFFFFF', 0, 2 ) ),
                      hexdec( substr( 'FFFFFF', 2, 2 ) ),
                      hexdec( substr( 'FFFFFF', 4, 2 ) ),
                      127 * ( 100 - 100 ) / 100
                    );
        imagefill($img, 0, 0, $backcolor);
            //create line color
        $linescolor = imagecolorallocatealpha(
                      $img,
                      hexdec( substr( '333333', 0, 2 ) ),
                      hexdec( substr( '333333', 2, 2 ) ),
                      hexdec( substr( '333333', 4, 2 ) ),
                      127 * ( 100 - 70 ) / 100
                    );
        //generate different lines
        for( $i=0; $i<10; $i++ ) {
            imageline($img, mt_rand(0,110), mt_rand(0,35),
             mt_rand(0,110), mt_rand(0,35), $linescolor);
            }
        //Font file path
        $font_path = "jokerman.ttf";
        //create color for font
        $font_color = imagecolorallocatealpha(
                      $img,
                      hexdec( substr( '000000', 0, 2 ) ),
                      hexdec( substr( '000000', 2, 2 ) ),
                      hexdec( substr( '000000', 4, 2 ) ),
                      127 * ( 100 - 100 ) / 100
                    );
        //add characters to the image
        imagettftext($img, 22, 0, 5, 28, $font_color, $font_path, $number);
        //store image
        imagejpeg($img, "captcha.jpg", 100);
        return $number;
    }
?>

UPDATE: chrome is showing updated image, firefox and ie are not updating image. cache problem. I have used no cache via php header but no luck.
Please advise.
Comment: I think your problem sits elsewhere...
Comment: Yes, I believe so. I am able to load file, but i am not able to reload it via a link by using same function.
Comment: Can you provide us the code from your captcha.php?
Comment: Yes. Thanks. captcha.php code added.
Comment: **UPDATE:** The captcha image is changing, but the changed image is not displaying. On reload > old image stays there, but if i validate that, it validates invalid because it has changed...it is just not refreshing. How to refresh it when I click reload.
Comment: Only firefox is not updating image. Image is changing and recreating by script but firefox is showing old version.
Answer: Use onclick instead of href="javascript:loadCaptcha();"
Reload

OR
Reload

Comment: try to bind click event by jquery
Comment: Tried this one, now...still not reloading.
Answer: IE and Firefox won't refresh captcha image due to cache problem. Work around is to delete the captcha image everytime and create new captcha image with unique name. Because name will be unique, captcha will be refreshed and FF will reload the image because its new.
I have fixed this issue with recreating unique captcha image everytime and calling that unique image on reload.


Power bi tachometer visualizing the last value

Question: I send a json with random temperature to Power BI:
[
{
"CPU_Temp" :"12",
"CPU_TempMin" :0,
"CPU_TempMax" :100,
}
]

Then I want to display current CPU data in tachometer (custom Power BI visual)
I use CPU_TempMin for "Start Value", CPU_TempMax for "End Value", CPU_Temp for "Value".
I convert CPU_Temp to a string before sending it to get rid of aggregation on Power BI end (I don't need SUM, AVG etc) but it doesn't have an option for "Don't summarize".
I've checked all the gauges and neither of them has such an option.
Comment: Are you loading in a single row table with those values in three columns?
Answer: Well,
I found the way to "avoid" aggregating functions.
Set all the values that you use(Start Value, End Value, Target Value etc) to AVG (average)
I need to add filter: drag into filters the CPU_Temp field
Than select Top N filter, type '1'
Drag Any Datetime field (you must have it in your JSON) to "By value", select Latest.
Eventually we display Average value calculate from 1 latest value, which is obviously equal to this latest value.


Identifying memory leak in webpack build

Question: I was wondering if someone could point me in the right direction here.
When I run my development server, and some times even the production server the build crashes sporadically saying the javascript heap is out of memory. I've tried attaching a debugger to webpack and as far as I can see it fails on parsing the less-files, but I've also seen it happen running at different stages as well.
I have absolutely no clue how to proceed in fixing this issue, but something tells me I have to fix the issue, as compared to the standard "just increase node's --max-old-space-size". I've already doubled the heap space twice and still experience the error some times. At the moment I've set it to use 8gb of ram, but it still fails.
I've attached a screenshot of debugger from when the debugger halted on a potential out of memory crash. As you probably guessed, I am fairly new to Webpack and would appreciate any hint on how I can get to the root of this problem as it is really impacting my workflow.
webpack.config.js
<code>// Path to the output folder
const rootFolder = "wwwroot";
const bundleFolder = `${rootFolder}/bundle`;

const customers = [
    // ### Removed
];

let entry = {
  load: "./ClientApp/load.ts",
  main: "./ClientApp/main.ts",
};
customers.forEach((e) => {
  entry[e] = `./ClientApp/www_files/${e}/${e}.ts`;
});

module.exports = (env, args) => {
  const devMode = args.mode !== "production";

  return {
    entry: entry,
    output: {
      path: path.resolve(__dirname, bundleFolder),
      publicPath: " ### Removed",
      filename: "[name].js",
      chunkFilename: "[id].[name].[chunkhash].js",
    },
    module: {
      rules: [
        {
          test: /\.vue$/,
          loader: "vue-loader",
        },
        {
          test: /\.js$/,
          loader: "babel-loader",
          query: {
            presets: ["es2015"],
            compact: devMode,
          },
        },
        {
          test: /\.ts?$/,
          use: [
            {
              loader: "awesome-typescript-loader",
            },
          ],
        },
        {
          test: /\.css$/,
          use: [
            devMode ? "vue-style-loader" : MiniCssExtractPlugin.loader,
            "css-loader",
          ],
        },
        {
          test: /\.scss$/,
          use: [
            devMode ? "vue-style-loader" : MiniCssExtractPlugin.loader,
            "css-loader",
            "sass-loader",
          ],
        },
        {
          test: /\.less$/,
          use: [
            devMode ? "vue-style-loader" : MiniCssExtractPlugin.loader,
            "css-loader",
            "less-loader",
          ],
        },
        {
          test: /\.(png|jpg|gif|svg)$/,
          loader: "file-loader",
          options: {
            name: "[name].[ext]?[hash]",
          },
        },
        {
          test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
          loader: "file-loader",
        },
        {
          test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
          loader: "file-loader",
        },
        {
          test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
          loader: "file-loader",
        },
        {
          test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
          loader: "file-loader",
        },
        {
          test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
          loader: "file-loader",
        },
        {
          test: /\.(html)$/,
          use: {
            loader: "html-loader",
            options: {
              attrs: [":data-src"],
            },
          },
        },
        {
          resourceQuery: /blockType=i18n/,
          type: "javascript/auto",
          loader: "@kazupon/vue-i18n-loader",
        },
      ],
    },
    resolve: {
      extensions: [".ts", ".js", ".vue", ".json"],
      alias: {
        vue$: "vue/dist/vue.esm.js",
      },
    },
    devServer: {
      contentBase: bundleFolder,
      // Added because of bug: https://github.com/webpack/webpack-dev-server/issues/1604
      disableHostCheck: true,
      hot: true,
      overlay: true,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods":
          "GET, POST, PUT, DELETE, PATCH, OPTIONS",
        "Access-Control-Allow-Headers":
          "X-Requested-With, content-type, Authorization",
      },
      port: 8080,
    },
    optimization: {
      minimizer: [
        new TerserPlugin(),
        new OptimizeCssAssetsPlugin({}),
      ],
    },
    plugins: [
      new CleanWebpackPlugin([bundleFolder]),
      new webpack.HotModuleReplacementPlugin(),
      new VueLoaderPlugin(),
      new CheckerPlugin(),
      new MiniCssExtractPlugin({
        filename: "[name].css",
        chunkFilename: "[id].[name].[chunkhash].css",
      }),
      new HardSourceWebpackPlugin(),
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ],
  };
};
</code>
Comment: I too have this problem when building for prod mode, in a centos server, with node version 6.x.x
Comment: Have you found a solution ?
Comment: I usually solve this by increasing the RAM allocation for the server on which i am running the webpack build pipeline, these days
Answer: I experience the same issue, although my setup is a bit different.
While I'm not sure how you could exactly debug it, a part of commenting out some not critical parts and see if it's going any better.
What you could try to do is:

If it's not the build for production skip the optimizations you've there in the optimization object.
I assume that your project is quite big, you might want to consider migrating to Vite: https://vitejs.dev/
Vite is supposed to scale very nicely without even adding more time to your build since there's no bundling.

While it might be nice to cut down some resources or time with Webpack, I think it'll be much better to migrate to Vite, the Developer experience would improve a lot, and you could save a lot of time.
We're going to do the same in the short term future.
Good luck :-)


Compute the order of non-unique array elements

Question: I'm looking for an efficient method to compute the "order" of each
item in a numpy array, with "order" defined as the number of
preceding elements equal to the element. Example:
order([4, 2, 3, 2, 6, 4, 4, 6, 2, 4])
[0 0 0 1 0 1 2 1 2 3]

Current solution loops in pure Python and is not fast enough:
def order(A):
    cnt = defaultdict(int)
    O = np.zeros_like(A)
    for i, r in enumerate(A):
        O[i] = cnt[r]
        cnt[r] += 1
    return O

I'm using order to implement scatter:
def scatter(A, c):
    R = A % c
    I = c * order(R) + R
    B = np.full(np.max(I) + 1, -1)
    B[I] = A
    return B

This is useful for multi-threading. For example, if the scattered
array contains addresses to write to then no two threads processing
the array in parallel will see the same address.
Question is are there numpy built-ins that I'm missing that I can use
to make order faster and to remove the explicit looping?
Comment: The numpy way to do [this](https://stackoverflow.com/questions/40602269/how-to-use-numpy-to-get-the-cumulative-count-by-unique-values-in-linear-time) is slower than your code, maybe you can check out [numba](https://numba.pydata.org/) for this.
Answer: Since what you're doing is essentially a Pandas cumcount, and Pandas uses NumPy internally, one idea would be to look at how they implemented cumcount, and do the same thing.
If you read the Pandas code for cumcount, it is internally implemented in this way:

Sort the array, keeping track of where each element came from.
Compare each element of the sorted array to the next element. If it is different, it is the start of a new run. (run)
Work out the length of each group. (rep)
Do a cumulative sum, incrementing by 1 for each element which is not part of a new run. (out)
Track how much each group is affected by groups before it which should not count. (out[run])
Repeat the value to subtract by rep.
Undo the initial sort to put elements back in their original place.

Here's how to do the same thing without relying on any of Pandas.
def order(array):
    # https://github.com/pandas-dev/pandas/blob/v1.3.5/pandas/core/groupby/groupby.py#L1493
    if len(array) == 0:
        return np.array([])
    count = len(array)
    # Can remove 'stable' here to increase speed if you
    # don't care what order the order is assigned in
    ind = np.argsort(array, kind='stable')
    array = array[ind]
    run = np.r_[True, array[:-1] != array[1:]]
    rep = np.diff(np.r_[np.nonzero(run)[0], count])
    out = (~run).cumsum()
    out -= np.repeat(out[run], rep)
    rev = np.empty(count, dtype=np.intp)
    rev[ind] = np.arange(count, dtype=np.intp)
    out = out[rev]
    return out

I find that this is approx 10x faster for arrays 1000 elements and larger.
Comment: Not bad! Though I found that piRSquared's `cumcount` is about 50% faster still: https://stackoverflow.com/a/41558148/189247


How to use jqmath script in angular application?

Question: I'm developing a Quiz application where i want to use jqMath script to display the maths equations. Problem is that there is syntax conflict whenever i use curly braces other than that all equation format are working fine. I have tried interpolation provider but its still the same. How can i solve this. please help!
Uncaught Error: Template parse errors:Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) (" Invalid ICU message. Missing '}'. ("

import {parseMath} from 'jqmath';

export class A{

  @ViewChild('exp') exp:ElementRef;

  func{
    var  exp = this.exp.nativeElement;
    parseMath(exp);
  }

}

$$x={-b±√{b^2-4ac}}/{2a}$$

Comment: You need to provide more input on your question by adding descriptive code.
Comment: @MithunR. i've added it . please have a look.
Answer: I haven't used angular, but it appears that it is triggered by double curly braces. To avoid this, try putting a space between the two braces, i.e. { { for {{, or } } for }}. jqMath will ignore the space inside mathematics.
Comment: I've tried your suggestion but it still the same. I know the problem is caused by angular delimiter "{ }" . If i can change this delimiter to some other symbol this problem might fix . The other way is to change the grouping symbol "{ }" used in jqMath ..
Comment: Ouch. It appears you could use ngNonBindable, or change the angular delimiter as you suggest. You can't change the "{}" characters in jqMath. See https://stackoverflow.com/questions/16868024/how-do-i-escape-curly-braces-for-display-on-page-when-using-angularjs.


iSCSI, multiple initiators for the same LUN

Question: I have a web application that is distributed over 3 servers. These 3 servers need a shared storage to access files. Since iSCSI is just a protocol, not a filesystem, it will not have any implementation of locking files; so if I just connect it as it is, I will just destroy all of the data.
According to my research, I would need an actual filesystem on these LUNs in order to function as I intend to use it.
How would that work? How can I implement a file system for the LUN?
OS Used: Ubuntu 16.* or 18.*
Comment: Hi, We need more information, especially what OS would access it.
Comment: @yagmoth555 sorry, added now. any other information would be useful ?
Answer: You need to have some sort of either a clustered file system or distributed lock manager to avoid metadata damage done to your file system with concurrent writes.
There's a good summary of this issue on StarWind forum.
https://forums.starwindsoftware.com/viewtopic.php?f=5&t=1392
Answer: Generally speaking, you need a cluster in order to share storage between multiple systems (unless you want one of them to act as a file server).
I don't actually know anything about building clusters on Ubuntu, but this looks promising: http://manpages.ubuntu.com/manpages/cosmic/man7/ocfs2.7.html.
Comment: thanks man, thats exactly what i was lookign for
Comment: it solved the problem partially, since ocfs2 allows storage up to 16TB, what would be a solution if my storage needs are about 60-80TB
Answer: So after some research, I came up with few solutions that would be interesting for those who are looking to set up remote storage or a cluster.

Reconsider your network and your needs. One thing that I ran into is setting up an iscsi with cluster-aware file systems is not an easy task. Additionally GFS and OCFS2 do not have well-documented troubleshooting guide available to the public. In the case of OCFS2, you would need to be Oracle's customer and have an active support account. same with GFS2. if you are Centos user, you are stuck with online tutorials and no support for it.
Most likely it is out of your budget anyway. Consider using NFS for hobby-small-medium business. it is much easier to set up, it has plenty of documentation online.
If you really need an iscsi LUN to be shared across multiple machines, then there are 3 solutions available out there. Oracles OCFS2, Red Hat GFS2, VMFS. all 3 are cluster-aware file systems. OCFS2 is simpler to set up but requires you to have access to oracle support which is not free, GFS2 is not as simple as OCFS2 because you would have to manually set up bits of it but it also makes it more customizable. ad VMFS which is cool to use with your ESXI server to keep your VM machines there.

I hope that helps some users in the future when deciding what you actually need for your network and storage. I personally opted for NFS as storage and dedicated iscsi to ESXI server for image booting.


How can I parallelize a for loop for use in PyTorch?

Question: I realize that for loops are slow with Python in general. I have some code that messes around with some tensors:

            for batch_index, mask_batch in enumerate(mask):
                mask_len = torch.sum(mask_batch).int()

                if mask_len == 0:
                    side_input = torch.zeros((max_inp_len, side_input.shape[1])).to(mask.device)
                else:

                    m_nonzero = mask_batch.nonzero().flatten()
                    first_nonzero = m_nonzero[0]
                    last_nonzero = m_nonzero[-1]

                    if side == 'left':
                        end_index = first_nonzero - 1
                        start_index = 0
                    elif side == 'right':
                        start_index = last_nonzero + 1
                        end_index = inputs[batch_index].size(1)

                    side_input = inputs[batch_index][start_index:end_index]

                    if end_index - start_index < max_inp_len:
                        pad_zeros = torch.zeros(
                            (max_inp_len - side_input.shape[0], side_input.shape[1])).to(mask.device)
                        if side == 'left':
                            side_input = torch.cat((pad_zeros, side_input), 0)
                        elif side == 'right':
                            side_input = torch.cat((side_input, pad_zeros), 0)

                side_inputs.append(side_input)

        return torch.stack(side_inputs)

I feel like this loop is REALLY slowing things down. Is there some way for me to do it without the loop?
Comment: Are not the for loop to be "slow"... How can you say that?
Anyway, if you do many slow operation in your loops consider using `threading` or `multiprocessing` libraries.
Comment: If your for-loop consists of iterating through a Tensor, and performing some operations on elements of the tensor, you should try to vectorize the operations.
Comment: Is it possible it's slow because you are accumulating gradients?  What if you put `with torch.no_grad()` in front of all your code?
Answer: Python does not have true parallelism within any given process. You would have to spawn a ProcessPool and make the inside of your loop a function taking batch_index, mask_batch, then map that function over the mask object in your current for loop. Thing is, I don't know if PyTorch will play nicely with this.
Like so
def f(batch_index, mask_batch):
    mask_len = torch.sum(mask_batch).int()

    if mask_len == 0:
        side_input = torch.zeros((max_inp_len, side_input.shape[1])).to(mask.device)
    else:
        m_nonzero = mask_batch.nonzero().flatten()
        first_nonzero = m_nonzero[0]
        last_nonzero = m_nonzero[-1]

        if side == 'left':
            end_index = first_nonzero - 1
            start_index = 0
        elif side == 'right':
            start_index = last_nonzero + 1
            end_index = inputs[batch_index].size(1)

            side_input = inputs[batch_index][start_index:end_index]

            if end_index - start_index < max_inp_len:
                pad_zeros = torch.zeros((max_inp_len - side_input.shape[0], side_input.shape[1])).to(mask.device)
                if side == 'left':
                    side_input = torch.cat((pad_zeros, side_input), 0)
                elif side == 'right':
                    side_input = torch.cat((side_input, pad_zeros), 0)
    return side_input

The other things you can look at are further vectorizing the code. Most things in PyTorch and Numpy can be vectorized away by using builtin functions and adding another dimension onto your tensors that represents the "loop" dimension. This will allow PyTorch to handle the parallelism for you.
PyTorch may have a concept of devices that you can put different iterations of the loop on, again this will require you to make a function for this loop and maybe take the device it goes on as an input.
Lastly you can look into just in time compliation like Numba or torch.jit to perform auto-vectorization for you.
None of this will work (most likely) if the mask is of an unknown length. If it is of a known length, I think vectorization, as hard as it is, is likely your best choice.
Answer: You should create a function containing the logic behind a loop iteration, and launch it as a thread for each column (see docs here). You could also use asyncio library for concurrency but you might probably obtain less improvements.
A good example a spawning a thread for each element of a list can be read here.


Show that there are infinitely many primes of the form $8n+1,8n+3,8n+5,8n+7$

Question: This is the full question

Let $P$ be an odd prime. Prove that if there is an integer $x$ such that,
$$ p\mid x^2+1   \text{ then } p \equiv 1 \pmod 4 $$
$$ p\mid x^2-2   \text{ then } p \equiv 1 \text{ or } 7\pmod 8 $$
$$ p\mid x^2+2   \text{ then } p \equiv 1 \text{ or } 3\pmod 8 $$
$$ p\mid x^4+1   \text{ then } p \equiv 1 \pmod 8 $$
Show that there are infinitely many primes of each of the forms $8n+1,8n+3,8n+5,8n+7$

I was able to show all the above four relations, but i don't understand how these imply that there are infintely many such primes.
Comment: A somewhat surprising fact is that an elementary proof (not invoking complex analysis techniques as in Dirichlet) is available for the infinitude of primes $p$ with $p\equiv a\pmod n$ *if and only if* $a^2\equiv1\pmod n$. With $n=8$ this holds for all odd $a$ covering this question nicely. I collected some links when preparing [this question](https://math.stackexchange.com/q/3214509/11619).
Comment: The key here is that if there are a finite number of primes of any type, you can exclude them from being factors by choosing $x$ carefully. If you also choose an expression which is guaranteed to have at least one prime factor of your target type, you will have found a prime not on the original list.
Comment: The first one should me "if $p\mid x^2+1$ then $p\equiv 1\pmod 4$", the second one should be "if $p\mid x^2-2$ then $p\equiv 1$ or $7\pmod 8$".
Comment: yes you are right @Wojowu, typo corrected
Answer: Say you have $p|x^2+2$ implies $p\in\{1,3\}\bmod 8$.  Now suppose there are only finitely many primes of the form $8n+3$.  Let $\Pi$ be the product of these primes and consider the combination
$M=\Pi^2+2$
None of the primes used to make $\Pi$ can be a factor of $M$ and the actual prime factors of $M$ cannot be all of the form $8n+1$ because $M\equiv 3\bmod 4$.  We are forced to allow more $8n+3$ prime factors, thus the proposed finite set of such primes could not have contained all of them.
Use your other expressions to render similar proofs for the other cases.
Answer: HINT.-All primes are of the form $4n+1$ or $4n+3$ or also of the form $8n+i$ where $i=1,3,5,7$. From your first four propositions you have proved you can deduce easily your four arithmetic progressions.Now you have to apply Dirichlet theorem to each of them.


Export product image with Commerce Cart API module

Question: I'm usng the "Commerce Cart API" module on my website to build a custom cart js layer.
The problem i am facing is the purchased entity has a field_image field and I would like get the url of that images instead of the file id.
The json response of cart?_format=json looks like the following:
<code>    [
  {
    "order_id": 9,
    "uuid": "a4604a10-f956-41e7-87f6-0d745b9345a4",
    "order_number": null,
    "store_id": 2,
    "order_items": [
      {
        "order_item_id": 12,
        "uuid": "33bca307-2ee1-4be4-9599-9ecf3604f83c",
        "order_id": 9,
        "purchased_entity": {
          "variation_id": 1181,
          "uuid": "8112b394-5008-4209-85dc-a9deaf5dfea1",
          "type": "default",
          "product_id": 470,
          "sku": "345",
          "title": "Glade Aerosol 330",
          "list_price": {
            "number": "1.000000",
            "currency_code": "ARS",
            "formatted": "ARS 1,00"
          },
          "price": {
            "number": "2.000000",
            "currency_code": "ARS",
            "formatted": "ARS 2,00"
          },
          "resolved_price": {
            "number": "4.000000",
            "currency_code": "ARS",
            "formatted": "ARS 4,00"
          },
          "field_imagenes": [
            122
          ]
</code>
In brief what i'm tring to get is field_imagenes as an array of image urls.
Is there a way to do it?
Thank you in advance!
Answer: It's reasonable for you to move to Commerce API?
That module is based on JSONA:API, therefore you should be able to get the data of relationship entities quite easily, look at include\relationship example on docs.
Plus, the headless system on Drupal mostly prefer json:api, including  commerce itself
Comment: That could be an option. Thanks!


Wordpress - Alterações nos arquivos não são salvas no servidor

Question: Estou alterando site wordpress direto do FTP, os arquivos editados a princípio são salvos, mas alguns minutos depois as alterações feitas são modificadas para o código anterior. Isso tem a ver com permissão do arquivo?
Comment: alguns servidores demoram para atualizar os arquivos por definitivo quando utilizamos FTP, faça a alteração aguarde alguns minutos e veja se a alteração foi concluida.
Comment: @RafaelAcioly durante algum tempo são salvas, mas depois retorna o código como estava antes das alterações.
Comment: as alterações são em arquivos php? tem possibilidade de você estar alterando os arquivos do cache?
Comment: @RicardoMoraleida são arquivos .css e .php baixados do ftp
Comment: @scooby vc tem algum plugin de cache instalado? Em quais pastas estão os arquivos?
Comment: alguns plugins de segurança tb tem um esquema de bloquear alterações diretas em arquivos php
Comment: Às vezes o próprio hosting possui algum mecanismo de cache, como é o caso da Godaddy. Já tive muitos problemas por causa dele mas, não com arquivos css. De qualquer forma, verifique se há algum mecanismo de deploy específico no seu hosting ou forma de limpeza do cache.
Answer: Isso já aconteceu comigo utilizando alguns plugins.
Quando eu editava alguma informação no wordpress, o plugin voltava a configuração original.
Eles fazem isso pois a alteração do mesmo, deve ser feito apenas pelo wordpress. Caso seja feita atualização do plugin, o mesmo continua funcionando com as alterações que você fez pelo wordpress, pois geralmente estão gravadas de forma específica no banco.


Composition types of music

Question: Composition types in Western classical music.
Is it possible for people to recognize the types of composition without the knowledge of the name given for the piece?
Comment: Providing a list, which may or may not be complete, is of very little help to anyone reading it. Vtc.
Comment: I'm not so sure this is all that off topic. Maybe it could be edited for clarity, but I feel that the real question here is not "Can someone give me a list of all the composition types?", but rather "How and why did the composition types develop over time?" which is an excellent, very on topic question if you ask me. Admittedly, my own answer only address the first "off topic" part of the question and I only read into it more after the fact. Honestly, at this point, I would blame my answer for being off topic more than the question itself and I am considering editing my answer to address this.
Comment: Even the individual questions "how and why did the sonata, or concerto, or toccata, develop" are too broad.  Long books have been written about each of these.
Answer:
How many composition types are there?

855, by counting the entries in a contemporary list.
Less jokingly, a list of composition types will teach someone no more about western music than a list of, say, the names of Chinese herbs would teach me about Chinese cuisine.
More useful is to read an introductory textbook about Western classical music, or study a "Music Appreciation 101" course.
Although a general introduction is too broad for this Q & A web site, the books cited at the end of Wikipedia's article are a useful start.
Comment: but this is rather a comment than an answer ;)
Comment: Please try to resist the temptation to answer off-topic questions - it gives people the [unfortunately now correct] impression they can ask anything & get an answer.
Comment: 855 looks like an answer to me. The question is not marked 'off-topic'. .
Comment: 855 was only after A.H.'s valid objection!
Comment: Well, I am really grateful for the comment you've posted, but I was not asking about "genre".
Answer: Instead of "composition types" I would call these forms, or styles or even (in more modern terminology) genres. Since these are really just classifications or categories, there are literally infinite possibilities, so it's impossible to put an exact number on it.
Here are the most common ones that I can think of:
Auria
Ballade
Canon
Caprice
Concerto
Etude
Fugue
Impromptu
Nocturne
March
Mass
Minuet
Opera
Oratorio
Polonaise
Prelude
Rhapsody
Requiem
Scherzo
Sonata
Sonatina
Suite
Symphony
Toccata
Waltz
Comment: Please try to resist the temptation to answer off-topic questions - it gives people the [unfortunately now correct] impression they can ask anything & get an answer.
Comment: and all the inventions that haven't been invented yet ...

Composition types of music


Current date in Oracle Db

Question: Date        Bus value
2014-02-05  1   10
2014-02-06  1   15
2014-02-07  1   16
2014-02-08  2   20
2014-02-09  2   17
2014-02-10  2   19

I have the above records already entered in a table in my database, say yesterday. I want to show the record based on sysdate. e.g. if today is 2014-02-05 show:
Date        Bus value
2014-02-05  1   10

Then, tomorrow show:
2014-02-06  1   15

Comment: You already know about `sysdate`, so what problem are you having?
Comment: -1 Are you asking people to write the code for you? This is not a valid SO question.
Answer: Try this:
SELECT "DATE", BUS, VALUE
FROM {your_table}
WHERE "DATE" >= trunc(sysdate) and "DATE" < trunc(sysdate+1)

Comment: the sysdate bit goes in the WHERE clause not the select list.

Current date in Oracle Db


Vue.js error 8:3 error Parsing error: Unexpected keyword 'new'

Question: I have an error in vuex store
error:   8:3  error  Parsing error: Unexpected keyword 'new'.

<code>// Vuex store
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = {
  new Vuex.Store({
    state: {
      count: 0,
    },
    getters: {
      increment: (state) => {
        state.count += 1;
      },
    },
  });
}</code>
Comment: Remove the curlies. `store = new …`
Answer: Try this, remove brackets and use syntax mentioned here
<code>// Vuex store
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store =
  new Vuex.Store({
    state: {
      count: 0,
    },
    getters: {
      increment: (state) => {
        state.count += 1;
      },
    },
  });
</code>