text:
Q: display multiple annotations on mapview I've been looking around on stackoverflow for a solution but I haven't yet successfully implemented it. If someone can give me some tips on where the problem lies, thank you so much. Here is what I have so far
Here is location class
class Location: NSObject, MKAnnotation {
var title: String?
var coordinate: CLLocationCoordinate2D

init(title: String, coordinate: CLLocationCoordinate2D) {
    self.title = title
    self.coordinate = coordinate
}

Method to display all annotations.
func displayAllEventsPins() {
    for event in events {
        let address = event.location
        geocoder.geocodeAddressString(address!, completionHandler: { (placemarks: [CLPlacemark]?, error: Error?) -> Void in
            if let placemark = placemarks?.first {
                let eventlat = placemark.location?.coordinate.latitude
                let eventlong = placemark.location?.coordinate.longitude
                let annotation = MKPointAnnotation()
                annotation.title = event.name
                annotation.coordinate = CLLocationCoordinate2D(latitude: eventlat!, longitude: eventlong!)
                self.locations.append(Location(title: annotation.title!, coordinate: annotation.coordinate))
                    for location in self.locations {
                    let pin = MKPointAnnotation()
                    pin.title = location.title
                    pin.coordinate = location.coordinate
                    self.mapView.addAnnotation(pin)
                }
            }
        })
    }

}

Edited: The problem here is that annotations doesnt show up on mapview. I can only see the currentlocation pin and nothing else.
Edited: This is the call i used to drop user current location pin.
extension Search : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedWhenInUse {
        locationManager.requestLocation()

    }
}

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //MARK: remove previous current pin for user location
    mapView.removeAnnotation(newPin)

    let location = locations.last! as CLLocation
    let center = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    self.currentLocation = location
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpanMake(0.03, 0.03))
    mapView.setRegion(region, animated: true)
    newPin.coordinate = location.coordinate
    mapView.addAnnotation(newPin)
}
}

Here is the code in the viewDidLoad method:
 override func viewDidLoad() {
    super.viewDidLoad()

    //MARK:  Request Current Location
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestAlwaysAuthorization()
    locationManager.requestLocation()
   displayAllEventsPins()
}

A: This should work for you.
By the way, looping through your locations whilst in the events loop is just going to add duplicates of the same pin, which will be very bad on memory and it's not a good thing to do.
import UIKit
import MapKit
import Firebase

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var map: MKMapView!

    let locationManager = CLLocationManager()

    var events = Array<Event>()

    var locations = Array<Location>()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        locationManager.requestWhenInUseAuthorization()

        locationManager.startUpdatingLocation()

        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        // This closure gets called once for every event in your database
        getEvents { (event, pin) in

            self.tableView.reloadData()

            if event != nil && pin != nil {

                print(event!)

                self.locations.append(pin!)

                self.events.append(event!)

            } else {

                print("Failed to get event.")
            }
        }
    }

    func getEvents(results: @escaping (_ event: Event?, _ pin:Location?)->()) {

        let ref = FIRDatabase.database().reference().child("Events")

        ref.observe(.childAdded, with: { (snapshot) in

            guard let value = snapshot.value as? Dictionary<String,String> else { return }

            guard let name = value["eventName"],
            let location = value["location"],
            let attending = value["attendance"],
            let dateTime = value["dateTime"],
            let addedByUser = value["addedByUser"] else { return }

            self.getEventPlacemark(address: location, results: { (placemark) in

                if let placemark = placemark {

                    let pin = Location(title: name, coordinate: placemark.coordinate)

                    var distance: Double = -1 // If user location is not avalible, this will stay at -1

                    if let currentLocation = self.locationManager.location?.coordinate {

                        distance = pin.coordinate.distance(to: currentLocation)
                    }

                    let event = Event(id: snapshot.key, name: name, location: location, dateTime: dateTime, addedByUser: addedByUser, attending: attending, distance: distance)

                    results(event, pin)

                    return
                }
            })
        })
    }

    func getEventPlacemark(address:String, results: @escaping (_ placemark: MKPlacemark?)->()){

        let geocoder = CLGeocoder()

        geocoder.geocodeAddressString(address) { (placemarks, error) in

            if let error = error {

                print(error.localizedDescription)

                results(nil)
            }

            if let placemark = placemarks?.first {

                results(MKPlacemark(placemark: placemark))
            }
        }
    }

    func displayAllEvents(){

        self.map.addAnnotations(self.locations)
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        if let userLocation = annotation as? MKUserLocation {

            let view = (mapView.dequeueReusableAnnotationView(withIdentifier: "userLocationPin") as? MKPinAnnotationView) ?? MKPinAnnotationView(annotation: userLocation, reuseIdentifier: "userLocationPin")

            view.pinTintColor = .purple

            view.canShowCallout = true

            return view
        }

        if let pin = annotation as? MKPointAnnotation {

            let view = (mapView.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKPinAnnotationView) ?? MKPinAnnotationView(annotation: pin, reuseIdentifier: "pin")

            view.pinTintColor = .red

            view.canShowCallout = true

            return view
        }

        return nil
    }
}

class Location: NSObject, MKAnnotation {

    var title: String?

    var coordinate: CLLocationCoordinate2D

    init(title: String, coordinate: CLLocationCoordinate2D) {

        self.title = title

        self.coordinate = coordinate
    }
}

struct Event {

    var name: String

    var location: String
}

extension CLLocationCoordinate2D {

    func distance(to: CLLocationCoordinate2D) -> CLLocationDistance {

        return MKMetersBetweenMapPoints(MKMapPointForCoordinate(self), MKMapPointForCoordinate(to))
    }
}

If you are going to implement my code above, you'll need to remove your code from
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

because you don't need to add the pin manually anymore.
Can you try putting this in your view did load function and not have anything else run. This should put a pin to the west of Africa.

Something to notice, if the coordinate is
  CLLocationCoordinate2D(latitude: 0, longitude: 0), the pin appears
  right down at Antartica on the date line, which is the bottom right of
  the map. So if for some reason your coordinate is the default 0,0,
  your pins might by sitting there.

let pin = MKPointAnnotation()

pin.title = "Null Island"

pin.coordinate = CLLocationCoordinate2DMake(0.000001, 0.000001)

self.map.addAnnotation(pin)

This could possibly be where your pins are.


text:
Q: How do I fix this cv2.imshow() syntax error? I cannot get the following code to run:
import cv2 # import Open Cv moudle
import numpy as np
import face_recognition
import matplotlib as plt

imgEloun=face_recognition.load_image_file  ("image/elounMask.jpg")        # load Image
imgEloun=cv2.cvtColor(imgEloun,cv2.COLOR_BGR2RGB)      # changing BGR clr to RGB

imgTest=face_recognition.load_image_file ("image/steve jobs.jpg")    # Load Image
imgTest=cv2.cvtColor(imgTest,cv2.COLOR_BGR2RGB)    # changing BGR clr to RGB

faceLocation=face_recognition.face_locations(imgEloun)[0]  #Detect face loaction in image
encodeELOUN=face_recognition.face_encodings(imgEloun)[0]  #encoding face location
cv2.rectangle(imgEloun,(faceLocation[3],(faceLocation[0]),(faceLocation[1],(faceLocation[2]),(255,0,255))

cv2.imshow('elounMask',imgEloun)   ######## here is error
cv2.imshow('steve jobs',imgTest)      # Show Image as output
cv2.waitKey(0)

Here is a Screenshot of my error in PyCharm.
Is anyone able to help out?

A: cv2.rectangle(imgEloun,((faceLocation[3],(faceLocation[0])),((faceLocation[1],(faceLocation[2])),(255,0,255))

you missed the parenthesis when giving the coordinates for rectangle. It should be in this format,
eg: cv2.rectangle(image, (5,5), (200,200), (255,255,0), 2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I show a ToolTip for a TextBox only under certain conditions In VB6 I could easily create a balloon message that would be shown next to the textbox.
It would automatically disappear as soon as the text is changed.
I could use this balloon tooltip for messages like "Enter a valid eMail address!".
I used the Windows API to create this balloon. I have attached the code below.
Is there no framework solution for this?
Thank you for the help!
Option Explicit

Private Const ECM_FIRST = &H1500                    '// Edit control messages

Private Const EM_SETCUEBANNER = (ECM_FIRST + 1)
Private Const EM_GETCUEBANNER = (ECM_FIRST + 2)     '// Set the cue banner with the lParm = LPCWSTR

Private Type EDITBALLOONTIP
    cbStruct As Long
    pszTitle As Long
    pszText As Long
    ttiIcon As Long ' ; // From TTI_*
End Type

Private Const EM_SHOWBALLOONTIP = (ECM_FIRST + 3)      '// Show a balloon tip associated to the edit control
Private Const EM_HIDEBALLOONTIP = (ECM_FIRST + 4)       '// Hide any balloon tip associated with the edit control
Private Declare Function SendMessageW Lib "user32" ( _
   ByVal hwnd As Long, _
   ByVal wMsg As Long, _
   ByVal wParam As Long, _
   lParam As Any) As Long

Private Declare Function LocalAlloc Lib "kernel32" (ByVal wFlags As Long, ByVal wBytes As Long) As Long
Private Declare Function LocalLock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function LocalUnlock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As Long
Private Const GMEM_FIXED = &H0
Private Const GMEM_ZEROINIT = &H40
Private Const GPTR = (GMEM_FIXED Or GMEM_ZEROINIT)

Private m_hWnd As Long
Private m_sCueBanner As String
Private m_sTitle As String
Private m_sText As String
Private m_eIcon As BalloonTipIconConstants

Public Property Let TextBox(txtThis As TextBox)
   m_hWnd = txtThis.hwnd
End Property

Public Property Let CueBanner(ByVal value As String)
   m_sCueBanner = value
   setCueBanner
End Property
Public Property Get CueBanner() As String
   CueBanner = m_sCueBanner
End Property
Public Property Let BalloonTipTitle(ByVal value As String)
   m_sTitle = value
End Property
Public Property Get BalloonTipTitle() As String
   BalloonTipTitle = m_sTitle
End Property
Public Property Let BalloonTipText(ByVal value As String)
   m_sText = value
End Property
Public Property Get BalloonTipText() As String
   BalloonTipText = m_sText
End Property
Public Property Let BalloonTipIcon(ByVal value As BalloonTipIconConstants)
   m_eIcon = value
End Property
Public Property Get BalloonTipIcon() As BalloonTipIconConstants
   BalloonTipIcon = m_eIcon
End Property

Public Sub ShowBalloonTip()

Dim lR As Long
   Dim tEBT As EDITBALLOONTIP
   tEBT.cbStruct = LenB(tEBT)
   tEBT.pszText = StrPtr(m_sText)
   tEBT.pszTitle = StrPtr(m_sTitle)
   tEBT.ttiIcon = m_eIcon
   lR = SendMessageW(m_hWnd, EM_SHOWBALLOONTIP, 0, tEBT)
End Sub
Public Sub HideBalloonTip()
    Dim lR As Long
   lR = SendMessageLongW(m_hWnd, EM_HIDEBALLOONTIP, 0, 0)
   Debug.Print lR
End Sub
Private Sub setCueBanner()
Dim lR As Long
   ' Reports success, but doesn'/t actually work...
   ' (is this because the VB text box is ANSI?)
   lR = SendMessageLongW(m_hWnd, EM_SETCUEBANNER, 0, StrPtr(m_sCueBanner))
   Debug.Print lR
End Sub

A: You can set a tooltip like this
Dim toolTip1 As New ToolTip()

toolTip1.SetToolTip(Me.textbox1, "Hello World")

and hide the tooltip with
toolTip1.SetToolTip(Me.textbox1, "")

Note that you can also add a ToolTip-Control to the form the toolbox instead of creating it programmatically. It magically adds a ToolTip-property to all controls in the properties window where you can enter a tooltip message. The controls themselves, however, will not aquire a ToolTip property and you can only set or remove the tooltip through the ToolTip.SetToolTip method in code.

A: I think it can only be done in the way I want it using the API way.
I found a perfect migration of my VB6 sample here:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=7109&lngWId=10


text:
Q: Send database to Dropbox - com.dropbox.sync.android.DbxRuntimeException$IllegalArgument: Illegal datastore ID I'm developing an app to build lists of different names. The content of a list is in a table contained inside of a database. What I wish is to send some of these tables toward Dropbox datastore in order to share them between several devices.
For my practice, I start by trying to create a simple table on Dropbox after having connected my app with it. But I have an error message and I cannot figure out why...
Here my activity:
public class ListingArticlesDropb extends Activity implements PersonneAdapterListener{

    static final int REQUEST_LINK_TO_DBX = 0;  // This value is up to you

    private Button mLinkButton;
    private Button mUnlinkButton;

    private DbxAccountManager mAccountManager;
    private DbxDatastoreManager mDatastoreManager;
    private DbxAccount account ;

    final private String APP_KEY = **** APP_KEY **** ;
    final private String APP_SECRET = **** APP_SECRET **** ;
    DbxDatastore datastore;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_articles);

        /**
         * Get objects from the precedent activity
         */
        Bundle bundle = getIntent().getExtras();
        final String extras = bundle.getString("Title");

        /**
         * Connection to the datastore Dropbox
         */
        // Set up the account manager
        mAccountManager = DbxAccountManager.getInstance(getApplicationContext(), APP_KEY, APP_SECRET);
        mAccountManager.startLink((Activity)ListingArticlesDropb.this, REQUEST_LINK_TO_DBX);

        // Set up the datastore manager
        if (mAccountManager.hasLinkedAccount()) {
            try {
                // Use Dropbox datastores
                mDatastoreManager = DbxDatastoreManager.forAccount(mAccountManager.getLinkedAccount());
                Toast.makeText(this, "Connection Dropbox", Toast.LENGTH_LONG).show();
            } catch (DbxException.Unauthorized e) {
                System.out.println("Account was unlinked remotely");
            }
        }
        if (mDatastoreManager == null) {
            // Account isn't linked yet, use local datastores
            mDatastoreManager = DbxDatastoreManager.localManager(mAccountManager);
            Toast.makeText(this, "Connection Locale", Toast.LENGTH_LONG).show();

        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_LINK_TO_DBX) {
            if (resultCode == Activity.RESULT_OK) {
                account = mAccountManager.getLinkedAccount();
                Toast.makeText(this, "onActivityResult", Toast.LENGTH_LONG).show();

                try {
                    // Migrate any local datastores to the linked account
                    mDatastoreManager.migrateToAccount(account);
                    // Now use Dropbox datastores
                    mDatastoreManager = DbxDatastoreManager.forAccount(account);

                } catch (DbxException e) {
                    e.printStackTrace();
                }
            } else {
                // Link failed or was cancelled by the user
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }

        // ---------- The problem comes here ------------- //
        try {
       //  This line makes my app to stop.
            DbxDatastore datastore = mDatastoreManager.openOrCreateDatastore("Articles");
        } catch (DbxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public void onClickNom(Article item, int position) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onClickNomToDelete(Article item, int position) {
        // TODO Auto-generated method stub

    }
}

Here the error message :
10-21 19:39:02.410: E/AndroidRuntime(22961): FATAL EXCEPTION: main
10-21 19:39:02.410: E/AndroidRuntime(22961): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=0, data=null} to activity {com.example.dvp_list7/com.example.dvp_list7.ListingArticlesDropb}: com.dropbox.sync.android.DbxRuntimeException$IllegalArgument: Illegal datastore ID 'Articles'.
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3337)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3380)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.app.ActivityThread.access$1100(ActivityThread.java:155)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.os.Looper.loop(Looper.java:137)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.app.ActivityThread.main(ActivityThread.java:5096)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at java.lang.reflect.Method.invokeNative(Native Method)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at java.lang.reflect.Method.invoke(Method.java:511)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at dalvik.system.NativeStart.main(Native Method)
10-21 19:39:02.410: E/AndroidRuntime(22961): Caused by: com.dropbox.sync.android.DbxRuntimeException$IllegalArgument: Illegal datastore ID 'Articles'.
10-21 19:39:02.410: E/AndroidRuntime(22961):    at com.dropbox.sync.android.DbxDatastore.checkId(DbxDatastore.java:534)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at com.dropbox.sync.android.DbxDatastoreManager.openOrCreateDatastore(DbxDatastoreManager.java:342)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at com.example.dvp_list7.ListingArticlesDropb.onActivityResult(ListingArticlesDropb.java:113)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.app.Activity.dispatchActivityResult(Activity.java:5342)
10-21 19:39:02.410: E/AndroidRuntime(22961):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3333)
10-21 19:39:02.410: E/AndroidRuntime(22961):    ... 11 more

Thanks a lot for people who will help me!

A: The error message is accurate. You used "Articles" as a datastore ID, but datastore IDs for private datastores must be "1-64 characters containing only lowercase letters, digits, dot, hyphen or underscore, and they must not begin or end with dot." (See https://www.dropbox.com/developers/datastore/docs/http#general.)
The issue here is the capital "A".


text:
Q: vb.net creating table. using textbox.text for the per column of table I have a program that add new employee it adds there personal information and there benefits id (ex. tax number). but i want to do is create a new table for there salary by making a new table and the columns will be there benefits id (ex.tax number) but i want to create the table automatically after the new employee is added here is my code if it will help you:
BTW IM GETTING A MESSAGEBOX THAT SHOW "incorrect syntax near '@idd'.
     Dim add As String = String.Empty
    add &= "insert into rec_member(firstname,middlename,lastname,age,birthday,pagibig,philhealth,sss,tin,department)"
    add &= "values "
    add &= "(@first,@middle,@last,@age,@bday,@pagibig,@philhealth,@sss,@tin,@dept);select scope_identity()"

    Dim benefits As String = String.Empty
    benefits &= "create table @idd(" & _
    "pagibig(@ibig) integer not null, " & _
    "philhealth(@phil) integer not null," & _
    "sss(@rsss) integer not null," & _
    "tin(@rtin) integer not null)"

    Using conn As New SqlConnection("server=WIN10;database=add_member;user=hradmin;password=admin;")
        Using cmd As New SqlCommand
            With cmd
                    .Connection = conn
                .CommandType = CommandType.Text
                .CommandText = add
                .Parameters.Add("@first", SqlDbType.VarChar).Value = afirstname.Text
                .Parameters.Add("@middle", SqlDbType.VarChar).Value = amiddlename.Text
                .Parameters.Add("@last", SqlDbType.VarChar).Value = alastname.Text
                .Parameters.Add("@age", SqlDbType.Int).Value = aage.Value
                .Parameters.Add("@bday", SqlDbType.Date).Value = abirthday.Text
                .Parameters.Add("@pagibig", SqlDbType.Int).Value = apagibig.Text
                .Parameters.Add("@philhealth", SqlDbType.Int).Value = aphilhealth.Text
                .Parameters.Add("@sss", SqlDbType.Int).Value = asss.Text
                .Parameters.Add("@tin", SqlDbType.Int).Value = atin.Text
                .Parameters.Add("@dept", SqlDbType.VarChar).Value = adepartment.SelectedItem
            End With

                Try
                    conn.Open()
                    If afirstname.Text.Length < 2 Then
                        MsgBox("Please input more value on the FIRST NAME")
                    ElseIf amiddlename.Text.Length < 2 Then
                        MsgBox("Please input more value on the MIDDLE NAME")
                    ElseIf alastname.Text.Length < 2 Then
                        MsgBox("Please input more value on the LAST NAME")
                    ElseIf aage.Value < 16 Then
                        MsgBox("Age must be appropriate")
                    ElseIf abirthday.Text > "1997-01-01" Then
                        MsgBox("Please select a birthday")
                    ElseIf apagibig.Text.Length < 5 Then
                        MsgBox("Please input more value on the PAG-IBIG")
                    ElseIf adepartment.SelectedItem = "" Then
                        MsgBox("Please Select a Department")
                    ElseIf aphilhealth.Text.Length < 5 Then
                        MsgBox("Please input more value on the PHILHEALTH")
                    ElseIf asss.Text.Length < 5 Then
                        MsgBox("Please input more value on th SSS")
                    ElseIf atin.Text.Length < 5 Then
                        MsgBox("Please input more value on the TIN")
                    Else

                        Dim id As Integer = CInt(cmd.ExecuteScalar)
                        MsgBox("NEW EMPLOYEE ADDED" & Environment.NewLine &
                               "ID NUMBER:" & id & Environment.NewLine &
                               "FIRST NAME:" & afirstname.Text & Environment.NewLine &
                               "MIDDLE NAME:" & amiddlename.Text & Environment.NewLine &
                               "LAST NAME:" & alastname.Text & Environment.NewLine &
                               "AGE:" & aage.Value & Environment.NewLine &
                               "BIRTHDAY:" & abirthday.Text & Environment.NewLine &
                               "PAG-IBIG:" & apagibig.Text & Environment.NewLine &
                               "PHIL-HEALTH:" & aphilhealth.Text & Environment.NewLine &
                               "SSS:" & asss.Text & Environment.NewLine &
                               "TIN:" & atin.Text & Environment.NewLine &
                               "DEPARTMENT:" & adepartment.SelectedItem & Environment.NewLine
                               )

                    Using cmd1 As New SqlCommand
                        With cmd1
                               .Connection = conn
                            .CommandType = CommandType.Text
                            .CommandText = benefits
                            .Parameters.Add("@idd", SqlDbType.Int).Value = id
                            .Parameters.Add("@ibig", SqlDbType.Int).Value = apagibig.Text
                            .Parameters.Add("@phil", SqlDbType.Int).Value = aphilhealth.Text
                            .Parameters.Add("@rsss", SqlDbType.Int).Value = asss.Text
                            .Parameters.Add("@rtin", SqlDbType.Int).Value = atin.Text
                        End With

                        cmd1.ExecuteNonQuery()
                        MsgBox("New Table is Set for new employee")
                    End Using
                End If
                afirstname.Clear()
                amiddlename.Clear()
                alastname.Clear()
                aage.Value = 0
                abirthday.Text = "1997-01-01"
                apagibig.Clear()
                adepartment.ResetText()
                aphilhealth.Clear()
                asss.Clear()
                atin.Clear()
                conn.Close()

            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

            End Using
        End Using

A: The problem is:
create table @idd ...

you cant send command with non static table-name.
for this, you need build the command-text with tokens:
benefits &= "create table {0}(" & _
"pagibig(@ibig) integer not null, " & _
"philhealth(@phil) integer not null," & _
"sss(@rsss) integer not null," & _
"tin(@rtin) integer not null)"

and:
Using cmd1 As New SqlCommand
    With cmd1
        .Connection = conn
        .CommandType = CommandType.Text
        .CommandText = String.Format(benefits, id)
        .Parameters.Add("@ibig", SqlDbType.Int).Value = apagibig.Text
        .Parameters.Add("@phil", SqlDbType.Int).Value = aphilhealth.Text
        .Parameters.Add("@rsss", SqlDbType.Int).Value = asss.Text
        .Parameters.Add("@rtin", SqlDbType.Int).Value = atin.Text


text:
Q: damaged file during upload with file_put_contents I try to upload an image in a directory using file_put_contents,The file is uploaded but it is damaged and I can not open it. here is my code :
define('UploadDir','../Dir/images');
$path = "image.png";
$data="..."; //image base64 string
$file = UploadDir ."/". $path;
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';

A:
$data="..."; //image base64 string

Assuming $data contains what the comment says, if you put a base64 string in an image it will obviously not be a valid image - it will be a file containing a base64 encoded string.
To be valid (or have a chance at being valid) decode the string before writing it to the file:
$data="..."; //image base64 string
$file = UploadDir ."/". $path;
$success = file_put_contents($file, base64_decode($data));

A: Is the directory ../Dir/images chmoded to 777? sometimes php won't allow you to access directories if they don't have enough permission.
Try to see if it has enough permissions, if not, then set it to 777 and try it.


text: Q: How to count individual cycles of a 24 GHz clocking signal? Are there digital counters or similar circuits available that can count cycles or even half cycles (e.g., by threshold crossing) of a 24 GHz clocking signal? I am not looking for frequency counters here, but instead for a digital counter that could in principle, given said clock signal, count 1 cycle and therefore resolve time at 42 picoseconds.


text:
Q: Run php script from link I have a small php script that gets the url of the current page and echo's it. I only want that to run when a user clicks on a submit button. There are no other form item's on the page, I just figured submit would be easier to work with than a link. If a link works too I'll gladly use that. I just need the script to run on that same page and not link to an external script (because it has to get the current page's url).  Any suggestions?
I'm fine with using javascript, or a page reload.
Some things I've tried so far:
1)
Current Page

That one doesn't work for me because it got the url.php page's address.
2)
<?php if(Input::exists()) { echo: $url; } ?>

This doesn't do anything for me because the submit button is the only form item, therefore my exists() function returns false because there is no other input.

A: Something like this?
<?php
    if($_POST["clicked"]){
        printURL();
    }
?>
<form method="post">
    <input type="submit" name="clicked" value="Click Me!"/>
</form>

A: Not sure what you want, but from what I understand, you want something like this:
<form action="yourscript.php">
    <input type="submit"/>
</form>

Or, without a form:
click here

EDIT:
Based on your comment, you want AJAX. Below is a sample of how to use AJAX. AJAX will run the script on the same page, without refreshing it.
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","myphpscript.php",true);
xmlhttp.send();
}

Then just call the function using a link. This function will display the result of the php script inside of an html element. You can change this behaviour as you see fit.


text:
Q: variable replacement not happening when using templates azure pipelines So I'm trying to submit a parameter in to my template deployment not sure what's wrong the other parameters are working as expected is only the new one that's not working, but if i set it to a boolean value without parameters it works.
there seems to be som variable substitution that doesn't happen and i just can't figure out why it must be something simple but i just can't find it
It's usek8s that's not working, image from variables tab

snippet from azure-pipelines.yml when it doesn't work
  - template: yml/pipeline-templates/deployment.yaml@parent
    parameters:
    usek8s: $(usek8s)
    stageId: Deploy_Dev
    vmImage: $(vmVersion)
    environment: 'dev'
    targetBranch: 'master'
    namespace: $(k8sNamespace)
    imagePullSecret: $(imagePullSecret)
    containerRegistry: $(dockerRegistryServiceConnection)
    tag: $(tag)
    imageRepository: $(imageRepository)
    kubernetesServiceConnection: $(k8sConnectionDev)
    dependsOn: Build_Docker_Deventer

snippet from azure-pipelines.yml when it works
  - template: yml/pipeline-templates/deployment.yaml@parent
    parameters:
    usek8s: false
    stageId: Deploy_Dev
    vmImage: $(vmVersion)
    environment: 'dev'
    targetBranch: 'master'
    namespace: $(k8sNamespace)
    imagePullSecret: $(imagePullSecret)
    containerRegistry: $(dockerRegistryServiceConnection)
    tag: $(tag)
    imageRepository: $(imageRepository)
    kubernetesServiceConnection: $(k8sConnectionDev)
    dependsOn: Build_Docker_Deventer

snippet from parent template
    parameters:
    - name: usek8s
      displayName: 'Use k8s deploy process?'
      type: boolean
      default: false
    - name: stageId
    - name: vmImage
    - name: targetBranch
    - name: environment
    - name: namespace
    - name: imagePullSecret
    - name: containerRegistry
    - name: tag
    - name: imageRepository
    - name: kubernetesServiceConnection
    - name: dependsOn
      default: []
stages:
- stage: ${{ parameters.stageId }}
  displayName: '${{ parameters.stageId }}'
  dependsOn: ${{ parameters.dependsOn }}
  condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/heads/${{ parameters.targetBranch }}'), eq(${{ parameters.usek8s }}, true))
  jobs:

error i get

if i remove the boolean data type and just run it with name i get the same kind of error only in the conditions row

A:
variable replacement not happening when using templates azure pipelines

This is a known issue and has been reported to the MS team. You could check following thread for some details:
Queue Time Variables Do Not Override Default Variable
That because we could not use queue variables to overwrite the compile time parameters.
So, MS team recently rolled out a new feature Runtime parameters, allow you to inject data into the pre-processor phases of pipeline compilation:
parameters:
- name: usek8s
  displayName: UseUsek8s?
  type: boolean
  default: False
When we queue the pipeline, we could select if we use the usek8s:

Hope this helps.


text:
Q: How return@map works I've just started learning Java stream API with kotlin and I'm using Project Reactor along with r2dbc API. I'm writing a simple code as given below and would appreciate in understanding how this works.
I want to know the line where t.let{} returns a MovieCeleb object using return@map. I want to know what this line does i.e., whether it creates a list/map and how it does this.
fun listAllMoviesBy(actor: String, client: DatabaseClient) {
    client.execute()
            .sql { "SELECT fin.id, full_name, movie_title, make_year, celeb_id, birth_date " +
                    "FROM featured_in fin JOIN film_celeb fc ON " +
                    " fin.celeb_id = fc.id WHERE fc.full_name = $1"
            }.bind(0, actor).map { t, u ->
                t.let {
                   val featuredIn = FeaturedIn(it.get("id") as Int, it.get("movie_title") as String, it.get("make_year") as Int)
                   val celeb = MovieCeleb(it.get("celeb_id") as Int, it.get("full_name") as String, it.get("birth_date") as LocalDate, featuredIn)
                    return@map celeb
                }
            }.all()
            .subscribe{
                println(it)
            }
}

A: Given
.map { t, u ->
            t.let {
               val featuredIn = FeaturedIn(it.get("id") as Int, it.get("movie_title") as String, it.get("make_year") as Int)
               val celeb = MovieCeleb(it.get("celeb_id") as Int, it.get("full_name") as String, it.get("birth_date") as LocalDate, featuredIn)
                return@map celeb
            }
        }

return@map celeb will return celeb reference value from map function (not from let!). It is just some kind of so-called non-local return, whereas you can manually specify the return scope of your statement.


text:
Q: bzip2 randomly launches on OS X 10.6.8 Is there an application for OS X that will let me view what parent process is launching bzip2? It randomly opens up and eats a massive amount of CPU so it sorta lags the computer. I'm not sure what's causing it so in order to figure out, I wanted something like Process Explorer but for mac where I get a tree-type view of the running processes so I can determine what its parent process is.
UPDATE:
Okay I discovered that there is a All Process, Hierarchically sorting mode which does just that. It seems bzip2 is being launched by newsyslog. Any thoughts on this?

A: If you open Activity Monitor.app, you can select the process, and open the Get Info… window (or press ⌘I).
You can then check the Open Files and Ports for specific information about that process. This is likely to be the best source of info, since most processes will only show launchd as the parent process.

A: Sorry I forgot to update here. As it turns out kdc.log, located inside /var/log/krb5kdc was chugging on huge amounts of size (it's increasing its size in MBs after a few seconds/minutes). What I did to stop this from happening was gain permission to access it first. This was the tricky part since its still being used by the system, I had to do some reboots to finally get it loose. I then deleted it and created a blank folder and named it kdc.log. I don't know where I learned this but it's somehow stock knowledge to me that if you replace a file with a same-name folder and try to overwrite it by attempting to write to a file, nothing happens so no log will be made.
I know this is unorthodox but it stopped what's causing the lag so yeah.


text:
Q: Maximum number of edges in unconnected graph In an undirected graph with n vertices and no edges, what is the maximum number of edges that can be added so that the graph remains unconnected? This is an interview question.

*

*NC2

*(N-1)C2

*N!

*(N-1)!

A: The maximum number of edges in a graph with N vertices is NC2 (link).
Note that, to remain unconnected, one of the vertices should not have any edges. More formally, there has to be a cut (across which there won't be any edges) with one side having only one vertex. Why not more than one vertex? Proof by induction:
The cases for 0, 1 and 2 vertices are trivial.
Consider a graph with 3 vertices. The best cut will be one with 2 vertices on one side and 1 vertex on the other side.
Now assume the best cut is one with N-1 vertices on one side and 1 vertex on the other with N >= 3. Now try to add a vertex. Adding the vertex to the side with one vertex will result in one edge that can be added. Adding the vertex to the other side will result in N-1 possible edges. Clearly N-1 > 1 for N >= 3. Thus it's always better to add the vertex to the side with N-1 vertices.
Now there are two ways to go from here:

*

*Consider the graph without one of the edges. The maximum number of edges of this sub-graph is (N-1)C2.

*Consider the maximum number of edges of the graph as is and subtract the number of edges from one vertex. This gives NC2 - (N-1) = N(N-1)/2 - 2(N-1)/2 = (N-2)(N-1)/2 = (N-1)C2.
So the answer is (N-1)C2, i.e. option 2.

A: b (n-1)C2
An example of such a graph is a complete graph of n-1 vertices and one isolated vertex.
In this example, the complement graph would have nC2 - (n-1)C2 = n-1 edges.
And either given graph or its complement is connected (proof).
Hence, if we constucted a graph with more than (n-1)C2 edges, then the complement would have less than n-1 edges and couldn't be connected, so our graph would be.


text:
Q: Debugging startup issues in a C Windows Service I'm trying to debug an issue that happens on service startup. Trying to attach while things are running is failing, windbg times out with an error about a link lock. I think that the error occurs before I have a chance to attach. A sleep might let me attach, but is there a more elegant solution?
I'd like to start up the debugger first thing as the service starts. C# has a Debugger.Launch() method to start a debugger at runtime. Is there an equivalent C call that can be used without .net? Something I could just drop in the start routine.
I can't call DebugBreak because at the time the service has started I'm not under a debugger.

A: Sleep is certainly a viable approach. It's crude yet effective. Somewhat less crude is to use a good logging framework to output diagnostics. With a sufficiently capable logging framework this can be very effective.


text:
Q: Webpack 2.0 checking existence of tree shaken ES6 module imports In Webpack 2.0 (@2.1.0-beta6), if I go to import a file that points to a file that doesn't exist, I get a build time error.
//x.js
import { foo } from './y'

//y.js
export function foo () { return 5 }

If I go to import an export that doesn't exist from a file that exists, I get a runtime error.
//x.js
import { baz } from './y'

//y.js
export function foo () { return 5 }

Is there a way to have Webpack check exports in the same way it resolves files?
//webpack.config.js
module.exports = {
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015-native-modules']
        }
    ],
  }
}

A: I believe a runtime error in this case is correct behavior. You probably aren't getting a runtime error from the import itself, but only when you try and use it it is undefined.
A file existing or not can be easily determined by a system call during build time. However, a module exporting a given value or not can be changed at runtime - not that that is a good idea - so Webpack doesn't make a build time decision as to whether or not it should bail out.
Consider the following code:
// hats.js
var hats = undefined;
if (Math.random() > 0.5) {
  hats = 'i have a hat!';
}
export const HATS = hats;
// index.js
import { HATS } from './hats';
console.log('hats is:', HATS}

Webpack can't know at build time whether or not HATS is going to exist at run time, so it won't error out when I try and import hats. However, HATS will correctly be either undefined or 'i have a hat!' when logged during execution. Similarly, if i remove the export line from hats.js, it will simply always report undefined, because Webpack cannot tell the difference after transpilation - HATS is simply undefined still. If I remove hats.js completely, Webpack knows something is definitely wrong and errors out.

A: As of webpack@2.1-beta15, warnings have now been added for imports of ES6 exports.


text:
Q: Need some initial guidance for Android and iOS app using MySQL I'm about to start the development of an app where I'll need to make use of queries to retrieve information from a database and print it on my app. I have a lot of experience doing this using PHP/MySQL coding but I have never done it on a mobile app. How would you recommend I begin my coding? Are there any tips you can share to help me develop this app?
I also need to develop this app in both android and iOS. What should I be aware of when doing this? Is there any builder (other than Flash builder) to export both versions of my app?
Thanks, and any information helps!

A: Are you storing database locally or accessing remote database.
I am a IOS developer so I can give u tips about  IOS only. But concept must be similar to Android as well.
If you are storing database locally in the app, there is Sqlite and coredata for that. And different wrapper framework such as FMDB for sqlite makes things easy for this.
If you are accessing remote database you could do that with the help of APIS that consumes JSON/XML formatted data from the server database. Apple has provided inbuilt XML and JSON parser for this. But framework like AFNetworking could be really handy.


text:
Q: How can I add a non singleton on to a DotNet Core 3.0 Worker Service? I have written a Windows Service using the new Worker Service in dotNetCore 3.0
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-3.0&tabs=visual-studio#app-configuration
I am now trying to add some services. One in particular for logging using Sentry.
Deep down in the Add it has a Transient service (the SentryClient)
.ConfigureLogging(loggerFactory =>
    loggerFactory.AddSentry(configuration["logging:sentry:dsn"]));

When I try and run it I get this Exception:

InvalidOperationException: Unable to resolve service for type
  'SharpRaven.IRavenClient' while attempting to activate
  'MyServiceName'.

How can I add services which are not singleton?
I have read about this before but I now can't find the article. Do I have to create a factory
EDIT:
Here is the Create Host Builder
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
                {
                    // The worker class
                    services.AddHostedService<Worker>();

                    var cronExpression = configuration[ActiveDirectoryJobConstants.CronExpression];

                    // Add Quartz services
                    services.AddSingleton<IJobFactory, SingletonJobFactory>();
                    services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
                    services.AddSingleton<QuartzHostedService>();

                    // Add our job
                    services.AddSingleton<SyncWithActiveDirectoryJob>();
                    services.AddSingleton(new JobScheduleDto(typeof(SyncWithActiveDirectoryJob), cronExpression));

                    services.AddSingleton<ILdapConnector, LdapConnector>();
                    services.AddUserServiceClient(configuration);
                    services.AddSentryClient(
                        configuration["logging:sentry:dsn"],
                        hostContext.HostingEnvironment.EnvironmentName);

                })
        .ConfigureLogging(loggerFactory =>
                loggerFactory.AddSentry(configuration["logging:sentry:dsn"]));


text:
Q: XML read and getting values How can I get a this: val="icon.weapon_small_sword_i00"/> from XML file by giving a itemId. I managed to do something like this but besides of choosing right itemId from file I dont know how to get the value I mentioned above.
Thats a code I have:
int ItemId = 15;
XmlTextReader reader = new XmlTextReader(@"D:\L2Eq\xml\items");
XmlNodeType type;
while (reader.Read())
{
    type = reader.NodeType;
    if (type == XmlNodeType.Element)
    {
        if (reader.Name == "item")
        {
            if (Int32.Parse(reader.GetAttribute(0)) == ItemId)
            {
                Console.WriteLine(reader.GetAttribute(0));
            }
        }
    }
}

And thats how XML file looks like:
<list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="items.xsd">
<item id="1" type="Weapon" name="Short Sword">
    <set name="icon" val="icon.weapon_small_sword_i00" />
    <set name="default_action" val="equip" />
    <set name="weapon_type" val="sword" />
    <set name="bodypart" val="rhand" />
    <set name="random_damage" val="10" />
    <set name="attack_range" val="40" />
    <for>
        <set order="0x08" stat="pAtk" val="8" />
        <set order="0x08" stat="mAtk" val="6" />
        <set order="0x08" stat="rCrit" val="8" />
        <set order="0x08" stat="pAtkSpd" val="379" />
    </for>
</item>
<item id="2" type="Weapon" name="Long Sword">
    <set name="icon" val="icon.weapon_long_sword_i00" />
    <set name="default_action" val="equip" />
    <set name="weapon_type" val="sword" />
    <set name="bodypart" val="rhand" />
    <set name="random_damage" val="10" />
    <set name="attack_range" val="40" />
    <for>
        <set order="0x08" stat="pAtk" val="24" />
        <set order="0x08" stat="mAtk" val="17" />
        <set order="0x08" stat="rCrit" val="8" />
        <set order="0x08" stat="pAtkSpd" val="379" />
    </for>
</item>
</list>

A: XmlTextReader is a very clumsy way to deal with XML; I'd never use it. The old System.Xml.XmlDocument API is a much better choice:
var findID = "1";
string iconValue = null;

var xdoc = new System.Xml.XmlDocument();

xdoc.Load(@"D:\L2Eq\xml\items");

iconValue = xdoc.SelectSingleNode("/list/item[@id=" + findID + "]/set[@name='icon']/@val")?.Value;

Or you could use the shiny new LINQ to XML classes:
var doc = XDocument.Load(@"D:\L2Eq\xml\items");

iconValue = doc.Descendants("item")
    .Where(d => d.Attribute("id")?.Value == findID)
    .Descendants("set")
    .Where(x => x.Attribute("name")?.Value == "icon")
    .FirstOrDefault()?.Attribute("val")?.Value;


text:
Q: dll load error in python due to insufficient stack size? I have a python code which imports dll's created by f2py (from fortran routines). Now the python program crashes if the arrays in fortran are too large. How do I manage with this? By increasing stack size? Or heap? I've tried to study the matter, but I still do not understand how I can increase the stack or should I use the heap instead and how I should do that..??? Python always crashes on the line where I try to import the dll, i.e., at line "import f90_routine". Someone also mentioned threads, but I do not know how to use them. Hope someone can help me!!

A: Your basic problem is that you are storing large arrays of data on the stack. This is bad design and is probably due to the way the Fortran code is implemented.
Large arrays need to be stored on the heap and dynamically allocated there.  To solve this problem you will need to understand and modify your Fortran code accordingly.
The ALLOCATE keyword is how you create heap allocated data in Fortran 90.  However, many compilers have options that for arrays to be allocated on the heap and that may be the most expedient route for you right now.

A: There is a utility called EDITBIN shipped with Visual Studio (and maybe also the Windows SDK) which is exactly what you want. See http://msdn.microsoft.com/en-us/library/xd3shwhf%28v=vs.71%29.aspx for reference.
To check the stack size, use
dumpbin /headers python.exe

and look for "size of stack reserve" under "optional header values".
editbin /stack:size_in_bytes python.exe

Note that you will have to distribute the modified Python.exe to all people who want to run your code.


text:
Q: Python Summing A 2D Array In Steps Defined With Element Number Range import Numpy as np

a = np.array([[5, 1, 8, 1, 6, 1, 3, 2],[2, 3, 4, 1, 6, 1, 4, 2]])
n = 2
[(a[0:2, i:i+n]).sum(axis=1) for i in range(0,a.shape[1],n)]

The output is:
[array([6, 5]), array([9, 5]), array([7, 7]), array([5, 6])]

How can I get a 2D array instead of 4 arrays I got in above output...Is there a better more elegant way doing this using reshape?

A: You can use sliding_window_view:
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view

a = np.array([[5, 1, 8, 1, 6, 1, 3, 2], [2, 3, 4, 1, 6, 1, 4, 2]])
n = 2

out = sliding_window_view(a, (n, n)).sum(axis=n+1)[:, ::n].squeeze()

Output:
array([[6, 5],
       [9, 5],
       [7, 7],
       [5, 6]])

A: You can always stack the results to get a single array:
import numpy as np

a = np.array([[5, 1, 8, 1, 6, 1, 3, 2],[2, 3, 4, 1, 6, 1, 4, 2]])
n = 2
np.stack([(a[0:2, i:i+n]).sum(axis=1) for i in range(0,a.shape[1],n)])

Giving you:
array([[6, 5],
       [9, 5],
       [7, 7],
       [5, 6]])

Alternatively, you can reshape the array and sum:
a.T.reshape(-1, n, 2).sum(axis=1)

Giving the same result. But note, the array will need to be reshape-able to the given n, so n=4 is fine n=3 is an error.

A: Another solution:
from numpy.lib.stride_tricks import sliding_window_view

a = np.array([[5, 1, 8, 1, 6, 1, 3, 2],[2, 3, 4, 1, 6, 1, 4, 2]])
n = 2

print(sliding_window_view(a, (n,n))[:,::n].sum(axis=n+1))

Prints:
[[[6 5]
  [9 5]
  [7 7]
  [5 6]]]


text:
Q: Powershell regex to capture string after new line I'm having the hardest time with this regex capture. basically, I've imported a csv, where the script reads the text in a column and captures a string within the text, placing it into a variable.
the problem that I'm having is that the capture is also capturing the carriage return. How do i not capture the carriage return?
for example, the text reads:
check the following key:
HKLM:\Software\yadda\yadda

code:
if($file.col2 -match "following key:(?<path>\s*(\S+\s*\S+))"){
  $Matches['path']
}

A: if your two line string is placed in $InStuff via something like Get-Content -Path $FullFileName -Raw, you can use the (?m) multiline regex option and a named capture group to put the path into $Matches.Path like this ...
$InStuff = @'
check the following key:
HKLM:\Software\yadda\yadda
'@

$Null = $InStuff -match '(?m)(?<Path>.+:\\.+)$'
$Path = $Matches.Path

$Path

output = HKLM:\Software\yadda\yadda


text:
Q: How to change (assign) new value in FloatTensor, Pytorch? I am changing/assigning the value on the array(torch.cuda.floatTensor). I tried some way but it does not work. Please help me!
#1
#dis is [torch.cuda.FloatTensor of size 3185x1 (GPU 0)]

s = dis.size(0) #3185
for i in range (0,s,1):
    if (dis[i,0] < 0):
        dis[i,0]== 0
#There is no error but It does not work.

#2
#dis is [torch.cuda.FloatTensor of size 3185x1 (GPU 0)]

s = dis.size(0)
a = torch.zeros(s, 1).cuda()
idx = (dis > a)
dis[idx] = a[idx]

AssertionError: can't compare Variable and tensor

#3
#dis is [torch.cuda.FloatTensor of size 3185x1 (GPU 0)]

s = dis.size(0)
a = torch.zeros(s, 1).cuda()
for i in range (0,s,1):
    if (dis[i,0] < a[i, 0]):
        dis[i,0]==a[i, 0]

#RuntimeError: bool value of Variable objects containing non-empty      torch.cuda.ByteTensor is ambiguous

A: IIUC, you need to replace values smaller than 0 with 0, Just use torch.clamp, which is meant for such use cases:
dis = dis.clamp(min=0)

Example:
import torch
dis = torch.tensor([[1], [-3], [0]])
#tensor([[ 1],
#        [-3],
#        [ 0]])

dis.clamp(min=0)
#tensor([[1],
#        [0],
#        [0]])


text:
Q: Meaning of this passage What is the meaning of the bolded part:

He stepped out beneath the arched doorway, past the children playing, past the elevators, until the shenai quieted. He had forgotten what it was like to move through a crowd feeling like a hypocrite among them, aware of the scrutinizing gaze of his father, expecting Amar to embarrass him, anticipating the lie he would tell before he even spoke.

A: It is not well written, with dangling modifiers, inconsistent tenses, etc. It probably means something like:

He had forgotten how the surrounding crowd made him realize that it would view him as a hypocrite. Moreover, he was aware of the scrutiny of his father, who anticipated, even before Amar opened his mouth, that he would be an embarrassment or would lie.

I cannot be sure that is what was intended. Not every published author writes comprehensible prose. If it is a translation, the fault may lie with either the author or the translator, or perhaps both are partially at fault.


text:
Q: Cannot return subclasses of abstract class in implementations of an abstract method I have two sub-classes of an abstract class which each implement an abstract method of their superclass. I want to have a different return type for each, though those return types are in turn sub-classes of a different abstract class. See below:
public abstract class Gardener {

    public abstract ArrayList<Flower> getFlowers();
}

public class GardererA extends Gardener {

    public ArrayList<Flower> getFlowers() {
        return new ArrayList<Daisy>();
    }
}

public class GardererB extends Gardener {

    public ArrayList<Flower> getFlowers() {
        return new ArrayList<Rose>();
    }
}

public abstract class Flower {}

public class Daisy extends Flower {}

public class Rose extends Flower {}

Obviously Java won't let me do this, but I'm at a loss for how to get this functionality. Any ideas?

A: Use wildcards:
public abstract class Gardener {

    public abstract ArrayList<? extends Flower> getFlowers();

}

A: You can use generics like this:
public abstract class Gardener<T extends Flower> {

    public abstract ArrayList<T> getFlowers();
}

public class GardererA extends Gardener<Daisy> {

    public ArrayList<Daisy> getFlowers() {
        return new ArrayList<Daisy>();
    }
}

public class GardererB extends Gardener<Rose> {

    public ArrayList<Rose> getFlowers() {
        return new ArrayList<Rose>();
    }
}

public abstract class Flower {}

public class Daisy extends Flower {}

public class Rose extends Flower {}


text:
Q: iOS 7 app optimized for iPhone 6 I have an iOS 7 app made since more than a year. I want to make it optimized for the new iPhone 6 and 6 Plus screens but want to keep the iOS 7 compatibility. Is it possible ?
I have already made this :
- Add Launch images at the sizes of iPhone 6 and 6 Plus
There are some UI issues, but I can handle them.
My question is : If the iOS Deployment Target and Base SDK are on "iOS 7.0", is it enough to make my app optimized for iPhone 6 and 6 Plus and iOS 7 compatible ?

A: Adding the Launch Images are the key to making sure you don't have those black spaces at the top and bottom of your screen. As long as you set your target deployment to 7.0 or 7.1, whichever you prefer, XCode and iTunes Build submission attempts will inform you on and methods or frameworks that are only available to 8.0>


text:
Q: Field where $e^2 + f^2 = -1$ implies existance of matrix $A$ with $A^2 = -E_2$? Suppose we have a field $K$ with a solution for $e^2 + f^2 = -1$. Is there a matrix $A \in K^{2\times 2}$ with $$ A^2 = \begin{pmatrix}-1 & 0 \\ 0 & -1 \end{pmatrix}? $$

A: $$
\left(
\begin{array}{rr}
e & f \\
f & -e
\end{array}
\right)
$$

A: Try first with a symmetric matrix, because $-E_2$ is symmetric. Consider the equation
$$
\begin{bmatrix} a & b \\ b & c \end{bmatrix}^2=
\begin{bmatrix} -1 & 0 \\ 0 & -1 \end{bmatrix}
$$
that becomes
\begin{cases}
a^2+b^2=-1 \\[4px]
ab+bc=0 \\[4px]
b^2+c^2=-1
\end{cases}
The second equation yields $c=-a$ or $b=0$; discarding the latter case which would imply $a^2=-1$, which we know nothing about, we get
$$
a^2+b^2=-1
$$
Thus choosing $a=e$, $b=f$ and $c=-e$ we are done.


text:
Q: How can I dynamically display Total number of items from the Database in a blade view in Laravel 7 I'm quite new to Laravel, In my Dashboard I would like to display Total number of projects coming from MySQL database table, called "projects" into a Bootstrap card (See the Screenshot) I have some code in my Controller that gets Total number of Projects from the Database but I'm getting "Undefined variable" error. I know my mistake is in my blade view. For now I'm just displaying static data in Bootstrap card. Please Help.
In my HomeController:
public function showTotals()
    {
        $allProjects = Project::count();

        return view('dashboard.index', compact('allProjects'));
    }

In my View:
<div class="col-md-3"

{{ $allProjects }}
Projects

A: Change to array in return view.Since count return number not an array
  return view('dashboard.index', ['allProjects'=>$allProjects]);

Since view expects second parameter to be an array
 view($view = null, $data = [], $mergeData = [])

A: It looks like your function showTotals() is not the one called in your route.
I suppose the route is calling in public function index(), where you actually should pass the $allProjects variable.
Either you call this in your index function or you change the routes/web.php to call HomeController@showTotals(). I suggest you should use the first one..
Please post your routes/web.php.


text:
Q: Why is this code resulting in an unhandled exception? The following code seems as though it should swallow any type of exception in the try block, but the IIS worker process periodically dies and restarts because of an unhandled exception (marked with a comment.)
try
{
    while (true)
    {
        DispatcherTask task = null;

        lock (sync)
        {
            task = this.getTask();

            if (task == null)
            {
                Monitor.Wait(sync);
                continue;
            }
        }

        lock (task)
        {
            task.Result = task.Task.DynamicInvoke(task.Params);
            // ^ Delegate.DynamicInvoke(object[]) throws a TargetInvocationException

            Monitor.PulseAll(task);
        }
    }
}
catch (Exception e)
{
}

UPDATE:
Definition of DispatcherTask:
private class DispatcherTask
{
    public Delegate Task;

    public object[] Params;

    public object Result;
}

A: You cannot catch the exceptions of another thread, at least not in this way. Catch your exception inside the newly opened thread and you will be fine.

A: In .NET 4 and up, AccessViolationException will bypass catch blocks by default. Catching of such exceptions can be enabled in web.config, but should not be, as they typically result from errors in unmanaged code and signal that the application state is corrupted.


text:
Q: java.lang.NoClassDefFoundError: org/eclipse/draw2d/LightweightSystem although it is added I am trying use draw2d for my plugin development. For now, all I have in my code is:
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.*;

public class GraphView extends ViewPart {

public GraphView() {

}
@Override
public void createPartControl(Composite parent) {

    //use LightweightSystem to create the bridge between SWT and draw2D
    final LightweightSystem lws = new LightweightSystem(new Canvas(parent, SWT.NONE));

}

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

}
}

I get the org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: org/eclipse/draw2d/LightweightSystem when I launch my eclipse application. I have org.eclipse.draw2d added to my project as an external jar.
Can someone please help me with this? Thanks in advance!

A: Adding the jar to the build path only makes your compiler in the IDE finds the classes. For an RCP application you have to add the jar in your plug-in.xml as an external jar. Then the jar gets bundled in your application and is available at the runtime of it.
You can do this in the Eclipse editor on the tab Runtime. Click Add... in the classpath section and add your jar here. This automatically adds the jar to your build path so you might better remove it here before.
You can find a detailed description (with images) here: Adding a jar file to your Eclipse RCP Plugin

A: Putting this as the answer to my question now:
My "required bundle" file in Manifest.mf looked like this when I got the errors:
Require-Bundle: org.eclipse.ui,
                org.eclipse.core.runtime

I changed it to:
Require-Bundle: org.eclipse.core.runtime,
                org.eclipse.ui,
                org.eclipse.draw2d,
                org.csstudio.swt.widgets;
bundle-version="2.0.1";resolution:=optional, org.csstudio.swt.xygraph;
bundle-version="2.0.1";resolution:=optional**


text:
Q: Store both IPv4 and IPv6 address in a single column I want to be able to store both IPv4 and IPv6 addresses in my table.  What is the most efficient way to store the IP address of a user regardless of whether it is an IPv4 or IPv6 address?
This will be used in a production environment, so future proof'd suggestions are preferred.

A: I would recommend to store every address in IPv6 format. There is an official mapping for that: the IPv4-mapped IPv6 address. It works like this:
Take for example IPv4 address 192.0.2.44
The IPv4-mapped IPv6 address would be ::ffff:192.0.2.44
Which can also be written as ::ffff:c000:022c (192 decimal is c0 hexadecimal, etc)
You can use the inet_pton() function to parse such addresses, and on my local system the inet_ntop() function also outputs them in the most readable format (::ffff:192.0.2.44). That way you only have one format to deal with in your application.
Also see this related answer.

A: Why does it have to be a single column? A few suggestions...
Have 2 columns, one for IPv4, one for IPv6.
Store the IP address in a single column and have another column that basically holds a boolean whether the address is IPv4 or not...


text:
Q: Is every distance-regular graph vertex-transitive? Is every distance-regular graph vertex-transitive?

A: Very small examples of distance-regular graphs that are not vertex-transitive are the Chang graphs on 28 vertices.  They are strongly regular but not vertex-transitive.  They are constructed from the very symmetric graph T(8).  The groups have sizes
http://en.wikipedia.org/wiki/Chang_graphs
http://www.win.tue.nl/~aeb/graphs/Chang.html
384,360 and 96, which is not even divisibly by 28.
It is not true either that for large diameter, they have to be vertex-transitive.  In 2005, Koolen and van Dam constructed new distance-regular graphs of arbitrary diameter d, by twisting the very symmetric Grassmann graphs (hence the name "twisted Grassmann graph").  They have two orbits on vertices.

A: Here's a quasi-proof that the answer is no. Wikipedia says that Moore graphs are examples of distance regular graphs. It also says "It is not known whether a Moore graph with girth 5 and degree 57 exists, but Higman proved that it cannot be vertex-transitive, unlike the known ones." Or were you asking the question in the hope of a cheap answer to this open problem?

A: I don't think so. There are examples of even strongly regular graphs with a trivial automorphism group. See a detailed discussion here.

A: Here is a counterexample - Tutte 12 cage.
According to Wolfram alpha
it is distance-regular yet not vertex-transitive.
Sage 5.2 confirms it is not vertex transitive and distance-regular.
Added Computer search with sage/networkx using graph enumeration didn't find small counterexamples

A: In my answer to this question I commented that in the diameter 2 case it may be that most distance regular graphs have no automorphisms.


text:
Q: Actionmode Bar doesn't cover whole titlebar In my app I need to use the ActionMode.
I have followed several Guides and Tutorials (https://medium.com/asos-techblog/style-actionmode-on-android-5e613fa77c32, https://developer.android.com/guide/topics/ui/menus e.g.) on implementing my Contextual Action Menu but as you can see in this image:
https://i.stack.imgur.com/ag2Mp.jpg
There is part of the titleBar still visible on the bottom. My question is if there is anything i can do to change this behaviour.
I also tried to change the style of my ActionModeBar but when i change the styling it becomes invisible (only showing the icons) and the titlebar is completely visible.
I have not made any changes to the ActionMode except the menu that contains the buttons:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/stopCab"
          android:title="Stop contextual action bar"
          app:showAsAction="ifRoom"
          android:icon="@drawable/ic_baseline_cancel_24"/>

    <item android:id="@+id/deleteCab"
          android:title="Delete selected items"
          app:showAsAction="ifRoom"
          android:icon="@drawable/ic_delete_white_24dp"/>
</menu>

Initializing the ActionMode:
    private ActionMode.Callback actionModeCallback = new ActionMode.Callback() {

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.contextual_action_bar_menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.deleteCab:
                    //TODO: do something
                    return true;
                case R.id.stopCab:
                    //TODO: do something
                    return true;
                default:
                    return false;
            }
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {
            FieldChooserActivity.this.actionMode = null;
        }
    };

And starting the ActionMode:
FieldChooserActivity.this.actionMode = startActionMode(FieldChooserActivity.this.actionModeCallback);

In my Style the AppTheme parent is Theme.AppCompat.Light.DarkActionBar
And each Activity has
android:theme="@style/AppTheme.NoActionBar">

in AndroidManifest.
Maybe this is the fault why i cant change the style without the ActionMode becoming invisible.
I hope someone can help me with this matter and thanks in advance!

A: I found a solution that fixed my problem (where the ActionMode bar doesn't cover the Toolbar).
As i looked at the layout of my activity i saw that in the Toolbar is a height attribute called '?attr/actionBarSize':
<androidx.appcompat.widget.Toolbar
    android:id="@+id/fieldChooserToolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay">

I then added the height to a custom style for my ActionMode:
<style name="ActionModeTheme" parent="AppTheme">
    <item name="windowActionModeOverlay">true</item>
    <item name="actionModeCloseDrawable">@drawable/ic_delete_white_24dp</item>
    <item name="actionMenuTextColor">@android:color/white</item>
    <item name="height">?attr/actionBarSize</item>
    <item name="background">@color/colorSecondary</item>
    <item name="android:src">@drawable/ic_baseline_close_24</item>
</style>

The last part was that i added following line to my AppTheme-styling:
<item name="actionModeStyle">@style/ActionModeTheme</item>

And then it worked!
The second problem where my ActionMode bar was invisible was most likely caused by adding the actionModeStyling to the AppTheme.NoActionBar.


text:
Q: How to convert an integer to a c-string and vice versa and other datatypes without using any in-built functions? I don't understand the basic concept of it.

A: 4567

means
4 * 10^3 + 5 * 10^2 + 6 * 10^1 + 7 * 10^0

This can also be written as
( ( 4 * 10 + 5 ) * 10 + 6 ) * 10 + 7

If the number is formed by repeatedly multiplying by 10, that means that taking it apart is done by repeatedly dividing by 10.
4567/10 = 456 + 7/10
 456/10 =  45 + 6/10
  45/10 =   4 + 5/10
   4/10 =   0 + 4/10

The remainder of these divisions, once added to '0', will given the digits of your string.

A: A string in C is a sequence of character values including a zero-valued terminator - the string "1234" is represented as the character sequence {'1', '2', '3', '4', 0}.  Assuming ASCII encodings, that's a byte sequence of {0x31, 0x32, 0x33, 0x34, 0x00}.
An integer value in C is a standard binary representation.  Assuming a 32-bit integer, the value 1234 is represented as 0x000004d2 - not anywhere similar to the string representation.
Converting a string representation of a decimal integer ("1234") to an integer value is fairly straightforward:
int result = 0;
char *p = "1234";

while ( *p )  // while we haven't reached the end of the string
{
  result *= 10;           // shift our result by 1 digit left
  result += (*p++ - '0')  // convert the current character
                          // to its decimal equivalent and
                          // add to the result, and advance
                          // p to point to the next character
}

So as we process the string "1234", we get
result = 0            // 0
result = 10 * 0 + 1   // 1
result = 10 * 1 + 2   // 12
result = 10 * 12 + 3  // 123
result = 10 * 123 + 4 // 1234

The C standard mandates that decimal digit encodings be sequential, so '1' - '0' yields 1, '2' - '0' yields 2, etc.
Going the other way (integer to string) is a little more involved.  You have to make sure your target buffer is large enough to hold the string, including a sign and the terminator.  It takes a little over 3 bits on average to represent a decimal digit, so a 32-bit integer could potentially represent 10 decimal digits. Your target buffer would need to be at least 12 characters wide to account for a possible sign and the terminator.
You can get the individual decimal digits from right to left by successively dividing the integer value by 10:
char target[14] = {0};
int value = 1234;
size_t end = 4; // this is a cheat
while ( value )
{
  digit = value % 10;   // isolate the least significant digit
  value /= 10;          // shift value one digit right
  char c = '0' + digit; // convert digit to character
  target[––end] = c;    // add the digit to the string.
}

I'm cheating a bit since I know how many digits to convert ahead of time - in the general case, you'd have to figure out how many digits to account for, and whether or not you have to take the sign into account.


text:
Q: How to reference a shared object file in multiple modules in Android NDK? I have a logger module in my project, this has been built as an shared object; so that it can be referenced from different modules in the same project. But facing issues during linking. My folder structure is like
jni
|- Logger (Folder Logger)
|- Module a(Folder a)
|- Module b(Folder b)
|- Module c(Folder c)

Logger has Android.mk file and creating the shared object of the logger. This logger module is being referenced from modules a, b & c. During compilation it is fine, but during linking getting undefined reference to error in all the modules for logger functions. I am referencing them in LOCAL_SHARED_LIBRARIES := logger in other modules. If I try to include the Logger/Android.mk file in the modules then getting error module was already defined. I tried including like LOCAL_LDLIBS := -llogger as well. But no luck :(.
Please let me know if anyone has resolved this issue.
Thanks.

A: Don't do include of the Logger/Android.mk file in multiple modules. Include the same in the Parent Android.mk file (jni/Android.mk) and in the rest of the modules define in LOCAL_SHARED_LIBRARIES := logger.
My Mistake. I did an include $(LOCAL_PATH)/../Logger/Android.mk in all the other modules as well.


text:
Q: SO keeps saying "visit your user page to set your name and email." When I log in to Stack Overflow, the top banner says "Welcome to Stack Overflow! Visit your user page to set your name and email." But I have set it, as witnessed by the Autobiographer badge.
Now that I have "registered" here, I get the same thing: "Welcome to Meta Stack Overflow! Visit your user page to set your name and email."
Is this normal?


text:
Q: React When i am trying to get into a nested object the fetch throws me an undefined error import React from 'react'
import { useEffect, useState } from 'react'

function PokemonCard() {
const [pokemon, setPokemon] = useState([])
useEffect(() => {
  fetch('https://pokeapi.co/api/v2/pokemon/charizard')
  .then(res => res.json())
  .then(setPokemon)
},[])
const pokemonType = pokemon.types
console.log(pokemonType)

//HERE I GET THE ERROR
pokemonType.map(x => console.log(x.type.name))
return (

{pokemon.name}

      {/*  */}
      {/*
Type: {pokemonType}
 */}

Height: {pokemon.height}

Weight: {pokemon.weight}

)
}

export default PokemonCard;

this is the link for the api
https://pokeapi.co/api/v2/pokemon/charizard
when i try to get into the pokemon.types.type.name i get a error saying
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at PokemonCard (PokemonCard.js:16:1)
at renderWithHooks (react-dom.development.j

A: That is due to pokemonType is undefined initially. Try using optional chaining operator:
pokemonType?.map((x) => console.log(x.type.name));

Answer for what you tried in the comment:
const pokemonType = pokemon.types?.[0]?.type.name;

If you wanted to get the types rendered then use this:

function PokemonCard() {
  const [pokemon, setPokemon] = React.useState([]);
  React.useEffect(() => {
    fetch("https://pokeapi.co/api/v2/pokemon/charizard")
      .then((res) => res.json())
      .then(setPokemon);
  }, []);

  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

  return (

{pokemon.name}

      {pokemon.types &&
        pokemon.types.map(({ type: { name } }) => (

{capitalizeFirstLetter(name)}

        ))}

Height: {pokemon.height}

Weight: {pokemon.weight}

  );
}

ReactDOM.render(<PokemonCard />, document.querySelector('.react'));

A: map over the types property in the JSX. Note that the objects in the types array doesn't hold height or weight properties so I'm assuming you wanted to add the height and weight from the pokemon object.
If you want to make the name uppercase add a class to the element that holds the name, and use CSS to make it uppercase. If you meant only to capitalise the first letter use .pokemonName { text-transform: capitalize; } instead.

const { useEffect, useState } = React;

function PokemonCard() {

  const [ pokemon, setPokemon ] = useState();

  useEffect(() => {
    fetch('https://pokeapi.co/api/v2/pokemon/charizard')
      .then(res => res.json())
      .then(setPokemon);
  }, [])

  if (!pokemon) return
Loading pokemon data
;

  return (

      {pokemon.types.map(({ id, type }) => {
        return (

              {type.name}

Height: {pokemon.height}

Weight: {pokemon.weight}

        );
      })}

  );

}

ReactDOM.render(
  <PokemonCard />,
  document.getElementById('react')
);
.pokemonName { text-transform: uppercase; }


text:
Q: Puppet - Variable for package name fails I'm new to puppet, and I am stumped.
I am installing gcc, gcc-c++, openssl and openssl-devel.
In the code shown, $openssl_devel works but $c_plus is undefined.
Why is puppet setting $c_plus to 'undef' ?
Cent OS 6
class torque::prerequisites {
case $operatingsystem {
      centos,redhat: {$openssl_devel    = 'openssl-devel'}
      centos,redhat: {$c_plus           = 'gcc-c++'}

      debian,ubuntu: {$openssl_devel    = 'libssl-dev'}
      debian,ubuntu: {$c_plus           = 'build-essential'}

      default:{fail("Unable identify opperating system. $operatingsytem not recognized") }
    }

    package {'openssl':
      ensure => latest,
    }
    package {$openssl_devel:
      ensure   => latest,
      require => Package['openssl'],
    }
    package {'gcc':
        ensure => installed,
    }
    package {$c_plus:
        ensure => installed,
        require => Package['gcc'],
    }
}

class {'torque::prerequisites':}

puppet apply torque_prerequisites
err: /Stage[main]/Torque::Prerequisites/Package[undef]/ensure: change from absent to present failed: Could not find package undef

A: I still don't know why the original syntax didn't work, but this syntax does works:
class torque::prerequisites {
case $::osfamily {
    Redhat: {
      $openssl_devel = 'openssl-devel'
      $c_plus_compiler  = 'gcc-c++'
    }
    Debian: {
      $openssl_devel = 'libssl-dev'
      $c_plus_compiler = 'build-essential'
    }

  default:{fail("Unable identify opperating system. $operatingsytem not recognized") }
}

package {'openssl':
  ensure => latest,
}
package {$openssl_devel:
  ensure   => latest,
  require => Package['openssl'],
}
package {'gcc':
    ensure => installed,
}
package {$c_plus_compiler:
    ensure => installed,
    require => Package['gcc'],
}
}

class {'torque::prerequisites':}


text:
Q: How much time and effort do you spend on IE6? I've often read that corporations will save millions once Internet Explorer 6 is finally laid to rest, but reading quotes like that make me wonder just how much time people are spending on IE6 development. I'll be happy once IE6 goes, but I've found that if I write valid HTML and CSS, use a JavaScript framework, keep the transparent images issue in mind, and don't try to over-complicate my design, I only need to write a few lines of IE6-specific CSS, which usually takes about 10-15 minutes. So I'm curious, how much time, effort, and money do you or your corporation spend on preparing your sites for IE6? Also, at what point will you drop IE6 support? If you've already dropped support, what has been your experience in terms of saved time and money and what has the switch done to your conversion rates and customer satisfaction?

A: According to some - browser - statistics, IE6 market share is still bigger than Chrome, Safari and Opera together, nearly as much as IE7.
Unless you target a very specific market (indeed check your stats to know for sure), neglecting to make your site looking at least decent with IE6 seems a bit foolish today...
I won't take the road to tell visitors what browser to use, for sure!

A: I'm already phasing it out. Every second spent on debugging for an outdated (7+ years old!!) browser is a second wasted in my books. What I've started doing is when an IE6 user first comes to the site (determined by cookies and some dodgy browser sniffing), I pop up an alert informing them that they are using an old browser which does not support much of the functionality required by many of today's web sites. I inform them that their experience might be slightly downgraded by continuing, but that can be easily alleviated by upgrading to a modern web browser (even if it sucks).
Don't go out of your way to make it crappy for them (though they might deserve it), but don't go out of your way (with non-standard CSS hacks etc) for these users either. There's only one way they'll learn.

A: I don't like it but I still support it. For small sites it isn't a problem, just make stuff work in Firefox first, then IE7, and IE6 last. I've used IE6-only css a number of times, and those only had a few rules in them.
For a larger project with complex layouts, I have wasted a lot of time on IE6. I'd be very happy to drop it entirely if it was impossible to provide one of my major features on it. So far, it's close enough that I'm still supporting it.
According to what I read online, about 1/4 people still use it, so it's probably not wise to drop support.
http://www.w3schools.com/browsers/browsers_stats.asp
Use your own judgement, based on your application and what you think you can expect from your users. I do not believe that a typical web user will upgrade/switch their browser just for one site. I think those people who have not upgraded from IE6 by now will never be motivated to do so. The number of IE6 users is dropping, but I think we'll be waiting for them to replace their computers rather than upgrade their browsers.

A: At my job all of our projects are for large corporations that aren't willing to drop support for a browser with such a large market share. Also, the designs we have are dictated to us by a third party design company so, even conforming to standards, there are still issues with complex designs in IE 6.
I would say for any given page about 5%-50% of the CSS development time is devoted to IE 6, depending on who the developer is and how complex the design is. The more experienced the developer and the simpler the design the better your odds are at hitting that 5% mark :) But even myself, with a good amount of IE 6 web-dev experience, have spent 3 hours on CSS for a page only to spend another 3 hours ironing out small quirks in IE 6.
Another thing that comes up is that certain markup + CSS approaches that seem so intuitive and simple in more modern browsers don't work at all in IE 6. If you go down one of these paths, you generally have to start from scratch once you realize that your code that works beautifully in FF and IE 7 doesn't have a chance in IE 6. More lost time...
I agree with the rest of you that if you can control your project and don't care about the IE 6 market, by all means forget about it. Unfortunately, some of us don't have that luxury quite yet.

A: We've already dropped it, but it depends on who you're marketing to.  Only other companies will ever see our product, so we can be fairly certain they're at least using an operating system that can support IE7.  If you're marketing to the entire internet then you may want to make certain that nothing breaks for a while yet.

A: Depends on the project. If I write the code conforming to web standards usually I don't have many issues.
If I'm using a template downloaded from the web, it often spells out very clear in bold letters: "manifest destiny is a bitch. don't trade blankets with anyone."

A: Unfortunately, I have a bunch of friends in other businesses that are sticking with IE6, and don't have a plan to upgrade.
They don't like the tabs in IE7, they don't want to go with another browser, etc, etc, etc.
There is enough of this that filters back to me, that I continue to test against IE6, and will do so for the indefinite future.  Doesn't make me happy...just do it.

A: The vast majority of our internal corporate users are still on IE6.  Until the powers-that-be decide to push out an update with IE7 or IE8 we will continue to support IE6 as our primary browser.
As far as I know, there are no immediate plans to upgrade.

A: Zero.  Dead and gone as far as I'm concerned.

A: Really, you should be answering this question for yourself.
If you don't have a decent web log statistics package such as AWStats, then there's the first thing you need to do.
Otherwise, decide how much time you spend supporting IE6, and see what percentage of your users that is.  If the time-to-customers ratio doesn't balance out, then you can decide to ditch IE6.  Another factor to consider is how important your product is to your customers.  If you're working on Salesforce.com, you can probably assume that they'll be willing to upgrade if you prompt them to do it.  If you're talking about a server that injects ads into webpages, then you'll probably be at their mercy of browser choice.


text:
Q: Query Rewriting with URL Parameter I cannot get the query rewriting to work as expected. The desired outcome is for requests going to wpsite.com/foo/bar/2/ to be rewritten as wpsite.com/foo/bar/?my_id=2.
functions.php
// Add custom URL parameters
function add_custom_query_var( $vars ){
  $vars[] = "my_id";
  return $vars;
}

add_filter( 'query_vars', 'add_custom_query_var' );

// Add rewrite for my_id
function custom_rewrite_basic()
{
    add_rewrite_rule('^foo/bar/([0-9]+)/?', 'foo/bar/?my_id=$matches[1]', 'top');
}

add_action( 'init', 'custom_rewrite_basic' );

bar.php
$my_id = filter_input( INPUT_GET, "my_id", FILTER_SANITIZE_NUMBER_INT );

var_dump($my_id);

When I call /foo/bar/?my_id=2 I see 2, when I use /foo/bar/2/, I do not.
Update
After flushing the cache the result improved. However, regardless of the passed parameter (3, 256205), $my_id comes back as 1.
wpsite.com/foo/bar/?my_id=2 shows 2
wpsite.com/foo/bar/2/ shows 1

A: This was solved by changing $matches[1] to $1:
// Add rewrite for my_id
function custom_rewrite_basic()
{
    add_rewrite_rule('^foo/bar/([0-9]+)/?', 'foo/bar/?my_id=$1', 'top');
}

add_action( 'init', 'custom_rewrite_basic' );

And of course flushing cache.


text:
Q: Left Join on three tables in access with Group by I have broken my head with syntax error response from Access Jet engine.
I have three tables.
First one "tblMstItem" is the master table for Item details contains two columns "colITemID" PK and "colItemName"
Second one "tblStocks" is the table where the purchases are maintained. This table has a column "colRQty" which keeps the quantity of the particular item purchased. "colItemID" FK from "tblMstItem"
Third one "tblSales" is the table where the sales are maintained. This table has a column "colSoldQty" which keeps the quantity of the particular item sold. "colItemID" FK from "tblMstItem"
Therefore "colItemID" is common in all the three tables and has links created.
My requirement is I need all the Items listed in the "tblMstItem" table columns are "colItemID" "colItemName" and if there is any item purchased or any item sold should be shown as sum of that particular item.
I have used Left Join shown in the following select statement but it always giving me an error message.
Select statement as follows:
SELECT
      i.colItemID,
      i.colItemName,
      s.rqty,
      n.soldqty
from tblMstItem i
left join
         ( select sum( colRQty ) as rqty from tblStocks group by colItemID ) s
on i.colItemID = s.colItemID
left join
         ( select sum( colSoldQty ) as soldqty from tblSales group by colItemID ) n
on i.colItemID=n.colItemID``

I tried the above given code with many different syntax but every time I get syntax error. It is making me to doubt do MS Access support three table joins, I am sure I am wrong.
See the error Message below

Table columns and table link shown below

I would be very thankful to get any help on this. Access sql please because this I am able to get results in SQL Server.
Thanks in Advance

A: MS Access has a picky syntax.  For instance, joins need extra parentheses.  So, try this:
select i.colItemID, i.colItemName,
       s.rqty, n.soldqty
from (tblMstItem as i left join
      (select colItemID, sum(colRQty ) as rqty
       from tblStocks
       group by colItemID
      ) as s
      on i.colItemID = s.colItemID
     ) left join
     (select colItemID, sum( colSoldQty ) as soldqty
      from tblSales
      group by colItemID
     ) as n
     on i.colItemID = n.colItemID;

You also need to select colItemID in the subqueries.


text:
Q: Try to installing git on pipenv I'd like to install ERP software and I want to install it using pipenv as package management. First of all the dependencies is listed in odoo github and I'd like to copy it to my computer. Apparently I don't have git so I tried to install it using pipenv install git but return this,
ERROR: Could not find a version that satisfies the requirement git (from versions: none)
ERROR: No matching distribution found for git
I could install git in the global but I tried to avoid this way since I want to isolate everything. Is there another way to make this works?


text:
Q: Vertically aligning text in a Button Is there a way to center the "+" and "-" font inside my buttons?
You can see that the "-" font is not vertically aligned in the center of the button. The only solution I could think of is adding an image icon of a "+" or "-" instead of using the a button but I would prefer to have a button font.

A: Not really, but in this particular case you could add padding-bottom: 0.2em; to that button's CSS as a workaround (fine-tune that value according to the used font).

A: you can add those tags to the button style
display:flex;
align-items:center;

it makes everything in a center vertically


text:
Q: Routing error - No route matches [POST] Have read many questions / answers on this issue, yet do not seem to find my fix.
Here is the issue: I am following the getting started for Rails to create a simple register of annotations. My forms work - can add new & update annotations. Yet when I add links to the index, I get a routing error:

*

*This: <%= button_to "Details", annotation_path(annotation), :class => "btn btn-primary btn-xs"%> results in: No route matches [POST] "/annotations/5"

*This: <%= button_to "Add Annotation", new_annotation_path, :class => "btn btn-primary btn-xs"%> to No route matches [POST] "/annotations/new"
Thanks for help
Routes.db:
Rails.application.routes.draw do
  root 'dashboard#index'
  devise_for :users
  resources :users, :annotations

Controller:
class AnnotationsController < ApplicationController

    def index
        @annotations = Annotation.all
    end

    def show
        @annotation = Annotation.find(params[:id])
    end

    def new
        @annotation = Annotation.new
    end

    def edit
        @annotation = Annotation.find(params[:id])
    end

    def create
        @annotation = Annotation.new(annotation_params)

        @annotation.save
        redirect_to @annotation
    end

    def update
        @annotation = Annotation.find(params[:id])

        if @annotation.update(annotation_params)
            redirect_to @annotation
        else
            render 'edit'
        end
    end

    def destroy
        @annotation = Annotation.find(params[:id])
        @annotation.destroy

        redirect_to annotations_path
    end

    private
        def annotation_params
            params.require(:annotation).permit(:name, :description)
        end
end

And the form (= partial)
<%= simple_form_for @annotation, url: annotations_path, html: { class: 'form-horizontal' },
    wrapper: :horizontal_form,
    wrapper_mappings: {
        check_boxes: :horizontal_radio_and_checkboxes,
        radio_buttons: :horizontal_radio_and_checkboxes,
        file: :horizontal_file_input,
        boolean: :horizontal_boolean
    } do |f| %>

    <%= f.error_notification %>

    <%= f.input :name, placeholder: 'Enter name' %>

    <%= f.input :description, placeholder: 'Description' %>

    <%= f.input :file, as: :file %>

    <%= f.input :active, as: :boolean %>

    <%= f.input :choice, as: :check_boxes,
    collection: [
      'Option one ...',
      'Option two ...'] %>

    <%= f.input :documenttype, as: :radio_buttons,
    collection: ['Type1', 'Type2'] %>

  <%= f.button :submit %>

<% end %>

Note on the form: to no avail, I tried using <%= simple_form_for :annotation, url: annotations_path,

A: The issue is because the button_to helper actually generates a form at code level and thus is POSTing said form, however the route for a new resource must be a GET.
The button_to tag really should not be used for GET requests so I would use a link_to with CSS classes instead (you already have the necessary classes), but you can do it using the below if you wanted:
<%= button_to "Details", annotation_path(annotation), class: "btn btn-primary btn-xs", method: :get%>

The better approach however is:
<%= link_to "Details", annotation_path(annotation), class: "btn btn-primary btn-xs" %>

A: Read doc here button_to
The method is by default :post change it using :method param
<%= button_to "Details", annotation_path(annotation), :class => "btn btn-primary btn-xs", method: :get%>

<%= button_to "Add Annotation", new_annotation_path, :class => "btn btn-primary btn-xs", method: :get%>


text:
Q: GET return undefined value out function I have global variable fan_coil_ai_bi, and I use that variable to store some data which I get from request, but problem is that len_1 is 1 ( what is ok value in this case ) and len_2 is undefined (what is wrong). How that happen in my function bellow ? How to achieve that len_2 have same value like len_1 ? What is wrong with this code ?
function read_required_fields(fan_coil_id) {
    var parameters = {};

    parameters['command'] = 'read_required_fields';
    parameters['fan_coil_id'] = fan_coil_id;

    $.get("php_scripts/network_script.php", parameters, function(data) {
        fan_coil_ai_bi=data;
        alert('len_1='+fan_coil_ai_bi.length);
    }, "json");
    alert('len_2='+fan_coil_ai_bi.length);
}

A: Asynchronous JavaScript and XML is asynchronous.
The get method means "Make an HTTP get request and when it gets a response, do this".
It does not pause execution of the function until the HTTP response arrives.
If you want to do anything with the data, do it in the callback function (or a function you call from it).
$.get("php_scripts/network_script.php", parameters, function(data) {
    fan_coil_ai_bi=data;
    alert('len_1='+fan_coil_ai_bi.length);
    alert('len_2='+fan_coil_ai_bi.length);
}, "json");

A: You might want to learn about asynchronous code. In your case, what's happening is:

*

*Request is being sent

*len_2 is being alerted

*Request finished (there is a response), len_1 is being alerted

So when len_2 is being alerted, fan_coil_ai_bi.length has not been defined yet.
There is no possibility to solve this; rather you already have a working solution: move dependencies into the callback.


text:
Q: how to create deployable war in spring using maven Creating war in spring what are the dependency needed ?
1) maven compiler and maven war plugins are required ?
2) How to add class path reference to war package ?

A: Create a Maven Spring project and in pom.xml change the packaging to war:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>Maven Spring Project</artifactId>
    <packaging>war</packaging>

And just build the project using Maven by executing goal : "clean install". It will automatically create war file in target folder of Maven project.

A: You can try this in your pom.xml
<build>
        <finalName>projectname</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.0</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin-version}</version>
                <configuration>
                    <source>${jdk-version}</source>
                    <target>${jdk-version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>${maven-war-plugin-version}</version>
                <configuration>
                    <warSourceDirectory>${basedir}/src/main/webapp</warSourceDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.17</version>
                <configuration>
                    <argLine>-XX:-UseSplitVerifier</argLine>
                </configuration>
            </plugin>
        </plugins>
    </build>

and to make war run this package tomcat7:run goal from eclipse


text:
Q: Kubernetes external secret with hashicorp vault - Error handling if secret not available In our helm based Kubernetes project, we're fetching external secrets from hashicorp vault, as shown in the below example. Deployment is done using Argocd
apiVersion: 'kubernetes-client.io/v1'
kind: ExternalSecret
metadata:
  name: hello-vault-service
spec:
  backendType: vault
  vaultMountPoint: my-kubernetes-vault-mount-point
  vaultRole: my-vault-role
  data:
  - name: password
    key: secret/data/hello-service/credentials

If vault path secret/data/hello-service/credentials is missing, currently we are getting 404 error. We need to handle this error by taking the default dummy secret value from values.yaml if external secret path not found.
Could someone please help