text:
Q: Turn GPS on programmatically like Ola Cabs Android app I am working on an application and need to integrate GPS location. I want to switch the GPS on programmatically. The condition is: I don't want to send the user to the Setting panel to enable it. I want to enable it forcefully or a single prompt will work (similar to the Ola Cabs Android app). A lot of questions are for this on this site but everyone is looking for the similar functionality like Ola Cabs app. So I have started this thread so that it can be clear for all of us.

A: Check the code below. Firstly, it will check if location is enabled or not and will prompt user to enable the location.
private GoogleApiClient googleApiClient;

final static int REQUEST_LOCATION = 199;

// check whether gps is enabled
public boolean noLocation() {
        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            //  buildAlertMessageNoGps();

            enableLoc();
            return true;
        }
        return false;

    }

 private void enableLoc() {

if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult connectionResult) {

                            Timber.v("Location error " + connectionResult.getErrorCode());
                        }
                    }).build();
            googleApiClient.connect();

            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

            builder.setAlwaysShow(true);

            PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(
                                        (Activity) context, REQUEST_LOCATION);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                    }
                }
            });
        }

        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REQUEST_LOCATION:
                switch (resultCode) {
                    case Activity.RESULT_CANCELED: {
                        // The user was asked to change settings, but chose not to
                        finish();
                        break;
                    }
                    default: {
                        break;
                    }
                }
                break;
        }

    }

}

A: Here is my 100% working code first add this dependencie compile 'com.google.android.gms:play-services:9.2.1' to your build.gradle(Module: app)
After that create class with name StartLocationAlert.java and copy this code and paste in this file
import android.app.Activity;
import android.content.IntentSender;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.example.googlemappromt.MainActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;

/**
 * Created by Anirudh on 20/07/16.
 */
public class StartLocationAlert implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener  {
    Activity context;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;
    GoogleApiClient googleApiClient;
    public StartLocationAlert(Activity context) {
        this.context = context;
        googleApiClient = getInstance();
        if(googleApiClient != null){
            //googleApiClient.connect();
            settingsrequest();
            googleApiClient.connect();
        }
    }

    public  GoogleApiClient getInstance(){
        GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        return mGoogleApiClient;
    }

    public void settingsrequest()
    {
        Log.e("settingsrequest","Comes");

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.
                       // Log.e("Application","Button Clicked");
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a dialog.
                       // Log.e("Application","Button Clicked1");
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(context, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                            Log.e("Applicationsett",e.toString());
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.
                        //Log.e("Application","Button Clicked2");
                        Toast.makeText(context, "Location is Enabled", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

    /*    MainActivity mm = new MainActivity();
        mm.requestLocationUpdates();*/
        Toast.makeText(context , "Connected", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }
}

Usage of this above class is show below
 @Override
    protected void onResume() {
        super.onResume();
        Activity mContext = MainActivity.this //change this your activity name
        StartLocationAlert startLocationAlert = new StartLocationAlert(mContext);

       requestLocationUpdates();

    }

And don't forget to add below permissions in AndroidManifest.xml file or else this might not work properly
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Hope this might help you..

A: I've created a library based on Anirudh answer.
Short guide how to use it:

*

*Add it to you build.gradle file:
compile 'net.alexandroid.utils:gps:1.6'

*Implement GpsStatusDetectorCallBack interface.

*Implement interface methods: onGpsSettingStatus and onGpsAlertCanceledByUser

*Create instance variable:
private GpsStatusDetector mGpsStatusDetector;

*Instantiate it in onCreate():
 mGpsStatusDetector = new GpsStatusDetector(this);

*In place you need to check the status and show a dialog if need add:
mGpsStatusDetector.checkGpsStatus();

*Override onActivityResult and add there:
mGpsStatusDetector.checkOnActivityResult(requestCode, resultCode);

More information about the library: https://github.com/Pulimet/GpsDetector-Library

Example:
public class MainActivity extends AppCompatActivity implements GpsStatusDetector.GpsStatusDetectorCallBack {

    private GpsStatusDetector mGpsStatusDetector;

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

        mGpsStatusDetector = new GpsStatusDetector(this);
        mGpsStatusDetector.checkLocationSettingStatus();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mGpsStatusDetector.checkOnActivityResult(requestCode, resultCode);
    }

    @Override
    public void onGpsSettingStatus(boolean enabled) {
        Log.d("TAG", "onGpsSettingStatus: " + enabled);
    }

    @Override
    public void onGpsAlertCanceledByUser() {
        Log.d("TAG", "onGpsAlertCanceledByUser");
    }
}

A: Since SettingsApi is deprecated and after checking into the developer site here. I was able to achive the same result as Ola app.
Add the below method in your Activity class
private void switchOnGPS() {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY));

    Task<LocationSettingsResponse> task = LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
    task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
        @Override
        public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
            try {
                LocationSettingsResponse response = task.getResult(ApiException.class);
            } catch (ApiException e) {
                switch (e.getStatusCode())
                {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED :
                        ResolvableApiException   resolvableApiException = (ResolvableApiException) e;
                        try {
                            resolvableApiException.startResolutionForResult(MainActivity.this,REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e1) {
                            e1.printStackTrace();
                        }
                        break;

                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            //open setting and switch on GPS manually
                            break;
                }
            }
        }
    });
    //Give permission to access GPS
    ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 11);
}

Call the above method in your Activity's onResume method like below
@Override
protected void onResume() {
    super.onResume();
    switchOnGPS();
}

Add respective Location permission in Manifest file.

A: Here I have user this code
private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3"));
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3"));
        sendBroadcast(poke);
    }
    }

Permissions in your manifest file:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

A: package com.example.user.myGPS;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.IntentSender;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.PendingResult;
    import com.google.android.gms.common.api.ResultCallback;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.location.LocationSettingsRequest;
    import com.google.android.gms.location.LocationSettingsResult;
    import com.google.android.gms.location.LocationSettingsStates;
    import com.google.android.gms.location.LocationSettingsStatusCodes;

public class MainActivity extends AppCompatActivity {

    private GoogleApiClient googleApiClient;
    final int REQUEST_CHECK_SETTINGS = 0x1;

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

        //-------Code to turn on GPS------------------
        if (googleApiClient == null) {

            googleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                    .addApi(LocationServices.API).build();
            googleApiClient.connect();
            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
            builder.setAlwaysShow(true);
            builder.setNeedBle(true);

            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final com.google.android.gms.common.api.Status status = result.getStatus();
                    final LocationSettingsStates state = result.getLocationSettingsStates();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try
                            {
                                status.startResolutionForResult(MainActivity.this,REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException e) {}
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            break;
                    }
                }
            });

        }

    }

}


text:
Q: How can I hide my App tag on a post I created on facebook I've created a facebook app from which anyone can post to his wall or his friend's wall. But at that post at the bottom the post it displays the app hyperlink. But want to remove it so that it should look like the user create it himself and not by my app.
Is there any way to do so. I use faecbook graph api with Javascript sdk.
Please help me out.

A: First: Posting to the wall of a friend is highly spammy and should be avoided as much as possible. With the PHP SDK it´s not even possible anymore afaik, or will be removed very soon because it is deprecated. The only way is to use the FB.ui feed dialog of the JavaScript SDK:
https://developers.facebook.com/docs/reference/dialogs/feed/
That being said, there is no way to remove the App Link. Postings made through an App always have to be easily identifiable. It may be possible that posting via the PHP SDK does not show the App Link, but as i said: that function is deprecated for spam reasons and should not be used anymore.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eloquent query get both tables using Find() I am trying to get all columns from 2 tables using eloquent.
So far I can only get the info from one.
This are my 2 models :
Clase model
public function courses() {
    return $this->hasMany('Course');
}

A class has many courses
Course Model
 public function clase() {
    return $this->belongsTo('Clase','Clase_id');
}

The Course table has Clase_id to link them
If I run this query
Clase::find(2)->courses;

It searches courses table clase_id = 2 and returns all columns
But how do I get the clase columns too??
Update
If I run this :
$values = course::with('clase')->find(3);

I get this array :
{"id":3,"course":"Essay June","desc":"English Essay for potentiL KD DK NVER ","points":10,"Clase_id":2,"active":0,"clase":{"id":2,"Year":"1","Name":"English","user_id":1}}

So Clase_id = 2 and Clase.id = 2 ,they are linked.
But my query searches for Courses.id and it needs to search Clase_id.

A: Try this:
Clase::find(2)->courses()->get();

OR
Clase::where('id', '=', 2)->courses()->get();

Let me know if that does the trick.
In hindsight... I suppose this does exactly the same thing as OP's query now doesn't it. Misread the question. Should be like so:
$clases = Clase::find(2)->courses();

Then read the courses/clases as usual:
foreach($clases AS $clase){
  echo $clase->column_name;
}

A: You already did, just use it;
$clase = Clase::find(2);

$courses = $clase->courses;

If you want all columns together for some reason, then use joins, but I doubt you really do.


text:
Q: When I use While Loop my Code no Longer works import pyautogui
import pydirectinput
import time

x = 1
while x <190:
 for number in range(190):
  time.sleep(0.1)
  pyautogui.click(480, 595)
  x = x+1
  if x == 190:

   pydirectinput.keyDown('shiftleft')
   time.sleep(2.5)
   pydirectinput.keyUp('shiftleft')
   x = 1

When I run this all it does is repeat the first code and does not activate the second code I am a newb at coding so I don't know why this is happening. It just activates the 2nd "x = 1" instead of doing the code above it first then resetting the loop.
I want the code to run indefinitely but run both codes instead of only the click code
What should I put in after "if x == 190:"

A: A while loop executes the code inside its body as long as its condition evaluates to true. Your condition is whether x is equal to 1 or not.
You initialize x to 1, but you never change its value in your while loop's body. So, the condition is always true, and you have an infinite loop.
You need to modify the value of x inside your while loop to break out of the loop.

A: import pydirectinput
import time

x = 1
while x == 1:
 for number in range(190):
  time.sleep(0.1)
  pyautogui.click(480, 595)

 pydirectinput.keyDown('shiftleft')
 time.sleep(2.5)
 pydirectinput.keyUp('shiftleft') ```


text:
Q: Using SugarCRM for free of cost and do the necessary changes I want to use SugarCRM  (I downloaded the free source code) for my client and do the necessary changes wherever required.
  In their domain they mentioned like we need to purchase the software. I am not sure why to purchase when we get the free source code from them and can do the changes.

A: There are several SugarCRM editions, see http://www.sugarcrm.com/crm/products/editions.html
If you don't need the professional features or support from the devs, you don't need to buy it.

A:
Sugar Community Edition is licensed under version 3 of the AGPL. Sugar Professional Edition and Enterprise Edition are distributed under a commercial license.

Source
AGPL 3 is a free software license (See the four freedoms/The Free Software Definition). You don't need to pay royalties to the licensor for making changes to the software if you could already acquired the code.
However, Sugar CRM does offer a free trial for Sugar Pro which is not licensed under AGPL but under a commercial license that might have restrictions for making changes to the software.

A: You can also follow Open Source SugarCRM version on github: https://github.com/sugarcrm/sugarcrm_dev
You can fork it and contribute back if you want to.


text:
Q: Change UIImage depending on transaction status import UIKit

class TransactionTableViewCell: UITableViewCell {

@IBOutlet weak var name: UILabel!
@IBOutlet weak var price: UILabel!
@IBOutlet weak var status: UIImageView!

let transactionStatus = DataManager.shared.transactionController.transactions

override func awakeFromNib() {
    super.awakeFromNib()

}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    Status()

}

func Status() {
    let arr = transactionStatus.compactMap { $0 }
    for i in 0..<arr.count {
        if arr[i].status == "returned" {
            status.image = UIImage(assetIdentifier: .statusReturned)
        } else if arr[i].status == "pending" {
            status.image = UIImage(assetIdentifier: .statusPending)
        } else if arr[i].status == "cleared" {
            status.image = UIImage(assetIdentifier: .statusCleared)
        } else {
            print("\(String(describing: arr[i].status)) + no matched ")
        }
}

extension UIImage {
  enum AssetIdentifier: String {
      // Status image names
      case statusPending, statusCleared, statusReturned
    }

    convenience init!(assetIdentifier: AssetIdentifier) {
      self.init(named: assetIdentifier.rawValue)
  }
}

Hi, so I have a question, I wrote a function that changes the status icon of the transaction depending on the status(String i receive from db), but it changes the icons of all transactions at once depending on the status of the last transaction received, such as if the last status was "returned" then everyone will have a status icon returned
I wonder why it works like that, so the question is how to make each icon change separately and not all at once
what i got
what i want
Please pay attention to icons on the left side of the screen


text:
Q: Embedded Document in symfony2 / MongoDB I know how to store a simple Product Object in mongodb using symfony2:
This YAML file :
Acme\StoreBundle\Document\Product:
    fields:
        id:
            id:  true
        name:
            type: string
        price:
            type: float

Will produce this collection :
{
"_id" : ObjectId("..."),
"name" : "...",
"price" : "..."
}

But now, I would like to know how to write something generating a structure like that :
{
"_id" : ObjectId("..."),
"name" : "...",
"price" :
   {
     "before" : "...",
     "after" : "..."
   }
}

Any idea or documentation link ?

A: You can use an embed document. http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/tutorials/getting-started.html

Acme\StoreBundle\Document\Product:
    fields:
        id:
            id:  true
        name:
            type: string
        referenceOne:
            price:
               targetDocument: Acme\StoreBundle\Documents\price
               cascade: all

Acme\StoreBundle\Documents\price:
    fields:
        before:
            type: float
        after:
            type: float


text:
Q: Problem with german umlauts in csv file when i write from php Greeting
I have a problem when I want to use the php script to enter data from the database into the csv file. It prints everything right in the database, but when it prints to the csv file, then it comes to a character error, i.e. does not print them well.
Examples of errors ö, ä, ü ... and what I need ä, ö, ü ....
If I can print somehow to the csv file the way it is in the database?
My code:
<?php

require_once 'connections.php';

$query = "SELECT Artikelnummer_im_Shop, EAN_GTIN_Barcodenummer_UPC,
 Herstellerartikelnummern_HAN_MPN, Hersteller_Markenname,
 Produktname,Preis_Brutto, Lieferzeit, Produktbeschreibung, ProduktURL,
 BildURL_1, Versandkosten, Vorkasse, Paydirekt, Paypal,
 Kreditkartenzahlung_uber_BS_PAYONE_GmbH, Versandkosten_Kommentar
FROM app_table";

$result = mysqli_query($connect, $query) or die("database error:".
mysqli_error($connect));

$file   = "inko-table.csv";
// Delete file if exist
unlink($file);
// Write to the file or create if not exist
$f      = fopen($file, 'w'); // Open in write mode ('w' will overwrite everything everytime)

$table      = "app_table";
$sql        = mysqli_query($connect, "SELECT * FROM $table");
$num_rows   = mysqli_num_rows($sql);
$products   = mysqli_fetch_array($sql);
// Writing data in file var $file

$i = 1;
while($row = mysqli_fetch_array($sql)) {

  $nameComma                  = $row['Produktname'];
    $name                       = str_replace(",", "", $nameComma);
    $pzn                        = $row['EAN_GTIN_Barcodenummer_UPC'];
    $url                        = $row['ProduktURL'];
    $brand                      = $row['Hersteller_Markenname'];
  $priceComma                 = $row['Preis_Brutto'];
    $price                      = str_replace(",", ".", $priceComma);
    $Artikelnummer              = $row['Artikelnummer_im_Shop'];
  $ProduktbeschreibungComma   = $row['Produktbeschreibung'];
    $Produktbeschreibung        = str_replace(",", "", $ProduktbeschreibungComma);
    $Herstellerartikelnummern   = $row['Herstellerartikelnummern_HAN_MPN'];
  $LieferzeitComma            = $row['Lieferzeit'];
    $Lieferzeit                 = str_replace(",", "", $LieferzeitComma);
    $BildURL_1                  = $row['BildURL_1'];
  $VersandkostenComma         = $row['Versandkosten'];
    $Versandkosten              = str_replace(",", ".", $VersandkostenComma);
    $Vorkasse                   = $row['Vorkasse'];
    $Paydirekt                  = $row['Paydirekt'];
    $Paypal                     = $row['Paypal'];
    $Kreditkartenzahlung        = $row['Kreditkartenzahlung_uber_BS_PAYONE_GmbH'];
  $KommentarComma             = $row['Versandkosten_Kommentar'];
    $Kommentar                  = str_replace(",", "", $KommentarComma);

    if ($i==1) {
        $product = "Artikelnummer im Shop".","."EAN / GTIN / Barcodenummer / UPC".","."Herstellerartikelnummern (HAN/MPN)".","."Hersteller / Markenname".","."Produktname".","."Preis (Brutto)".","."Lieferzeit".","."Produktbeschreibung".","."ProduktURL".","."BildURL_1".","."Versandkosten".","."Vorkasse".","."Paydirekt".","."Paypal".","."Kreditkartenzahlung über BS PAYONE GmbH".","."Versandkosten Kommentar"."\n".$Artikelnummer.",".$pzn.",".$Herstellerartikelnummern.",".$brand.",".$name.",".$price.",".$Lieferzeit.",".$Produktbeschreibung.",".$url.",".$BildURL_1.",".$Versandkosten.",".$Vorkasse.",".$Paydirekt.",".$Paypal.",".$Kreditkartenzahlung.",".$Kommentar."\n";
    } else {
        $product = $Artikelnummer.",".$pzn.",".$Herstellerartikelnummern.",".$brand.",".$name.",".$price.",".$Lieferzeit.",".$Produktbeschreibung.",".$url.",".$BildURL_1.",".$Versandkosten.",".$Vorkasse.",".$Paydirekt.",".$Paypal.",".$Kreditkartenzahlung.",".$Kommentar."\n";
    }

    $i++;

    fwrite($f, $product);
}
fclose($f);

?>

A: Try:
string utf8_decode ( string $data );

for example:
$ProduktbeschreibungComma   = utf8_decode ($row['Produktbeschreibung']);

It should return the correct umlauts.
If it is in your csv file. Use utf_decode before output. Try to change the file_encoding of the csv file to utf8.


text:
Q: Trying to understand how this is being called on the UI Thread I am work my way through different open source projects to get a feel for how people approach the same problem in different ways. This time it's Event Aggregators, specifically Caliburn.Micro's one.
I notice that Rob said that if no thread is supplied that the EA will marshal to the UI thread. The line specifically is:
public static Action<System.Action>
DefaultPublicationThreadMarshaller = action => action();

and then further on:
marshal(() =>
         {
           *SNIP*
         });

What I don't understand his how can you say this will be called on the UI thread, are all actions called on the UI thread unless you specify one that is not? (You can specify which action is called btw, the line above is just if no action is supplied).

A: Action can be invoked either in the thread that calls it:
Action a = () => Foo();
a.Invoke();

Or it can be invoked asynchronously
Action a = () => Foo();
a.BeginInvoke();

If the event aggregator is configured to use a synchronous call then it is possible that the event gets handled in the UI thread. However it is very unlikely, and usually an event aggregator uses asynchronous execution and the action is executed in a thread pool.
In the code in question there will be a place, where it (internally and not included here) calls either Invoke or BeginInvoke on the action, this is where the difference is.
N.B. This answer is not specific to any particular event aggregator.


text:
Q: Turn server is requirement for clients which behind of firewall I developed p2p webrtc application which users can video call from web application to mobile application. Web application will run on kiosk and kiosks will be behind firewall. Is it required turn server and all of data relayed by turn server?

A: It doesn't matter where your application is hosted at, what matters is if the clients on the ends of their calls are behind firewalls or other restrictions that restrict p2p and WebRTC, in that case, the data will have to be relayed through TURN servers.
So, no, not all data will be relayed through TURN servers, it depends on the clients' internet environment, but generally TURN servers are a requirement for production applications since there will be a significant amount of situations (about 20% to 30% in average, based on my own experience) where a TURN server is needed for WebRTC to connect.

A: All kiosks will be behind the firewall, so all traffic goes through turn server means high hardware costs. All of the calls will be from kiosks.10-20% of the traffic to pass through, but not 100% of the cost will increase a lot


text:
Q: android java.util.zip.ZipException: duplicate entry I have a project named MyProject.
It includes 2 library projects abc.aar and xyz.aar.
These both library projects uses and have one common jar dummy.jar (package name: com.example.dummy).
When I include both library projects, it gives me
    android java.util.zip.ZipException: duplicate entry com/example/dummy/DummyClass$1.class

I have tried following things -
configurations {
    // to avoid double inclusion
    all*.exclude group: 'com.example.dummy'
}

and this too
compile (name:'abc', ext:'aar'){
    transitive = false
    exclude module: 'libs/dummy*.jar'
    exclude group: 'com.example.dummy'
    exclude module: 'com.example.dummy'
}

Please suggest to avoid double inclusion of dependency jar because of multiple dependency library project using same jar.
My both library projects are not on any repositories.


text:
Q: Spring mvc: One step view or Two Step View? I am reading famous Fauler's book "Enterprise application patterns"
And I can't understand semantic difference between One step view(top part) and Two Step View(bottom part)

I read all text but I understood only one thing:
In case of two step view I have 1 additional intermediate logical view. And this is executed by some global "entity".
It is really not clear for me why do I need it. In my practice I use spring - mvc for web application. Could you explain which pattern is used inside this framework? Could I choose/change it ?

A: Stages responsibility

*

*The first stage translates a model to a logical view - you may think about it as a model described in terms of some universal form (Fowler uses XML for this purpose).

*The second stage is able to read logical view and is responsible for rendering this to rich interface with styles, formatting, and all stuff we love.
The way we get a view
You need to make some HTML having an object of next class:
public class Customer {
    private String name; //value: John Snow
    private String address; //Winterfell
}

On the first stage you translate that customer data into logical view:
<screen>
<title>Customer data</title>
<name>John Snow</name>
<address>Winterfell</address>
</screen>

XML is a good form to be transformed by XSLT, so our second stage is presented by some XSLT that transform our XML to some HTML code and surround it by footer, header, some menu items, etc.
Now we have a scheme: model -> fist stage -> xml -> second stage(XSLT) -> html -> user
What we can do with this
That scheme will let you:

*

*To create some themes for your application. In this example you can use XSLT script as a theme. You change the theme, your application appearance changes as well.

*To make some global changes in your application appearance by changing only one XSLT script.

If you use one-step view, you will have to change every view this case.
It's how Fowler describe this. You might find this interesting because in your edition of the book it might be described in a different way:

Two Step View deals with this problem by splitting the transformation
  into two stages. The first transforms the model data into a logical
  presentation without any specific formatting; the second converts that
  logical presentation with the actual formatting needed. This way you
  can make a global change by altering the second stage, or you can
  support multiple output looks and feels with one second stage each.

How it is related to Spring MVC
Spring MVC implements another pattern - model-view-controller. Our pattern is a view part and we are free to decide what exactltly view technology to use with Spring MVC. If you will find some view framework that implements this pattern, you are free to plug it to Spring MVC.
If you don't know why you need to use two-stage view pattern, probably, you don't. In my expierence I've never seen this implemented in any project I've worked at.
What if we use one step view instead
In this case if we need to make global changes in our application appearance, we have to change every view that generates html for user.
Conclusion
Remember that the book is written about 20 years ago, and nowadays we have a lot of great technologies that didn't exist 20 years ago.


text:
Q: nodemon app crashed - waiting for file changes before starting? PS D:\PROGRAMMING\2077\SHOPIT> npm run dev

> shopit@1.0.0 dev D:\PROGRAMMING\2077\SHOPIT
> SET NODE_ENV=DEVELOPMENT& nodemon backend/server

> [nodemon] 2.0.7
> [nodemon] to restart at any time, enter `rs`
> [nodemon] watching path(s): *.*
> [nodemon] watching extensions: js,mjs,json
> [nodemon] starting `node backend/server.js`
> D:\PROGRAMMING\2077\SHOPIT\backend\routes\product.js:6
> router.routes('/products').get(getProducts);
       ^

> TypeError: router.routes is not a function
>   at Object.<anonymous> (D:\PROGRAMMING\2077\SHOPIT\backend\routes\product.js:6:8)
>   at Module._compile (internal/modules/cjs/loader.js:1063:30)
>   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
>   at Module.load (internal/modules/cjs/loader.js:928:32)
>   at Function.Module._load (internal/modules/cjs/loader.js:769:14)
>   at Module.require (internal/modules/cjs/loader.js:952:19)    at require >(internal/modules/cjs/helpers.js:88:18)
>   at Object.<anonymous> (D:\PROGRAMMING\2077\SHOPIT\backend\app.js:8:18)
>   at Module._compile (internal/modules/cjs/loader.js:1063:30)
>   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
>   [nodemon] app crashed - waiting for file changes before starting...

A: It says why in the error, you are trying to call something, maybe an array/object etc. instead of calling a function.
router.routes = ['/','/api','/ping'];
router.routes(); // ERROR

Check the type of router.routes


text:
Q: Install some parts of the DevExtreme UI component in my project Actually, I am going to use the DevExtreme chart in my angular project.
Is it possible to install just the DevExtreme chart pack instead of the full package in my project?
thank you for your help

A: you can install only DevExtreme chart instead of the full package for that you need to study the documentation of DevExtreme.
Here you can check Support center of devExtreme.
Here is how to Use


text:
Q: Unattend install: "REG ADD" doesn't work I'm trying to execute this commands in OOBE pass on Windows 7 unattend install:
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <AutoLogon>
                <Enabled>true</Enabled>
                <Username>Administrator</Username>
                <Password>
                    <Value>UABhAHMAcwB3AG8AcgBkAA==</Value>
                    <PlainText>false</PlainText>
                </Password>
            </AutoLogon>
            <Display>
                <ColorDepth>32</ColorDepth>
                <DPI>96</DPI>
                <HorizontalResolution>1280</HorizontalResolution>
                <VerticalResolution>800</VerticalResolution>
            </Display>
            <OOBE>
                <HideEULAPage>true</HideEULAPage>
                <NetworkLocation>Other</NetworkLocation>
                <ProtectYourPC>3</ProtectYourPC>
                <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
            </OOBE>
            <TimeZone>Russian Standard Time</TimeZone>
            <UserAccounts>
                <AdministratorPassword>
                    <Value>QQBkAG0AaQBuAGkAcwB0AHIAYQB0AG8AcgBQAGEAcwBzAHcAbwByAGQA</Value>
                    <PlainText>false</PlainText>
                </AdministratorPassword>
                <LocalAccounts>
                    <LocalAccount wcm:action="add">
                        <Password>
                            <Value>UABhAHMAcwB3AG8AcgBkAA==</Value>
                            <PlainText>false</PlainText>
                        </Password>
                        <DisplayName>Admin</DisplayName>
                        <Group>Administrators</Group>
                        <Name>Admin</Name>
                    </LocalAccount>
                </LocalAccounts>
            </UserAccounts>
            <LogonCommands>
                <AsynchronousCommand wcm:action="add">
                    <CommandLine>reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v prog /t REG_SZ /d c:\Myprogram\prog.exe /f</CommandLine>
                    <Order>1</Order>
                </AsynchronousCommand>
                <AsynchronousCommand wcm:action="add">
                    <Order>4</Order>
                    <CommandLine>reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Network\NwCategoryWizard" /v Show /t REG_DWORD /d 00000000 /f</CommandLine>
                </AsynchronousCommand>
                <AsynchronousCommand wcm:action="add">
                    <Order>3</Order>
                    <CommandLine>reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Network\NwCategoryWizard" /v Suppress /t REG_DWORD /d 00000001 /f</CommandLine>
                </AsynchronousCommand>
                <AsynchronousCommand wcm:action="add">
                    <Order>2</Order>
                    <CommandLine>reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v Teamviewer /t REG_SZ /d C:\Program Files\TeamViewer\TeamViewer.exe /f</CommandLine>
                </AsynchronousCommand>
            </LogonCommands>
        </component>

And registry not changed after install completed. Why?
(I also tried to run .cmd file with similar commands and import .reg file, but it doesn't worked.)


text:
Q: How to multiply two numbers in a string I have a string like "1X6TAB". Now I apply some regular expression to this string to remove "TAB" and replacing "X" with "*", so my final string will be "1*6". The expected result is "6", but I get "1*6" as the result.
Code:
Regexonlynumber("1X6TAB");
function Regexonlynumber($number){
    $number = preg_replace("/[^0-9.X]/", '', $number);
    echo str_replace('X',"*",$number);die;
}

A: You are almost there. Just add one step more to explode and multiply, like this:
<?php
    function Regexonlynumber($number){
        $number = preg_replace("/[^0-9.X]/", '', $number);
        $arr = explode("X", $number);
        echo $arr[0]*$arr[1];
    }
    Regexonlynumber("2X6TAB");
?>

Demo.
You can even just do it like:
function Regexonlynumber($number){
    $arr = explode("X", $number);
    echo $arr[0]*$arr[1];
}

Demo.

A: Regexonlynumber() function help you to to get product of numbers from string
array_product() Function :-  The array_product() function calculates and returns the product of an array.
str_split() Function :-  The str_split() function splits a string into an array.
<?php
    function Regexonlynumber($number){
        $number = preg_replace("/[^0-9,.]/", "", $number);
        echo array_product(str_split($number));
    }

    Regexonlynumber("1X6TAB");
?>

A: It's better to use eval(), which will also be able to compute more complex expressions:
Regexonlynumber("3X6-13TAB");
function Regexonlynumber($number){
    $number = preg_replace("/[^0-9.X\-\+\/]/", '', $number);
    $str = str_replace('X',"*",$number);
    eval("\$result = {$str};");
    echo $str . " = " . $result . "\n";
}

A: Instead of str_replace(), you can explode() it by 'X' delimiter, then use array_product().
Regexonlynumber("1X6TAB");
function Regexonlynumber($number){
    $number = preg_replace("/[^0-9.X]/", '', $number);
    echo array_product(explode('X', $number));
}


text:
Q: Unit testing in Angular This is my first time testing in Angular and my first day at a new job. I am trying to write a test to see that the MainCtrl.lables contains something (or ideally get the values from dataRepository)
Does anyone know how to do this or know any good resources for angular testing for controllers that require a service? Im having trouble finding good information for how to use mocks.
MainCtrl.js
var app = angular.module("ChartApp", ["chart.js"]);

    app.controller("MainCtrl", ["$scope",
      function ($scope, dataRepository) {
          $scope.labels = dataRepository.labels;
          $scope.data = dataRepository.data;
          $scope.type = dataRepository.type;
          $scope.title = dataRepository.title;
      }
    ]);

DataSrv.js
angular.module("ChartApp")
    .factory('dataRepository', function () {
        return {
            labels: ["Reading", "Coding", "Thinking About Coding", "Reddit", "StackOverflow"],
            data: [500, 300, 300, 40, 220],
            type: 'PolarArea',
            title: "Angular Chart Expriment"
        };
    });

MainCtrlSpec.js
/// <reference path="../../Scripts/angular/angular.js" />
/// <reference path="../../Scripts/angular/angular-mocks.js" />
/// <reference path="../../Scripts/chartjs/Chart.js" />
/// <reference path="../../Scripts/angular-chart.js-master/dist/angular-chart.js" />
/// <reference path="../../Scripts/controller/main-controller.js" />
/// <reference path="../../Scripts/service/data-service.js" />
/// <reference path="../../libs/jasmine/jasmine.js" />

describe("Controller: MainCtrl", function () {
    beforeEach(module("ChartApp"));

    var ctrl, scope;

    beforeEach(inject(function ($controller) {
        scope = {};
        ctrl = $controller("MainCtrl" });
    }));

    it("should have scope defined", function () {
        expect(MainCtrl.lables).toBeDefined();
    });
});

A: If you want to test the service then you should write a test for that service, not for the controller. But if you want to test it in the controller you can do it like so:
describe('Controller: NewCtrl', function () {
var NewCtrl, scope;
    beforeEach(module('myApp'));
    beforeEach(inject(function (_myService_, $controller, $injector, $rootScope) {
    var scope = $rootScope.$new();
    ...
        NewCtrl = $controller('NewCtrl', {
                    $scope: scope, // here you specify the custom mocked value you wish to set for the injected service
        });
    ...

  });
 it('should have labels defined', function(){
         expect(scope.labels).toBeDefined();
        });
    ...
    });

And in your controller, you would have to do something like:
$scope.labels = dataRepository.labels;
I also suggest using Karma runner since it has lots of great addons like:

*

*karma-coverage

*karma-phantomjs launcher
And also, if you're using a modern IDE it will probably integrate well with your workflow ;)
A very good resource to get started with unit testing controller is this one since it also dives into $httpBackend which is a very important tool when using $resource or $http in your code.


text:
Q: Using Eval() in body I have Football Leagues site and I want to change my background with admin panel but my background in my master page's body section like

    <form id="form1" runat="server">

        <uc1:Header runat="server" ID="Header" />

            <uc1:Menu runat="server" ID="Menu" />

                LİGLER

                <asp:DataList ID="DataList1" runat="server" Width="200px">
                    <ItemTemplate>

                          <a href="LigDetay.aspx?LigId=<%# Eval("LigId") %>" class="a">
                            <asp:Label ID="Label1" runat="server" CssClass="auto-style80" Text='<%# Eval("LigAd") %>'></asp:Label>

                             (
                            <asp:Label ID="Label2" runat="server" Text='<%# Eval("LigAdet") %>'></asp:Label>
                            )

                    </ItemTemplate>
                </asp:DataList>

                <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>

        <uc1:Footer runat="server" ID="Footer" />
    </form>

and I want to get that background with my database. I tried
ImageUrl='<%# Eval("ArkaplanImg") %>'

instead of
style="background-image:url('images/Arkaplanlar/Webp.net-resizeimage1.png')"

but i keep getting Validation (HTML5): Attribute 'ImageUrl' is not a valid attribute of element 'body'.


text:
Q: ng serve gives un expected errors I am running the ng serve command , and it is giving unexpected errors.
the errors are:
PS C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend> ng serveYour global Angular CLI version (13.0.3) is greater than your local version (10.1.6). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".
[Browserslist] Could not parse C:\Users\SAYED-SADAT\Desktop\package.json. Ignoring it.
10% building 3/3 modules 0 active(node:14892) [DEP0111] DeprecationWarning: Access to process.binding('http_parser') is deprecated.
(Use `node --trace-deprecation ...` to show where the warning was created)

chunk {main} main.js, main.js.map (main) 1.85 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 686 bytes [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {scripts} scripts.js, scripts.js.map (scripts) 12.3 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 239 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 339 kB [initial] [rendered]
Date: 2021-11-29T06:54:58.534Z - Hash: 388a52fd9471c8c66792 - Time: 1115ms

ERROR in ./node_modules/@swimlane/ngx-datatable/index.scss (./node_modules/css-loader/dist/cjs.js??ref--13-1!./node_modules/postcss-loader/src??embedded!./node_modules/resolve-url-loader??ref--13-3!./node_modules/sass-loader/dist/cjs.js??ref--13-4!./node_modules/@swimlane/ngx-datatable/index.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Error: Node Sass version 6.0.0 is incompatible with ^4.0.0.
    at getSassImplementation (C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend\node_modules\sass-loader\dist\utils.js:84:13)
    at Object.loader (C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend\node_modules\sass-loader\dist\index.js:34:59)

ERROR in ./src/assets/sass/app.scss (./node_modules/css-loader/dist/cjs.js??ref--13-1!./node_modules/postcss-loader/src??embedded!./node_modules/resolve-url-loader??ref--13-3!./node_modules/sass-loader/dist/cjs.js??ref--13-4!./src/assets/sass/app.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Error: Node Sass version 6.0.0 is incompatible with ^4.0.0.
    at getSassImplementation (C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend\node_modules\sass-loader\dist\utils.js:84:13)
    at Object.loader (C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend\node_modules\sass-loader\dist\index.js:34:59)

ERROR in The Angular Compiler requires TypeScript >=3.9.2 and <4.1.0 but 4.4.4 was found instead.

Note: when I downgrade the typescript version TypeScript >=3.9.2 and <4.1.0 it still gives the errors.

A: I think you might be able to find your answer here. Looks like it is a comprehensive guide on similar issues.


text:
Q: Create Geographical Grid based on data using K-D Trees (python) For my research, I need to divide the geographical area of a city (i.e.Chicago or New York) using a grid. Later, I have data points consisting of GPS longitude and latitude location that I want to associate to its corresponding cell in the grid.
The simplest way to do this is dividing the space into squared cells of same size. However, this will lead to cells with very few points in non-populated (rural areas) areas and cells with a high number of points (city centre). In order to have a more fair representation and the relation between the number of points and cell size, an adaptative grid that create cells of size based on data density would be a better option.
I came across this paper that utilise a K-D tree to do the space partition and retrieve the cells from the nodes. However, I cannot find any implementation (in python) that does that. Many of the implementations out there only index data points in the tree to perform Nearest Neighbour search, but they not provide code to extract the polygon-rectangles that k-d tree generates.
For example, given the following image:

My resulting grid will contain 5 cells (node1 to node5) where each cell contains the associated data points.
Any idea on how to do that?
Anyone knows any implementation?
Many thanks,
David


text:
Q: Laravel get all records where the date in one column is 7days less or equal to the date in another column I have two date columns in a table, created_at and encountered_at. I want to get all rows where encountered_at is 1 week less than created_at. How do I go about it without doing any looping?
This is an example
id | encountered_at | created_at
1  | 2020-04-17     | 2020-04-23
2  | 2020-04-17     | 2020-04-24
3  | 2020-04-17     | 2020-11-29

the first two records should show up. I guess this is straigt in SQL, how do I achieve this with Eloquent?
...

A: you could do it using whereRaw  and dateDiff ....
$result=MyModelClass::whereRaw('DATEDIFF(created_at,encountered_at)<=7')
select('*')->get();

please note that the result here will contains the rows where the diff if less or equal than 7 days ... if you want it to be only 7 days you can just omit '<' ....

A: In general, you want to SELECT * FROM table WHERE "DIFF OF encountered_at AND created_at LESS THAN 1 Week" - so you want to calculate the difference and then test it to be less than a week. I recommend the following mysql doc-page: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_datediff

A: The whereBetween method verifies that a column's value is between two values.
$from = date('2020-01-01');
$to = date('2020-05-02');
Model::whereBetween('date', [$from, $to])->get();

You can check date between two dates using carbon object.You can get current date then start date and end date between date then return true otherwise false return.
$startDate = \Carbon\Carbon::createFromFormat('Y-m-d','2020-10-01');
$endDate = \Carbon\Carbon::createFromFormat('Y-m-d','2020-10-30');
$check = \Carbon\Carbon::now()->between($startDate,$endDate);
dd($check); // return true or false


text:
Q: ImageView increases slightly in size when moving RelativeLayout (Android) I've got an annoying problem where when i move my RelativeLayout, the ImageView in it increases in size to fill the full screen in width. I've replaced the image with a colored background so it's easier to see.
Don't mind the way it looks, the layout is a W.I.P
GIF here to show the problem: https://gyazo.com/ae31b8e70e4f96fe89ba041549db22bb
Below is the code for my OnTouchListener
private View.OnTouchListener relativeListener = new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        final int X = (int) event.getRawX();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) view.getLayoutParams();
                _xDelta = X - lParams.leftMargin;
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                break;
            case MotionEvent.ACTION_POINTER_UP:
                break;
            case MotionEvent.ACTION_MOVE:
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
                layoutParams.leftMargin = (X - _xDelta);
                layoutParams.rightMargin = -(X - _xDelta);
                view.setLayoutParams(layoutParams);
                break;
        }
        _root.invalidate();
        return true;
    }
};

Below is the xml that defines the ImageView and RelativeLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="me.tech.myapp.Fragments.HomeFragment">
<TextView
    android:id="@+id/tvCurrentTheme"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_margin="16dp"
    android:text="StringCurrentTheme"
    android:textAlignment="center"
    android:textSize="18sp" />

<RelativeLayout
    android:id="@+id/relativeRoot"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">

    <ImageView
        android:id="@+id/ivMainImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:contentDescription="Foto jonguh"
        android:cropToPadding="false"
        android:scaleType="centerCrop"
        app:srcCompat="@android:color/holo_blue_bright" />

    <Button
        android:id="@+id/btnReportImage"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_alignTop="@+id/ivMainImage"
        android:layout_margin="16dp"
        android:background="@drawable/ic_menu_send"
        android:visibility="visible" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabSendImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/btnReportImage"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="17dp"
        android:clickable="true"
        app:backgroundTint="@android:color/holo_orange_dark"
        app:elevation="4dp"
        app:fabSize="normal"
        app:srcCompat="@drawable/ic_menu_camera" />

</RelativeLayout>
</LinearLayout>

A: android:scaleType="fitCenter"
android:adjustViewBounds="true"

Try to add these to properties to ImageView

A: It is normal that the ImageView to occupy the entire layout if you have
<ImageView
        android:id="@+id/ivMainImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
....

try wrap_content instead match_parent

A: Fixed it by just changing the width manually in code.


text:
Q: The second resonance of string? What is the relationship between "the second resonance " and string and the wavelength. Like in this question: if the length of the string is 2cm with second resonance, then what is wavelength?

A: The first resonant vibrational mode for a string clamped at both ends looks like:

You should be able to deduce the wavelength from that diagram.  The second mode looks like:

Both of the images above are from http://www.clickandlearn.org/Physics/sph3u/Music/Music.htm and that site will spell it out in more detail for you.
If your string length is $2\:\mathrm{cm}$ then the wavelength of the first vibrational harmonic is $4\:\mathrm{cm}$.  The second vibrational mode has a wavelength of $2\:\mathrm{cm}$.
If the string is open at one or both ends the modes are different however using the link above you should be able to figure it out without issue.


text:
Q: Need suggestions to get a unique index keys for two or more tables on mysql Usually, I use auto_increment attribute to get an unique key/id for each row on a single table to use as a primary index. Now I have two tables and unfortunately auto_increment can't create a new key using the last id/key on another table to keep all the keys/id unique in both. If I'll use auto_increment on both index columns, the possibility to have two identical ID is assured! There is a easy way to do it?

A: If you have:

*

*table A with ids 1,2,3.

*table B with ids 1,2,3.

Then you already have the following (virtual) unique identifiers:

*

*A1, A2, A3, B1, B2, B3

You don't need to make any changes to your database. This is purely a presentation issue.

A: At least from a perspective of relational database design, your requirement seems unsound.  You ought to create a separate table with the common auto_increment field and point to that from the other two tables with foreign keys.


text:
Q: Should I user meteor packages or copy js files? There are many js libraries built by enthusiasts that are incredible. And some of them have found a place in atmospherejs (some of them migrated not by their autor). Should I use the original ones (js files) or add the meteor packages that are the meteor version of these libraries?
For example:
Sweet alert:
Meteor version by someone else
Original version by ther author

A: You can do both, if you take a look in usage you will find first one (meteor one) you need meteor to install it:
Usage
meteor add kevohagan:sweetalert

And second one you have a working plugin installable via bower or npm
Usage
Method 1: Install through bower:
$ bower install sweetalert

Method 2: Install through NPM:
$ npm install sweetalert

So, if it is not last option, you dont need to get manually any files.


text:
Q: Property 'id' does not exist on type 'void' Im trying to implement an audit trail for all actions for my angular application, like 'delete' 'addUser' 'update' etc. i was able to implement this successfully with the 'post blog' function which is in the "posts-dashboard.component.ts" and now im trying to do the same with the 'delete user' function which is in the "student-user.component.ts" but the compiler returns an error "Property 'id' does not exist on type 'void'"
i've tried defining id as 'id: any;' and 'id =''' but i don't think that's the solution. the error wont go away. The audit trail function  is supposed to print the output (audit trail) in the console and store the audit trail log in the database under the audit-trail model
this is my student-user.component.ts. Look out for the deleteStudent(value) function...that's where i'm implementimg it
import { Component, OnInit } from '@angular/core';
import { map, catchError} from 'rxjs/operators';
import {FirebaseService} from '../services/firebase.service';
import {Router} from '@angular/router';
import { AngularFirestore} from "angularfire2/firestore";
import { Observable } from 'rxjs';
import { AuditTrailService } from 'src/app/services/audit-trail/audit-trail.service';
import { AngularFireStorage } from '@angular/fire/storage';

@Component({
  selector: 'app-student-user',
  templateUrl: './student-user.component.html',
  styleUrls: ['./student-user.component.scss']
})

export class StudentUserComponent implements OnInit{
  students: any;
  students_data :any;
  public searchString: string;
  response: any;
  is_loading: any;
  ideas; any;
  term = '';
  //id: any[];

  constructor(
    public firebaseService: FirebaseService,
    private router: Router,
    public db: AngularFirestore,
    private storage: AngularFireStorage,
    public _auditTrailService:AuditTrailService
  ) { }

 ngOnInit() {

  this.getStudents()
  this.searchStudents(event)

}

getStudents() {
  this.students_data = this.db.collection('User', ref => ref.where('role', '==', 'student')).snapshotChanges().pipe(map(changes => {

  return changes.map(a => {
  const data: any = a.payload.doc.data();
  data.id = a.payload.doc.id;
  return data;
  });
  })
  );

  this.students_data.subscribe(
  res => {
  console.log(res);
  this.students = res;
  //this.blogs_snapshot = res;
  });

  }

  searchStudents(event){
    if (event.key === "Enter"){
      console.log(this.term)
      this.db.collection('User', ref => ref.where('full_name', '==', this.term)).valueChanges().subscribe(
      res => {
      this.response = res;
      console.log(this.response);

      this.ideas = res;
      this.is_loading = false;
        }
        );
    }
  }

  deleteStudent(value){
    this.db.collection('User').doc(value).delete().then(
      res =>{
      console.log(res)
      this.students = res;
      const _audit_trail = {
        'action' : ' has deleted a student ',
        'object': res.id,
        'created_at': new Date(),
        'user':{
          'id': '4545454545454545454',
          'email':'daanyu@gmail.com' }
         }
      console.log(_audit_trail)

      this._auditTrailService.createAuditTrailLog(_audit_trail)

    },

    err=>{
      console.log(err)
    }
    )
  }

}

this is my error ...
ERROR in src/app/student-user/student-user.component.ts(87,23): error TS2339: Property 'id' does not exist on type 'void'.

Im using Firebase as my Database and this is what i expect returned in the db under my audit-trail model:
action " has deleted a student"
created_at July 22, 2019 at 5:49:33 PM UTC+3
user:
email "daanyu@gmail.com"
id "4545454545454545454"

A: I have not worked with Firebase previously, but your error leads me to believe that the delete() method in Firestore does not return a success response since it implies res is of type void. You can use the id from this.students or this.response instead as per your use case.


text:
Q: How do I get realtime updates for facebook user actions? Currently I have implemented facebook realtime updates . But here I am getting only user actions related to movie likes, statuses and normal likes. How can i get actions like music.listens, places checkins, videos watched etc.

A: You can only get updates for objects listed in here: https://developers.facebook.com/docs/graph-api/real-time-updates/v2.2


text:
Q: External SVG not loading media queries Im currently using external svg that have inline styling applied, however it won't load the styling.
Initially I used an img to include the external svg like so:
<img id="temp" src="https://lw.com/example.svg">

Where the SVG file looked similar to this:
<svg xmlns="http://www.w3.org/2000/svg" role="img" width="300" height="300" aria-labelledby="loading-aria" viewBox="0 0 300 300" preserveAspectRatio="none">
      <style>
        @media only screen and (max-width: 300px) {
          #mini-cart-rect {
            transform: scale(0.9);
          }
        }
      </style>
      <title id="loading-aria">Loading...</title>
      <rect id="mini-cart-rect" x="0" y="0" width="100%" height="100%" clip-path="url(#mini-cart-clip-path)" style="fill: url("#mini-cart-fill");"/>
      <defs>
        <clipPath id="mini-cart-clip-path">
            <rect x="79" y="13" rx="3" ry="3" width="160" height="11"/>
            <rect x="79" y="63" rx="3" ry="3" width="20" height="11"/>
        </clipPath>
        <linearGradient id="mini-cart-fill">
          <stop offset="0.599964" stop-color="#f3f3f3" stop-opacity="1">
            <animate attributeName="offset" values="-2; -2; 1" keyTimes="0; 0.25; 1" dur="2s" repeatCount="indefinite"/>
          </stop>
        </linearGradient>
      </defs>
    </svg>

But this didn't load the style block at all, so I tried with object instead:
<object type="image/svg+xml" id="temp" data="https://lw.com/example.svg"></object>

However this loads the media query but it apply the style no matter the screen size, so it's not working properly. If screen width is 1000px it still applies the (max-width: 300px).

A: Let it be done by a native JavaScript Web Component <load-file>

*

*Load the SVG from an external file

*Inject SVG Inline into a shadowRoot (no conflicts with any other styled content)

*inject <style> into shadowRoot

See: Full documation of this <load-file> Web Component

<script src="https://load-file.github.io/element.js"></script>

<load-file src="//load-file.github.io/heart.svg">
  <style shadowRoot>
    svg {
      height:180px; // StackOverflow snippet height
      dispay: block;
      background: lightgreen;
    }
    @media only screen and (max-width: 600px) {
        svg {
          background:pink; // Resize StackOveflow Browser tab to see effect
        }
      }
  </style>
</load-file>


text:
Q: New computer turns off after few minutes of using it. Powers back on. PSU? These are the problems I have experienced:

*

*Computer turns off while trying to install Windows 10 for the first time.

*After many tries, I was able to install Windows but can´t use it as computer turns off before the login screen

*Was able to install Ubuntu Linux and can use it a few minutes before the same thing happens

My built has the following SPECS:

*

*Msi Mag Vampiric 010 (Case)

*Corsair TX 750W (CMPSU-750TX)

*Gigabyte Intel Z490 Aorus Elite AC

*Intel Core i7-10700K

*DDR4 16gb 3200mhz Dimm HyperX Fury Black x 2 (32 GB)

*SSD 500GB Kingston A2000, M.2 2280, NVMe PCIe

*WD Black WD1001FALS 1TB 7200 RPM 32MB Cache SATA 3.0Gb/s

*BE QUIET! PURE LOOP 280MM - NA0000050186

Everything is new except the PSU which I bought 11 years ago and the WD Black drive.
The PSU works fine in my old computer.
The motherboard has 3 ATX power connectors (24 pin, 8 pin and 4 pin).
My power supply has only a 24 pin and 8 pin, so only those are connected.
I left the 4 pin alone. (see image)

I have done the following (with no success):

*

*I am able to enter the BIOS and edit settings.

*I have flashed the BIOS with different versions.

*I have tried different combinations of RAM sticks (I have 2)

*

*A1 - 16GB (both of them separately)

*A1 - 16GB / B1 - 16 GB

*A2 - 16GB (both of them separately)

*A2 - 16GB / B2 - 16 GB

*CPU Temperature has not gone over 50ºC

*Removed WD Black and tried installing OS on Kingston M.2

*Removed Kingston M.2 and tried installing OS WD Black

Questions:

*

*Is there a "y-cable" splitter from 8 pin to 8 pin and 4 pin or something like that?

*Could I use one of the PCIe or SATA power cables with some sort of adapter?

*Is it mandatory to connect the 4 pin cable? (I have read all sorts of opinions but they usually says it's ok not to unless you overclock the CPU.)

*I will try another PSU just in case.

*Any BIOS settings I should consider tweaking?

*Is there another thing I should try?

*Any bootable USB with diagnosis tools I could use?
Thanks for your help.

A: It maybe that the CPU is not getting enough power due to the 4 pin connector not being connected.
Try underclock (if that is an option) the CPU to see if the system is more stable.
You can split the existing 8 pin connector but you need to check if the power supply provides enough current on those pins for both connectors.

A: You motherboard manual isn't very clear on this point but it looks to me you can either use the 2x2 or the 2x4 connector. You don't need to connect them both.
First check if nothing is overheating. Are all your fans running?
If that is OK it is most likely the PSU.
Either it is faulty (as already said in the comments these older Corsair PSU are prone to capacitor issues), but the fault may not trigger when used in another system (or only show there under heavy load).
Or your setup draws too much power on one of the powerrails of the PSU causing something to overheat inside the PSU or trip a fuse.
This is typical for older PSU's. Newer motherboards, especially those with fancy on-board power-regulators like yours tend to draw a lot more 12V power than 5V power, while older PSU's typically can supply more 5V than 12V.
If that is the case it may help to re-arrange the distribution of devices across the various power-outputs of the PSU to get a better balance across the rails, but since your motherboard draws the vast majority of the power and you can't change that this will most likely not help.


text:
Q: Square root of a prime is irrational How can one prove that the square root of a prime number (e.g. $ \sqrt 61$) is irrational.
First we need to prove that $61$ is prime. This can be done by simply showing that $$ 49 < 61 < 64$$ and so $$ 7 < \sqrt 61 < 8$$ then the only possible prime factors of $61$ are $2 , 3, 5, 7$. Then by contradictions and DIC we can show that $61$ is prime.
Now how can we show that $\sqrt 61$ is irrational?

A: Suppose $61=a^2/b^2$, where $a$ and $b$ are both in lowest terms. Then $$
61 \cdot b^2 =a^2
$$ since $a^2$ is multiple of $61^2$, or not at all, this simply cannot happen in lhs --- it has odd number of factor of 61, if any.


text:
Q: Как разместить простое ASP.NET MVC приложение на IIS сервере? Второй день не могу найти ничего путного по данному вопросу. Делаю так:

*

*Захожу в "Диспетчер служб IIS".

*ПКМ по "сайты" -> "Добавить новый сайт".

*Ввожу имя, указываю физический путь "C:\inetpub\wwwroot", IP своего ПК, имя узла как в названии.

*После импортирую опубликованную версию проекта на сайт.

Когда пытаюсь зайти, пишет: "Не удается получить доступ к сайту. Не удалось найти IP-адрес сервера...ERR_NAME_NOT_RESOLVED".
Подскажите пожалуйста, что я не так делаю? Или посоветуйте годное видео с решением.
P.S. Пытаюсь запустить на локальном компьютере.


text: Q: Inter rater agreement where categories are not predetermined How can I measure inter-rater agreement, e.g., using the Kappa coefficient, during an exploratory study where the categories are not predetermined?


text:
Q: JTable with autoresize, horizontal scrolling and shrinkable first column I am having trouble creating a JTable with scrollbars.
I want a JTable with 2 columns and no visible scrollbars.
If I enlarge one of the columns the scrollbars should become visible and the columns resize.
I followed this answer How to make JTable both AutoResize and horizontall scrollable? and works fine which basically comes down to:
JTable table = new JTable() {
  @Override
  public boolean getScrollableTracksViewportWidth() {
    return getPreferredSize().width < getParent().getWidth();
  }
};
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

However, with this solution I cannot shrink the first column. Only if I enlarge the 2nd column and the scrollbars become visible I can shrink the first one.
The required behavior is that the 2 columns are automatically resizable. Meaning that the 1 column can shrink and afterwards extend without the scrollbars popping up. Only when extending one of the columns, so that the view should extend, the scrollbars should pop up.
A scenario:

*

*Shrink the 1st column -> 2nd one enlarges, no scrollbars

*Enlarge the 1st column -> 2nd one shrinks, still no scrollbars

*Enlarge the 2nd column -> 1 column stays the same, 2nd one enlarges and scrollbars appear

Any ideas on fixing this?
An SSCCE:
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.AbstractTableModel;
import java.awt.BorderLayout;
import java.awt.Container;

public class TableTest {
public TableTest() {

JDialog mainDialog = new JDialog();
mainDialog.setResizable( true );
mainDialog.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
Container contentPane = mainDialog.getContentPane();

JTable myTable = new JTable() {
  @Override
  public boolean getScrollableTracksViewportWidth() {
    return getPreferredSize().width < getParent().getWidth();
  }
};

myTable.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
myTable.setModel( new MyTableModel() );
JScrollPane scrollPane = new JScrollPane( myTable );
contentPane.add( scrollPane, BorderLayout.CENTER );

mainDialog.pack();
mainDialog.setVisible( true );
}

public static void main( String[] args ) {
new TableTest();
}

private class MyTableModel extends AbstractTableModel {

@Override public int getRowCount() {
  return 1;
}

@Override public int getColumnCount() {
  return 2;
}

@Override public Object getValueAt( int rowIndex, int columnIndex ) {
  return "ARandomValue";
}
}
}

A: It's not quite enough to override the getTracks method, you have to fool super's layout into doing the right-thingy if tracking:
JTable myTable = new JTable(10, 4) {
    private boolean inLayout;

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return hasExcessWidth();

    }

    @Override
    public void doLayout() {
        if (hasExcessWidth()) {
            // fool super
            autoResizeMode = AUTO_RESIZE_SUBSEQUENT_COLUMNS;
        }
        inLayout = true;
        super.doLayout();
        inLayout = false;
        autoResizeMode = AUTO_RESIZE_OFF;
    }

    protected boolean hasExcessWidth() {
        return getPreferredSize().width < getParent().getWidth();
    }

    @Override
    public void columnMarginChanged(ChangeEvent e) {
        if (isEditing()) {
            // JW: darn - cleanup to terminate editing ...
            removeEditor();
        }
        TableColumn resizingColumn = getTableHeader().getResizingColumn();
        // Need to do this here, before the parent's
        // layout manager calls getPreferredSize().
        if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF
                && !inLayout) {
            resizingColumn.setPreferredWidth(resizingColumn.getWidth());
        }
        resizeAndRepaint();
    }

};

Might not be entirely complete (probably still isn't, even after the edit to take care of columnMarginChanged, copied from JXTable (of the SwingX project) which support that behaviour by an additional layout property
xTable.setHorizontalScrollEnabled(true);

A: With the implementation of @kleopatra, I noticed that you get a scrollbar, when you reduce the size of a column and then increase it again just slightly (which happens quite often by accident). So I've slightly changed the code slightly:
protected boolean hasExcessWidth() {
    return getPreferredSize().width - getParent().getWidth() < 50;
}

This allows to slowly increase the size of a column without loosing the auto resize.
Not really sure yet if the magic "50" is a good measurement, but works quite well in initial tests


text:
Q: Providing an API to a Portable Area I've managed to get Portable Areas working greatly and I think it's a very clean solution to allowing drop in sections for a web application.
One thing that I feel is missing that I've not come across in any tutorials I've found is the ability to provide the Portable Area an interface that it can use as an API.
I want to do this as I want to integrate the area completely into the context of the running application as a plugin vs a completely self contained area that runs in concert with the application.
Is this possible?

A: I believe this is the purpose of the IApplicationBus. See http://lostechies.com/erichexter/2009/11/02/asp-net-mvc-portable-areas-part-2/


text:
Q: How to embed an XUL Application in SWT Browser? I want to host my XUL application inside another Java application that uses SWT.
I know that it is possible to embed the browser windows using SWT.MIZILLA as a flag.
But how do I host my XUL application inside that browser window?

A: You should be able to load your XUL file using Browser.setUrl() method. If you are on Linux, no need to specify SWT.MOZILLA (as embedded Firefox is also capable of loading XUL). Be careful when using SWT 3.7 (its M1 is just released), as it uses WebKitGtk+ as the default browser on Linux.


text:
Q: Automatically link keywords within page texts from word list My site has a lot of dynamic stats with names of people, places and topics that all have their own associated pages. I want to automatically link each of these to their page based on data I've set up in a MySQL database of 'words' and 'links'.
What would be an efficient way of automatically linking 20-50 occurrences of potentially 15-20,000 keywords and links? I'm using MySQL and PHP.
Here's a similar query for C++

A: Generally, you want to do this sort of link-searching as infrequently as possible, because there's no particularly efficient way to do it. You didn't specify what sort of data your site has on it, but I'm going to assume it's something like a wiki, or a blog. I'm going to talk about this sort of functionality as it would be done for a wiki, but a similar approach would work for anything.
With a wiki, you only want to be doing the link-searching when a page is changed (or submitted in the first place). Note that there are two different ways that links have to be processed. First, when a page is created or edited, you need to search that page's text to determine what links should be in it. Second, whenever any page is created, renamed, or deleted, you need to (in addition to the search of this page in the case of creation) search all other pages to add/update/remove links as needed. There are a few options for how to store these links.
One option is to keep two "versions" of every page's text in the database. One version is the original "markup" version, this is what you actually entered, and what will be displayed if you choose to edit the page. The second version is the parsed/processed "display" version. This is the data that is used to display the page to normal viewers.
For example, if your wiki markup for bold is **, the "markup version" has **bold text**, and the "display version" has bold text. This makes it so that you don't have to process your markup on every page view.
This approach is applied to page-links by doing a search through the submitted text to find words that should be linked, and putting those links into the "display version". For example, when a page is submitted, you would step through every word in the page's text and compare it against a list of "link words" (make sure you have this list cached, you don't want to be doing a database query for every word). This can be made fairly efficient by storing the potential linkwords as keys into a hash. If the word being tested is in the "link word" list, you put a link to the relevant page around the word when you copy it into the "display version" text. If it's not, you just put the word in, exactly as it was in the "markup version".
There are a few other options about how to implement this, but that's a fairly straightforward one. I'll leave you with that for now, but if you'd like to me to describe any of the other options, let me know in a comment and I'll edit it in.

A: PHP wrapper for the Snowball perhaps?


text: Q: Show Custom Post Type meta boxes only on Page Edit I've went through the laborious process of creating the CPT. I see it on the sidebar of my WP install, I can add new, save data, and on frontend I can output the data. Is it possible with WP to move the CPT meta boxes into a Page Edit? I know I see the default 'Custom Fields' with the dropdown that shows the CPT values, but this is very bad UX. I'd like the post meta box to just show up only on the Page Edit for a specific template. I am curious how I would approach this. Any help would be greatly appreciated.


text:
Q: Unflattening a sequence to sequences of repeating elements (clojure) In Clojure, how do you partition a sequence to subsequences of repeating elements? E.g. :
[1 2 2 3 3 3 4 2 2 1 1 1]

to
[[1] [2 2] [3 3 3] [4] [2 2] [1 1 1]]

I've been playing around with some examples trying to understand clojure better, and was stuck on this one for some time.

A: (map (juxt count first)
     (partition-by identity [1 1 1 3 2 2]))
((3 1) (1 3) (2 2))
Three ones, then one three, followed by two twos!

A: user> (partition-by identity [1 2 2 3 3 3 4 2 2 1 1 1])
((1) (2 2) (3 3 3) (4) (2 2) (1 1 1))

user> (vec (map vec (partition-by identity [1 2 2 3 3 3 4 2 2 1 1 1])))
[[1] [2 2] [3 3 3] [4] [2 2] [1 1 1]]


text:
Q: power series tayllor arrest criteria problem Hi guys i created a c program to confront taylor taylor series of cosine and interpolation but i have a problem . The problem is about the function cosine (calculated by using taylor method) because the programme  always gives me a  degree of 3 , or 1 . My teacher said that i should use this arrest criteria
x^(2k)/(2k!)<t where t is tau in my code , the tolerance. Really thanks to anyone who can help me!
#include<stdio.h>
#include<math.h>

double read_tolerance();
double put_x();
void cosine(double,double,int &,double,double);
double Li(int,int,double[],double);
double Pn(int,double[],double[],double);
void interpo_Lagrange(int);

int main()
{

    int k=1;
    double cos_initial=1,a=1;

    double tau=read_tolerance();
    double x=put_x();
    cosine (cos_initial,a,k,x,tau);
    interpo_Lagrange(k+1);
return 0;
}

double read_tolerance()
{
    double t;

        printf("\n choose the value of tolerance: ");
        scanf("%lf", &t);

    return t;
}

double put_x()
{
    double x;

    printf("\nput value of  x: ");
    scanf("%lf",&x);

    return x;
}

void cosine(double coseno,double a,int &k,double x,double tau)
{
     do {
    a *= pow(-1,k)*((x*x) / (2*k));
    coseno += a;
    k=k+2;

}while (a> tau);

printf("value of cosine of %lf is %lf\n",x,coseno);
printf("degree with taylor is ' %d\n",k);
return ;
}

double Li(int i, int n, double x[], double X){
    int j;
    double prod=1;
    for(j=0;j<=n;j++){
        if(j!=i)
            prod=prod*(X-x[j])/(x[i]-x[j]);
    }
        return prod;
}

double Pn(int n, double x[], double y[], double X){
    double sum=0;
    int i;
    for(i=0;i<=n;i++){
        sum=sum+Li(i,n,x,X)*y[i];
    }
    return sum;
}

void interpo_Lagrange(int n)
{
     int i;
    printf("the number of data-points are %d:\n",n);

    double x[n];
    double y[n];
    printf("Enter the x data-points:\n");
    for(i=1;i<=n;i++){
        x[i]=Pi*i/(8);
        printf("%lf\n",x[i]);
    }

    printf("Enter the y data-points:\n");
    for(i=1;i<=n;i++){

    y[i]=cos(Pi*i/(8));
        printf("%lf\n",y[i]);
    }

    double X;
    printf("Enter the value of x for which you want the interpolated value of y(x):\n");
    scanf("%lf",&X);
    printf("The interpolated value is %lf",Pn(n,x,y,X));
}

A: The implementation of tayllor series is incorrect and here is the right one
do {
    a *= -((x * x) / ((2 * k - 1) * (2 * k)));
    coseno += a;
    k = k + 1;
} while (fabs(a) > tau);

i hope this fixes your problem

A: The first issue is that the term can be negative. So the stopping criteria
must used the absolute value of it.
Another issue is that the used formula is not correct. The calculation of the denominator (fatorial) was not correct.
A last issue is that is is better a little bit that the function return the calculated value: more clear.
Output:
cos calculated = 0.707107
Error = -1.14623e-010

#include <iostream>
#include <cmath>

double cosine (double x, double tolerance) {
    double x2 = x*x;
    double term = 1;
    double y = 1;
    int sign = -1;
    int k = 2;
    do {
        term *= x2/(k*(k-1));
        y += sign * term;
        k += 2;
        sign = -sign;
    } while (term > tolerance);

    return y;
}

int main() {
    double tolerance = 1.0e-6;
    double angle = 3.141592/4;
    double calculated = cosine (angle, tolerance);
    double exact = cos(angle);
    double err = calculated - exact;
    std::cout << "cos calculated = " << calculated << std::endl;
    std::cout << "Error = " << err << std::endl;
    return 0;
}


text:
Q: Loading FeynCalc I am trying to install the FeynCalc package, but I cannot load it, it always gives the following errors:

Loading FeynCalc from /home/gabi/.Mathematica/Applications
  SetDirectory::cdir: Cannot set current directory to fcdevel. >>
  SetDirectory::cdir: Cannot set current directory to fcloops. >>
  General::cdir: Cannot set current directory to .gvfs. >>
General::stop: Further output of SetDirectory::cdir will be suppressed
  during this calculation. >>
ResetDirectory::dtop: Directory stack is empty. >>

A: Maybe this is the problem, there is a bug with feyncalc 8 and linux 12
http://www.feyncalc.org/forum/0768.html


text:
Q: Resharper suggesting to make overloaded method private I have methods similar to below:
public string Method(string s)
{
    Console.WriteLine("Called Method(string s)");
    return s;
}

public string Method(object o)
{
    Console.WriteLine("Called Method(object o)");
    return Method(o == null ? null : o.ToString());
}

Resharper says on the first method

Method 'Method' can be made private

I believe this is incorrect because if I call:
Method(new SomeClass())

Then the output is

Called Method(object o)
   Called Method(string s)

and if I call
Method("some string")

the output is

Called Method(string s)

So why is Resharper suggesting this seemingly incorrect refactoring?

A: ReSharper is smart enough to determine where a particular class member is actually being used. If it isn't used outside the type it's in (not even in derived types), it will offer to mark the member as private. If the member is used in derived classes too, it will offer to mark it as protected.
Source


text:
Q: Is there a way to handle parquet file with INT96 parquet type residing in GCS using Data Fusion? I want to load a parquet file with INT96 parquet type residing in GCS to BigQuery using Data Fusion.
Created a pipeline with GCS ad BigQuery component without any Wrangler as Wrangler does not support parquet format.
"MapReduce program 'phase-1' failed with error: MapReduce JobId job_1567423947791_0001 failed. Please check the system logs for more details"
Q.1:- Can we check detailed Map reduce log for this job id ? I know we can do this in Cloudera supported Apache Hadoop.
Q.2:- Failure without wrangler is not only occurring in case of parquet but even in case of plain text file. Does Wrangler is mandatory to have in pipeline ?
Q.3:- When we tried Spark Engine instead of Map Reduce it resulted in showing failure reason as "INT96 not yet implemented". Any work around to overcome this error ? Parquet file without INT96 field got processed successfully.


text:
Q: Laravel Eloquent Query to have values first instead of column name I'm trying to run below query in laravel eloquent, but i'm unable to do so.
SELECT * FROM vehicle_unavailabilities WHERE ("2021/06/05" NOT BETWEEN from_date and to_date) AND ("2021/06/07" NOT BETWEEN from_date and to_date)

If i try
->whereNotBetween("2021/06/05",['from_date',['to_date'])

it gives me error of column "2021/06/05" not found. How can i achieve this??

A: This should be your column name.
SELECT * FROM vehicle_unavailabilities WHERE ("COLUMN_NAME" NOT BETWEEN from_date and to_date) AND ("COLUMN_NAME" NOT BETWEEN from_date and to_date)
->whereNotBetween("COLUMN_NAME",['from_date', 'to_date'])

A: ->whereRaw("? BETWEEN `from_date` AND `to_date`", [$from_date])

This resolved the issue.


text:
Q: Wordpress themes and plugins not work I have created a Wordpress site, it's very ok on Localhost but has problems when runs on live host.
After uploading Wordpress site's folder and database, everything was ok.
But the problems happened in the first time accessing "wp-admin", in the plugins page there were some lines
"The plugin ........... has been deactivated due to an error: The plugin does not have a valid header."
In "appearance/themes", the information of themes was just " by anonymous". Then all plugins didn't work anymore :(
I've tried to upload a new fresh Wordpress and database, but the problems still happened.
Sorry for my bad English and thanks for any help!

A: Make sure you have
<?php wp_head(); ?>
</head>

in your header.php file inside the active theme folder and
<?php wp_footer(); ?>
</body>

in your footer.php file inside the active theme folder.
Not having those would stop the plugins from running correctly.


text:
Q: How can I force one to one relationship in SharePoint lists? I have one parent list and only one child can be associated with one parent item. For example,
Employee -> company access card
Each employee can have one access card and new access card can only be created when certain conditions are met in the employee list

A: I am assuming that you have Employee list(Parent list) and Access card list (Child list) with lookup column "Employee" from parent list.
To force one to one relationship, in child list lookup column, select the option "Enforce Unique Values". This will make sure that only one item added in child list per employee.


text:
Q: Windows Form ListView - How to get values of selected Item I am currently trying to create an app for a shopping basket where you enter an item and then a price in two boxes. On hitting the add button the Item is Added to a List View. You can do this multiple times to add more items to your Basket.
If you decide that you don't want an item in your basket i have a remove button which removes the item which you have selected by clicking on it. My problem is that no matter what item you remove, the values of the last item that you add is taken from the Total instead of the correct one.
My Code for adding an item here:
decimal total = numberPicker.Value * priceSetter.Value;
MessageBox.Show("You want " + numberPicker.Value + " " + txtName.Text + " which cost £" + priceSetter.Value + " each. Your Total cost is: £" + total, "My App");
ShoppingCart.Items.Add("Item: " + txtName.Text + "     " +
                       "Value: " + priceSetter.Value + "     " +
                       "Quantity: " + numberPicker.Value + "     " +
                       "Total: " + (priceSetter.Value * numberPicker.Value)).ToString();
runningTotal = runningTotal + total;
resultBox.Text = runningTotal.ToString();
File.AppendAllText(@"C:\ShoppingCartExperiment\Reciept.txt", ("Item: " + txtName.Text + " " + "Price: £" + priceSetter.Value + " " + "Quantity: " + numberPicker.Value + " " + " Running Total: £" + runningTotal + Environment.NewLine));

My Code for the removal is here:
var selectedItem = ShoppingCart.SelectedItem;
ShoppingCart.Items.Remove(selectedItem);
decimal total = numberPicker.Value * priceSetter.Value;
runningTotal = runningTotal - total;
var SelectedTotal = (priceSetter.Value * numberPicker.Value);
File.AppendAllText(@"C:\ShoppingCartExperiment\Reciept.txt", ("You removed " + txtName.Text + Environment.NewLine));
MessageBox.Show(txtName.Text + " has been removed from basket");
File.AppendAllText(@"C:\ShoppingCartExperiment\Reciept.txt", ("You new total is: £" + runningTotal + Environment.NewLine));

My Project is very small so these two pieces of code are almost all that i have.
My Thought on this is that whenever i add a new Item, my priceSetter and NumberPicker (quantity) are being over ridden. Selecting the item does not seem to store the values of the item that i have selected, but only of what I added last.
I am quite new to coding to please excuse any Naivety. All help is Appreciated.


text:
Q: FxCop analysis failing with MsBuild Sonar Runner I am trying to scan a .NET code using MsBuild Sonar-Runner plugin from jenkins. The system details are as:

*

*Jenkins : 1.651.2

*Sonarqube version: 5.6.1

*C# plugin on Sonarqube:5.3.2

*SonarQube Scanner for MSBuild: SonarQube Scanner for MSBuild 2.1

*FxCop installation:C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Static Analysis Tools\FxCop\FxCopCmd.exe

*MSBuild installation - C:\Program Files (x86)\MSBuild\14.0\Bin\MsBuild.exe

Using default SonarDB so no changes in sonar.properties file.
Error:  FxCop must be installed when some of its rules are enabled in the SonarQube quality profile. FxCop is included as part of Visual Studio.
FxCop command is able to be executed from jenkins as well as command line on sonar server, but the MsBuild faisl with this error.
Kindly suggest.

A: I think the fault lies in your fxcop configurations .
Running Code Analysis (FxCop 12.0 / 14.0) on build agent without installing Visual Studio 2013 / 2015
this link can help you re-config all the steps required