text:
Q: Permission denied in custom buildpack I am writing a custom buildpack that downloads a file and stores it inside /var/lib/myfolder
To do this I first run mkdir -p /var/lib/myfolder
But this results in a Permission Denied when running the buildpack.
How can I solve this?

A: Only the /app folder will be stored at the end of your build, and your buildpack doesn't have sudo access.
You need to store all files inside that folder, and configure your libraries to use dependencies under the right path there.


text:
Q: How to serialize an XmlDocument to a well-formatted human-readable XML? I use an XmlDocument.WriteTo(XmlWriter) method to serialize an XmlDocument to a text file. I have also tried XmlDocument.OuterXml. Both output a single-line XML text which is very hard (up to impossible in case of a reasonably big XML document) to read for a human.
Is there a way to output a well-formatted human-readable XML text instead? I mean with every element starting at a new line and indentation used to visualize hierarchy levels.

A: I agree to BoltClock.
Here is the sample code-
//Create a writer to write XML to the console.
XmlTextWriter writer = null;
writer = new XmlTextWriter (Console.Out);
//Use indentation for readability.
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;

A: If you're using XmlTextWriter to write to the file, you can set its Formatting property to Formatting.Indented before you write.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Application metrics monitoring of Kubernetes Pods We are already using node-exporters to pull/collect docker/container metrics within our kubernetes environment. Next we would also like to be able to collect application metrics (provided by spring-actuator in our case, eg. http://pod-name:8080/prometheus). How is this typically done, keeping in mind we cannot use Kubernetes services as fixed DNS names (they are load balanced over the pods behind the service) and the fact that pods disappear and appear all the time, changing their name and hence addressability?
Our initial naive approach was the following (but this will not be sufficient since it is load-balanced by the service):
- job_name: 'example-service'
  scheme: http
  metrics_path: '/prometheus'
  static_configs:
   - targets: ['example-service:8080']

Any advice or examples would be really great.
Thanks a lot in advance,
Bart

A: I found an example in the meanwhile... question closed.
# Example scrape config for pods
#
# The relabeling allows the actual pod scrape endpoint to be configured via the
# following annotations:
#
# * `prometheus.io/scrape`: Only scrape pods that have a value of `true`
# * `prometheus.io/path`: If the metrics path is not `/metrics` override this.
# * `prometheus.io/port`: Scrape the pod on the indicated port instead of the default of `9102`.
- job_name: 'kubernetes-pods'

  kubernetes_sd_configs:
  - role: pod

  relabel_configs:
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
    action: keep
    regex: true
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
    action: replace
    target_label: __metrics_path__
    regex: (.+)
  - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
    action: replace
    regex: ([^:]+)(?::\d+)?;(\d+)
    replacement: $1:$2
    target_label: __address__
  - action: labelmap
    regex: __meta_kubernetes_pod_label_(.+)
  - source_labels: [__meta_kubernetes_namespace]
    action: replace
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_pod_name]
    action: replace
    target_label: kubernetes_pod_name


text:
Q: VolumeMount Name not found I have below StatefulSet postgres for EKS. When I run it I am getting below error.
Events:
  Type     Reason        Age               From                    Message
  ----     ------        ----              ----                    -------
   Warning  FailedCreate  7s (x17 over 1m)  statefulset-controller  create Pod postgres-0 in StatefulSet postgres failed error: Pod "postgres-0" is invalid: spec.containers[0].volumeMounts[0].name: Not found: "postgredb"

StatefulSet:
  apiVersion: apps/v1
  kind: StatefulSet
  metadata:
    name: postgres
  spec:
    selector:
      matchLabels:
        app: postgres # has to match .spec.template.metadata.labels
    serviceName: "postgres"
    replicas: 1
    template:
      metadata:
        labels:
          app: postgres
      spec:
        terminationGracePeriodSeconds: 10
        containers:
          - name: postgres
            image: postgres:10.4
            imagePullPolicy: "IfNotPresent"
            ports:
              - containerPort: 5432
            volumeMounts:
              - name: postgredb
                mountPath: /var/lib/postgresql/data
    volumeClaimTemplates:
      - metadata:
          name: postgresdb
          annotations:
            volume.beta.kubernetes.io/storage-class: "aws-efs"
        spec:
          accessModes: [ "ReadWriteOnce" ]
          resources:
            requests:
              storage: 1Gi

I have StorageClass configured as well. What am I doing wrong here?

A: Just a typo.
volumeMounts:
  - name: postgredb

It should be name:postgresdb, not name:postgredb.


text:
Q: Delay interval in recurring jobs in Hangfire We have a recurring job in Hangfire that runs every 5 minutes.
But we want to wait for 1 min after every 5 min when the next job will start.
Is there any way to do this in hangfire.
Thanks


text:
Q: How to enable emulator control in android device monitor This is my screen shot of my problem which am facing. Help me to enable this emulator control in android device monitor.so can you help me with the solution ?

A: Enable telnet client on your computer.
If you are windows user follow this step:
1.go to control panel
2.go to programs and features
3.click on "turn windows feature on or off" a prompt box will be appear()
4.mark the checkbox of Telnet Client
5.open command prompt and type "telnet localhost port_number" (see cmd image) after this connection will be establish.
device monitor in android studio only works for the default emulators. It does not work for genymotion or mobile device.


text:
Q: Display 'Assigned To' field of task in text format into LWC I have created LWC where i need to display task field 'ASSIGNED TO' in text format. but I am getting error as
"Unsupported reference Task.Owner.Name of type sobjectField in file partnerTaskRecordReadForm.js"
.html :
<template>
<lightning-card>

        <template if:true={TaskRecord}>
            <lightning-record-form
            record-id={TaskRecord}
            object-api-name={taskObject}
            >

            <lightning-messages></lightning-messages>

                <lightning-accordion active-section-name="A">
                    <lightning-accordion-section name="A" label="Task Details">

                                    Assigned To

{ownerName}

                    </lightning-accordion-section>
                </lightning-accordion>

        </lightning-record-form>
        </template>

</lightning-card>

.js file:
import { LightningElement, api, wire} from 'lwc';
import { getRecord, getFieldValue }   from 'lightning/uiRecordApi';
import Task_OBJECT                    from '@salesforce/schema/Task';
import Task_Assigned_To               from '@salesforce/schema/Task.Owner.Name';

const fields =  [Task_Assigned_To];

export default class partnerTaskRecordReadForm extends LightningElement
{
   @api  TaskRecord;
   @api  recordId;
    taskObject        = Task_OBJECT;

  @wire(getRecord, { recordId: '$TaskRecord', fields})
  Task;

  get ownerName()
  {
      return getFieldValue(this.Task.data, Task_Assigned_To);
  }
}

It did work for opportunity, but not working for task. Can any one please suggest how to achieve this?

A: User Interface API does not support the "Task" object so you can't get the task record using the getRecord() method of lightning/uiRecordApi module.
You can find all the supported standard objects here - https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_get_started_supported_objects.htm
For your issue, you have to use the apex controller method to get the task record.

A: Lightning record form is not supported by Task,Event object yet as documented : https://developer.salesforce.com/docs/component-library/bundle/lightning:recordForm/documentation


text:
Q: How to add DataGridViewComboboxColumn to a Datagrid I am creating a table view where some info is given and the user gets a chance to add some additional info found in a Combobox.
Adding the normal text fields is no problem. But when I try to add the Combobox column I get the following error:

Error  CS1503  Argument 1: cannot convert from >'System.Windows.Forms.DataGridViewComboBoxColumn' to >'System.Data.DataColumn' test    C:\Users\TomekJasinski\Documents>\Hello_world\test\test\Window1.xaml.cs 52  Active

private void populateGrid(List<String> str)
{

     DataTable table = new DataTable();

     DataColumn xCord = new DataColumn("X Cord", typeof(string));
     DataColumn yCord = new DataColumn("Y Cord", typeof(string));
     DataColumn rotation = new DataColumn("Rotation", typeof(string));
     DataColumn partRef = new DataColumn("Part Reference", typeof(string));
     DataColumn partNumb = new DataColumn("Part Number", typeof(string));

     table.Columns.Add(xCord);
     table.Columns.Add(yCord);
     table.Columns.Add(rotation);
     table.Columns.Add(partRef);
     table.Columns.Add(partNumb);

     DataGridViewComboBoxColumn dgvCmb = new DataGridViewComboBoxColumn();
     dgvCmb.HeaderText = "Name";
     dgvCmb.Items.Add("Ghanashyam");
     dgvCmb.Items.Add("Jignesh");
     dgvCmb.Items.Add("Ishver");
     dgvCmb.Items.Add("Anand");
     dgvCmb.Name = "cbColumn";
     table.Columns.Add(dgvCmb); // <- Error

     foreach (string current in str)
     {
           string[] temp = current.Split(Convert.ToChar(","));
           DataRow row = table.NewRow();
           row[0] = temp[0];
           row[1] = temp[1];
           row[2] = temp[2];
           row[3] = temp[3];
           row[4] = temp[4];

           table.Rows.Add(row);
      }
      dataGrid.ItemsSource = table.DefaultView;
}

A: You should add a System.Windows.Controls.DataGricComboBoxColumn to the DataGrid:
DataGridComboBoxColumn dgvCmb = new DataGridComboBoxColumn();
dgvCmb.ItemsSource = new List<string>
{
    "Ghanashyam",
    "Jignesh",
    "Ishver",
    "Anand"
};
dataGrid.Columns.Add(dgvCmb);

WPF isn't Windows Forms. In WPF, you generally define UI elements in XAML.


text:
Q: removing outline color of scatter plot in matplotlib python Suppose I have gridded data with dimensions (x,y) and values are in z.
so simply we can make scatter plot for third dimension by:
import numpy as np
import matplotlib.pyplot as plt

x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
plt.scatter(x, y, c = z, s=150, cmap = 'jet')
plt.show()

what i am thinking now is to remove the line color of each circular scatter plot. And also instead of circle can we make it square??
I did not find any way to do that. your help will be highly appreciated.

A: *

*Pass the argument edgecolors='none' to plt.scatter. The patch boundary will not be drawn.

*Pass the argument marker='s' to plt.scatter. The marker style will be square.

Then, we have,

The source code,
import numpy as np
import matplotlib.pyplot as plt

x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
plt.scatter(x, y, c = z, s=150, cmap = 'jet', edgecolors='none', marker='s')
plt.show()

Refer to matplotlib.pyplot.scatter for more information.


text:
Q: Regarding Multiple UIPickerview I have three Pickerview as it shown in the image below. I main pickerview, left pickerview, and right pickerview.
The array of main pickerview has group of names, and each name has group of units. I have made array inside array in order to show them where it belongs. But I could not do it. The array for main pivkerview apears in both thr righ and left of pickerviews.
enter image description here
here is my code :
import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
@IBOutlet weak var mainPicker: UIPickerView!
@IBOutlet weak var leftPicker: UIPickerView!
@IBOutlet weak var rightPicker: UIPickerView!
@IBOutlet weak var textFieldLeft: UITextField!
@IBOutlet weak var textFielfRight: UITextField!
@IBOutlet weak var equal: UILabel!

var mainPickerData = []
var leftPickerData = []
var rightPickerData = []

//yourPicker.backgroundColor = UIColor(patternImage: UIImage(named: "back.jpg")!)

override func viewDidLoad() {
    super.viewDidLoad()

    // Connect data:
    self.mainPicker.delegate = self
    self.mainPicker.dataSource = self

    self.leftPicker.delegate = self
    self.leftPicker.dataSource = self

    self.rightPicker.delegate = self
    self.rightPicker.dataSource = self

    let theWidth = view.frame.size.width
    let theHeight = view.frame.size.height

    mainPicker.center = CGPointMake(theWidth/2, theHeight/2 - 182.5)
    leftPicker.center = CGPointMake(theWidth/2 - 100, theHeight/2)
    rightPicker.center = CGPointMake(theWidth/2 + 100, theHeight/2)
    textFieldLeft.center = CGPointMake(theWidth/2 - 90, theHeight/2 + 110)
    textFielfRight.center = CGPointMake(theWidth/2 + 90, theHeight/2 + 110)
    equal.center = CGPointMake(theWidth/2, theHeight/2 + 110)

    let Area = ["Square Mile", "Square Yard", "Square Foot", "Square Inch", "Hectare", "Acre", "Square Kilometer", "Square Meter", "Square Centimeter", " Square Millimeter"]

    let Energy = ["Btus", "Calories", "Ergs", "Foot-Pounds", "Joules", "Kilogram-Calories", "Kilogram-Meters", "Kilowatt-Hours", "Newton-Meters", "Watt-Hours"]

    let Length = ["Mile", "Yard", "Foot", "Inch", "Kilometer", "Meter", "Centimeter", "Millimeter"]

    let Power = ["Btus/Minute", "Foot-Pounds/Min", "Foot-Pounds/Sec", "Horsepower", "Kilowatts", "Watts"]

    let Pressure = ["Pounds/Sqr Ft", "Pounds/Sqr In", "Atmospheres", "Bars", "In of Mercury", "Cm of Mercury", "Kilograms/Sqr Meter", "Pascals"]

    let Speed = ["Knots", "Miles/Hr", "Miles/Min", "Feet/Min", "Feet/Sec", "Kilometers/Hr", "Kilometer/Min", "Meters/Sec"]

    let Temperature = ["Celsius C˚", "Fahrenheit", "Kelvin"]

    let Time = ["Years", "Months", "Weeks", "Days", "Hours", "Minutes", "Seconds", "Millisconds", "Microseconds", " Nanoseconds"]

    let Volume = ["Cupic Feet","Cubic Meter", "Gallon (Imp)", "Gallon (US)", "Quart (US)", "Pint (US)", "Fluid Oz", "Cup", "Tablespoon", "Teaspoon", "Dram (US)", "Liter"]

    let Weight = ["Short Ton (US)","Long Ton (UK)", "Pound (U.S)", "Ounce (US)", "Stone", "Metric Ton", "Kilogram", "Gram"]

    // Pickerview at the center top side of Screen.
    mainPickerData = ["Area", "Energy", "Length", "Power", "Pressure", "Speed", "Temperature", "Time", "Volume", "Weight"]

    // Pickerview at the lower left side of Screen.
    leftPickerData = [["Square Mile", "Square Yard", "Square Foot", "Square Inch", "Hectare", "Acre", "Square Kilometer", "Square Meter", "Square Centimeter", " Square Millimeter"], ["Square Mile", "Square Yard", "Square Foot", "Square Inch", "Hectare", "Acre", "Square Kilometer", "Square Meter", "Square Centimeter", " Square Millimeter"], ["Mile", "Yard", "Foot", "Inch", "Kilometer", "Meter", "Centimeter", "Millimeter"], ["Btus/Minute", "Foot-Pounds/Min", "Foot-Pounds/Sec", "Horsepower", "Kilowatts", "Watts"], ["Pounds/Sqr Ft", "Pounds/Sqr In", "Atmospheres", "Bars", "In of Mercury", "Cm of Mercury", "Kilograms/Sqr Meter", "Pascals"], ["Knots", "Miles/Hr", "Miles/Min", "Feet/Min", "Feet/Sec", "Kilometers/Hr", "Kilometer/Min", "Meters/Sec"],["Celsius C˚", "Fahrenheit", "Kelvin"], ["Years", "Months", "Weeks", "Days", "Hours", "Minutes", "Seconds", "Millisconds", "Microseconds", " Nanoseconds"], ["Cupic Feet","Cubic Meter", "Gallon (Imp)", "Gallon (US)", "Quart (US)", "Pint (US)", "Fluid Oz", "Cup", "Tablespoon", "Teaspoon", "Dram (US)", "Liter"], ["Short Ton (US)","Long Ton (UK)", "Pound (U.S)", "Ounce (US)", "Stone", "Metric Ton", "Kilogram", "Gram"]]

    // Pickerview at the lower Right side of Screen.
    rightPickerData = [["Square Mile", "Square Yard", "Square Foot", "Square Inch", "Hectare", "Acre", "Square Kilometer", "Square Meter", "Square Centimeter", " Square Millimeter"], ["Square Mile", "Square Yard", "Square Foot", "Square Inch", "Hectare", "Acre", "Square Kilometer", "Square Meter", "Square Centimeter", " Square Millimeter"], ["Mile", "Yard", "Foot", "Inch", "Kilometer", "Meter", "Centimeter", "Millimeter"], ["Btus/Minute", "Foot-Pounds/Min", "Foot-Pounds/Sec", "Horsepower", "Kilowatts", "Watts"], ["Pounds/Sqr Ft", "Pounds/Sqr In", "Atmospheres", "Bars", "In of Mercury", "Cm of Mercury", "Kilograms/Sqr Meter", "Pascals"], ["Knots", "Miles/Hr", "Miles/Min", "Feet/Min", "Feet/Sec", "Kilometers/Hr", "Kilometer/Min", "Meters/Sec"],["Celsius C˚", "Fahrenheit", "Kelvin"], ["Years", "Months", "Weeks", "Days", "Hours", "Minutes", "Seconds", "Millisconds", "Microseconds", " Nanoseconds"], ["Cupic Feet","Cubic Meter", "Gallon (Imp)", "Gallon (US)", "Quart (US)", "Pint (US)", "Fluid Oz", "Cup", "Tablespoon", "Teaspoon", "Dram (US)", "Liter"], ["Short Ton (US)","Long Ton (UK)", "Pound (U.S)", "Ounce (US)", "Stone", "Metric Ton", "Kilogram", "Gram"]]
}

// The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if mainPicker.tag == 1 {

        return mainPickerData.count

    }else if leftPicker.tag == 2 {

        return leftPickerData.count

    }else{

        return rightPickerData.count
    }
}

// The data to return for the row and component (column) that's being passed in
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    if mainPicker.tag == 1 {

        return mainPickerData[row] as? String
    }else if leftPicker.tag == 2 {

        return leftPickerData[row] as? String

    }else{

        return rightPickerData[row] as? String
    }

}

// Catpure the picker view selection
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    self.view.endEditing(true)

}

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let titleData = mainPickerData[row]
    let myTitle = NSAttributedString(string: titleData as! String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 15.0)!,NSForegroundColorAttributeName:UIColor.blueColor()])
    return myTitle
}

}

A: Instead of taking an Array, create a Dictionary for you main datasource like this and use it properly to get numberOfRowsInComponent count and  titleForRow.
let dataDict:NSMutableDictionary = ["Area":["Square Mile", "Square Yard", "Square Foot", "Square Inch", "Hectare", "Acre", "Square Kilometer", "Square Meter", "Square Centimeter", " Square Millimeter"]
        ,"Energy":["Btus", "Calories", "Ergs", "Foot-Pounds", "Joules", "Kilogram-Calories", "Kilogram-Meters", "Kilowatt-Hours", "Newton-Meters", "Watt-Hours"]]
let mainPickerData = dataDict.allKeys;
let leftPickerData = dataDict.objectForKey("Energy"); //here you can pas the string return from pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) delegate for main picker

print(mainPickerData);
print(leftPickerData);

if you left and right picker is supposed to contain same data, you can use one data source for that.
Also in the delegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
don't check the tag on your picker instance, if you have already set tags for your pickers, then use the pickerView object in the method signature to check for tag.Do it like this
if pickerView.tag == 1 {...}
else if (pickerView.tag == 2) {...}

The reason that data is showing same in all picker is that in your func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
 the condition is always true . i.e.  mainPicker.tag == 1 , if you have set the tag 1 for mainPicker, hence it return same the data for all pickers.
UPDATED SOLUTION
 // The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    switch (pickerView.tag) {

    case mainPicker.tag:

        return mainPickerData.count

    case leftPicker.tag,rightPicker.tag:

        let currentSelectedIndex = mainPicker.selectedRowInComponent(0)
        leftRightPickerData = (dataDict.objectForKey(mainPickerData[currentSelectedIndex] as! String) as! NSArray)

        return leftRightPickerData.count;

    default:
        break;
    }
    return 0;
}//F.E

// The data to return for the row and component (column) that's being passed in
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    switch (pickerView.tag) {

    case mainPicker.tag:

        return mainPickerData[row] as? String;

    case leftPicker.tag,rightPicker.tag:

        let currentSelectedIndex = mainPicker.selectedRowInComponent(0)
        leftRightPickerData = (dataDict.objectForKey(mainPickerData[currentSelectedIndex] as! String) as! NSArray)

        return leftRightPickerData[row] as? String;

    default:
        break;
    }

    return "";

}

// Catpure the picker view selection
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
    if(pickerView.tag == 1 ){

        let currentSelectedIndex = mainPicker.selectedRowInComponent(0)
        leftRightPickerData = (dataDict.objectForKey(mainPickerData[currentSelectedIndex] as! String) as! NSArray)

        leftPicker.reloadAllComponents();
        rightPicker.reloadAllComponents();
    }
}

Above is the implementation for your UIPickerView delegate and datasource.
Write the following code in your viewDidLoad()
    dataDict = ["Area":["Square Mile", "Square Yard", "Square Foot", "Square Inch", "Hectare", "Acre", "Square Kilometer", "Square Meter", "Square Centimeter", " Square Millimeter"]
        ,"Energy":["Btus", "Calories", "Ergs", "Foot-Pounds", "Joules", "Kilogram-Calories", "Kilogram-Meters", "Kilowatt-Hours", "Newton-Meters", "Watt-Hours"]]
    mainPickerData = dataDict.allKeys;
    leftRightPickerData = dataDict.objectForKey(mainPickerData.firstObject as! String) as! NSArray

I just have added 2 key/value pair for your code, you can add rest of the values in dataDict.
Paste the following code in your class before viewDidLoad()
var dataDict:NSMutableDictionary!
var mainPickerData:NSArray!
var leftRightPickerData:NSArray!


text:
Q: Creating External Table in Hive from Spark I am getting below error while trying to create external table in Hive from Spark and saving the contents .
 The root scratch dir: /tmp/hive on HDFS should be writable. Current permissions are: rw-rw-rw-

I even tried setting permission to /tmp/hive folder to chmod 777 but no success.

A: You might be wrong about giving permission because I think you gave permission to local /tmp/hive directory but you should give permission to /tmp/hive in HDFS
hadoop fs -chmod 777 /tmp/hive

A: Check in hive-site.xml if you are using hdfs, cfs or local filesystem first of all.
For cfs, you will have to use sudo dse hadoop fs -chmod 777 /tmp/hive
For hdfs, you will have to use
sudo hdfs dfs -chmod 777 /tmp/hive or sudo hadoop fs -chmod 777 /tmp/hive
And local i guess, you already took care of.

A: The better way to set scratch directory is /user/${username}/tmp/hive in hive-site.xml. This way all the query details will be written to submitted user scratch dir. In that you case you do not need to change permissions tot he scratch dir. Otherwise global scratch dir should be writable by all users.


text:
Q: Clear terminated EC2 instances from AWS console I'm using Terraform to provision some infrastructure, but the debugging process causes a lot of terminated instances (destroy/recreate). When listing instances in the AWS console, all terminated instances are still listed. Is there a way to clear them? This is causing a lot of clutter.

A: You can remove the clutter by adding a search filter. Type Instance State : !Terminated in the search filter bar at the top. (note the spaces around :)

A: Another (likely less popular) answer: Stop using the console. It's just a thin layer on the Amazon APIs. Write small scripts (using the AWS CLI or Boto) or a small website that will query AWS and show your infrastructure the way you want to see it.

A: They'll disappear after some time (~30 mins)

A: According to official documentation it will be remove automatically after some time.
you can check here
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html


text:
Q: SVG scale absolute size I am trying to display multiple SVG items in the same size, but each SVG item seems to have completely arbitrary size. Setting width/height to the top element did not work. Only transform=scale() worked, but since the argument of scale is ratio, that means that I have to specify different ratio to each item to make them the same size. So, instead of scaling them by ratio, is there any way to scale them to absolute size? Something like "scale to width 100px and height 100px", instead of "scale to 10% width and 10% height".

Mr Michael Mullany, I had tried that before posting this, but it did not work. Did I miss something?

*

*NZ flag was very big and setting size made only the top/left show up:

*Swiss flag was very small and setting the size did not enlarge it:

A: Not an expert on SVG, but:
No, I don't think that's how SVG works, because that kind of scaling operation would require to first draw the thing in some "native" size, then see how much that differs from the desired size, then calculate a correction factor for all coordinates (which is effectively scaling to some percentage of the original size), and redrawing it. And SVG supports effects which are scale-invariant but affect an object's bounding box, so this is mathematically impossible, as far as I can tell!

A: I might not be understanding the question - but is there a reason why you wouldn't use SVG's built-in image element, specifying width and height? (And no preservation of the aspect ratio - which is what I think you want?)
<svg width="1000px" height="1000px" viewBox="0 0 1000 1000">
  <image x="0" y="0" width="100" height-"100" xlink:href="http://yourdomain.com/yourimage.svg" preserveAspectRatio="none"/>
</svg>


text:
Q: Cannot import MPI from mpi4py in cluster I want to running my python code including mpi4py in a cluster.
I made my anaconda environment for mpi4py in the cluster and tested that the mpi4py is installed properly.

But, the cluster throw errors when it runs my code:

What happened on my job? The cluster has found mpi4py, but not MPI! I cannot understand this situation. Please can you give me a guide to make the cluster recognize the MPI setting? The cluster has slurm workload manager.

A: Solved.
Terminal line called python3 from /opt/~~~ path.
Slurm called python3 from /home/user/.conda/~~~ path.
So, I should clarify the path of python in the conda env setting


text:
Q: Wolverine's regeneration capabilities
Possible Duplicate:
How much of Wolverine has to be left to heal?

If someone were to cut off a limb of Wolverine using a weapon sharp enough to cut Adamantium, would the limb regenerate completely, as in regrowing the limb?  Or would the regeneration just heal the skin.

A: The answers and discussions here, here, and a number of other questions already discuss the limits of his healing powers.
Wolverine has had his bone claws broken on a number of occasions and they've grown back just fine.
As it stands, though, the only weapon powerful enough to sever one of his adamantium covered limbs is also able to block his healing power and kill him.


text:
Q: Links Browser via Tor Is it possible to force the Links text browser to use Tor? Links itself contains only socks4a proxy options, which is no good for Tor current. Specifying Privoxy, with Privoxy forwarding to Tor, using http/s proxy Links options doesn't work. Attempting to set http/s environment proxy to Privoxy doesn't work.
How can Links be made to use Tor?

A: I know you specifically asked about the Links web browser, but is it possible for you to use ELinks instead? It is a fork of Links and can be found in most official repositories. ELinks can connect to Tor using Torsocks, a wrapper to torify applications.

Installing Torsocks on Debian based distributions:
# apt install torsocks

Starting Tor:
# systemctl start tor.service

Running ELinks with Torsocks:
$ torsocks elinks https://check.torproject.org


text:
Q: Рассылка на Телеграмм с сайта На сайте есть пользователи с номерами телефонов, у многих есть Телеграмм аккаунты. Нужно сделать так, чтобы админ мог отправить сразу всем (у кого есть телеграмм аккаунт) сообщение на Телеграмм.
Например, в админке есть форма для рассылки, админ заполняет текстовое поле и нажимает на волшебную кнопочку ОТПРАВИТЬ, и это сообщение "идёт" всем у кого есть ТГ.
В какую сторону копать, что читать? В интернете нашел кучу материалов только на тему как создать бота, но про рассылку ничего не говорится.

A: Для рассылки сообщений через бота, пользователи должны будут написать вашему боту (подписаться на бота).
Если слать одинаковые сообщения без бота на более чем 40, 50, ну максимум наверное 100 аккаунтов - вас автоматически забанят за спам.
Придется использовать прокси, множество аккаунтов, уникализировать текст

A: На PHP существует библиотека danog/madelineproto.
$MadelineProto = new \danog\MadelineProto\API();
$MadelineProto->phone_login(readline('Enter your phone number: '));
$MadelineProto->complete_phone_login(readline('Enter the code you received: '));
$MadelineProto->messages->sendMessage(['peer' => '@danogentili', 'message' => 'lel'], ['noResponse' => true]);

Документации тоже немного, но побольше чем на официальных ресурсах телеграма. Автор русский, на нормальные вопросы даже отвечает в телеграме.
Одной секунды между отправками сообщения может быть слишком мало. Необходимую длительность задержек вам придётся угадывать.


text:
Q: Date custom format issue when opening an EPPlus generated Excel file on iOS
*

*I generate an Excel file using EPPLUS.

*It has a date column with CustomFormat.

*I can open this file using Excel (desktop) as well on Android devices without any problem.

*But if I open this file (e-mail attachment) on iPAD/iPhone the date changes to Number.

*If I open and save this file in desktop Excel and
6 Then open this on iPAD/iPhone, the dates are fine

*If a generate a new file using desktop EXCEL.

*Just Open and save it using EPPLUS (no content changes)
9  Then open it on iPAD/iPhone, the date is again changes to Numbers.

*There seems to be some header problem while saving the file in EPPLUS.

Any help shall be highly appreciated.


text:
Q: random product from the list
Possible Duplicate:
php loop random product from the list

i need product list, from witch i could display 4 items randomly.
i have tried to write php code, but need help with syntax and variables to finish up.
<?php

// my product list
function productlistX {
    $array = array(

        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};
        $product {$name = 'product name', $link = 'product link', $img = "product image"};

    )

    // need to display 4 random products from the array above
    foreach  {
        echo "<li>".$name . $link . $img . "</li>"
    }
}

// display these random products in my ajax tab (products.php?order=mytab)
$data['mytab'] = $productlistX;

if (isset($data[$_GET['order']])) {
    echo $data[$_GET['order']];
}
?>

thanks in advance!


text:
Q: The method put(String,Employee3) in the type Map is not applicable for the arguments (int,Employee3) The method put(String, Employee3) in the type Map<String,Employee3> is not applicable for the arguments (int, Employee3 I'm getting like this ...Can anyone say what's the issue?!
Map<String, Employee3> employees = new HashMap<>();
//Employee3 employee1 = new Employee3(1001,"Neethu" , 600000);
//employees.put(employee1.getid(), employee1);
//Employee3 employee2 = new Employee3("1002", 20, 700000);
//employees.put(employee2.getid(), employee2);
//Employee3 employee3 = new Employee3("1003", 20, 1000000);
//employees.put(employee3.getid(), employee3);
//Employee3 employee4 = new Employee3("1004", 20, 1000000);
//employees.put(employee4.getid(),employee4);
// TODO Auto-generated method stub
Employee3 employee5 = new Employee3(1005,"Neethu","doe");
Employee3 employee6 = new Employee3(1006,"Sandy", "doe");
employees.put(employee5.getid(), employee5);
employees.put(employee6.getid(), employee6);
String oldid = "1002";
String newid = "10021";
if (employees.containsKey(oldid)) {
Employee3 employee = employees.get(oldid);
employees.remove(oldid);
employees.setid(newid);
employees.put(newid, employee);
System.out.println("Employee ID Updated Successfully.");
}else {
System.out.println("Employee not found with ID: " + oldid);
}
//Employee3 employeesToUpdate = employees.get(5);
//employeesToUpdate.setid("1005");
//employees.put(employeesToUpdate.getid(), employeesToUpdate);
}
}
The method put(String,Employee3) in the type Map<String,Employee3> is not applicable for the arguments (int,Employee3)


text:
Q: setting MAXDOP server default value Hi I've a server with 2 physical processors with 8 cores each.
Looking through Management Studio Shows me a tree with NUMA 0 and NUMA 1 and inside 8 childs.
The current maxdop is on 0, should I set a different maxdop for the server?
If so this should be 2 or 16?
Should MAXDOP be based on physical or logical processors count?
Thanks, any help is appreciated.
Gabriel

A: This article from Microsoft has some good general guidelines for setting MAXDOP.  In general, you'd want to base this off of logical processor count, and you'd want to set it to 8 for a system with 8 or more processors.  We have a system with 64 logical processors, and we see extreme performance problems when this is set to 0.  We have it at 8, and it seems to work pretty well.  Your best bet is to experiment with a few settings while under your normal load and see how it performs.

A: MAXDOP should be zero unless you have a clear, defined issue caused by the default setting.
I'd do nothing unless I had to, most likely under direction of MS PSS.


text:
Q: each loop in underscore.js template I'm doing something wrong here but I can't see it! Im trying to loop an array in a underscore template. It doesn't work though so I'm missing something, Here's my code, my templates work fine otherwise, it's just the _.each stuff that's bugging out:

I've also done some template settings like this:
_.templateSettings = {
    interpolate: /\<\@(.+?)\@\>/gim
};

A: Because you've only defined an interpolation regex in your custom template settings, underscore doesn't know when to evaluate expressions. When you define custom template settings you need to define and differentiate between interpolation and evaluation. From the underscore template() documentation:

Define an interpolate regex, and an (optional) evaluate regex to match expressions that should be inserted and evaluated, respectively. If no evaluate regex is provided, your templates will only be capable of interpolating values.

In a standard (no custom settings) template the difference is evaluation: <% %> and value interpolation: <%= %>.
So, for example, your template above should be (with standard template settings):
<% _.each([0,1,2,3,4], function(i) { %>
<%= i %>
 <% }); %>

If you want to continue using custom settings you'll need to define an evaluation regex in _.templateSettings as well. Based on your questions and comments something like:
   _.templateSettings = {
      interpolate: /\<\@\=(.+?)\@\>/gim,
      evaluate: /\<\@(.+?)\@\>/gim
  };

And then update your template to use the evaluation form around code blocks and the interpolation form around values, like so:

source: http://documentcloud.github.com/underscore/#template


text:
Q: How does distributed tensorflow work ? (Issue with tf.train.Server) I have some troubles with the new option of tensorflow that allows us to run distributed tensorflow.
I just would like to run 2 tf.constant with 2 tasks but my code never ends. it looks like that :
import tensorflow as tf

cluster = tf.train.ClusterSpec({"local": ["localhost:2222", "localhost:2223"]})
server = tf.train.Server(cluster,
                        job_name="local",
                        task_index=0)

with tf.Session(server.target) as sess:
    with tf.device("/job:local/replica:0/task:0"):
        const1 = tf.constant("Hello I am the first constant")
    with tf.device("/job:local/replica:0/task:1"):
        const2 = tf.constant("Hello I am the second constant")
    print sess.run([const1, const2])

And I have the following code that works (just with one localhost:2222):
import tensorflow as tf

cluster = tf.train.ClusterSpec({"local": ["localhost:2222"]})
server = tf.train.Server(cluster,
                        job_name="local",
                        task_index=0)

with tf.Session(server.target) as sess:
    with tf.device("/job:local/replica:0/task:0"):
        const1 = tf.constant("Hello I am the first constant")
        const2 = tf.constant("Hello I am the second constant")
    print sess.run([const1, const2])

out : ['Hello I am the first constant', 'Hello I am the second constant']

Maybe I don't understand the functions... So if you have an idea let me know please.
Thank you ;).
EDIT
Ok I found that with a ipython notebook it is not possible to run it like I did. I need to have a python program and execute it with a terminal.
But now I have a new issue when I am running my code, now the server tries to connect to the 2 ports given whereas I tell him to only run on one.
My new code looks like this :
import tensorflow as tf

tf.app.flags.DEFINE_string('job_name', '', 'One of local worker')
tf.app.flags.DEFINE_string('local', '', """Comma-separated list of hostname:port for the """)

tf.app.flags.DEFINE_integer('task_id', 0, 'Task ID of local/replica running the training')
tf.app.flags.DEFINE_integer('constant_id', 0, 'the constant we want to run')

FLAGS = tf.app.flags.FLAGS

local_host = FLAGS.local.split(',')

cluster = tf.train.ClusterSpec({"local": local_host})
server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_id)

with tf.Session(server.target) as sess:
    if(FLAGS.constant_id == 0):
        with tf.device('/job:local/task:'+str(FLAGS.task_id)):
            const1 = tf.constant("Hello I am the first constant")
            print sess.run(const1)
    if (FLAGS.constant_id == 1):
        with tf.device('/job:local/task:'+str(FLAGS.task_id)):
            const2 = tf.constant("Hello I am the second constant")
            print sess.run(const2)

I run the following command line
python test_distributed_tensorflow.py --local=localhost:3000,localhost:3001 --job_name=local --task_id=0 --constant_id=0

and I get the following logs
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:755] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 970M, pci bus id: 0000:01:00.0)
I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:206] Initialize HostPortsGrpcChannelCache for job local -> {localhost:3000, localhost:3001}
I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:202] Started server with target: grpc://localhost:3000
E0518 15:27:11.794873779   10884 tcp_client_posix.c:173]     failed to connect to 'ipv4:127.0.0.1:3001': socket error: connection refused
E0518 15:27:12.795184395   10884 tcp_client_posix.c:173]     failed to connect to 'ipv4:127.0.0.1:3001': socket error: connection refused
...

EDIT 2
I found the  solution. it is just mandatory to run all tasks that we give to the Server. So I have to run this :
python test_distributed_tensorflow.py --local=localhost:2345,localhost:2346 --job_name=local --task_id=0 --constant_id=0 \
& \
python test_distributed_tensorflow.py --local=localhost:2345,localhost:2346 --job_name=local --task_id=1 --constant_id=1

I hope that can help someone ;)

A: Latest version of Tensorflow provides distribution strategy to work multiple system.
With example distribution strategy is explained.Take a look at this link.


text:
Q: How to use R that is installed in conda environment from the standalone (non-Anaconda) installation of RStudio? Is there a way to use R that is installed in conda environment from the standalone (non-Anaconda) installation of RStudio? The reason for it is that Anaconda version of RStudion is very outdated.
Warning!  If you select path to conda R version here Tools...Global Options...General...R Version, nothing is displayed in RStudio window and you will need to reinstall RStudio and reset all settings.


text:
Q: Oracle - Round all the numeric values in all columns this is my first question.
For the first time I need to ROUND ALL THE NUMERIC VALUES contained in an Oracle table.
I start from the classic "SELECT * FROM ... WHERE ..." (I have 147 columns) and I would like to round all the decimals I find in my rows / columns.
Is there a way to do that ?
Thank you !

A: You can use the dynamic query as follows:
BEGIN
    FOR ALL_COLS IN (
        SELECT TABLE_NAME,
               COLUMN_NAME
          FROM USER_TAB_COLUMNS
         WHERE TABLE_NAME = '<YOUR_TABLE_NAME>' AND DATA_TYPE = 'NUMBER'
    ) LOOP
        EXECUTE IMMEDIATE 'UPDATE ' || TABLE_NAME
                       || ' SET ' || COLUMN_NAME || ' = ROUND(' || COLUMN_NAME || ') '
                       || ' WHERE ' || COLUMN_NAME || ' <> ROUND(' || COLUMN_NAME || ')';
    END LOOP;
COMMIT;
END;
/

A: You can build you query like the below
    SELECT 'SELECT '
           || Listagg(Decode(data_type, 'NUMBER', 'ROUND('
                                                  ||column_name
                                                  ||') '
                                                  || column_name,
                                        column_name), ',')
                within GROUP (ORDER BY column_id)
           ||' FROM '
           ||'TABLE_NAME'
    FROM   user_tab_cols
    WHERE  table_name = 'TABLE_NAME'

A: thanks for all your answers ...
finally, I made a loop for all my columns and I re-wrote the query: the user insert a "SELECT " and I replace the "" with all the columns name (and the ROUND on the numerics).
It is not the "fastest" solution but it works ...


text:
Q: Get missed calls in windows mobile For Windows Mobile 6, I'd like to get the count of missed calls in my application.
Is there a function to retrieve the missed calls?

A: Have a look at the SystemState.PhoneMissedCalls property.


text:
Q: Does clang support a double-word-compare-and-exchange operation? I have been reading through and coding up examples from Anthony Williams' book Concurrency in Practice and needed to enable double-word-compare-and-exchange for gcc4.8 using -mcx16 so that a struct containing a pointer an int could be manipulated in a lock-free atomic manner.
Does Clang (any version) support double-word-compare-and-exchange on x64?
The following code gives linking errors in GCC4.8 and Clang 3.3 without extra compiler options:
#include <atomic>
#include <thread>

struct ReferenceCountedPointer
{
  int referenceCount;
  void* data;
};

int main()
{
  std::atomic<ReferenceCountedPointer> arcp;
  ReferenceCountedPointer rcp;

  arcp.compare_exchange_weak(rcp, rcp);

  return 0;
}

The above program is pointless but illustrates the linking errors I see.
Compilation commands I used for Clang and GCC are:
Clang 3.3:
clang++-mp-3.3 -std=c++11 -stdlib=libc++ CX16.cpp -o CX16

Fails with:
Undefined symbols for architecture x86_64:
"___atomic_compare_exchange", referenced from:
  _main in CX16-plVSvq.o
ld: symbol(s) not found for architecture x86_64

GCC4.8:
g++-mp-4.8 -std=c++11 CX16.cpp -o CX16

Fails with:
Undefined symbols for architecture x86_64:
"___atomic_compare_exchange_16", referenced from:
  std::atomic<ReferenceCountedPointer>::compare_exchange_weak(ReferenceCountedPointer&,        ReferenceCountedPointer, std::memory_order, std::memory_order) in ccOjp95s.o
ld: symbol(s) not found for architecture x86_64

A: The issue here is that SOME models of 64-bit processors do not have a cmpxchg16b. The -mcx16 tells the compiler that "I know that this processor supports the cmpxchg16b instructions, so you can generate it". This is to avoid problems with older 64-bit processors which don't support this instruction - they would then cause an "illegal opcode trap". It's the same thing as using for example SSE4.

A: ReferenceCountedPointer is trivially copyable, so the code is valid under C++11. Apparently the library does not conform to the standard.


text:
Q: How can I get null values row using Criteria Builder in java? I am using criteria builder query to get rows of two dependent table from oracle database. I am using two tables T1 and T2 and i am taking ID column from T1 in T2 Table as T1_id Name column and it may be null in T2_Table when I have select fields from T2_Table and if T1_id column are null then i am not getting rows which contains null value of T1_Id column so how can I get all rows from T2 table if field of Table T1 in Table T2 are null.
I have two tables like:-
Table T1 which has field ID,T1_Name, Description.
Table T2  which has field ID,T2_Name,T1_id.
T1_id column in table T2 are ID column of Table T1.
I am using criteria Builder Query to get results of T2 Table but if T1_id column is null then i m not getting rows.
Code are:-
 CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
        CriteriaQuery<Task> criteria = criteriaBuilder.createQuery(Table_T2.class);
        Root<Task> taskRoot = criteria.from(Table_T2.class);
        criteria.orderBy(getCriteriaBuilder().desc(taskRoot.get(Table_T2.ID)));
        criteria.multiselect(taskRoot.get(Table_T2.T1_id),taskRoot.get(Table_T2.ID),taskRoot.get(Table_T2.T2_Name))

In above mention code if my T1_ID is null then not giving rows.
Data in my Table T2 are:-
ID  T2_Name  T1_id
1    test    t1_1
22   test1   null

I am getting only first row not getting second row.


text:
Q: How to get authentication token programmatically using facebook api? I have created an app in facebook and I have AppID and AppSecret keys.  Now I want to get the authentication token for that app.  I can use the graph api tool provided by facebook to get the token but I want to get the token programmatically using facebook api.  Also I want to get the token without logging in to the facebook account actually.  Is there any way to get it
programmatically using facebook api?

A: As far as know, you can't get it without actually logging to Facebook.

A: You can't generate a long-lived access token without going through Facebook's OAuth process (the Graph Explorer tool token expires after two hours).
The OAuth process can be automated to an extent, but there is one part that requires the user to click a button to authorize your application to access their Facebook account. Facebook OAuth is therefore a two step process:

*

*Show the authorization URL and get the user to click 'allow'

*Retrieve the access token once the user has clicked 'allow'

The Temboo SDK breaks the Facebook OAuth process down in to two steps - InitializeOAuth and FinalizeOAuth - that you can use in your app. These steps map to the process I outlined above. You can learn more about how to handle Facebook OAuth via Temboo here. To see this behavior in action you can check out a live example (with source code available) on the Temboo examples page.
(Full disclosure: I work at Temboo)

A: NO, you can't have long lived access token without login in Facebook, because for long lived access token you need to have short lived access token  which you will be needed in below Facebook graph API:
STEPS FOR LASTING PAGE ACCESS TOKEN
1- You have to get page access token for a user by this API:
https://graph.facebook.com/{User-id}/accounts?access_token={access-token}

2- Then u have to refresh the save token by below API which will last for 60 days:
https://graph.facebook.com/oauth/access_token?client_id={your-client-id}&client_secret={client-secret}&grant_type=fb_exchange_token&fb_exchange_token={previous-access-token}


text:
Q: How to use sultry?
Sultry: very hot and humid

That is the meaning of sultry I am familiar with and have seen used in books. However Merriam - Webster Dictionary has another meaning

2 a : hot with passion or anger

How can sultry be used in a sentence with the sense of anger?
Would "He left the room in a sultry rage" be correct, or "She screamed at him in a sultry temper"?

A: Oald's definition is better. Sultry weather can make you feel uncomfortable.
A sensual and sexy woman can have the same effect if she is too eager to have sex.
http://www.oxfordlearnersdictionaries.com/us/definition/american_english/sultry?q=sultry


text:
Q: How to authenticate to box-api without oauth redirecting I am trying to make a simple integration to BOX where I only access my own account. Since this is a server-side access, (the server-process calls the Box-api), having the Oauth 2.0 redirecting is a problem.
Is there a way I could acquire a token (even manually) and use it in my code, by-passing the hassle of Oauth 2.0 and the redirection ? Or may be some other way for this kind of scenario ?

A: Right now you can do this with a Developer Token, but that only lasts for 1 hour.
You can also do the auth on your laptop, then put the Refresh tokens into your server in a config file, much like you might do for a database-password file (hopefully only readable by the service-account on the machine that has access to run your script).
Then build your script to take the refresh-token, go get a token pair with it, and write the new refresh token into the config file.


text:
Q: Why can't I use Solver qpsolver anymore? I just coded a quadratic programming and it has worked very well but after the someday it works not at all.
Does anyone have any idea what the problem is?
My code is:
import time
import numpy as np
from numpy import array, dot
from qpsolvers import solve_qp

Matrix10 = np.load(r'C:\Users\skqkr\Desktop\Semesterarbeit/Chiwan_Q7.npz')
start = time.time()

P = Matrix10['Q']  # quick way to build a symmetric matrix
q = Matrix10['p']
G = Matrix10['G']
h = Matrix10['h']

x = solve_qp(P, q, G, h )>print("QP solution: x = {}".format(x))
print("time :", time.time() - start)

And the result is:
ImportError: cannot import name 'solve_qp' from 'qpsolvers' (C:\Users\skqkr\qpsolvers.py)

I don't understand why it isn't suddenly going well.

A: I do not think the code you shared is the one you are really using hence it is not easy to understand what is going on. However there are few reason for your problem to happen
The python ImportError: cannot import name error occurs when the import class is inaccessible or the imported class in circular dependence. The import keyword is used to load class and function. The keyword from is used to load the module. For any reason, if the import class is not available in the python class path, The "ImportError: cannot import name" python error is thrown.
The following are the reasons for the ImportError: cannot import name
The import class is not available or not created.
The import class name is mis-named or mis-spelled
The import class name and module name is mis-placed.
The import class is not available in python class path
The import class is not available in python library
The import class is in circular dependency
The python module is just a python file with the .py extension. The keyword from will be used to load the python module. A class in a python module is imported using the keyword import. If the imported class is not in the referred python file, the python interpreter will throw the error ImportError: Cannot import name.
If two python files refer to each other and attempt to load the other file, it will create the circular load dependence. That will cause error in heap memory. If the python interpreter detects the circular dependence, it throws the error ImportError: Can't Import Name.


text:
Q: How to multiple source in openURL in AppDelegate.m? I'm trying to handle both of Twitter and deep link in openURL, using ReactNative.
The code below does not work, ending up go into if (LinkingHandled) even when handling Twitter.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
  bool TwitterHandled = [[Twitter sharedInstance] application:application openURL:url options:options];
  bool LinkingHandled =[RCTLinkingManager application:application openURL:url options:options];
  if (TwitterHandled) {
    return TwitterHandled;
  }
  if (LinkingHandled) {
    return LinkingHandled;
  }
  return NO;
}

What is wrong with this? I'm new to ObjC.

A: Use } else if { so only Twitter goes if it gets handled, and 'linking' will only go if TwitterHandled is NO and LinkingHandled is YES.
This can be simplified into one expression:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    return [Twitter.sharedInstance
            application:application
                openURL:url options:options] ||
           [RCTLinkingManager
            application:application
                openURL:url
                options:options];
}

Switch to Swift if you can.


text:
Q: Sockets, Streams and object size/types I'm making a message app (surprise!) and there's strategies I'd like comments on.

*

*Want to send different objects/classes... are inner classes the best way or sending different class objects and trapping(ClassNotFoundException) and retying? Currently I use a serializable class with 2 inner serializable classes to hold my two main class structures. The parent class holds holds a variable that tells what class to use on the other end of the stream.

*Would it be best to use ArrayList<MyObject> for multiple messages or MyObject[] in the streams? I know ArrayList is serializable already.

*Size of messages... this would be a mobile device to server. I want to keep message size as small as possible. Do methods take up a bunch of data size?
I want a nice, simple and data conserving/small multi-purpose socket message.
Just looking for best practice that isn't super complicated!


text:
Q: itextsharp form name and saving pdf I am using itextsharp in ASP.NET. We populate a PDF with fields that are taken from one of our online forms. I need to change the way we handle the documents - we need to be able to use some of the fields as the name of the document(firstname-lastname.pdf), and to save that PDF into a directory. Here is the code I am using now:
    PdfStamper ps = null;
        DataTable dt = BindData();
        if (dt.Rows.Count > 0)
        {
            PdfReader r = new PdfReader(new RandomAccessFileOrArray("http://www.example.com/Documents/ppd-certificate.pdf"), null);
            ps = new PdfStamper(r, Response.OutputStream);

            AcroFields af = ps.AcroFields;

            af.SetField("fullName", dt.Rows[0]["fullName"].ToString());
            af.SetField("presentationTitle", dt.Rows[0]["presentationTitle"].ToString());
            af.SetField("presenterName", dt.Rows[0]["presenterFullName"].ToString());
            af.SetField("date", Convert.ToDateTime(dt.Rows[0]["date"]).ToString("MM/dd/yyyy"));

            ps.FormFlattening = true;

            ps.Close();
        }

A: PdfStamper and PdfWriter both use the generic Stream class so instead of Response.OutputStream you can use a FileStream or a MemoryStream
This example writes directly to disk. Set testFile to whatever you want, I'm using the desktop here
//Your file path here:
var testFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    PdfReader r = new PdfReader(new RandomAccessFileOrArray("http://www.example.com/Documents/ppd-certificate.pdf"), null);
    var ps = new PdfStamper(r, fs);
    //..code
}

This next example is my preferred method. It creates a MemoryStream, then creates a PDF inside of it and finally grabs the raw bytes. Once you've got raw bytes you can both write them to disk AND Response.BinaryWrite() then.
byte[] bytes;
using (var ms = new MemoryStream()) {
    PdfReader r = new PdfReader(new RandomAccessFileOrArray("http://www.example.com/Documents/ppd-certificate.pdf"), null);
    var ps = new PdfStamper(r, ms);
    //..code

    bytes = ms.ToArray();
}

//Your file path here:
var testFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");

//Write to disk
System.IO.File.WriteAllBytes(testFile, bytes);

//Send to HTTP client
Response.BinaryWrite(bytes);


text:
Q: Как получить число из EditText Цифра введённая пользователем регулирурет длину будущего пароля.
xml
<EditText
    andriod:id = "@+id/youPasswordLength"
    android:inputType="number"
    />

MainActivity.java
for(int i = 0; i < youPasswordLength; i ++){
      int justCaseNumberForRandomChar = randomNumber.nextInt(charForPassword.length);
            passwordHolder.append(charForPassword[justCaseNumberForRandomChar]);
            showPasswordView.setText(passwordHolder.toString());
}

Не хочет работать с "youPasswordLength", пробовал через Integer.parseInt результат то-же, подчёркивает красным. Всё что нужно импортировал, переменные везде объявил.   Скажите пожалуста что почитать на эту тему

A: Разобрался, если кому интересно:
 Похоже нельзя напрямую "брать" цифру даже несмотря на то что параметр EditText-a настроен как android:inputType="number"
Для начала я должен перевести данные в стрингу а потом стрингу парсить в цифру...
String longOfPass = yourPasswordLegth.getText().toString();// переводим в строку
int longOfPassword_int = Integer.parseInt(longOfPass); // парсим цифру, а дальше
                                                      //спокойно работаем с цифрой


text:
Q: How does Nginx's $request_length correspond to byte size? I'm using Nginx and I would like to know the byte size of the data which is returned to the client as well as the size received from the client.
I'm doing this as following:

*

*$bytes_sent is the size in bytes which the server is sending to the client. This is what I want

*$request_length is the length of the request from the client which includes the request line, header, and request body.

Now my question is this: How does the length of the request map onto the bytes received by the server?


text:
Q: Socket disconnection in IOS I need some help in IOS Socket programming. I have implemented a successful TCP Socket connection between IOS and a Java Server, however I found that it is imposible to reconnect it after the socket fails (I disconnect my network and reconnect it).
That's the code I use to open the streams:
- (void)initCommunication{
@try {
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"XXX.XXX.XXX.XXX", 4454, &readStream, &writeStream);

    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;

    //Asignamos los delegates
    inputStream.delegate = self;
    outputStream.delegate = self;

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [inputStream open];
    [outputStream open];
    connected = true;
    }
}
@catch (NSException *exception) {
    connected = false;
    NSLog(@"Error connecting socket: %@", exception.reason);
    [self checkConnection];
}
}

And when I receive a NSStreamEventErrorOccurred or a NSStreamEventEndEncountered I try to close the connection and reconnect again.
I close it with:
-(void) close{

[inputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream close];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream setDelegate:nil];
inputStream = nil;
[outputStream setDelegate:nil];
outputStream = nil;

connected = false;
}

The problem is that the socket is not reconnecting again... I am thinking on using SmallSockets or CocoaAsyncSockets to see if I can reconnect the socket... Do you see any implementation problem? Do you recommend using SmallSockets or CocoaAsyncSockets??
Thank you in advance!!

A: Finally I did implement it with CocoaAsyncSockets https://github.com/robbiehanson/CocoaAsyncSocket and it was really easy doing a reconnection with this socket.
First I initialize the socket object:
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

To connect I use:
NSError *err = nil;
if ([socket connectToHost:@"XXX.XXX.XXX.XXX" onPort:YYYY error:&err])
{
NSLog(@"Connection performed!");
}
else
{
NSLog(@"Unable to connect: %@", err);
}

And then you can use the delegate to do reconnection whenever it failed:
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"Socket:DidConnectToHost: %@ Port: %hu", host, port);

connected = YES;
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
NSLog(@"SocketDidDisconnect:WithError: %@", err);
    connected = NO;
    //We will try to reconnect
    [self checkConnection];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    [self processReceivedData:data];
    [sock readDataWithTimeout:-1 tag:0];
}

I found very easy to use that library. I hope that helps anyone.
Thanks a lot.


text:
Q: Set row index with ag-grid in Angular I am trying to create a table with ag-grid in Angular.
Is there a way to set the row index at this time?
Other than that I create a seq column and use a function to change the value. I'm sure it can be set as an option, but it doesn't seem to exist when I searched the documentation...
example image


text:
Q: swift 3 parse json array as key value i have a json, which i parse as a dictionary. Now most is simply a key value pair like "title":{"this is the title"}. The one thing bugging me is a key value pair that has an array for value.
"hashTags":[{"name":"pizza"},{"name":"salami"},{"name":"diet"}]

i do not want to use SwiftyJSON, since this is the only part i am unable to solve. What i need is to convert this value into an Array, which i can iterate. I had some approaches, they failed because they added new lines or stopped displaying äöü symbols.
Thank you in advance!

A: *

*hashTags is an array of dictionaries with String keys and values, cast it to [[String:String]]

*Iterate thru the array with a for loop and print all values for key name
if let hashTags = json["hashTags"] as? [[String:String]] {
   for tag in hashTags {
       print(tag["name"])
   }
}

It's assumed that json is the parent object which contains the key hashTags.

A: All you need is using codable.
You can use Codable to parse Json to your desired model easily. you can check following document for more detail:
https://developer.apple.com/documentation/foundation/archives_and_serialization/using_json_with_custom_types
https://developer.apple.com/documentation/swift/codable


text:
Q: devise token auth and devise duplication in controllers I have put together a Rails 6 backend with Devise and Devise token auth and a frontend Angular Nativescript application which uses the API. Ref;
Backend: https://github.com/map7/backend_rails6_template
Mobile Frontend: https://github.com/map7/frontend_nativescript
My question is, do I have to duplicate my controllers for the API and Web pages if I don't need versioning?
Devise_token_auth suggests I need namespacing if I'm going to use it alongside Devise.
At the moment I have a Home Controller for the Rails views;
class HomeController < ApplicationController
  before_action :authenticate_user!
end

Which uses this ApplicationController
class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
end

For the API calls I have another Home Controller in api/v1/home_controller with the following;
module Api
  module V1
    class HomeController < ApplicationController
      before_action :authenticate_user!

      def index
        render json: {message: "Welcome to the Ruby on Rails backend"}
      end
    end
  end
end

Which uses this ApplicationController
module Api
  module V1
    class ApplicationController < ActionController::API
      include DeviseTokenAuth::Concerns::SetUserByToken
      before_action :authenticate_user!
      before_action :configure_permitted_parameters, if: :devise_controller?

      protected

      def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:sign_in, keys: [:email, :password])
      end
    end
  end
end

My routes.rb file looks like;
Rails.application.routes.draw do
  devise_for :users             # Standard devise routes must come first!
  resources :home, only: [:index]
  root to: "home#index"

  namespace :api, defaults: {format: 'json'} do # namespace devise token routes to stop duplication
    namespace :v1 do
      mount_devise_token_auth_for 'User', at: 'auth'
      resources :home, only: [:index]
    end
  end
end

It may not look like much duplication for now but I'm trying to convert a large app in which there would be a large amount of duplication. If I try to call the /home route for the API call then I get an 'unauthorized error'.


text:
Q: How to find the instances of a class in Java Virtual Machine? I want to test one of the class in a big project, however I cannot modify any files of the project (thus static public arrays are not the case).
Beside this, I can only initialize the framework of project (to be tested) but again there is no reference to objects.
The only thing I have, my test class and framework is running on the same Java Virtual machine.
Therefore, I want to reach the instances of a single class from my test class.
How can I find them in Virtual machine?

A: You can use some aop framework, like spring-aop, to track each time an object is created.

A: There's a couple of other questions like this on here to, the best answer seems to be this one: https://stackoverflow.com/a/1947200/1140456

A: In Java you cannot access an object that you have no reference to. You need to have someone update the framework to allow you to access the objects either directly or through other objects.


text:
Q: Problem with \mathsf I have a weird problem that I can't seem to figure out. In a beamer document I use \mathsf to specify how I want some of the text to appear. The specific command is
$\mathsf{ASG}_{1}=\sigma_{\mathsf{ENO} \leq \mathsf{"E3"}}(\mathsf{ASG})$
which puts in a \ after \leq and before E3as shown in the attached figure. I can't figure out why. Any help would be appreciated.
Here is a MWE
\documentclass{beamer}
\usepackage{amsmath}

\begin{document}
\begin{frame}{test}
 $\mathsf{ASG}_{1}=\sigma_{\mathsf{ENO} \leq \mathsf{"E3"}}(\mathsf{ASG})$
 \end{frame}
\end{document}

A: You can define math symbols for the quotes:
\documentclass{article}
\usepackage{amsmath}

\DeclareMathSymbol{\mathopenquotes}{\mathalpha}{operators}{"5C}
\DeclareMathSymbol{\mathclosedquotes}{\mathalpha}{operators}{"22}

\newcommand{\quoted}[1]{\mathopenquotes{#1}\mathclosedquotes}

\begin{document}

$\mathsf{ASG}_{1}=\sigma_{\mathsf{ENO} \leq \mathsf{\quoted{E3}}}(\mathsf{ASG})$

$A_{1}=\sigma_{E\le\quoted{E3}} B$

\end{document}

Note: this assumes your math alphabets are taken from OT1 encoded fonts.


text:
Q: Javascript Detect click event outside of div I have a div with id="content-area", when a user clicks outside of this div, I would like to alert them to the fact that they clicked outside of it. How would I use JavaScript to solve this issue?

      Display Conents

A: I made a simple and small js library to do this for you:
It hijacks the native addEventListener, to create a outclick event and also has a setter on the prototype for .onoutclick

Basic Usage
Using outclick you can register event listeners on DOM elements to detect whether another element that was that element or another element inside it was clicked. The most common use of this is in menus.
var menu = document.getElementById('menu')

menu.onoutclick = function () {
    hide(menu)
}

this can also be done using the addEventListener method
var menu = document.getElementById('menu')

menu.addEventListener('outclick', function (e) {
    hide(menu)
})

Alternatively, you can also use the html attribute outclick to trigger an event. This does not handle dynamic HTML, and we have no plans to add that, yet

Have fun!

A: In pure Javascript
Check out this fiddle and see if that's what you're after!
document.getElementById('outer-container').onclick = function(e) {
    if(e.target != document.getElementById('content-area')) {
        document.getElementById('content-area').innerHTML = 'You clicked outside.';
    } else {
        document.getElementById('content-area').innerHTML = 'Display Contents';
    }
}

http://jsfiddle.net/DUhP6/2/

A: Use document.activeElement to see which of your html elements is active.
Here is a reference:
document.activeElement in MDN

A: The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node or not
You can catch events using
document.addEventListener("click", clickOutside, false);
function clickOutside(e) {
   const inside = document.getElementById('content-area').contains(e.target);
}

Remember to remove the event listened in the right place
document.removeEventListener("click", clickOutside, false)

A: Bind the onClick-Event to an element that is outside your content area, e.g. the body. Then, inside the event, check whether the target is the content area or a direct or indirect child of the content area. If not, then alert.
I made a function that checks whether it's a child or not. It returns true if the parent of a node is the searched parent. If not, then it checks whether it actually has a parent. If not, then it returns false. If it has a parent, but it's not the searched one, that it checks whether the parent's parent is the searched parent.
function isChildOf(child, parent) {
    if (child.parentNode === parent) {
      return true;
    } else if (child.parentNode === null) {
      return false;
    } else {
      return isChildOf(child.parentNode, parent);
    }
}

Also check out the Live Example (content-area = gray)!

A: $('#outer-container').on('click', function (e) {
     if (e.target === this) {
        alert('clicked outside');
     }
});

This is for the case that you click inside the outer-container but outside of the content-area.

A: use jquery as its best for DOM access
$(document).click(function(e){
 if($(e.target).is("#content-area") || $(e.target).closest("#content-area").length)
  alert("inside content area");
else alert("you clicked out side content area");
});

A: Here is the fiddle : http://jsfiddle.net/uQAMm/1/
$('#outercontainer:not(#contentarea)').on('click', function(event){df(event)} );
function df(evenement)
{
    var xstart = $('#contentarea').offset().left;
    var xend = $('#contentarea').offset().left + $('#contentarea').width();

    var ystart = $('#contentarea').offset().top;
    var yend = $('#contentarea').offset().top + $('#contentarea').height();

    var xx = evenement.clientX;
    var yy = evenement.clientY;

    if ( !(  ( xx >=  xstart && xx <=  xend ) && ( yy >=  ystart && yy <=  yend )) )
    {
        alert('out');
    }

}

A: Put this into your document:

A: Here is a simple eventListener that checks all parent elements if any contain the id of the element. Otherwise, the click was outside the element
html

js
const handleMouseDown = (ev) => {
    let clickOutside = true
    let el = ev.target
    while (el.parentElement) {
        if (el.id === "element-id") clickOutside = false
        el = el.parentElement
    }
    if (clickOutside) {
        // do whatever you wanna do if clicking outside
    }
}
document.addEventListener("mousedown", handleMouseDown)


text:
Q: Multi-dimensional array transposing I have a row-based multidimensional array:
/** [row][column]. */
public int[][] tiles;

I would like to transform this array to column-based array, like following:
/** [column][row]. */
public int[][] tiles;

...But I really don't know where to start

A: try this:
@Test
public void transpose() {
    final int[][] original = new int[][]{
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}};

    for (int i = 0; i < original.length; i++) {
        for (int j = 0; j < original[i].length; j++) {
            System.out.print(original[i][j] + " ");
        }
        System.out.print("\n");
    }
    System.out.print("\n\n matrix transpose:\n");
    // transpose
    if (original.length > 0) {
        for (int i = 0; i < original[0].length; i++) {
            for (int j = 0; j < original.length; j++) {
                System.out.print(original[j][i] + " ");
            }
            System.out.print("\n");
        }
    }
}

output:
1 2 3 4
5 6 7 8
9 10 11 12

 matrix transpose:
1 5 9
2 6 10
3 7 11
4 8 12

A: a bit more generic way:
/**
 * Transposes the given array, swapping rows with columns. The given array might contain arrays as elements that are
 * not all of the same length. The returned array will have {@code null} values at those places.
 *
 * @param <T>
 *            the type of the array
 *
 * @param array
 *            the array
 *
 * @return the transposed array
 *
 * @throws NullPointerException
 *             if the given array is {@code null}
 */
public static <T> T[][] transpose(final T[][] array) {
    Objects.requireNonNull(array);
    // get y count
    final int yCount = Arrays.stream(array).mapToInt(a -> a.length).max().orElse(0);
    final int xCount = array.length;
    final Class<?> componentType = array.getClass().getComponentType().getComponentType();
    @SuppressWarnings("unchecked")
    final T[][] newArray = (T[][]) Array.newInstance(componentType, yCount, xCount);
    for (int x = 0; x < xCount; x++) {
        for (int y = 0; y < yCount; y++) {
            if (array[x] == null || y >= array[x].length) break;
            newArray[y][x] = array[x][y];
        }
    }
    return newArray;
}

A: I saw that all of the answers create a new resultant matrix. This is simple:
matrix[i][j] = matrix[j][i];

However, you can also do this in-place, in case of square matrix.
// Transpose, where m == n
for (int i = 0; i < m; i++) {
    for (int j = i + 1; j < n; j++) {
        int temp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = temp;
    }
}

This is better for larger matrices, where creating a new resultant matrix is wasteful in terms of memory. If its not square, you can create a new one with NxM dimensions and do the out of place method. Note: for in-place, take care of j = i + 1. It's not 0.

A: The following solution does in fact return a transposed array instead of just printing it and works for all rectangular arrays, not just squares.
public int[][] transpose(int[][] array) {
    // empty or unset array, nothing do to here
    if (array == null || array.length == 0)
        return array;

    int width = array.length;
    int height = array[0].length;

    int[][] array_new = new int[height][width];

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            array_new[y][x] = array[x][y];
        }
    }
    return array_new;
}

you should call it for example via:
int[][] a = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}};
for (int i = 0; i < a.length; i++) {
    System.out.print("[");
    for (int y = 0; y < a[0].length; y++) {
        System.out.print(a[i][y] + ",");
    }
    System.out.print("]\n");
}

a = transpose(a); // call
System.out.println();

for (int i = 0; i < a.length; i++) {
    System.out.print("[");
    for (int y = 0; y < a[0].length; y++) {
        System.out.print(a[i][y] + ",");
    }
    System.out.print("]\n");
}

which will as expected output:
[1,2,3,4,]
[5,6,7,8,]

[1,5,]
[2,6,]
[3,7,]
[4,8,]

A: If you want to go for in place transpose of a matrix(in which case row count = col count) you can so following in Java
public static void inPlaceTranspose(int [][] matrix){

    int rows = matrix.length;
    int cols = matrix[0].length;

    for(int i=0;i<rows;i++){
        for(int j=i+1;j<cols;j++){
            matrix[i][j] = matrix[i][j] + matrix[j][i];
            matrix[j][i] = matrix[i][j] - matrix[j][i];
            matrix[i][j] = matrix[i][j] - matrix[j][i];
        }
    }
}

A: public int[][] tiles, temp;

// Add values to tiles, wherever you end up doing that, then:
System.arraycopy(tiles, 0, temp, 0, tiles.length);

for (int row = 0; row < tiles.length; row++) // Loop over rows
    for (int col = 0; col < tiles[row].length; col++) // Loop over columns
        tiles[col][row] = temp[row][col]; // Rotate

That should do it for you.

A: import java.util.Arrays;
import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        //asking number of rows from user
        int rows = askArray("Enter number of rows :", input);
        //asking number of columns from user
        int columns = askArray("Enter number of columns :", input);
        int[][] array = Array(rows, columns, input);
        //displaying initial matrix
        DisplayArray(array, rows, columns);
        System.out.println("Transpose array ");
        //calling Transpose array method
        int[][] array2 = TransposeArray(array, rows, columns);
        for (int i = 0; i < array[0].length; i++) {
            System.out.println(Arrays.toString(array2[i]));
        }
    }

    //method to take number of rows and number of columns from the user
    public static int askArray(String s, Scanner in) {
        System.out.print(s);
        int value = in.nextInt();

        return value;
    }

    //feeding elements to the matrix
    public static int[][] Array(int x, int y, Scanner input) {
        int[][] array = new int[x][y];
        for (int j = 0; j < x; j++) {
            System.out.print("Enter row number " + (j + 1) + ":");
            for (int i = 0; i < y; i++) {
                array[j][i] = input.nextInt();
            }
        }
        return array;
    }

    //Method to display initial matrix
    public static void DisplayArray(int[][] arra, int x, int y) {
        for (int i = 0; i < x; i++) {
            System.out.println(Arrays.toString(arra[i]));
        }
    }

    //Method to transpose matrix
    public static int[][] TransposeArray(int[][] arr, int x, int y) {
        int[][] Transpose_Array = new int[y][x];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                Transpose_Array[j][i] = arr[i][j];
            }
        }
        return Transpose_Array;
    }
}

A: public int[][] getTranspose() {
    int[][] transpose = new int[row][column];
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
            transpose[i][j] = original[j][i];
        }
    }
    return transpose;
}

A: Use this function (replace String by int if necessary). It takes the matrix as string array and returns a new matrix which is the transpose. It checks for the edge case of an empty array, too. No prints.
private String[][] transposeTable(String[][] table) {
    // Transpose of empty table is empty table
    if (table.length < 1) {
        return table;
    }

    // Table isn't empty
    int nRows = table.length;
    int nCols = table[0].length;
    String[][] transpose = new String[nCols][nRows];

    // Do the transpose
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            transpose[j][i] = table[i][j];
        }
    }

    return transpose;
}

A: Here is my 50 cents: a utility method and test to transponse multidimensional array (for doubles in my case):
/**
 * Transponse bidimensional array.
 *
 * @param original Original table.
 * @return Transponsed.
 */
public static double[][] transponse(double[][] original) {
    double[][] transponsed = new double
            [original[0].length]
            [original.length];

    for (int i = 0; i < original[0].length; i++) {
        for (int j = 0; j < original.length; j++) {
            transponsed[i][j] = original[j][i];
        }
    }
    return transponsed;
}

@Test
void aMatrix_OfTwoDimensions_ToBeTransponsed() {
    final double[][] original =
            new double[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

    double[][] transponsed = Analysis.transponse(original);

    assertThat(transponsed[1][2], is(equalTo(10)));
}

A: Here's what I came up with about a year ago, I was only just learning at the time so I came up with the solution within two weeks of learning Java.
We get a list of values:
int[] jest = new int[] {1, 2, 3, 4, 5, 6};

Then we produce empty double lists and get the length of the single list, and store these within the double list.
int[][] storeValues = null;
int[][] valueLength = new int[jest.length][jest.length];
int[][] submit = null;
int[][] submitted = null;

Create a double for-loop to increment a value until the length of the list. Then we store these and go over the array range to make it horizontal.
for(int i=0; i<jest.length;i++) {
        for(int j = 0; j < jest.length;j++) {

        storeValues = new int[][] {jest};
     valueLength[j][i] = storeValues[0][i];

     submit = Arrays.copyOfRange(valueLength, 0, j+1);

     submitted = Arrays.copyOfRange(submit, j, j+1);
    }

Full working code:
import java.util.Arrays;

public class transMatrix {

    public static void main(String[] args) {
    int[] jest = new int[] {1, 2, 3, 4, 5, 6};
        int[][] storeValues = null;
        int[][] valueLength = new int[jest.length][jest.length];
        int[][] submit = null;
        int[][] submitted = null;
    for(int i=0; i<jest.length;i++) {
        for(int j = 0; j < jest.length;j++) {

        storeValues = new int[][] {jest};
     valueLength[j][i] = storeValues[0][i];

     submit = Arrays.copyOfRange(valueLength, 0, j+1);

     submitted = Arrays.copyOfRange(submit, j, j+1);
    }

    }System.out.println(Arrays.deepToString(submitted));
}}

Output:
[[1, 2, 3, 4, 5, 6]]

A: import java.util.*;

public class TestClass {
    public static void main(String args[]) throws Exception {
        Scanner in = new Scanner(System.in);
        int iSize = in.nextInt();
        int jSize = in.nextInt();
        int arr[][] = new int[iSize][jSize];
        int array[][] = new int[jSize][iSize];
        for (int i = 0; i < iSize; i++) {
            for (int j = 0; j < jSize; j++) {
                arr[i][j] = in.nextInt();
            }
            System.out.println("\n");
        }

        for (int n = 0; n < arr[0].length; n++) {
            for (int m = 0; m < arr.length; m++) {
                array[n][m] = arr[m][n];
                System.out.print(array[n][m] + " ");
            }
            System.out.print("\n");
        }
    }
}


text:
Q: Run JUnit test in a maven project that depends on javaee 6 api Im trying to run a test that depends on Javaee6-api.
My pom setup is the following:
<project>
   <dependencies>
      <dependency>
         <groupId>javax</groupId>
         <artifactId>javaee-api</artifactId>
         <version>6.0</version>
         <scope>provided</scope>
      </dependency>
      [...]
   </dependencies>
</project>

When i run my JUnit test i get the following exception:
   java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/faces/event/FacesEvent
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)

        at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
            at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
            at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    [...]
            org.eclipse

.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

A: I just put the following dependencie:
<dependency>
  <groupId>org.jboss.spec.javax.faces</groupId>
  <artifactId>jboss-jsf-api_2.1_spec</artifactId>
  <version>2.0.1.Final</version>
  <scope>provided</scope>
</dependency>


text:
Q: What is the new firefox fingerprinter feature doing? Community, Firefox has a new function . Called fingerprinter (settings under privacy).
I know what fingerprinting means. What I like to ask you is: what is Firefox doing exactly when this feature is activated, what data is being changed by this setting?
Because when you do a test on panopticlick.eff.org, in both cases, active/inactive fingerprinter setting, you still get a unique html canvas hash assigned to you.
So, what is firefox exactly "preventing" or "changing" by this fingerprinter setting then?

*

*And can you give your short opinion: is it better to activate this new fingerprint setting, or not? If you like to be "less" easier identifiable during web surfing? I have read differing opinions. There are those who say if you block fingerprinting you look more "unique", and those who say, If you allow fingerprint, you "less unique" in the masses...

Thanks all!

A: Browser finger printers are a subset of trackers that allow sites to gather a certain amount of information about a visitor's browser and device, even without the use of a cookies.
Firefox new feature can help you block fingerprinting coming from many ad trackers.
Keep in mind blocking fingerprinting may cause some sites to break or make them look strange, or the layout will be different. It can also slow down your online experience.


text:
Q: What is local component in Yii2? In the documentation "info" section Yii 2 says:

Using too many application components can potentially make your code harder to test and maintain. In many cases, you can simply create a local component and use it when needed.

What is local component? How create it?

A: Local component it is just local instance of component. So instead using:
$value = Yii::$app->cache123->get($key);

which will force you to define cache123 component in app config, you can use local instance:
$cache = new ApcCache();
$value = $cache->get($key);

Or assign it to module for example:
class MyModule extends \yii\base\Module {

    private $_cache;

    public function getCache(): \yii\caching\Cache {
        if ($this->_cache === null) {
            $this->_cache = new ApcCache();
        }

        return $this->_cache;
    }
}

And then in controller you can use:
$value = $this->module->getCache()->get($key);

You can also define components in module config:
'modules' => [
    'myModule' => [
        'class' => MyModule::class,
        'components' => [
            'cache' => FileCache::class,
        ],
    ],
],

And then in controller you can use:
$value = $this->module->cache->get($key);

In this way you can split your app into multiple independent modules with separate components. It may be easier to maintain this if you have large number of components if they're grouped in modules, especially if some of them are used only in one place or one module.


text:
Q: How to handle Redis connection across multiple modules? I'm building an application that uses Redis as a datastore. Accordingly, I have many functions that interact with Redis, usually as wrappers for a group of Redis commands.
As the application grows past my initial .py file, I'm at a loss for how to handle the Redis connection across multiple modules. Currently, my pointer to the Redis connection is declared at the top of the file and every function assumes it's present rather than passing it to every function. If I spread these functions into multiple files, then each module creates its own Redis pointer to use and each instance of the application opens up multiple connections to Redis.
I would like one instance to just make use of the same connection.
I don't want to do this:
import redis
class MyApp(object):
    def __init__(self):
        self.r = redis.Redis()
    (all my app functions that touch redis go here)

I also don't want to pass the Redis pointer as an argument into every function.
Is there some other way I can get functions from different modules to share a single Redis() instance?

A: Something like this:
Module redis_manager:
class RedisManager(object):
    def __init__():
        # Connect to redis etc
        self.redis = 12345

redis_manager = RedisManager()

Then in your other modules, you can do:
from redis_manager import redis_manager

redis_manager.redis.stuff


text:
Q: Access-Control-Allow-Origin not appearing on headers I am searching for this problem for almost 3 hours.
So i am using codeigniter in developing my application.
So I am trying to make an AJAX request in this url 'login/loguser'
However, it is saying that there is No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ssmis.wc.lt' is therefore not allowed access.
I know you will say I should put header() about access control origin. So I've done this
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class LogIn extends Ss_Controller{

    function __construct(){
        //So in case we have to do something in the constructor we dont override the parent constructor.
        parent::__construct();

    }

    function index(){
        $data['title'] = "Login";
        $data['page_content'] = "login_view.php";

        $extra_css = array(
            "http://fonts.googleapis.com/css?family=Play",
            "public/system_css/login.css",
        );

        $data['extra_css'] = $extra_css;

        $extra_js = array(
            "public/system_js/modules/main.js",
            "public/system_js/login.js",
            "public/system_js/modules/login_module.js"
        );

        $data['extra_js'] = $extra_js;

        $this->load->view('includes/template.php',$data);
    }

    function loguser(){
        header("Access-Control-Allow-Origin: *");
        $data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter

        $this->load->model('usermod');

        $validated = $this->usermod->validate_credentials($data);

        //when $result returns true redirect to home page.
        if($validated){
            //set sessions cookies.
            $data = array(
                "username" => $data['batch_id'],
                "is_logged_in" => true
            );

            $this->session->set_userdata($data);
            //redirect to home page.
            $response['success'] = true;
            $this->echo_response($response,200,'OK');
        }else{
            //redirect to log-in page with error message
            $response['success'] = false;
            $this->echo_response($response,201,'Not OK!');
        }
    }

}

This is my ajax code:
var login = function login(formdata){
        $.ajax({
            type: 'POST',
            url: Main.Vars.host + 'login/loguser',
            contentType: false,
 headers: { 'Access-Control-Allow-Origin': '*' },
       crossDomain: true,
            cache: false,
            processData:false,
            data: formdata,
            dataType: 'json',

            success: function(data){

                if(data.success == true){
                    window.location.assign(Main.Vars.host + "home/");
                }else{
                    alert("Cannot logged in!");
                }

            }

        });
    };

As you can see I already put Access-Control-Allow-Origin in my ajax call and in my controller class because i am so desperate right now.
I tried also putting header on my custom Base_Controller which looks like this:
This is my Base_Controller which extends CI_Controller
//echo response in json format.
    public function echo_response($data, $code, $status_message){
        $this->output->set_header('Content-Type: application/json; charset=utf-8');
    $this->output->set_header('Access-Control-Expose-Headers: Access-Control-Allow-Origin');
        $this->output->set_status_header($code, $status_message);
        echo json_encode($data);
    }

I tried all the things that I've research, but still no luck. Access COntrol Allow Origin header still not present when performing the ajax call. I really need help.
PS i also tried jsonp in ajax but gives me error.
Thank you!


text:
Q: Extract the values from the url using jsoup What I'm trying to do is extract the values from html tag  ul, li, span  the following url:
http://www.huffingtonpost.com/2014/11/23/israel-new-laws_n_6207042.html#comments
from the URl i want to get Number of comments count and Number of share count
Example:

<a href="http://www.huffingtonpost.com/2014/11/23/israel-new-laws_n_6207042.html" data- send="false" data-layout="box_coun

  Share
  283

  Tweet
   103


text:
Q: How do I reliably retrieve a file's last modified time on OS X? I'm experiencing a problem on OS X, where stat intermittently returns a struct whose st_mtime has a value of 0, for certain files.
Why does this happen, and is there any alternative function that will provide me with a reliable modified date for a file?

A: If you are using Objective-C, NSFileManager has a nice API named "attributesOfItemAtPath:error:" where one of the things passed back in the NSDictionary object is "fileModificationDate".
You also can use CoreFoundation CFURL functions, like "CFURLCopyResourcePropertyForKey" which has something called "kCFURLAttributeModificationDateKey" which you can get the value of.

A: I don't know their reliability, but what about ls -l or find -ls?
EDIT:
I just found this: Getting the last modified date of a file in C

On OS X, st_mtimespec.tv_sec is the equivalent of st_mtime.

A: This may sound silly, but check the return code of stat(). If it returns anything but zero, there was an error (e.g., file not found).
I just spent a few hours tracking this down myself.


text:
Q: HTML comment containing URL breaks if followed by another HTML comment While fixing up a broken imgur link on StackApps, I noticed that a HTML comment in a post that contains a URL that Markdown might parse will break in the preview if that comment is followed by at least one more HTML comment. It also breaks in the rendered post if that comment is followed by at least two more HTML comments, as is the case in the screenshot below.
In less confusing terms, this happens:

Live example:

gives us

This may be related to a recent change to address this issue, since this worked fine before.

A: This wasn't even really a new bug – this was always broken:
You may be right  about this.

turned into

You may be right http://xkcd.com/386 --> about this.

because the auto-linker did this:
You may be right  about this.

and the tag sanitizer eats anything starting with a < until the next > (or end of text) that is not whitelisted – and the "tag"


text:
Q: Tracking objects using javaCV I am trying to track faces using Camshift in JavaCV. I have found Open CV equivalent at:
https://gist.github.com/231696
I have been successfully able to convert much part of the code, but struggling to figure out the equivalent of the following in JavaCV. Any help will be really appreciated.
TrackedObj* obj;

if((obj = malloc(sizeof *obj)) != NULL) {

obj->hsv  = cvCreateImage(cvGetSize(image), 8, 3);
obj->mask = cvCreateImage(cvGetSize(image), 8, 1);
obj->hue  = cvCreateImage(cvGetSize(image), 8, 1);
obj->prob = cvCreateImage(cvGetSize(image), 8, 1);
}

A: Well, we can define a class similar to the struct TrackedObj like this:
class TrackedObj {
    IplImage hsv;
    IplImage hue;
    IplImage mask;
    IplImage prob;
    CvHistogram hist;
    CvRect prev_rect;
    CvBox2D curr_box;
}

And we can translate the bit of code you point out in a very similar fashion like this:
TrackedObj obj = new TrackedObj();
obj.hsv  = cvCreateImage(cvGetSize(image), 8, 3);
obj.mask = cvCreateImage(cvGetSize(image), 8, 1);
obj.hue  = cvCreateImage(cvGetSize(image), 8, 1);
obj.prob = cvCreateImage(cvGetSize(image), 8, 1);