text:
Q: javascript/angular 4 property is undefined after interval tries to get value I am trying to build an timer, but it is not working.
What I do is I have a button which starts the timer. It sets the begin time and after that start an interval to count on screen. But the function which is called by the interval fails because the beginning time is undefined. I debuged to see if the beginning time is being set, and it is. But when it is called through the interval it is undefined.
Here is my code
Some properties
 timeBegan = new Date();
  started = null;

the start function
start() {
this.timeBegan = new Date();
document.getElementById('ticker').innerHTML = '00:00:00.000';

this.started = setInterval(this.clockRunning, 10);
  }

the clockrunning function
public clockRunning() {
const currentTime = new Date();
console.log(this.timeBegan);
console.log(currentTime.getTime());
const timeElapsed = new Date(currentTime.getTime() - this.timeBegan.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

console.log(currentTime.getSeconds());
console.log(this.timeBegan);
document.getElementById('ticker').innerHTML =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 999 ? ms : ms > 9 ? '0' + ms : '000' + ms);

 }

What am I doing wrong?

A: Use it like this in start function:
this.started = setInterval(this.clockRunning.bind(this), 10);

or:
this.started = setInterval(function(e){
      this.clockRunning();
}.bind(this), 10);

It will definitely solve your problem.

A: It is not working because you are referencing:
this.timeBegan

However, "this" is not refering to the "this" you want it to refer to. "this" is the function defined in setInterval. This is because ES5 functions have their own "this".
You could try using an ES6 function which will prob use the "this" you want.
Alternatively, force "this" within your function to refer to the "this" you want by doing:
this.clockRunning = this.clockRunning.bind(this)

This means that the "this" within clockRunning will ALWAYS be the "this" passed to bind(). Make sure you pass the right "this" to bind :) viz the "this" that has the timeBegan property.


text:
Q: cURL error 2: easy handle already used in multi handle (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) Google Client Access Token I am using google Authentication using GoogleClient on my website. when I am trying to get Google access token with Auth code I am getting the following error.
$accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code'])

This is the error
cURL error 2: easy handle already used in multi handle (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Please help me.

A: I am posting my solution here.
Problem:
In my case I guess, when my server auto-update something it affected some functionality to handle multiple cUrl requests.
Solution:
I am using Yii Framework and I am using guzzlehttp vendor in my project. this module was raising this issue. so I commented a piece of code to solve the issue.
Open the file.
vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php
Go to the function release
and comment the following lines.
if (count($this->handles) >= $this->maxHandles) {
   curl_close($resource);
} else {
   // Remove all callback functions as they can hold onto references
   // and are not cleaned up by curl_reset. Using curl_setopt_array
   // does not work for some reason, so removing each one
   // individually.
   curl_setopt($resource, CURLOPT_HEADERFUNCTION, null);
   curl_setopt($resource, CURLOPT_READFUNCTION, null);
   curl_setopt($resource, CURLOPT_WRITEFUNCTION, null);
   curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, null);
   curl_reset($resource);
   $this->handles[] = $resource;
}

and Add the following line instead
curl_close($resource);

See the complete Function after applying solution.
public function release(EasyHandle $easy)
{
    $resource = $easy->handle;
    unset($easy->handle);

    /*if (count($this->handles) >= $this->maxHandles) {
        curl_close($resource);
    } else {
        // Remove all callback functions as they can hold onto references
        // and are not cleaned up by curl_reset. Using curl_setopt_array
        // does not work for some reason, so removing each one
        // individually.
        curl_setopt($resource, CURLOPT_HEADERFUNCTION, null);
        curl_setopt($resource, CURLOPT_READFUNCTION, null);
        curl_setopt($resource, CURLOPT_WRITEFUNCTION, null);
        curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, null);
        curl_reset($resource);
        $this->handles[] = $resource;
    }*/
    curl_close($resource);
}

I hope it will help you.

A: Go to server and serch EasyApache 4 and click customize and left side  look in php extention click now and select php version , search curl and unistall the curl
 your error solve

redpajama_set_name: RedPajamaStackExchange


text:
Q: Datasets for benchmarking Fuzzy Clustering method with millions of data We want to test the performance of some fuzzy clustering algorithms that some collaborators have developed. Our interest lies in 2D datasets with a lot of data, where we could benchmark these algorithms. Do you know where can one find such datasets?

A: One excellent dataset is the one provided by this website.  StackExchange provides an anonymized dump of all publicly available data found on their sites here: https://archive.org/details/stackexchange
You can read about the data schema here: https://meta.stackexchange.com/questions/2677/database-schema-documentation-for-the-public-data-dump-and-sede
I have a copy of the data from a year ago and it has over 16 million records just for this site (StackOverflow.com) and the dump has all of their sites.

A: You can generate dataset from http://www.mockaroo.com/. It is pretty good an you can have many option.

A: There are many large "open data" collections with scientific data around the web. Some have rather, shall we say, nontrivial data set sizes of well over a Terabyte. So, depending on which size you need, take a look at genome sites like Proteomecommons or the datasets from Stanford's Natural Language Processing group.
Smaller dumps can be found in the geologists' projects like this one.


text:
Q: How to change the value of a field (obtained dynamically) in firestore document from cloud functions? My question is really simple. How can I update a field in a firestore document if the name of the field is only known dynamically in a variable?
const myCounterName = "exampleName";
const docRef = admin.firestore().collection("metadata").doc("myDoc");
docRef.set({myCounterName : admin.firestore.FieldValue.increment(1)}, {merge: true});

The problem is that firestore is going to consider that the name of the field I want to change is "myCounterName" and not "exampleName".

A: You can do as follows, using the square brackets notation:
const myCounterName = "exampleName";

const payloadObj = {};
payloadObj[myCounterName] = admin.firestore.FieldValue.increment(1);

const docRef = admin.firestore().collection("metadata").doc("myDoc");
docRef.set(payloadObj, {merge: true});


text:
Q: Error at rendering circles - Google Maps Javascript I'm developing a web app which has a map and where the user can set circles wherever he wants. Then he can see every circle he has set.
But when I load the circles that the user has, this happens:

The user that I´m using to test has 5 circles, the ones that appear complete. The rest is junk that just appears there and I´m not sure why.
This is my code (I´m using RoR):
Javascript:
function initMap() {

  var mapOptions = {
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: true
  };

  map = new google.maps.Map(document.getElementById('map'), mapOptions);

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      var marker = new google.maps.Marker({
          position: pos,
          map: map,
          icon: "<%= asset_path('marker.png') %>"
        });

      map.setCenter(pos);

    }, function(e) {
      console.log(e);
    });
  }
}

function loadUserTargets() {
  $.getJSON('/circles/list', function(circlesList) {
    if(circlesList.length > 0) {
      jQuery.each(circlesList, function(index, circle){
        var circleCenter = new google.maps.LatLng(circle.latitude, circle.longitude);
        drawCircleAt(circleCenter, circle.radius);
      });
    }
  });
}

function drawCircleAt(location, radius) {

  return new google.maps.Circle({
    strokeWeight: 0,
    fillColor: '#efc537',
    fillOpacity: 0.7,
    map: map,
    center: location,
    radius: radius
  });
}

When I call getJSON('/circles/list', ...) I get the following in return:
[{"id":4,"latitude":-34.9001517737747,"longitude":-56.1877727508545,"radius":456},
{"id":5,"latitude":-34.8983567053717,"longitude":-56.1922359466553,"radius":367},
{"id":6,"latitude":-34.9032138587385,"longitude":-56.1949396133423,"radius":100},
{"id":7,"latitude":-34.9053255749513,"longitude":-56.2041234970093,"radius":200},
{"id":8,"latitude":-34.9103230869756,"longitude":-56.18408203125,"radius":500}]

Does anybody know what´s going on?
Thanks!
UPDATE
This bug was handled in the isssue https://issuetracker.google.com/issues/38211242.
It was fixed in August 2017.


text:
Q: Image url being treated as a page request in yii2 I am working on a project which is developed in Yii2. Today I came across a weird and funny issue of image url being treated as a page request.
When I try accessing image with url as https://www.websitename.com/images/image1.jpg, it shows me the image. And when I try accessing image with url as https://www.websitename.com/images/image1-lockdown.jpg then it shows 404 Error. On checking I found that internally the request was changed to "/site/images/image1.jpg". As we all know to access images no controller call is made.
Same issue was generated on local machine (Ubuntu 16.04). Just added "lockdown" into the name of image url.
I am using Yii2 Advanced Template. OS: For production CentOS and for development Ubuntu 16.04.
Note: I couldn't verify if the same issue exists for windows or not.
Kindly Help!
Edited: .htacess (root folder on production)
Options -Indexes
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule admin(.+)?$ /backend/web/$1 [L,PT]
  RewriteRule gamer/(.+)?$ /gamer/web/$1 [L,PT]
  RewriteCond %{REQUEST_URI} !^public
  RewriteRule ^(.*)$ /frontend/web/$1 [L]
</IfModule>

.htaccess (frontend/web on production)
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php


text:
Q: VBA MapNetworkDrive to server with windows credentials I'm using windows 7 and Access 2010. I'm trying to connect to our server to see files.
My problem is that I don't want to have the username or password in the code. I would like to have windows to prompt for it if authentication needed (from my tests, once you authenticate you don't have to re-do it for a while).
From MapNetworkDrive Object MSDN, strUser and strPassword is optional and uses current users credentials, but this doesn't seem to work for a server.
Dim objFSO As Object
Dim objFolder As Object
Dim objNetwork As Object
Dim strShareLetter As String
Dim strURL As String, strUser as String, strPassword as String
strShareLetter = "L:"

Set objFSO = CreateObject("Scripting.FileSystemObject")
strURL = "\\company@SSL\DavWWWRoot\companydav\nodes\12345678\"

Set objNetwork = CreateObject("WScript.Network")
objNetwork.MapNetworkDrive strShareLetter, strURL, False, strUser, strPassword

Set objFolder = objFSO.GetFolder(strURL)

MsgBox objFolder.Files.Count
MsgBox objFolder.SubFolders.Count

Set objFolder = Nothing
Set objFSO = Nothing

objNetwork.RemoveNetworkDrive (strShareLetter)
Set objNetwork = Nothing

If I write my user/password in the code everything works. But I need other users to be able to use it and I don't want my credentials being used everywhere. I would like a windows credentials prompt or something along that way. I don't want to prompt for the user password via vba for security reasons.
Any ideas? I searched google for solutions but I can't seem to find one. thank you

A: It sounds like you've already recognized that you need some sort of user form in your project to collect the user's credentials.
Here's how I would do that.  I'd insert a User-Form from the VBA editor.  From there I'd grab a couple of text boxes and labels to it, label one box as "User ID" and the other as "Password."  For the password text box I'd be sure to insert "*" in the PasswordChar property to mask the password.  I'd also put a button on there that says "Submit" or "Log In" or something to that effect.
Once you've done that, You'll need a couple of properties:
Private pUserId As String
Private pPassword As String

Public Property Let UserId(value as string)
    pUserId = value
End Property

Public Property Get UserId() as string
    UserId = pUserId
End Property

Public Property Let Password(value as string)
    pPassword = value
End Property

Public Property Get Password() As String
    Password = pPassword
End Property

Then you will want to use your log in button's click event to load the information from the text boxes into the properties and hide the form.
Private Sub CommandButton1_Click()
    UserId = TextBox1.text
    Password = TextBox2.text
    Me.hide
End Sub

Then all you have to do is dim and display the user form to the user.
...
Set objNetwork = CreateObject("WScript.Network")
Dim LogInForm As UserForm1
Set LogInForm = New UserForm1
LogInForm.Show vbModal
objNetwork.MapNetworkDrive strShareLetter, strURL, False, LogInForm.UserId, LogInForm.Password
...

And that's pretty much it.  You might need to learn how to create user forms in VBA or brush up on that.


text:
Q: Java persistence - getSingleResult() did not retrieve any entities I am testing a JPA project as follows:
try {
            emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
            EntityManager em = emFactory.createEntityManager();
            Query qry = em.createQuery("select t from TestCon t");
            System.out.println(qry);
            TestCon tcon = (TestCon) qry.getSingleResult(); //qry.getSingleResult();
            rslt = tcon.getB();
            if (rslt == null || rslt.equals(""))
                rslt = "Could not get result";
            System.out.println(rslt); //new ShowMsg(rslt);
        } catch (Exception ex) {
            System.out.println(ex); //new ShowMsg("Exception occured");
        }

The output is:
javax.persistence.NoResultException: getSingleResult() did not retrieve any entities.

The qry string is:
EJBQueryImpl(ReadAllQuery(referenceClass=TestCon sql="SELECT a, b FROM C##test.testcon"))

When I test directly in SQLPLUS:
SELECT a, b FROM C##test.testcon

it gives me the correct result. I can not find out where the program fails.

A: Create a transaction before executing the query.
try {
    emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = emFactory.createEntityManager();

    em.getTransaction().begin(); //added

    Query qry = em.createQuery("select t from TestCon t");
    System.out.println(qry);

    //need to use getResultList() if table has > 1 row
    List<TestCon> tcon = (List<TestCon>) qry.getResultList();

    for(Testcon rslt:tcon){
         rslt = tcon.getB();
         if (rslt == null || rslt.equals("")){
             rslt = "Could not get result";
         }
         System.out.println(rslt); //new ShowMsg(rslt);
    }

    entityManager.getTransaction().commit(); //added
    entityManager.close(); //added
} catch (Exception ex) {
 System.out.println(ex); //new ShowMsg("Exception occured");
}


text:
Q: compile cilk plus code centos 7 gcc-5.2 devtoolset-4 #include <iostream>
#include <cilk/cilk.h>

int fib(int n)
{
 if (n < 2)
 return n;
 int x = cilk_spawn fib(n-1);
 int y = fib(n-2);
 cilk_sync;
 return x + y;
}

int main(int argc, char ** argv)
{
    for (int i = 0; i != 20; ++i)
    {
        std::cout << "fib(i)=" << fib(i) << std::endl;
    }
}

compiled like so can't find the library
$ g++ -Wall -O3 -fcilkplus fib.cpp -o fib
/opt/rh/devtoolset-4/root/usr/libexec/gcc/x86_64-redhat-linux/5.2.1/ld: cannot find -lcilkrts
collect2: error: ld returned 1 exit status

So I try find and adding it with the -L switch
$ find /opt/rh/devtoolset-4 -name "cilkrts"
/opt/rh/devtoolset-4/root/usr/lib/gcc/x86_64-redhat-linux/5.2.1/32/libcilkrts.a
/opt/rh/devtoolset-4/root/usr/lib/gcc/x86_64-redhat-linux/5.2.1/32/libcilkrts.so
/opt/rh/devtoolset-4/root/usr/lib/gcc/x86_64-redhat-linux/5.2.1/libcilkrts.spec
$ g++ -Wall -O3 -fcilkplus fib.cpp -o fib -L/opt/rh/devtoolset-4/root/usr/lib/gcc/x86_64-redhat-linux/5.2.1/32
/opt/rh/devtoolset-4/root/usr/libexec/gcc/x86_64-redhat-linux/5.2.1/ld: skipping incompatible /opt/rh/devtoolset-4/root/usr/lib/gcc/x86_64-redhat-linux/5.2.1/32/libstdc++.so when searching for -lstdc++
/opt/rh/devtoolset-4/root/usr/libexec/gcc/x86_64-redhat-linux/5.2.1/ld: skipping incompatible /opt/rh/devtoolset-4/root/usr/lib/gcc/x86_64-redhat-linux/5.2.1/32/libcilkrts.so when searching for -lcilkrts
/opt/rh/devtoolset-4/root/usr/libexec/gcc/x86_64-redhat-linux/5.2.1/ld: cannot find -lcilkrts
/opt/rh/devtoolset-4/root/usr/libexec/gcc/x86_64-redhat-linux/5.2.1/ld: skipping incompatible /opt/rh/devtoolset-4/root/usr/lib/gcc/x86_64-redhat-linux/5.2.1/32/libgcc_s.so when searching for -lgcc_s
/opt/rh/devtoolset-4/root/usr/libexec/gcc/x86_64-redhat-linux/5.2.1/ld: skipping incompatible /opt/rh/devtoolset-4/root/usr/lib/gcc/x86_64-redhat-linux/5.2.1/32/libgcc.a when searching for libgcc.a
collect2: error: ld returned 1 exit status

$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/opt/rh/devtoolset-4/root/usr/libexec/gcc/x86_64-redhat-linux/5.2.1/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --enable-bootstrap --enable-languages=c,c++,fortran,lto --prefix=/opt/rh/devtoolset-4/root/usr --mandir=/opt/rh/devtoolset-4/root/usr/share/man --infodir=/opt/rh/devtoolset-4/root/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --enable-plugin --with-linker-hash-style=gnu --enable-initfini-array --disable-libgcj --with-default-libstdcxx-abi=gcc4-compatible --with-isl=/builddir/build/BUILD/gcc-5.2.1-20150902/obj-x86_64-redhat-linux/isl-install --enable-libmpx --enable-gnu-indirect-function --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 5.2.1 20150902 (Red Hat 5.2.1-2) (GCC)

Pointers appreciated

A: If I asked it I guess I should post the answer when I work it out:
sudo yum install devtoolset-4-libcilkrts-devel
is the missing piece.


text:
Q: How can I minimize the repetition of code with this jquery ajax? I have many functions on a page, where the following code is exactly the same, except for the data being sent, and the success div to display the result to. For example:
One ajax post:
$.ajax({
    type: 'POST',
    url: 'unique_file.php',
    data: {qty: 2, item_id: 13},
    cache: false,
    success: function(data) {
       $('#return_div').html(data);
    }
});

Another ajax post:
$.ajax({
    type: 'POST',
    url: 'another_unique_file.php',
    data: {no_shipping: 4},
    cache: false,
    success: function(data) {
      $('#a_different_div').html(data);
    }
});

So I was thinking it would be ideal to make this into a function like so
function do_ajax(post_file,results_div,post_data) {
$.ajax({
    type: 'POST',
    url: post_file,
    data: {post_data}, // this doesn't appear to work
    cache: false,
    success: function(data) {
      $(results_div).html(data);
    }
});
}

Then I can achieve #1 ajax like so:
do_ajax('unique_file.php','#return_div','qty: 2, item_id: 13');

This seems logical to me, but the limits of my logic are how to get the data into my function.    Perhaps the post_data is not just a string like that but more something like:
do_ajax('purchase_create.php','#create_purchase_window','item_id:'+$item_id+', qty: '+$qty+'');

Which looks pretty messy... but mostly, it just doesn't work. Is there a cleaner way of perhaps putting all the data into an array and giving that to the function?

A: You can use ajaxSetup to set defaults.
$.ajaxSetup({
  cache: false,
  type: 'POST'
});

then
$.ajax({
    url: post_file,
    data: {post_data: post_data}, // this doesn't appear to work
    success: function(data) {
      $(results_div).html(data);
    }
});

{post_data} is not correct syntax. So I changed it to {post_data: post_data}

A: You're on the right track:
function do_ajax(post_file,results_div,post_data) {
$.ajax({
    type: 'POST',
    url: post_file,
    data: post_data,
    cache: false,
    success: function(data) {
      $(results_div).html(data);
    }
});
}

do_ajax('purchase_create.php, '#create_purchase_window', {
    item_id: 3,
    qty: 2
});

You're passing an object to POST, so just pass that object into your do_ajax function and pass it along.


text:
Q: How to make 3D rounded corner JLabel in Java? I know there is a way to extend a JLabel to paint 3D borders and a way to paint round borders, but how do you get both? Here is my code
protected void paintComponent(Graphics g) {
     g.setColor(getBackground());
     g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 25, 25);
     g.fill3DRect(10, 10, 30, 30, true);
     super.paintComponent(g);

A: Use LineBorder with rounded corners or a variant of the TextBubbleBorder.

A: You refer this code to create Round Corner JLabel:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class RoundedLineBorder extends JPanel {

    public RoundedLineBorder() {
        super(true);
    setLayout(new BorderLayout());

        JLabel label = new JLabel("Rounded Corners");

        label.setHorizontalAlignment(JLabel.CENTER);

    LineBorder line = new LineBorder(Color.blue, 2, true);

        label.setBorder(line);

        add(label, BorderLayout.CENTER);
    }

    public static void main(String s[]) {
         JFrame frame = new JFrame("Rounded Line Border");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(500, 200);
         frame.setContentPane(new RoundedLineBorder());
         frame.setVisible(true);
    }
}


text:
Q: ActionController :: UnknownFormat when I try to delete in db I have the following code and I want to create a modal confirmation to delete a campaign in my app.
The part of my view where the button is is:

  <%= form_for @campaign, method: 'delete', html: {class: 'remove_campaign'} do |f| %>
    <button type='submit' class="waves-effect waves-light btn grey">Remover</button>
  <% end %>

I created _remove_member_modal.html.erb as follows:

      <%= form_for(@campaign, :method => :delete, class: "col s12 remove_campaing_form") do %>

Remover Campanha

Você quer mesmo deletar a campanha?

            <%= submit_tag("Remover", class: "btn red right") %>

      <% end %>

And I have campaigns.coffee where I have the following code:
$('.remove_campaign').click (e) ->
  $('#remove_campaign_modal').modal('open')
  $('.remove_campaign_form').attr('action', 'campaigns/' + e.target.id)
  return false

  $('.remove_campaign_form').on 'submit', (e) ->
    $.ajax e.target.action,
      type: 'DELETE'
      dataType: 'json',
      data: {}
      success: (data, text, jqXHR) ->
        $(location).attr('href','/campaigns');
      error: (jqXHR, textStatus, errorThrown) ->
        Materialize.toast('Problema na remoção da Campanha', 4000, 'red')
  return false

Inside the modal when I click the delete button I get the following error:

ActionController::UnknownFormat in CampaignsController#destroy

My controller's destroy action is as follows:
def destroy
  @campaign.destroy

  respond_to do |format|
    format.json { render json: true }
  end
end

How can I resolve this error?


text:
Q: checkSelfPermission returns false if user has chosen "While using the app" optin To check locations permission, I call
private fun isLocationPermissionAllowed(): Boolean {
    val locationPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        Manifest.permission.ACCESS_BACKGROUND_LOCATION
    } else {
        Manifest.permission.ACCESS_FINE_LOCATION
    }

    return ContextCompat.checkSelfPermission(
        app,
        locationPermission
    ) == PackageManager.PERMISSION_GRANTED
}

Problem is that this code piece will return false if user chooses "While using the app".
This function is called on apps startup, meaning, that it will ask permission all the time when app has been re-opened. Is this normal behaviour? I thought that checkSelfPermission will return false if user has chosen DENY and true for the rest of the cases.


text:
Q: Вместо иконок svg чёрные квадраты Пытаюсь создать иконочный шрифт на https://icomoon.io/, загрузил svg иконки и большинство из них отображаются как черный квадрат. Если открыть иконку браузером всё отлично. Может в коде svg нужно что-то изменить?

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="35" height="35" viewBox="0 0 35 35" fill="none">
<rect width="35" height="35" fill="url(#pattern0)"/>
<defs>
<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
<use xlink:href="#image0_192_7" transform="scale(0.00195312)"/>
</pattern>
<image id="image0_192_7" width="512" height="512" xlink:href="data:image/png;base64...


text:
Q: ITMS-90338: Non-public API usage -> ADBannerView Apple has sent us this email:

We identified one or more issues with a recent delivery for your app. Please correct the following issues, then upload again.
ITMS-90338: Non-public API usage - The app contains or inherits from non-public classes in Project: ADBannerView . If method names in
your source code match the private Apple APIs listed above, altering
your method names will help prevent this app from being flagged in
future submissions. In addition, note that one or more of the above
APIs may be located in a static library that was included with your
app. If so, they must be removed. For further information, visit the
Technical Support Information at
http://developer.apple.com/support/technical/

I do a research and we dont have any class called ADBannerView, and the only reference to an object called ADBannerView is inside our iAd sdk implementation:
import iAd
private var adBannerView: ADBannerView!

iAd is from apple... I dont know how to solve this problem.
Any idea?


text:
Q: Angular bind 2 select dropdowns to object and store only the selected value In my Angular component I'm using 2 html select dropdowns. The model dropdown shows the models of the selected brand above. Currently the problem is that I want to store both as string but in code I get the whole object from brand dropdown. If I change ngValue of brand into [ngValue]="brand.name", the bind with the model select will not work anymore. Currently the selected car brand is on submit of my form stored as the brand object and the car model stored as a string.
How can I select a model of the selected brand and also store the brand as string?
This is my code
<form *ngIf="car" #carEditForm="ngForm" name="form" (ngSubmit)="carEditForm.form.valid
&& onSubmit()">
    Car brand
    <select class="form-control" [(ngModel)]="car.brand" name="brand" required>
        <option *ngFor="let brand of brands" [ngValue]="brand">{{ brand.name }}</option>
    </select>
    Model
    <select *ngIf="car.brand" [(ngModel)]="car.model" class="form-control" name="model"
     required>
        <option *ngFor="let model of car.brand.models" value="{{ model }}">
            {{ model }}
        </option>
    </select>
    ...
</form>

And the classes:
export class Car {
  key: string
  brand: string
  model: string
}

export class Brand {
  key: string
  name: string
  models: []
}

Edit: Solution in comments


text:
Q: How to create a formset from form-instance in Python Django I am trying to get a Django - Formset out of an instance of a form class.
In my form class i add some fields in the init method because the form has to offer some flexibility. Therefore i can't pass the class as parameter to the formset_factory function.
--forms.py
class ConfigForm(forms.Form):
    def __init__(self, fields, fields_choices, *args, **kwargs):
        super(ConfigForm, self).__init__(*args, **kwargs)

        for field in fields:
            # instanciate Field from field data
            exec(
                f'self.fields["{field.name}"] ='
                f'forms.{field.field_type.field_type}('
                f'required = {field.required},'
                f'disabled = {field.disabled},'
                f'label = "{field.label}",'
                f'initial = "{field.value}",'
                f'widget = {field.widget},'
                f'help_text = "{field.description}"'
                f')'
                )
            # if field is a ChoiceField add choices to the field instance
            if 'ChoiceField' in field.field_type.field_type:
                self.fields[field.name].choices = [fields_choices[field.name]]

--views.py
...
form = forms.ConfigForm(active_fields, field_choices)
formset = formset_factory(form, extra=1)

...
But if i try to call formset_factory with an instance of ConfigForm, the following error occurs:
Internal Server Error: /machines/testconfig/mw0-sap-001/
Traceback (most recent call last):
  File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "D:\Users\BKU\maximilianwiederer\OneDrive - Deutsche Bahn\Documents\Programmierung\Eclipse\sap4cloud-dev\machines\views.py", line 83, in get
    formset = forms.formset_factory(form, extra=1)
  File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\formsets.py", line 441, in formset_factory
    return type(form.__name__ + 'FormSet', (formset,), attrs)
AttributeError: 'ConfigForm' object has no attribute '__name__'

A: You can't pass an instance of a form into a formset factory. It expects a class, not an instance. However, you can provide a dictionary of arguments to the factory to give to each instance of the form that is created.
https://docs.djangoproject.com/en/2.2/topics/forms/formsets/#passing-custom-parameters-to-formset-forms
Here's how I would suggest writing your code.
ConfigFormset = forms.formset_factory(forms.ConfigForm)
formset = ConfigFormset(
    form_kwargs={
        'fields' : active_fields,
        'fields_choices': {}
        }
    )


text:
Q: How to save scraped contents to pandas dataframe with dynamical column names I have to scrape an e-commerce web page which includes the normal elements like: price, sku etc. and a table. After scraped the elements on each link page, i scraped the table in nested loop and found the elements which i need. There are two values and as you can see the column names has to be dynamically created.
# loop trough all links and launch one by one
 for link in links:
 driver.get(link)
 # scrape here
 price = driver.find_element_by_css_selector('body > div.page-wrap > section > div > div.content--wrapper > div > div.product--detail-upper.block-group > div.product--buybox.block > div > div.product--price.price--default > span').text
 delivery_status = driver.find_element_by_css_selector('body > div.page-wrap > section > div > div.content--wrapper > div > div.product--detail-upper.block-group > div.product--buybox.block > div > div.product--delivery > p > span').text
 image_href = driver.find_element_by_xpath("//span[@class='image--element']/span/img").get_attribute('srcset')
 sku = driver.find_element_by_css_selector('body > div.page-wrap > section > div > div.content--wrapper > div > div.product--detail-upper.block-group > div.product--buybox.block > ul > li > span').text
 title = driver.find_element_by_css_selector('body > div.page-wrap > section > div > div.content--wrapper > div > div.tab-menu--product.js--tab-menu > div.tab--container-list > div.tab--container.has--content.is--active > div.tab--content > div.content--description > div.content--title').text
 product_descripion_list = driver.find_element_by_css_selector('body > div.page-wrap > section > div > div.content--wrapper > div > div.tab-menu--product.js--tab-menu > div.tab--container-list > div.tab--container.has--content.is--active > div.tab--content > div.content--description > div.product--description').get_attribute('innerHTML')
 # table of attributes
 attributes = driver.find_elements_by_xpath("//tr[@class='product--properties-row']")

 titles.append(title)
 product_descripion_lists.append(product_descripion_list)
 prices.append(price)
 delivery_statuses.append(delivery_status)
 skus.append(sku)
 images.append(image_href)

 # set i
 i = 1

 for row in attributes:
    data = {}
    cells = row.find_elements(By.TAG_NAME, 'td')
    data['Attribut '+str(i)+' Name'] = cells[0].text
    data['Attribut '+str(i)+' Wert'] = cells[1].text
    print(data)
    i+=1

then i want to add this to dataframe and created an extra dictionary:
#save dataframe to file
  dict = {'Name' : titles, 'Beschreibung': product_descripion_lists, 'Regulärer Preis' : prices, 'Verfügbarkeit' : delivery_statuses, 'Nummer' : skus, 'Bild' : images}

     df = pd.DataFrame(dict)

     df.to_excel('output.xlsx')

Now my question is: How to add that two columns with the dynamic column names to the dataframe with its values ? Desired outcome should look like this:
| Name | Beschreibung | Regulärer Preis | Verfügbarkeit | Nummer | Bild | Attribut 1 Name | Attribut 1 Wert | Attribut 2 Name | Attribut 2 Wert | etc.
The Attribut x should be as much columns as much attributes found in the loop.


text:
Q: Is it possible to define a ValueConversion on a private field? EF Core lets you specify a private field to use in the database using string syntax:
modelBuilder.Entity<MyEntity>().Property("myField");

And you can specify value conversions for properties:
modelBuilder
    .Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasConversion(
        v => v.ToInt(),
        v => new MyProperty(v));

But is it possible to specify a value conversion for a private field? This doesn't compile, presumably because the type is unknown:
// won't work
modelBuilder.Entity<MyEntity>().Property("myField")
    .HasConversion(
        v => v.ToInt(),
        v => new MyFieldType(v));

Nor can you use the generic type parameter, because those are for predefined value converters provided by EF Core:
// won't work
modelBuilder.Entity<MyEntity>().Property("myField")
    .HasConversion<MyFieldType>(
        v => v.ToInt(),
        v => new MyFieldType(v));

Is it possible to define a ValueConversion on a private field?

A:
EF Core lets you specify a private field to use in the database using string syntax

It also allows you to specify the property type:
modelBuilder.Entity<MyEntity>()
    .Property<MyFieldType>("myField")
//                 ^

Now all the standard typed value converter fluent APIs work:
.HasConversion(
    v => v.ToInt(),
    v => new MyProperty(v));

A: Yes, you just have to define a new ValueConverter first:
ValueConverter<MyFieldType, int> myConverter = new ValueConverter<MyFieldType, int>(
    v => v.ToInt(),
    v => new MyFieldType(v));

modelBuilder.Entity<MyEntity>()
    .Property("myField")
    .HasConversion(myConverter);


text:
Q: How do you make a PyArrow Dataset out of an IO stream? I have a python program reading a parquet file in as a filereader, and am trying to use this to construct a pyarrow dataset. I am able to read the filereader into a pyarrow table, using:
    import pyarrow.parquet as pq

    table = pq.read_table(file_reader)

However, passing the filereader directly to the dataset initializer gives an error. This makes sense because the pyarrow documentation shows the ds.dataset function does not accept a filereader as a data source:
    import pyarrow.dataset as ds

    dataset = ds.dataset(file_reader) # TypeError: Expected a path-like, list of path-likes or a list of
                                       # Datasets instead of the given type

A current work-around I'm trying is reading the stream in as a table, and then reading the table as a dataset:
    import pyarrow.parquet as pq
    import pyarrow.dataset as ds

    table = pq.read_table(input_stream)
    dataset = ds.dataset(table)

However, I'm not sure this is a valid workaround for a Dataset, because the dataset may expect the table being passed to be backed by an underlying file, which it is not.

A: I'm not entirely certain what you mean by a "filereader".  Arrow has a C++ class parquet::arrow::FileReader but I don't think pyarrow has documented bindings for that although it is used internally for functions like pyarrow.parquet.ParquetFile.iter_batches.
Either way, the answer is probably that you cannot create a dataset from a file reader but you also probably don't need to.
Typically datasets are used to create a scanner which can then be used directly for iterative processing (possibly filtering or projecting the data) or as input to something like pyarrow.dataset.write_dataset.
import pyarrow as pa
import pyarrow.parquet as pq
import pyarrow.dataset as ds

tab = pa.Table.from_pydict({'a': [1, 2, 3], 'b': ['x', 'y', 'z']})
pq.write_table(tab, '/tmp/foo.parquet')

parquet_file = pq.ParquetFile('/tmp/foo.parquet')
schema = parquet_file.schema_arrow
itr = parquet_file.iter_batches()

scanner = ds.Scanner.from_batches(itr, schema=schema, columns=['a'], filter=ds.field('b') == 'y')
print(scanner.to_table())

The main thing that is missing here is you won't have any filter pushdown.  Obviously we can't do any partition-based filtering because there is only one file but we also don't get to use parquet's statistics-based row group filtering.
You will also need to make sure when you create the file to only ask for the columns you need (e.g. the one's selected by the scanner's projection and filter).  Otherwise it will load those columns in memory only for the scanner to drop them later.


text:
Q: How can I stop a django server programatically I want to perform some checks across a few environments being pointed to on startup of my django server to ensure consistency of the different environment configrations. For example, that they are all in dev configuration, or all in prod configuration. If this is not the case I would like to shut down the server.
My question is what is the best way to shut down the server and report the issue? At the moment my plan is to raise a RuntimeError with the appropriate exception message. But I was wondering if there is any problem with this approach, or if there is a more suitable approach which I can not find.
Researching the issue has unfortunately not yielded sufficient information.

A: I assume you'll be running with apache, which can't, or perhaps more accurately shouldn't, be controlled by Django.
What you should aim to do use python logging & if you find an issue log a critical level message. You can then have a handler setup to use mail_admins for those logging messages; https://docs.djangoproject.com/en/2.0/topics/logging/#examples
There are several levels to logging;

*

*Debug

*Info

*Warning

*Error

*Critical

If you set a level, it's the base level that will be required by the handler or logger etc. So if you set 'level': 'ERROR' it'll log error and critical messages.
If you've implemented logging, you can then do similar to the following in your code;
import logging

logger = logging.getLogger(__name__)

...

if error_found:
    logger.critical("Oh no, we've found an error")

try:
    ...
except RuntimeError:
    logger.error("We've got a problem", exc_info=True)

For some further reading on setting up logging have a read of this.


text:
Q: ATtiny85 simulation in AtmelStudio 6.1 (build 2730, SP2) I have written a piece of code which manipulates the DDR for port B:
#include <avr/io.h>

int main(void)
{
    DDRB = 0;

    DDRB = 1;
    DDRB = 2;
    DDRB = 4;
    DDRB = 8;
    DDRB = 16;
    DDRB = 32;
    DDRB = 64;
    DDRB = 128;

    return 0;
}

I'm using the simulator and I'm having a hard time in figuring out how this maps in the I/O view, and what will happen on the actual device. I'm stepping over the DDRB=1..128 instructions.
As expected, DDRB values in the I/O view go from 0x1 to 0x20 as I execute the first 6 instructions, DDRB=1..32. However the other two instructions DDRB=64,128 have the effect of setting DDRB in the I/O view to 0x0. In a way this is not entirely surprising, as the ATtiny85 has only 6 PB pins. But is this behavior expected?
The real question is: what are the little squares in the I/O view next to the value of DDRB saying? Here is the state of DDRB in I/O view after each single instruction in main:
DDRB=  0;  --> DDRB    0x37    0x0    000000
DDRB=  1;  --> DDRB    0x37    0x1    000000
DDRB=  2;  --> DDRB    0x37    0x2    000000
DDRB=  4;  --> DDRB    0x37    0x4    000001
DDRB=  8;  --> DDRB    0x37    0x8    000010
DDRB= 16;  --> DDRB    0x37    0x10   000100
DDRB= 32;  --> DDRB    0x37    0x20   001000
DDRB= 64;  --> DDRB    0x37    0x0    000000
DDRB=128;  --> DDRB    0x37    0x0    000000

Also, if I hover the mouse on the little squares, their names range from Bit 2 (the rightmost) to Bit 7 (the leftmost). How does this map to the pins of the real device? and also Why are they named from 2 to 7 instead than from 0 to 5, as on the device (PB0-PB5)?.
I thought initially that the configuration fuses in the simulator are responsible for certain bits of DDRB not being programmable. For instance I know that RSTDISBL must be unprogrammed to enable PB5, and I guess the same is true for the corresponding DDR. But which column is PB5 on the I/O view?.
I also tried to set the fuses in C code:
FUSES =
{
    .low = 0x62,
    .high = 0x5f,
    .extended = 0xff
};

The setting 0x5f for the high fuse should mean that RSTDISBL is disabled, according to the online fuse calculator. However the behavior in I/O view is still the same.

A: The ATtiny85 has no pin PB6 and PB7 so you are trying to address hardware pins that simply aren't there. According to the datasheet (paragraph 10.4.2 - 10.4.4) these bits for DDRB, PINB and PORTB are always 0.

A:
In a way this is not entirely surprising, as the ATtiny85 has only 6 PB pins. But is this behavior expected?

According to the ATtiny85 datasheet

bits 7:6 of PORTB, DDRB and PINB registers are read only locations with an initial value of 0.
So essentially you are writing to a location that the manufacturer says it is read only in which case all bets are off regarding the expected behaviour. It may work fine or it may cause problems.

what are the little squares in the I/O view next to the value of DDRB saying?
  But which column is PB5 on the I/O view?.

Each square is one bit, starting from 0 (right-most side) to 7 (left-most side).
My version is slightly older (v6.x) and shown the bit numbers fine

I have added with red the bit representation of each box

Regarding the fuses, I don't think they have any effect on the simulation and you can't change them at runtime either.
Adding them in the code (I have never used that way) is just a way to tell the programmer to set them at a specific value during the device programming, it doesn't have an effect during the code execution.


text:
Q: Using a different controller for GET and POST in Laravel but using the same name I am writing route and controller rules for a web application. In a number of rules, a problem has emerged, which is that I need to match both GET and POST verbs, and send them to the controller, but different methods.
I considered using Route::controller('tracking', 'TrackingController') for this, but then it requires different names for each internal route, whereas I want to specify one name for both. Besides, I've read nothing but negativity regarding the usage, suggesting that it is not a good idea.
Here's what I have currently:
Route::match(['get', 'post'], '/tracking', [
    'as' => 'tracking',
    'uses' => 'TrackingController@index'
]);

While implementing this, I have discovered that I need to have two controller methods, index and track. How can I efficiently route GET to index and POST to track, while maintaining the same controller (TrackingController) and the same name (tracking)?
I considered using two separate routes, e.g. Route::get and Route::post, but that doesn't feel very eloquent.

A: you can use easily Route Controller,like this
Route::controller('tracking', 'TrackingController')

In here if you wanna use same method for both get and post,just use any prefix in method,like
//for both get and post
public function anyUrl();
//only get
public function getUrl();
//only post
public function postUrl();

Or use
Route::any('/url', function () {
return 'Hello World';
});


text:
Q: Remove enclosing html tags from selection in textarea I am working on a custom CMS and want to be able to select a section of HTML displayed for editing in a textarea and replace any enclosing tags with another tag. For instance, I may want to select a paragraph element and turn it into an h3 with one click, leaving any other tags untouched.
I have implemented rangyinputs to allow getSelection/replaceSelectedText operations on textareas, and so far I have this:
function add_html_tag(target_ID, replace_tag) {
  $(target_ID).focus();
  $(target_ID).replaceSelectedText('<' + replace_tag + '>' + $(target_ID).getSelection().text.replace(/(<([^>]+)>)/ig,"") + '</' + replace_tag + '>');
}

This works OK but it removes ALL tags from the target text, not just the enclosing ones so any other tags within the selected text would also be removed.
Any ideas, I think it will just involve changing the regex in the replace statement. Since the textarea contains just plain text I can't use jQuery methods such as unwrap. Obviously doing regex operations like this on HTML is error prone, but for now I will presume users select the text correctly!

A: this demo turns "A" tags into "LINK" tags; invalid, but shows the functionality you describe:
function add_html_tag(target_ID, replace_tag, new_tag_name) {
  var elm=$("#"+target_ID).focus()[0];
  elm.value=elm.value.replace(  new RegExp("<(\\\/?)"+replace_tag+"\\b", "gi"), "<$1"+new_tag_name);
}

add_html_tag(textAreaID, "a", "link");


text:
Q: Check if post of title already exists I'm writing a plugin that takes an xml feed and posts it into WordPress using wp-cron
Everything is working dandy, except it keeps adding the same posts over again.
So, I'm working on a system to check to see if a post of that title already exists.
I've written this, but its always returning 'already exists'
global $wpdb;
        $query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title = %s', $article->heading);
        $wpdb->query( $query );

        if ( $wpdb->num_rows ) {
            error_log('already exists');
        } else {
            wp_insert_post($post, $wp_error);
        }

I'm fairly new to working with the database side of WordPress and I saw the $wpdb when googling for help. Now, I haven't defined this anywhere but the place I was reading seemed to suggest it was built in.
All help appreciated!
Thanks

A: Yes $wpdb is built in and is loaded by the WordPress Core on every page load.
I don't see any critical problem with your code. I am going to suggest some improvements because I see some places where could go wrong, but mostly that should work. That makes me think that $article->heading is not matching up to the inserted post_title. So...
Try to normalize your title with sanitize_title_with_dashes which is how WordPress builds the post slug, and then check for that slug instead.
global $wpdb;
        $query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_name = %s', sanitize_title_with_dashes($article->heading));
        $cID = $wpdb->get_var( $query );

Now your query is looking for post_name, which is the slug or permalink tail, and I changed $wpdb->query to $wpdb->get_var since you are looking for a single variable, which we save to $cID.
Use a better check for your conditional.
if ( !empty($cID) ) {
However, this might not be the right approach at all. Look into the XML_RPC API mentioned by @kaiser. It has post insertion capabilities.

A: <?php post_exists( "post_name" ); ?>

https://developer.wordpress.org/reference/functions/post_exists/


text:
Q: Custom meta box data in rss feed Im using WP Alchemy to set up some custom meta boxes. Since these are being used for audio files, when I create a feed the data does not come in and i cannot create a podcast feed for them.

A: Ok I got it
// Add the audio link to the feeds so we can podcast
function feed_customMeta($content) {
global $post, $id, $radioMeta;

  if ( !is_feed() )
    return $content;

 $getRadioLink = 'get_the_value('radioLink').'">Download Audio';

  if( $getRadioLink)
    $content .= $getRadioLink;
    return $content;
}
add_filter('the_excerpt_rss', 'feed_customMeta');
add_filter('the_content_feed', 'feed_customMeta');


text:
Q: Why Drop down gets reset after post back? My requirement is to select a value from a drop down and fetch the corresponding three fields and drop down must have the selected value in it.
However my code it fetches the corresponding three fields and sets the drop down selected value to first value.
Please tel me how to solve this issue.
Below are my code at page load and corresponding methods:
public partial class RegisterWebPartUserControl : UserControl
{
string titleid;
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
string names = oSPWeb.CurrentUser.ToString();
TxtEmployeeName.Text = names.ToString();
SPList oSPListCalender = oSPWeb.Lists["Scheduled Courses"];
DataTable dataTable = oSPListCalender.Items.GetDataTable();
dataTable.TableName = "Table1";
ds.Tables.Add(dataTable);
ddlDrop.DataSource = ds.Tables["Table1"];
ddlDrop.DataTextField = "Title";
ddlDrop.DataValueField = "TitleID";
titleid = ddlDrop.SelectedValue;
ddlDrop.DataBind();
}
protected void ddlDrop_SelectedIndexChanged(object sender, EventArgs e)
{
FetchReadOnlyFields(titleid);
}
public void FetchReadOnlyFields(string titleID)
{
string oStartDate = null;
string oEndDate = null;
string oPrerequisite = null;
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
SPListItemCollection oItemCollection = oSPList.Items;
SPListItem ospListItem = oItemCollection.Add();
SPList oSPList1 = oSPWeb.Lists["Scheduled Courses"];
SPListItemCollection oItemCollectionCourse = oSPList1.Items;
SPFieldCalculated titleIDCourse = (SPFieldCalculated)oItemCollectionCourse.Fields["TitleID"];
SPField fieldStartDate = oItemCollectionCourse.Fields["Start Date"];
SPField fieldEndDate = oItemCollectionCourse.Fields["End Date"];
foreach (SPListItem ospListItemCourse in oItemCollectionCourse)
{
string value = titleIDCourse.GetFieldValueAsText(ospListItemCourse["TitleID"]);
if (titleID == value)
{
oPrerequisite = ospListItemCourse["Prerequisite"].ToString();
TxtPrerequisite1.Text = SPHttpUtility.ConvertSimpleHtmlToText(oPrerequisite, oPrerequisite.Length);
oStartDate = ospListItemCourse["Start Date"].ToString();
TxtStartDate.Text = oStartDate;
oEndDate = ospListItemCourse["End Date"].ToString();
TxtEndDate.Text = oEndDate;
break;
}
}
}
}

Hope to seek your help.
Thank you

A: This code
ddlDrop.DataBind();

Should be called only once. On the first load of the page.
Try
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){ // this is what has changed
DataSet ds = new DataSet();
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
string names = oSPWeb.CurrentUser.ToString();
TxtEmployeeName.Text = names.ToString();
SPList oSPListCalender = oSPWeb.Lists["Scheduled Courses"];
DataTable dataTable = oSPListCalender.Items.GetDataTable();
dataTable.TableName = "Table1";
ds.Tables.Add(dataTable);
ddlDrop.DataSource = ds.Tables["Table1"];
ddlDrop.DataTextField = "Title";
ddlDrop.DataValueField = "TitleID";

ddlDrop.DataBind();
}

titleid = ddlDrop.SelectedValue;
}


text:
Q: Pinned icons not showing original app's icon in Windows 7 My OS is Windows 7 Ultimate. After installing Paragon Partition Manager 10 Personal, 3 of the 6 application icons in the taskbar are not rendering properly. Generic file icons is being rendered there instead of original app's icon. Googleing about the problem shows that this is a known issue and one solution is to change the size of the taskbar icons to small, then revert back to large (I use large by default). But this solution doesn't work for my case. I tried restarting the PC which doesn't work either.
Is there any other solution for the problem? Thanks.

A: Right-click the taskbar shortcut while holding the Shift key and select Properties.
Change the icon as you would for any other desktop shortcut.
You need to reboot for the change to take effect.
Or alternatively to booting, just kill explorer.exe from the Task Manager, then re-run it from the menu File -> New task.

A: In my case deleting the icon cache as described in this solved the problem.


text:
Q: Why is plotly express so much more performant than plotly graph_objects? I'm visualizing a scatterplots with between 400K and 2.5M points.  I expectected to need to downsample before visualizing but to see just how much I ran a pilot test with a 400k dataset in plotly express, and the plot popped up quickly, beautifully, and responsively.
In order to make the interractive figure I really need to use plotly.graph_objects, as I need multiple traces with different colorscales, so I made basically the same graph with graph_objects and it wasn't just slower, it crashed my computer.
I'd really like to downsample as little as possible and I'm surprised by the sheer performance difference between these two approaches so I guess that boils down to my question:
Why is there such a performance difference and is it possible to change layout/figure/whatever parameters in graph_objects so to close the gap?
Here is a snippet to show what I mean by basically the same graph:
graph_objects
        fig = go.Figure()
        fig.add_trace(go.Scatter(x = x_values, y = y_values, opacity = opacity, marker = {
                'size': size,
                'color': community,
                'colorscale': colorscale
            }))

express
        pacmap_map = px.scatter(x = x_values, y = y_values, color_continuous_scale=colorscale,  opacity = opacity, color = community)
        pacmap_map.update_traces(marker = {
                'size': size
            })

I would have expected performance to either be identical or at least in the same ballpark, but express works like a dream and graph_objects crashes the jupyter kernel and whatever IDE it is running from, so a large difference.

A: Running the following simple example:
import numpy as np
import plotly.graph_objects as go
import plotly.express as px

x = np.linspace(-2, 2, 100000)
y = np.cos(x)

fig = go.Figure(data=[go.Scatter(x=x, y=y)])
fig2 = px.scatter(x=x, y=y)

type(fig.data[0]), type(fig2.data[0])
# out: (plotly.graph_objs._scatter.Scatter, plotly.graph_objs._scattergl.Scattergl)

As you can see, plotly express appears to switch to Scattergl when the number of points is higher than some threshold. Scattergl renders on an html5 canvas, hence it uses the GPU (hence efficiency). Whereas Scatter creates svg objects that get inserted in the current document, consuming muuuuuch more memory.


text:
Q: Frankly, do you prefer Cowboy coding? Most programmers defending methodologies politically correct like Agile, Waterfall, RUP, etc. Some of them follow the methodology but not all of them. Frankly, if you can choose the methodology, you certainly would go to mainstream "correct" methodologies or you would prefer the "easier" methodology like cowboy programming? Why?
I know it depends. Please, explain when you would use one or another. Please, say what advantages do you see on Cowboy coding.
See about Cowboy coding on Wikipedia

A: It depends on circumstances. For example, after some disastrous trading scandals, several electronic stock exchanges insisted that auto-trading flags were added to all trades. And this had to be for all trading software inside  a week. I mean it had to be done - if the flag wasn't there you couldn't trade. In circumstances like that, all good practices go by the board - you just have to go (as we used to say) "hacky, hacky, hacky". And in those circumstances, writing code fast and accurately is key. Particularly as there were no test systems available.

A: Depends on the problem. A good senior developer will write very compact, simple, and robust code that's very stable and uses all best practices without churning through pages of documentation and tons of different patterns and paradigms. But he will also know when he can afford to do such things.
I would be shocked if he would take a new problem and start to design an application that requires man-months from scratch. But if it's a plugin, simple tool you can write in 2 hours, a function that does some conversion and is not intended for a reuse, design and patterns are actually only good for wasting the time.
Also, I guess large part of the design was already processed in a background thread somewhere inside the senior developers head.
You have to start worrying when the senior developer starts churning classes of a complex system, or new applications from scratch, and without planning step.

A: Yes.
I also prefer leaving my socks on the floor where I took them off, my desk covered in printouts and old snack wrappers, my sink full of dirty dishes, and my bed unmade.
I don't consider a vacation planned in advance to be a proper vacation, a meal eaten with a mind toward nutrition proper food, or staying on known trails proper hiking.
I like to have fun, be surprised, learn new things, make mistakes, and never be quite sure if I'm going to make it back. And sometimes, that attitude is exactly what's required to get a project off the ground...
...but most of the time, it's just irresponsible. When the dance ends, the piper will be paid... Forget this at your peril.

A: This kind of person is called a hacker, and it's usually not a complimentary term from the more professional among us.
As you've noticed, the time saved in design, organisation and control is lost in debugging. And often in finding which release of code was the one that was actually shipped. If you can find it at all!
I find this kind of person is too wrapped up in themselves, think they're too good to work with the 'limitations' others have to suffer and so don't bother with them, and that loses even more time as the rest of the team has to clean up after them. They are also not too involved in the bug-fixing process (that's a maintenance developer's task, well beneath the 'l33t coder's skills and talent).
So, it might be a common approach elsewhere, but at my place (and I'm a senior coder who has tendencies to this approach, ahem) we do not suffer it. It's not that we demand a ton of processes and procedures, but we do insist on a minimal amount of organisation, source code control (which to be honest is bloody east and damn useful!)
Kent Beck et al, are all professionals who saw the old process-laden ways were bad in themselves, so they created new methodologies to organise coding while still keeping it more craft-oriented, and then told everyone else about it - by publishing books (how else did you do it back then before the Internet?)
You sound like you have it right - do not accept poor practice just because someone else can't hack it. Your team lead or manager should be coming down hard on this 'rockstar', but if they're not.. well, that still doesn't prevent you from doing the right thing. Just do not accept shoddy practice from her, if she screws up (and she will!) then let her clean it up. You stick to good practices (and you know what they are) without letting them take over to the detriment of your coding productivity, and you'll be good for the future.
Here's an essay from a truly insightful writer. It doesn't fix your problem, but it does give you a few insights into why it's like it is and maybe a few tips to deal with it professionally.

A: From my experience, cow boy coding WITH source control is the best and most bug free way to develop large software systems.

A: I think one of the commentators had it right - its all about the results.
If the person can produce a good product - something that does what its supposed to do, and is maintainable and reliable - then what does it matter if formal methodologies or processes are followed?  Processes are great to ensure a floor in quality, but if someone's working above that floor already, then the processes add nothing into the equation.  Too many developers these days, imo, seem to think the point of programming is to adhere to processes, as opposed to producing a good product.

A: You might find some insight in my answer to Frankly, do you prefer cowboy coding?  The trouble is, "cowboy coding" means different things to different people, and it's not immediately obvious, to the untrained eye, which version you're seeing.
When somebody can look at a problem and immediately start belting out code, quickly and accurately, that may be the sign of a master engineer who has seen it all a thousand times before and already knows the best way to solve the problem.
Or, it may be the sign of a rank amateur.
I will tell you one thing: Refusing to use version control or write tests because they are too "academic" is definitively not a "senior" or even remotely professional approach.  You will never, ever see this kind of thing being done at a major software shop such as Microsoft or Google, and will probably not see it in most startups or reasonably mature enterprise teams either.
The risks are just too great.  What if your PC dies overnight?  Bye bye 3 years of productivity.  Okay, so you make backups; then what happens when you make a major change, realize that it was completely wrong, and have to revert it?  This happens even to the most experienced and talented of developers because the requirements are wrong.  If you're not running any kind of version control, you're just going to be spinning your wheels in the mud.  I've been there, once, and would never go back.
There's just no excuse - it takes 10 minutes to set up a repository and 10 seconds to do a commit.  It makes up maybe 1% of your total development time.  Tests, if you're in a hurry, can easily be whittled down to 20-30 minutes a day and still be reasonably useful.
I'm no fan of Agile (note the capital A) methodologies but sometimes you really do need to just roll up your sleeves and start writing the damn code.  I've seen people and teams with "analysis paralysis" and productivity really does take a visible hit.  But dismissal of the basic tools of our trade such as revision control and tests is really the clincher for me; this person does not belong in a senior position.

A: This really comes down to the question of whether or not you can implement things correctly without a tight structure in place and lots of time eaten up in planning.
I'm going to throw something out here on this one that may be really unpopular: customers generally want things handled in a cowboy fashion.
That is, they want to request something get done, and have someone jump on it, execute it, and get it out there. No project management, meetings, conference calls, or forms. Just do it. I've never had a customer say "hey, this was done a little too quickly for our tastes, we'd appreciate it if you would put a little waterfall or something in there next time".
Team methodologies and structure are designed to level the playing field of a project and get varying levels of developers on the same page, working for the same goals, in the same ways.
The successful "cowboys" that I have worked with are able to:

*

*Identify the simplest way to implement something quickly

*Know at what point it will break

*Write clean, readable, and straightforward code

*Predict how the users will use it, abuse it, and break it

*Scale it / abstract it in the right places, and not go architecture astronaut on it

*Know where and how to handle edge cases and exceptions

People like this produce truly great results with very little management and structure overhead, but they are rare.

A: You're exactly correct.  This "cowboy programming" approach may get the first revision of the code out faster, but that time savings will be more than lost thanks to:

*

*Additional bugs

*Additional time needed to find the bugs you would would have had anyway

*Having to reverse engineer your code to remember what you did when you need to make a change in six months

*Extra time spent training additional developers that need to work on your code

*Not having a log of revisions to look back to when you make a change that breaks something

*Not having modules you can easily reuse in later projects

*And on and on and on

Like Neil Butterworth mentioned in his answer, sometimes you gotta do what you gotta do. As a general practice though, no, banging out code as fast as possible with no time spent on source code control, patterns, documentation, etc. is a very bad habit to get in to.
Good for you for analyzing your coworkers and considering whether their habits are beneficial or harmful instead of blindly doing as they do.

A: The only important fact is the long term product results of the team.
There is a claim that a team including one great programmer (or more) will produce better results than a team with an even larger number of average programmers coding at an average rate.
If the cowboy produces stuff that the regular programmers don't (for a given deadline or spec), and the team with the cowboy even has to spend a few man weeks/months cleaning up the cowboy's mess, they might still end up with the better result sooner.
If the team with the cowboy can't clean up (document, debug, integrate, maintain) the mess even after many man months/year's, then whatever advance the cowboy created did not give the team a long run advantage.
Decide which, and optimize the team's roster.
Not every programmer works (or should work) the same way, as long as the end result is good.

A: I think almost every experienced programmer has gone through three stages and some go through four:

*

*Cowboy coders or nuggets know little to nothing about design and view it as an unnecessary formality.  If working on small projects for non-technical stakeholders, this attitude may serve them well for a while; it Gets Things Done, it impresses the boss, makes the programmer feel good about himself and confirms the idea that he knows what he's doing (even though he doesn't).

*Architecture Astronauts have witnessed the failures of their first ball-of-yarn projects to adapt to changing circumstances.  Everything must be rewritten and to prevent the need for another rewrite in the future, they create inner platforms, and end up spending 4 hours a day on support because nobody else understands how to use them properly.

*Quasi-engineers often mistake themselves for actual, trained engineers because they are genuinely competent and understand some engineering principles.  They're aware of the underlying engineering and business concepts: Risk, ROI, UX, performance, maintainability, and so on.  These people see design and documentation as a continuum and are usually able to adapt the level of architecture/design to the project requirements.
At this point, many fall in love with methodologies, whether they be Agile, Waterfall, RUP, etc.  They start believing in the absolute infallibility and even necessity of these methodologies without realizing that in the actual software engineering field, they're merely tools, not religions.  And unfortunately, it prevents them from ever getting to the final stage, which is:

*Duct tape programmers AKA gurus or highly-paid consultants know what architecture and design they're going to use within five minutes after hearing the project requirements.  All of the architecture and design work is still happening, but it's on an intuitive level and happening so fast that an untrained observer would mistake it for cowboy coding - and many do.
Generally these people are all about creating a product that's "good enough" and so their works may be a little under-engineered but they are miles away from the spaghetti code produced by cowboy coders.  Nuggets cannot even identify these people when they're told about them, because to them, everything that is happening in the background just doesn't exist.
Some of you will probably be thinking to yourselves at this point that I haven't answered the question.  That's because the question itself is flawed.  Cowboy coding isn't a choice, it's a skill level, and you can't choose to be a cowboy coder any more than you can choose to be illiterate.
If you are a cowboy coder, then you know no other way.
If you've become an architecture astronaut, you are physically and psychologically incapable of producing software with no design.
If you are a quasi-engineer (or a professional engineer), then completing a project with little or no up-front design effort is a conscious choice (usually due to absurd deadlines) that has to be weighed against the obvious risks, and undertaken only after the stakeholders have agreed to them (usually in writing).
And if you are a duct-tape programmer, then there is never any reason to "cowboy code" because you can build a quality product just as quickly.
Nobody "prefers" cowboy coding over other methodologies because it isn't a methodology.  It's the software development equivalent of mashing buttons in a video game.  It's OK for the beginner levels but anybody who's moved past that stage simply won't do it.  They might do something that looks similar but it will not be the same thing.

A: When I think "traditional" methodologies, I think "management doesn't know how to understand developers, so instead of coming into the developers world and understanding enough to know what's going on, they make the developers come into their world".
Fundamentally, when I think of "Agile", I think "you do what you need to do to minimize the inefficiencies introduced by multiple people working together." So I'm firmly in the camp that "there's no such thing as THE Agile Methodology, just a set of values and principles".
In other words, there are things you need to do on a very large project, and there are things you need to do on small projects, and there are things that you do on both.
For example, I would not have more than the simplest of backlogs for a project I'm working on myself... It would just be a to-do list. If there are two of us, I'd probably have that list shared, but in a very simple format (probably just a note stored in our code repository). Once I have 3 or 4, I'm looking for some sort of work item system.

A: Yes, but you have to recognize when NOT to do it.
On anything small you are probably fine, but if you have something complex, dangerous, constrained, etc you need to be able to recognize when a proper design is worth the extra time.
I also think you should definitely think through Aaronaught's answer.  Cowboy means different things to different people.

A: It completely depends on whether I'm working solo, or in a team.
If I work in a team, some conventions and agreements are required - everyone in the team must follow some commonly agreed standard to work towards the common goal so that their efforts are compatible.
But if I work alone, then of course I want to be a cowboy. All great creations in the world have been invented by a single mind, or at most two, working cowboy-style. Just to name a few:

*

*Classical mechanics? Cowboy Isaac Newton, later additions from Leibniz, Lagrange, Hamilton.

*Airplane? Cowboys Wright.

*Theory of relativity? Cowboy Albert Einstein.

*Fundamental science of computers? Cowboy Alan Turing.

*Transistor? Cowboys Walter Brattain and John Bardeen.

Teams are good at making incremental improvements and putting together new systems based on proven recipes fairly quickly (provided that they're being led well), but it's rare to hear about an actual invention made by a team. Team work and the methods it requires have their virtues, but so does cowboy coding.

A: EDIT: For future reference, my answer is for another question, which has been merged into this one. It's quite out of place here, but that was not my call.

She's just lazy, arrogant, ignorant and extremely selfish. This behavior is reckless.
I mean, it's not that she uses an unconventional or maybe outdated methodology. She just consciously uses none. No standards. No quality assurance. No whatsoever. Where does she expect software quality to come from? Trees?
It is funny she actually denies the experience of the people you quote, when she quite obviously lacks it. Providing verifiable and relevant arguments to question their claims is valid. But just trying to discredit them by denying their experience is not.
But, the main point is: How much time does version control take?
If she cannot be convinced to invest the 5 seconds every now and then, you should take it up to her boss. Version control is not optional. Full stop.
And once you have her using version control, you can easily track which bugs she introduced. And let her fix them. It's her mess, why should you clean it up? If she thinks her approach is better, then let her do it - all the way.
Assuming she actually can do it (within reasonable time), you still have a problem: teamwork with her is close to impossible. And this is something you will have to solve by either convincing her (which sounds unlikely), making her leave (for the sake of your company) or leaving (for the sake of your sanity).
But her failure in the first place is far more likely and should definitely prove your point. And then she'll start adhering to best practices as many people with a lot of experience do.

A: Only when prototyping of very simple features.
Then once done and considered the right way, I ditch the code and get serious.

A: I've done it once on a real project (at the time we called it Samurai Programming, after the Samurai Tailor series of sketches on Saturday Night Live), and much to my amazement, it worked out well. Of course, what I started with was garbage, so there was little risk of making it worse.
However, I am a "neat" at heart and dislike the shoot-from-the-hip style of development.
On the other hand, heavily process-laden modus operandi is not to my taste either. I just like to plan before I act.
All in all, I feel that the amount of formal process that is appropriate depends heavily on the magnitude (size of the code, duration of the project, number of developers, kinds of requirements, etc.) of the project. I want rigor and strict criteria to be imposed on people developing the software for avionics or biomedical equipment, e.g. For games, e.g., there's far less down-side to any failures, so the cost and burden of rigorous and methodical development practices is not really justified.

A: It depends (heavily) on the size of the project. On one hand, to get a decent result you need to have a design. On the other hand, if the project is small enough that you can conceptualize the entire design (are most of it anyway) without writing it down, drawing diagrams, etc., then you're probably just as well off without that extra work of documenting everything you do.
Almost everybody has heard enough horror stories to realize that trying to jump in without a clear idea of what you're doing and where things are going is a recipe for disaster. What's far more rarely pointed out is that the opposite can be equally disastrous. Just for example, most of us routinely write small tools in the process of programming. Writing a complete specification, tests, documentation often just isn't worthwhile. There's a threshold below which productization isn't worthwhile -- people often dislike reinventing the wheel, but in some cases it's easier to reinvent than avoid it.
In cases like this, what's often is worthwhile is productizing a library to make tasks like this easy. With that, the front-end code often becomes so trivial that writing (or modifying) code to do what you want becomes easier than sorting out how to get a complete program to do what you want. Consider, for exmaple, gnu indent with its 50+ different flags, many of which interact in various subtle ways, so about the only reasonable choices are 1) don't use it at all, or 2) decide to like what it gives you instead of trying to get what you originally wanted.

A: There appear to be two camps - those who favour results, and those who favour principles. I fall into the latter.
I am a mediocre but arguably conscientious programmer - my main concern when coding, beyond getting the job done, is that I am helping whoever uses my code to get THEIR job done. I can't say as that I've always achieved that - but that's what I aim to do.
Sure, you may have a hotrod on your team - but what happens when they take a couple of weeks leave and you're asked to debug their work, or add stuff to it? Ultimately, cowboy programmers are not team players. They may make great code, but if the team depends on them - then it's dangerous.

A: No, never.
I always do requirements analysis, think about architecture, design the details, and then code. Even if I work solo at home for a personal project.
And I would instantly fire a developer in my team if he/she were working in a cowboy style. We are engineers and have a responsibility with the customer and the users.

A: I don't think cowboy coding is a senior approach.
As others have said, there's a real danger in discarding version control. Skipping documentation and analysis could also mean risking delivery of something the user doesn't want. Just my opinion, but I don't think you go from "coder to developer" if all you do is cowboy code.
However, yes, there are exceptions like the one Neil Butterworth mentions. And in these situations, I'd rather have an experienced senior developer be the one that has to do the cowboy coding.

A: I have the feeling that your distaste for her style is causing you to slightly misrepresent it. You say the cowboy approach is paid in debugging - is this what is already happening, or is that your assumption of how it will play out?
Fair disclosure - I am a senior developer myself, and I often forgo a formal process for design and going on experience. Not having a formal process for someone who is very experienced in the problem domain is quite common. If you have solved a problem dozens of time, you don't need a formal process to formulate a similar solution again.
A formal process deals with the design of code - I don't see why more bugs should be introduced because a formal process is missing. The only big problem I read in your account is that revision control is not being used - which is not only selfish, but downright reckless on the developer's behalf. Is she in fact not committing at all, or just not committing in a pattern that is to your liking?
Not having a formal approach to design is not 'cowboy coding' in my book (not using revision control is though). Experience should be used for exactly that - to reduce time needed to come up with a 'good enough' solution. Remember, you have to solve the problems you have currently and make the code easy to change, not design for future scenarios that might never happen. With experience you get a good feel for how to do that very fast.

A: I find your post interesting. I've often shared views with your subject, and her feeling is that over-formalized methods are stifling. As someone else noted, if she's a genius and can track a multitude of mental notes at the same time without forgetting or getting confused, then it's quite possible to maintain a monolithic chunk of convoluted code and get it to do amazing things with completely obscure changes. There's a certain mental happiness that comes to the brains of people that can do that - it's like being a God of a little universe in your mind.
However, smart employers have learned the hard way that nobody but the original author can ever do anything worthwhile to that code. If the programmer moves on, they end up wasting a lot of money figuring out that the only option is to re-write (I used to think that meant total loss, but I realize these days that you don't destroy the intrinsic result of iterative development at the level of external functionality).
Personally, I woulnd't mind having someone like that on the team, because in a crunch, they might do something that nobody else thinks of.
On the other hand, be your own person and decide for yourself what the answer to your question is, because the only thing that's for sure is that nobody has it figured out when it comes to building software.  It's one of the things that makes it an interesting field...

A: Cowboy programming is a rather sure way of creating a big ball of mud. Which, as unpleasant as it sounds, tends to deliver...

A: I think newer programmers tend to do some cowboy coding things when taking on aspects of a project / scopes that they may not have a lot of experience with or when they are trying to "just get things done" due to pressure from a boss, etc. I know I have definitely gone down this path a few times because I was lacking in knowledge of the proper pattern to use and just "hacked my way through it".
The difference between me and the person you are complaining about is that I usually soon after realize that I could have done it better and made it more maintainable and it usually spurs me to learn more and improve my skills (by reading books / articles on the subject). When I go back to debug some of these hacked solutions I usually find it to be a pain and it contributes more to my wanting to learn how to do it the "right way". I think this person you are describing is basically stuck at an infantile level of self reflection and it letting their own ego get in the way of actually improving their skills as a software developer, doesn't seem like someone I would want to work with.


text:
Q: Get unique events from Event Log and their count I have a working script that is able to pull a report of Windows Application, Security, Setup and System logs that displays only the critical and error events in the past 30 days. However, I would also really like the script to count the number of times each reported critical or error event occurred in the past 30 days. Here's the working command:
Get-EventLog Application -ComputerName $server -After $starttime |
    ? { $_.entryType -Match "Error" -and "Critical" } |
    Sort-Object EventID -Unique |
    Select-Object TimeGenerated,EventID,Source,Message |
    ft -AutoSize -Wrap |
    Out-File $file -Append

And here is an example of the output in the text file:
TimeGenerated       EventID Source                                      Message
-------------       ------- ------                                      -------
7/8/2016 1:23:20 PM       0 SQL Server Report Service                   Service cannot be started. Microsoft.ReportingS
                                                                    ervices.Diagnostics.Utilities.InternalCatalogEx
                                                                    ception: An internal error occurred on the repo
                                                                    rt server. See the error log for more details.
                                                                       at Microsoft.ReportingServices.Library.Nativ
                                                                    e.GetSid(String name, Int32& length)
                                                                       at Microsoft.ReportingServices.Library.Nativ
                                                                    e.NameToSid(String name)
                                                                       at Microsoft.ReportingServices.Library.Servi
                                                                    ceAppDomainController.StartRPCServer(Boolean fi
                                                                    rstTime)
                                                                       at Microsoft.ReportingServices.Library.Servi
                                                                    ceAppDomainController.Start(Boolean firstTime)
                                                                       at Microsoft.ReportingServices.NTService.Rep
                                                                    ortService.OnStart(String[] args)
                                                                       at System.ServiceProcess.ServiceBase.Service
                                                                    QueuedMainCallback(Object state)
7/8/2016 1:23:20 PM     121 Report Server Windows Service (MSSQLSERVER) The Remote Procedure Call (RPC) service failed
                                                                    to start.

It would be great to have another column in the results that displays the occurrences of each EventID in the specified time period.

A: You could do it like so (line 3 & 4 are new and Count in Select-Object)
Technically you could also remove the -Unique from Sort-Object as after grouping them and passing through only the first item of the group  is more or less the same.
Get-EventLog Application -ComputerName $server -After $starttime |
    ? { $_.entryType -Match "Error" -and "Critical" } |
    Group-Object -Property EventID |
    % { $_.Group[0] | Add-Member -PassThru -NotePropertyName Count -NotePropertyValue $_.Count } |
    Sort-Object EventID -Unique |
    Select-Object Count, TimeGenerated, EventID, Source, Message |
    ft -AutoSize -Wrap |
    Out-File $file -Append


text:
Q: Recursive reference to a list within itself So I came across something very weird in python. I tried adding a reference to the list to itself. The code might help demonstrate what I am saying better than I can express. I am using IDLE editor(interactive mode).
>>>l=[1,2,3]
>>>l.append(l)
>>>print(l)
[1,2,3,[...]]
>>>del l[:-1]
>>>print(l)
[[...]]

So far the output is as expected. But when I do this.
y=l[:]
print(y)

To me it seems that the output should be
[[...]]

But it is
[[[...]]]

Apparently instead of creating a copy of the list, it puts a reference to the list in y.
y[0] is l returns True. I can't seem to find a good explanation for this. Any ideas?

A: The difference is only in the way the list is displayed. I.e. the value of y is exactly what you'd expect.
The difference in the way the lists are displayed results from the fact that, unlike l, y is not a self-referencing list:
l[0] is l
=> True
y[0] is y
=> False

y is not self-referencing, because y does not reference y. It references l, which is self-referencing.
Therefor, the logic which translates the list to a string detects the potential infinite-recursion one level deeper when working on y, than on l.

A: This is perfectly expected. When Python prints recursive lists, it checks that the list it is printing hasn't yet been encountered and if it has prints [...]. An important point to understand is that it doesn't test for equality (as in ==) but for identity (as in is). Therefore,

*

*when you print l = [l]. You have l[0] is l returns True and therefore it prints [[...]].

*now y = l[:] makes a copy of l and therefore y is l returns False. So here is what happens. It starts printing y so it prints [ ??? ] where ??? is replaced by the printing of y[0]. Now y[0] is l and is not y. So it prints [[???]] with ??? replaced by y[0][0]. Now y[0][0] is l which has already been encountered. So it prints [...] for it giving finally [[[...]]].

A: You need to have a full copy of the objects.  You need to use copy.deepcopy and you would see the expected results.
>>> from copy import deepcopy
>>> l=[1,2,3]
>>> l.append(l)
>>> print(l)
[1, 2, 3, [...]]
>>> del l[:-1]
>>> print(l)
[[...]]
>>> y=deepcopy(l)
>>> print(y)
[[...]]
>>> y[0] is l
False
>>>

When you use the slice notation to copy the list, the inner references are retained which cause the behavior that you observe.

A: Slicing generates list of items. There is only one item - list "l". So, we have new list of one element - list "l".


text:
Q: Is there any analytical solution of this system of two linear inhomogeneous first-order PDE? So, I have a system of linear inhomogeneous PDE for a function $u(\rho, z)$:
$$u_{,\rho} = \rho \phi_{,z}\\ u_{,z} = -\rho \phi_{,\rho}$$ with $\phi(\rho, z)$ being an axially symmetric solution of Laplace equation in cylindrical polar coordinates: $\phi_{,\rho\rho}+\frac{1}{\rho}\phi_{,\rho}+\phi_{,zz} = 0$.
My question is whether there is any procedure/trick to obtain a solution of this problem analytically.
For example, I've found out that it is possible to solve such an equation without any assumptions about $\phi(\rho, z)$: $$u_{,\rho}\phi_{,z}-u_{,z}\phi_{,\rho} = 0$$ Indeed, $u = Ф(\phi(\rho, z))$
I have tried reducing my problem to a single equation $u_{,\rho}\phi_{,\rho}+u_{,z}\phi_{,z} = 0$, but, unfortunately, do not see any sign of success in such a way. Method of characteristics won't work for general enough $\phi(\rho, z)$.
I will appreciate any kind of help or advice.


text: Q: Visual Studio Interdev 6.0 Installation I have been tasked with putting together a development server and client (Windows 10), using Microsoft Visual Studio 6.0 with Visual Interdev, so that a team of developers can debug a very large ASP Classic website.  I have studied up and found that Visual Studio 6.0 can be installed on Windows 10, so that takes care of the client side, but I am wondering what version of Windows Server I should use for the development server?  I have access to 2003, 2012 R2, 2016, and 2019 versions.  The original OS used back in the day appears to have been Windows Server NT.


text:
Q: Mouse pick point snap to isnappingfeedback location I have created one BaseTool for placing point on polygon feature. mousemove event showing mouse move time vertex & edges & endPoints but picked point snapped at vertex.
 public override void OnMouseMove(int Button, int Shift, int X, int Y)
        {
            IMxDocument pMxdoc = m_application.Document as IMxDocument;
            IMap pMap = pMxdoc.FocusMap;
            pPosition = pMxdoc.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
            if (pPosition != null)
            {

                ISnappingResult snapResult = null;
                //Try to snap the current position
                snapResult = pSnapper.Snap(pPosition);
                pSnappingFeedback.Update(snapResult, 0);
                ISnapAgent agent = pSnappingEnv as ISnapAgent;
                if (snapResult != null)
                {
                    pPosition = snapResult.Location;
                }
                else
                {
                    IPoint point = pMxdoc.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
                    var activeView = pMxdoc.ActiveView;
                    point = pPosition;
                    var Chamged = psnapEnv.SnapPoint(point);
                }
            }
            // TODO:  Add Tool1.OnMouseMove implementation
        }

 public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            IMxDocument pMxdoc = m_application.Document as IMxDocument;
            IMap pMap = pMxdoc.FocusMap;
            ESRI.ArcGIS.Carto.IActiveView pview = pMxdoc.FocusMap as IActiveView;
            pMap.ClearSelection();
            pPosition = pMxdoc.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
            if (pPosition != null)
            {
                for (int i = 0; i < pMap.LayerCount; i++)
                {
                    ILayer pLayer = pMap.Layer[i];
                    IFeatureLayer pFlayer = pLayer as IFeatureLayer;
                    IFeatureClass pFclass = pFlayer.FeatureClass;
                    if (pLayer.Name == "Edit Comment")
                    {
                        ESRI.ArcGIS.Geometry.Point pntclass = pMxdoc.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y)as ESRI.ArcGIS.Geometry.Point;
                        CreateFeature(pFclass, pPosition, pFlayer);
                    }
                }
            }
            // TODO:  Add Tool1.OnMouseDown implementation
        }


text:
Q: MINIFS using OR function I'm trying to find the minimum date in column B if any cell in columns E, F, or G contains the word banana.
Give the minimum date in column B
IF: column E contains "banana"
OR IF: column F contains "banana"
OR IF: column G contains "banana"
I'm not quite sure how to nest these statements or if an array formula is needed. I tried a variety of nested MAX(IF(OR formulas but kept getting a parse error. Also tried an array but also got a parse error. Appreciate help trying to understand how to get this formula.

A: Also
=min(filter(B:B,(D:D="Banana")+(E:E="Banana")+(F:F="Banana")))

(you can only get an AND condition out of MINIFS - see this question for how to get an OR condition generally)
Here is a version that finds "Banana split" etc.
=min(filter(B:B,isnumber(search("Banana",D:D))
               +isnumber(search("Banana",E:E))
               +isnumber(search("Banana",F:F))))

A: you can try something like:
=MINIFS(B1:B, E1:E, "banana")
=MINIFS(B1:B, F1:F, "banana")
=MINIFS(B1:B, G1:G, "banana")
and then:
=MIN(I1:K1)
https://docs.google.com/spreadsheets/d/


text:
Q: how to append a xml file in c#? i am adding tracing for audit purposes of a simple process i have built as an .exe and set in the scheduler to run every 10 minutes. i want to have the application output the results into an xml file.
if the file exists then open and append data to it, if it does not exist i want to create a new xml file that will be persisted and used on next run.
here is my code now, what do i need to add, how do i open the xml file (on c:/file.xml) and use it to append nodes to?
static void Main(string[] args)
{
    XmlDocument doc = new XmlDocument();

    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
    doc.AppendChild(dec);// Create the root element

    XmlElement root = doc.CreateElement("STATS");
    doc.AppendChild(root);

    XmlElement urlNode = doc.CreateElement("keepalive");
    urlNode.SetAttribute("runTime", DateTime.Now.ToString());

    try
    {
        WebProxy wp = new WebProxy("http://proxy.ml.com:8083/");
        WebClient w = new WebClient();
        w.Proxy = wp;

        if (w.DownloadString("http://wwww.example.com") != "")
            urlNode.SetAttribute("result", "UP");
        else
            urlNode.SetAttribute("result", "DOWN");
    }
    catch
    {
        urlNode.SetAttribute("result", "DOWN");
    }
    finally
    {
        root.AppendChild(urlNode);
        doc.Save("c:/keepAlive.xml");
    }
}

A: You can't append an XML file - you'll have to load the file in memory , modify/add/etc, and then write it to disk.
EDIT :
Well, for loading a file you would use :
XmlDocument xmlDoc= new XmlDocument(); // create an xml document object.
if(System.IO.File.Exists("yourXMLFile.xml")
    xmlDoc.Load("yourXMLFile.xml");// load from file
else{
   // create the structure of your xml document
   XmlElement root = xmlDoc.CreateElement("STATS");
   xmlDoc.AppendChild(root);
}

and then start adding the keepalive stuff.
I would actually go a bit further and not mess around with xml. I'd create a class that contains everything I need and just serialize and deserialize it.
Like this:
[XmlRoot]
public class Stats{
  public Stats(){}
  public IList<StatsItem> Items{get;set;}
}

public class StatsItem{
  public StatsItem(){}

  public string UrlName{get;set;}
  public DateTime Date{get;set;}
}

now just serialize this, and you have your xml document. When the time comes, deserialize it, add stuff to the Items list and serialize and save it to disk again.
There are lots of resources on google , so just search a bit for those.

A: using System;
using System.Xml.Linq;
using System.Xml.XPath;

...

public void Append(){
    XDocument xmldoc = XDocument.Load(@"yourXMLFile.xml"));
    XElement parentXElement = xmldoc.XPathSelectElement("yourRoot");
    XElement newXElement = new XElement("test", "abc");

    //append element
    parentXElement.Add(newXElement);

    xmldoc.Save(@"yourXMLFile.xml"));
  }


text:
Q: check_snmp_mem.pl Icinga2 configuration broken I can successfully run
check_snmp_mem.pl -v -H kvm.lala.bo -l bravo -x th3r4m1N+ -X j4bAdeHu5 -w 50,70 -c 80,90

but configuring "snmp-memory" check in Icinga2 is not working.
Here's what I have in the config file for kvm.lala.by:

check_command = "snmp-memory"
host_name  = "kvm.lala.bo"
vars.snmp_v3 = "true"
vars.snmp_warn = "50,70"
vars.snmp_crit = "80,90"
vars.snmp_perf = "true"
vars.snmp_login = "bravo"
vars.snmp_password = "th3r4m1N+
vars.snmp_v3_use_privpass = "true"
vars.snmp_privpass = "j4bAdeHu5"

Icingaweb2 keeps printing

Can't mix snmp v1, 2c, 3 protocols! Usage:
  /usr/lib64/nagios/plugins/check_snmp_mem.pl [-v] -H  -C
   [-2]

A: Not using the plugin, but I guess the problem is snmp_community having a default value. Please try setting it to false.