text:
Q: How can I find the real user JID of user in MUC? When I join in a room XMPP xmpp, usually the other user see my JID as myconference@conference.localhost/myname instead of myname@localhost.
Pidgin is able to recover also my real JID when I talk with some of my friends (myname@localhost).
How is it possible? What kind of request should I make to the server?
This is important for me, because when I start talking with someone, I don't want to open two tabs, only because my client believes that my friend that I can see both in my roster and in the group roster, isn't the same guy.

A: See XEP-0045, section 7.2.4.  In a non-anonymous room, the server will send all participants' jids in their presence stanzas:
<presence
    from='coven@chat.shakespeare.lit/thirdwitch'
    id='17232D15-134F-43C8-9A29-61C20A64B236'
    to='crone1@shakespeare.lit/desktop'>
  <x xmlns='http://jabber.org/protocol/muc#user'>
    <item affiliation='none'
          jid='hag66@shakespeare.lit/pda'
          role='participant'/>
  </x>
</presence>


text:
Q: Give single value to scanf that require two behaive strange #include<stdio.h>
int main()
{
  int x,y;
  printf("please input 2 numbers:\n");
  scanf("%d,%d",&x,&y);
  printf("Now the value for x is %d, and value for y is %d",x,y);
  return 1;
}

what I input two numbers and seperated them by , then things works as expected.
But if I give one number 2345, then a strange result occured:
Now the value for x is 3456, and value for y is 32767
I can't figure out why it is.

A: When you call scanf(), you must check the return value of that function to see whether it succeeded or not. On my system, it is documented to return the number of input item assigned.

A: This strange value, is memory garbage. In C,all uninitialized variables(except static and extern) points to memory garbage.
When you use the value of this variable, anything can happen, you have an UB.You must initialize the values of this variables and check the return-value from scanf().
As @Michael Dorst mentioned on comments, set x and x to some uncomum values(e.g, -1) and after scanf() call, check if the values of them have changed too.

A: It is because of your scanf statement.
Usually, scanf statements have this kind of format:
scanf("%d %d",&x,&y); //without the commas inside the ""'s

But you have made this format:
scanf("%d,%d",&x,&y); //with the commas inside the ""'s

which means that you need a comma separator between the two inputs.
Look at the following trials
TRIAL1:(note: input is 2345)

Please input 2 numbers:
2345
Now the value for x is 2345, and value for y is 134513867.

TRIAL2: (note: input is 23,45)
Please input 2 numbers:
23,45
Now the value for x is 23, and the value for y is 45.

TRIAL3: (note: input is 23+45)
Please input 2 numbers:
23+45
Now the value for x is 23, and the value for y is 134513867.

So, according to the trials, the scanf("%d,%d",&x,&y); requires the input to have a comma separator. What happened to the output for the first and third trial is that, the y variable did contain garbages because these y values are left unchanged/uninitialized. But it seems that the x variable got the correct value because of the first %d on your scanf.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как чередовать вывод информации в c#? Есть 9 кнопок, при нажатии на произовльную кнопку(при условии, что все остальные пустые) ставится текст "Х" на неё.Если выбрать след.произвольную кнопку, должен поставиться текст "0".Дальше 3-ю проивзольную кнопку, ставится "Х". Как это можно чередовать ?
 var buttons = new[] { Resource.Id.button1,
                              Resource.Id.button2,
                              Resource.Id.button3,
                              Resource.Id.button4,
                              Resource.Id.button5,
                              Resource.Id.button6,
                              Resource.Id.button7,
                              Resource.Id.button8,
                              Resource.Id.button9}.Select(b => FindViewById<Button>(b)).ToList();

        void buttonHandler(object sender, EventArgs e)
        {
            Button clicked = sender as Button;
            if (clicked.Text == "")
            {
                clicked.Text = "X";
            }
            else
            {
                clicked.Text = "0";
            }

        }

        for (var i = 0; i<9; i++)
        {
            buttons[i].Click += new EventHandler(buttonHandler);
        }

A: Решается через флаг.
private bool isCross { get; set; }

А дальше по коду:
if (clicked.Text == "")
{
    clicked.Text = isCross ? "X" : "0";
    isCross = !isCross; // не забываем поменять состояние флага
}


text:
Q: What is the difference between kmeans and cvKMeans2 algorithms in OpenCV? I want to find dominant N colors on the picture. For this purpose I decided to use KMeans algorithm. My project written on C, that is way I used cvKMeans2 algorithm. But it gives me very strange results. Then I decided to try kmeans algorithm on OpenCV C++. It gives me more accurate results. So, where is my fault? Could someone explain it to me?
1. I used this image for test.

2. Implementation on C.
#include <cv.h>
#include <highgui.h>

#define CLUSTERS 3

int main(int argc, char **argv) {

    const char *filename = "test_12.jpg";
    IplImage *tmp = cvLoadImage(filename);
    if (!tmp) {
        return -1;
    }

    IplImage *src = cvCloneImage(tmp);
    cvCvtColor(tmp, src, CV_BGR2RGB);

    CvMat *samples = cvCreateMat(src->height * src->width, 3, CV_32F);
    for (int i = 0; i < samples->height; i++) {
        samples->data.fl[i * 3 + 0] = (uchar) src->imageData[i * 3 + 0];
        samples->data.fl[i * 3 + 1] = (uchar) src->imageData[i * 3 + 1];
        samples->data.fl[i * 3 + 2] = (uchar) src->imageData[i * 3 + 2];
    }

    CvMat *labels = cvCreateMat(samples->height, 1, CV_32SC1);
    CvMat *centers = cvCreateMat(CLUSTERS, 3, CV_32FC1);

    int flags = 0;
    int attempts = 5;
    cvKMeans2(samples, CLUSTERS, labels,
              cvTermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 10000, 0.005),
              attempts, 0, flags, centers);

    int rows = 40;
    int cols = 300;
    IplImage *des = cvCreateImage(cvSize(cols, rows), 8, 3);

    int part = 4000;
    int r = 0;
    int u = 0;
    for (int y = 0; y < 300; ++y) {
        for (int x = 0; x < 40; ++x) {
            if (u >= part) {
                r++;
                part = (r + 1) * part;
            }
            des->imageData[(300 * x + y) * 3 + 0] = static_cast<char>(centers->data.fl[r * 3 + 0]);
            des->imageData[(300 * x + y) * 3 + 1] = static_cast<char>(centers->data.fl[r * 3 + 1]);
            des->imageData[(300 * x + y) * 3 + 2] = static_cast<char>(centers->data.fl[r * 3 + 2]);
            u++;
        }
    }

    IplImage *dominant_colors = cvCloneImage(des);
    cvCvtColor(des, dominant_colors, CV_BGR2RGB);

    cvNamedWindow("dominant_colors", CV_WINDOW_AUTOSIZE);
    cvShowImage("dominant_colors", dominant_colors);
    cvWaitKey(0);
    cvDestroyWindow("dominant_colors");

    cvReleaseImage(&src);
    cvReleaseImage(&des);
    cvReleaseMat(&labels);
    cvReleaseMat(&samples);
    return 0;
}

3. Implementation on C++.
#include <cv.h>
#include <opencv/cv.hpp>

#define CLUSTERS 3

int main(int argc, char **argv) {
    const cv::Mat &tmp = cv::imread("test_12.jpg");
    cv::Mat src;
    cv::cvtColor(tmp, src, CV_BGR2RGB);

    cv::Mat samples(src.rows * src.cols, 3, CV_32F);

    for (int y = 0; y < src.rows; y++)
        for (int x = 0; x < src.cols; x++)
            for (int z = 0; z < 3; z++)
                samples.at<float>(y + x * src.rows, z) = src.at<cv::Vec3b>(y, x)[z];

    int attempts = 5;
    cv::Mat labels;
    cv::Mat centers;

    kmeans(samples, CLUSTERS, labels, cv::TermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 1000, 0.005),
           attempts, cv::KMEANS_PP_CENTERS, centers);

    cv::Mat colors(cv::Size(CLUSTERS * 100, 30), tmp.type());
    int p = 100;
    int cluster_id = 0;
    for (int x = 0; x < CLUSTERS * 100; x++) {
        for (int y = 0; y < 30; y++) {
            if (x >= p) {
                cluster_id++;
                p = (cluster_id + 1) * 100;
            }
            colors.at<cv::Vec3b>(y, x)[0] = static_cast<uchar>(centers.at<float>(cluster_id, 0));
            colors.at<cv::Vec3b>(y, x)[1] = static_cast<uchar>(centers.at<float>(cluster_id, 1));
            colors.at<cv::Vec3b>(y, x)[2] = static_cast<uchar>(centers.at<float>(cluster_id, 2));
        }
    }

    cv::Mat dominant_colors;
    cv::cvtColor(colors, dominant_colors, CV_RGB2BGR);
    cv::imshow("dominant_colors", dominant_colors);
    cv::waitKey(0);

    return 0;
}

4. Result of code on C.

5. Result of code on C++.

A: I found my mistake. It is related to IplImage's widthStep field. As I read here widthStep gets padded up to a multiple of 4 for performance reasons. If widthStep is equal to 30 it will padded up to 32.
int h = src->height;
int w = src->width;
int c = 3;
int delta = 0;
for (int i = 0, y = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
        for (int k = 0; k < c; ++k, y++) {
            samples->data.fl[i * w * c + c * j + k] = (uchar) src->imageData[delta + i * w * c + c * j + k];
        }
    }
    delta += src->widthStep - src->width * src->nChannels;
}

With pointers
for (int x = 0, i = 0; x < src->height; ++x) {
    auto *ptr = (uchar *) (src->imageData + x * src->widthStep);
    for (int y = 0; y < src->width; ++y, i++) {
        for (int j = 0; j < 3; ++j) {
            samples->data.fl[i * 3 + j] = ptr[3 * y + j];
        }
    }
}


text:
Q: Amortization table Visual C# I am building an amortization table in Visual C#, with a list view to display the elements and with an array of strings to store them, I can put the numbers of pays, the amounts and interests, but I want to calculate the capital base on the rest of amounts minus interests.
How can I solve it?
public void Agregar(string aCuota, string aMontoCuota, string aInteres, string aCapital, string aMonto)
{
    string[] row = { aCuota, aMontoCuota, aInteres, aCapital, aMonto };

    itemsProcess = new ListViewItem(row);
    lvConsulta.Items.Add(itemsProcess);
}

//Agrega las consultas a las funciones establecidas en la clase
private void btnConsulta_Click(object sender, EventArgs e)
{
    double tasaPeriodicaConsulta = 0.0;
    double cuotas = 0.0; ;
    double interes = 0.0; ;
    double capital = 0.0; ;

    //Plazos para pagar en meses
    int cantFilas = int.Parse(tbTiempo.Text);

    //Calculo de la tasa periodica
    tasaPeriodicaConsulta = calculo.TasaPeriodica(tbTasaAnual, tbTiempo);

    for (int i = 0; i <= cantFilas; i++)
    {
        if(i == 0)
        {
            cuotas = 0;
            interes = 0;
            capital = 0;
            saldoFinal = int.Parse(tbMontoConsulta.Text);
        }
        else
        {
             cuotas = calculo.MontoCuota(tbMontoConsulta, tbTiempo, tasaPeriodicaConsulta);
             interes = calculo.Interes(tbMontoConsulta, tasaPeriodicaConsulta);
             capital = calculo.Capital(cuotas, interes);
             saldoFinal = calculo.SaldoFinal(tbMontoConsulta, capital);
        }

        Agregar(i.ToString(), cuotas.ToString(), interes.ToString(), capital.ToString(), saldoFinal.ToString());
    }
}


text:
Q: How to check automatically that I didn't forget to add ef core code first migration We are using Entity Framework Core 2.2 with code first. Sometimes I change one of the entities, but forget to create a new migration, or I create a migration but only in one context (we have for different db engines). I want to check it automatically (ideally as NUnit test) so it runs in our CI server for every commit.
Manually I would try to create a new migration and check that created Up() and Down() methods are empty. It there any way to do it as a NUnit test?

A: Where is difficulty in creating a test that :

*

*Creates a new DB

*Applies all current migrations to create a schema

*Tries to use all the entities. It can be as simple as adding an entity, querying that entity and deep-comparing they are the same.

*Drops the DB

If the schema doesn't have a migration for new entity or change in entity, you are sure to get and SQL error out of this.
Sure, every time you create a new entity, you would need to add a new test. But that should be already happening if you are using TDD.
And speed shouldn't be a problem either, as creating and dropping a DB shouldn't take more than few seconds and there won't be many of these kind of tests. And they can be parallelized.
If you want to get fancy and don't want to write test for each entity, it could be possible to do something like this :

*

*Use reflection to get all entity types supported by a Context.

*Use auto data generator like Bogus or AutoFixture to fill the entities with data.

*Round-trip the entities through DB.

*Compare the original with retrieved using deep-comparer like Compare-Net-Objects.

The usefulness of such automated approach would depend on complexity of your data model. Would just work for simple model. But would require lots of tweaking and overrides if the model is complex.


text:
Q: Ubuntu Installer cannot see windows os partition and sees my hard drive as blank? Good day,
I have just downloaded ubuntu 12.10 today using windows 7 and installed it to my SD card. I booted up using the sdcard, and everything was going perfectly well until Ubuntu said i currently have no operating systems. So instead, I tried the 'Something Else' option, but it said that my hard drive is blank. Please help.

A: I never heard of installing to an SD card before that's an interesting idea but it could also be your problem, I would recommend installing the .iso to a USB [also called a pendrive] with at least close to a gig of free space [it's easer if it's empty but that's not mandatory] you can find some software for doing this at pendrivelinux.com [YUMI is my favourite] also make sure if you have a 64bit computer you download the 64bit .iso . Some computers [mine included] do not work well with the 32bit version [64bit does not work at all on 32bit computers!]
Good Luck!!!!

A: The symptom of a blank hard disk is most often caused by one of two conditions:

*

*A partition table error -- Overlapping partitions, ambiguous GPT/MBR status, partitions too big for the disk, and other problems cause libparted (upon which most Linux partitioning tools are based) to flake out. A common symptom is a disk that appears to be empty. My FixParts program (included in the Ubuntu gdisk package, IIRC) can fix many of these problems.

*Leftover RAID data -- A disk that used to be used in a motherboard-based software RAID configuration may have leftover RAID data that will confuse the system. You can usually remove this data by typing sudo dmraid -E -r /dev/sda (substituting the disk device filename for /dev/sda, if necessary). You must be sure that the disk is no longer used in a RAID configuration before you do this, though. You might also want to check your motherboard's firmware settings to be sure that RAID support is disabled.

A: Check whether there is only one primary disk drive using any partitioning tools.If more than one primary drive is found convert it into logical drive. Don't change the windows drive to logical. There will be no problem in converting primary to logical, i.e, no data loss. I used Easeus Partition Master to do it and done it successfully.


text:
Q: Caret position relative to screen coordinates in javaFX I am trying to find a way to get the corresponding screen location of the caret-position in a text area in JavaFX. I need the location to show Popups in text at the caret location.
I found request or it here:
https://bugs.openjdk.java.net/browse/JDK-8090849
and some workarounds here:
https://community.oracle.com/thread/2534556
They work somehow, but there are a few issues with location not updating correctly sometimes. Does anyone have a suggestion of how to get the caret position in terms of screen X and Y?

A: Just wanted to follow-up with an answer to this question for TextField controls in JavaFX. I'm sure the same could apply to other text input controls as well. I got the idea from looking at some code that involved changing the default colour of the caret using a subclass of TextFieldSkin class. If you look closely, the TextFieldSkin superclass holds a reference to the Path instance which represents the caret in a protected field called caretPath. Although this is kind of a hack'ish solution, it does provide developers with the absolute coordinates of the Caret in a much safer way than most of the hacks I've seen out there.
public class TextFieldCaretControlSkin extends TextFieldSkin {
    public TextFieldCaretControlSkin(TextField textField, Stage stage) {
        super(textField);
        Popup popup = new Popup();

        // Make the popup appear to the right of the caret
        popup.setAnchorLocation(PopupWindow.AnchorLocation.CONTENT_BOTTOM_LEFT);
        // Make sure its position gets corrected to stay on screen if we go out of screen
        popup.setAutoFix(true);
        // Add list view (mock autocomplete popup)
        popup.getContent().add(new ListView<String>());

        // listen for changes in the layout bounds of the caret path
        caretPath.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
            @Override
            public void changed(ObservableValue<? extends Bounds> observable,
                                Bounds oldValue, Bounds newValue) {
                popup.hide();
                // get the caret's x position relative to the textfield.
                double x = newValue.getMaxX();
                // get the caret's y position relative to the textfield.
                double y = newValue.getMaxY();
                Point2D p = caretPath.localToScene(x, y);

                /*
                 * If the coordinates are negatives then the Path is being
                 * redrawn and we should just skip further processing.
                 */
                if (x == -1.0 || y == -1.0)
                    return;

                // show the popup at these absolute coordinates.
                popup.show(textField,
                        p.getX() + caretPath.getScene().getX() +
                             caretPath.getScene().getWindow().getX(),
                        p.getY() + caretPath.getScene().getY() +
                             caretPath.getScene().getWindow().getY() -
                             newValue.getHeight()); // put the popup on top of the caret
            }
        });
    }
}

To use you'd have to embed this in some sort of subclassed text input control and remember to do textField.setSkin(new TextFieldCaretControlSkin(textField)). There may be better ways to do this since I am not a JavaFX expert but I just wanted to share this solution with the rest of the world just in case it provided some insight.
Hope this helps!

A: This is how you use RichTextFX to position a popup window 4px to the right of the caret:
InlineCssTextArea area = new InlineCssTextArea();
Popup popup = new Popup();
popup.getContent().add(new Label("I am a popup label!"));
area.setPopupWindow(popup);
area.setPopupAlignment(PopupAlignment.CARET_CENTER);
area.setPopupAnchorOffset(new Point2D(4, 0));

You still need to control the visibility of the popup window yourself by calling
popup.show(ownerWindow);
popup.hide();

See also this working demo.


text:
Q: regex - boundary characters (^ and $) versus escaped characters (\A and \Z) What are the differences between,
\A  Match at only beginning of string
\Z  Match at only end of string (or before newline at the end)

^   Match the beginning of the line
$   Match the end of the line (or before newline at the end)

A: From the perl documentation (I can't see them in the standard regex syntax):

The "\A" and "\Z" are just like "^" and "$", except that they won't match multiple times when the "/m" modifier is used, while "^" and "$" will match at every internal line boundary.

You should be adding a perl tag if this is related just to Perl (or those languages or libraries using PCRE, Perl-Compatible Regular Expressions).

A: \A always matches the start of a string, and never matches after a line break, while many dialects have the possibility to make ^ match the beginning of a line as well.
http://www.regular-expressions.info/reference.html (look for 'Anchors').


text:
Q: $.Deferred reject ignored and does not fire any callbacks in a specific situation I'm trying to make a fade in that stops the fade out where it is and fades in starting at the opacity the fade out left off at. Currently, the first time I type a key, if I interrupt the fadeOut with another keystroke, it'll cause animOpacityPromise to never resolve no matter what until a page refresh. If I let the fadeOut complete, any subsequent animOpacityPromiseCtrl.reject(); will be ignored until a page refresh, allowing the fadeOut to complete. For example, in the JSFiddle, if I type a key, wait until I see clearOverlay animate promise completed in the log, then type in "ABC", wait for it to start fading out and interrupt it's fade out with "SS", the overlay will instantly disappear on the first S and reappear with the content "SS" on the second S. The expected behavior is for it to not clear the searchString and overlay until the overlay is finished fading out and instead interrupt the fadeout with a fade in and append the keys to the search string and overlay. If I interrupt the first fadeout with a keystroke, the animation behavior is how I want with the fade in that stops the fade out where it is and fades in starting at the opacity the fade out left off at but animOpacityPromise.done and animOpacityPromise.always will never be called in any keystroke until a page refresh.
JSFiddle
function initQuickSearch() {
  var overlay = $('#searchOverlay');
  var overlayIsFadingOut = false;
  var fadeOutTimeOut;
  var searchString = '';
  var animOpacityPromiseCtrl = $.Deferred();

  function showOverlay() {
    var fadeDelay = 200;

    if (overlayIsFadingOut) {
      console.log('clearOverlay animate promise rejected');
      animOpacityPromiseCtrl.reject();
      overlayIsFadingOut = false;
      clearTimeout(fadeOutTimeOut);
      fadeDelay = 100;
    }
    overlay.css({'visibility': 'visible'});
    overlay.stop(true, false).animate({opacity: 1}, {duration: fadeDelay, queue: true}, 'easeOutQuint');
  }

  function clearOverlay(bool) {
    var fadeDelay = 1000;
    var fadeDuration = 400;
    var animOpacityPromise;

    if (bool === true) {
      fadeDelay = 0;
      fadeDuration = 200;
    }

    overlayIsFadingOut = true;

    fadeOutTimeOut = setTimeout(function() {
      console.log('clearOverlay setTimeout called');
      animOpacityPromise = $.when(overlay.animate(
        {opacity: 0},
        {
          duration: fadeDuration,
          queue: true,
          start: function() {
            console.log('Fade out started.');
          },
          done: function() {
            console.log('Fade out done. Resolving promise.');
            animOpacityPromiseCtrl.resolve();
          }
        },
      'easeOutQuint').promise(), animOpacityPromiseCtrl);

      animOpacityPromise.done(function() {
        console.log('clearOverlay animate promise completed');
        overlay.css({'visibility': 'hidden'});
        searchString = '';
        $('#searchOverlay span').html('');
      });

      animOpacityPromise.always(function() {
        console.log('clearOverlay animate promise always');
        overlayIsFadingOut = false;
      });
    }, fadeDelay);
  }

  function addChar(char) {
    searchString = searchString + String.fromCharCode(char.which);
    console.log('Character "' + String.fromCharCode(char.which) + '" added to searchString. searchString is now "' + searchString + '"');

    $('#searchOverlay span').append(String.fromCharCode(char.which));
  }

  function removeChar() {
    searchString = searchString.substring(0, searchString.length - 1);
    $('#searchOverlay span').text(function(iter, txt) {
      return txt.slice(0, -1);
    });
  }

  $(window).keydown(function(key) {
    //If it's not an alphabetical character or the backspace key.
    if (!(key.which > 64 && key.which < 91) && key.which != 8) {
    } else {
      showOverlay();
      clearOverlay();
      if (key.which == 8) {
        removeChar();
      } else if (searchString.length <= 20) {
        addChar(key);
        key.preventDefault();
      } else {
        return false;
      }
    }
  });

  overlay.click(function() {
    clearOverlay(true);
  });
}

A: The bug was it kept reusing the same promise object. So I've assigned animOpacityPromiseCtrl to a new deferred object every time clearOverlay was called and it fixed the problem.
Updated JSFiddle.


text:
Q: Can I execute a method everytime I get an exception on Rails 3? I tried almost everything on web, all I want is to call a method whenever an exception like "ActiveRecord::RecordNotFound" or "No route matches" appears.
Rescues from ApplicationController does not work, but why?
class ApplicationController < ActionController::Base
  protect_from_forgery

  private
    def self.send_report_error(message)
      Notifier.page_failure(message).deliver
    end

rescue ActiveRecord::RecordNotFound
  # handle not found error
  send_report_error ActiveRecord::RecordNotFound.to_s
rescue ActiveRecord::ActiveRecordError
  # handle other ActiveRecord errors
  send_report_error ActiveRecord::ActiveRecordError.to_s
rescue # StandardError
  # handle most other errors
  send_report_error "common error"
rescue Exception
  # handle everything else
  send_report_error "common exception"
end

A: Use rescue_from.  For example:
class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :send_report_error
end

http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html


text:
Q: enable wifi with elevated rights in Powershell (without entering credentials) I am trying to enable and disable the wifi adapter without entering the administrator credentials.
I an logged as a user without administrator rights but I have the administrator password.
This is my script, but it's not working
$username = '.\Administrator'
$password = 'pass'

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe" -Credential $credential -ArgumentList '-command "$wmi = Get-WmiObject -Class Win32_NetworkAdapter -filter "Name LIKE '%Wireless%; $wmi.disable()'"

What i want to achieve is what this code does:
$wmi = Get-WmiObject -Class Win32_NetworkAdapter -filter "Name LIKE '%Wireless%'"
$wmi.disable()

How can be done this ?
@Edit
Or something similar in order to be able to disable and enable the WIFI

A: $adminaccount = ".\Administrator"
$PASSWORD = ConvertTo-SecureString "pass" -AsPlainText -Force
$UNPASSWORD = New-Object System.Management.Automation.PsCredential $adminaccount,$PASSWORD
$wmi = Get-WmiObject -Class Win32_NetworkAdapter -filter "Name LIKE '%Wireless%'"
$wmi.disable() -Credential $UNPASSWORD

This could possibly work, but I can't be certain as I'm using Linux at the moment and cannot test it. Assuming the disable() method is the command that requires authentication, and that it accepts arguments such as that, this may work.
Click here for where I got my details, it should work.
The other option is to hold shift and right click on your script with just the following in and clicking run as different user, then enter in the admin credentials.
$wmi = Get-WmiObject -Class Win32_NetworkAdapter -filter "Name LIKE '%Wireless%'"
$wmi.disable()

This option would mean you would have to type the admin credentials in, but you wouldn't have to switch user to do it.
Another possible way would be do try a different command to disable the adapter:
Disable-NetAdapter -Name "Ethernet 2"

This could be ran like the following:
$username = '.\Administrator'
$password = 'pass'

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe" -Credential $credential -ArgumentList '-command "Disable-NetAdapter -Name 'Ethernet 2'"'

All you'd have to do is replace "Ethernet 2" with your adapter name.


text:
Q: How to suppress ListedColormap object location displayed on plot? I wrote a function to plot rows of digits that correspond to the conformations of single amino acids in a polypeptide taken from a molecular dynamics simulation. Here is the code:
def plot_matrix_wt(matrix, title='KTPP Conformations'):
    cmap = colors.ListedColormap(['k','y','b','g','r','c']);
    rcParams['figure.figsize'] = 10, 5
    plt.imshow(matrix,cmap=cmap)
    plt.title(title)
    cbar = plt.colorbar(ticks=[0.4, 1.25, 2.1, 2.95, 3.75, 4.6],label=cmap)
    cbar.ax.set_yticklabels(['None', 'Beta', 'PPII', 'Alpha', 'L-Alpha', 'Alpha_Turn'])
    plt.xticks([5,15,25,35],('K','T','P','P'));
    plt.ylabel('Proportion of Simulation Frames [%]')
    plt.show()

function output
The problem is that I get the object location of the ListedColormap displayed alongside the colorbar on my plot. Is there any way to suppress it? Ive used %matplotlib inline and ; after defining the cmap as suggested in other responses to similar questions but nothing has worked yet. Thanks very much


text:
Q: Which elements or isotopes can be analyzed by Neutron activation analysis (NAA)? Some sources name only a handful, but that might refer to the use of optical film. Others state more than 70. I would like to know which elemets or isotopes can be detectet/imaged by NAA.

A: NAA depends on the capture of a neutron by a nucleus which results in the production of a heavier radioactive nucleus.  Many nuclei will become radioactive after capturing a single neutron. Some nuclei may require 2 or more extra neutrons before becoming radioactive.  The probability of producing a radioactive nucleus will depend on the nuclear neutron capture cross-section. The probability of a neutron being captured is small. If a nucleus requires 2 or more neutrons, the probability is even smaller.
When a radioactive nucleus is produced it will undergo gamma decay. By measuring the energy of the gamma ray and the half-life of the nucleus one can determine the nucleus that decayed and hence the element.
Some nuclei will have a neutron capture cross-section that is so small that measurements aren't sensitive enough to detect. Others require more than two neutron captures and hence production of these are too small to measure. And some produce radioactive nuclei which decay almost instantly. these require a different technique to measure the gamma rays and half lives. About 70% of elements can be measured using the normal methods of NAA. (Reference 1)
(1) Overview of Neutron Activation Analysis. University of Missouri Archaeometry Laboratory
http://archaeometry.missouri.edu/naa_overview.html


text:
Q: JvectorMap add color to small countries I know that in JvectorMap some small countries are missing.
But I need a way to assign a color also to small countries, because I need to loop over a list of state and get the color.
myMap.series.regions[0].elements[state].element.properties.fill

Because small countries are not present, the script give errors when it checks Singapore for example.
How could fix this?


text:
Q: Reversing an array, remains in original order I'm trying to reverse an array in typescript. Here's what the original array looks like:

But when I call reverse() on the array, it's unchanged:

recommendations is an array of arrays, declared like so:
recommendations: any;

And instantiated:
me.recommendations = [[]];

Can anyone tell me why the array isn't being reversed and how to fix this issue?
Thanks

A: The array has been reversed. You've tricked yourself in the debugger.
reverse reverses the array in-place and returns a reference to the array. In other words,
> var x = [1, 2, 3];
> var y = x.reverse();
> x
    [3, 2, 1]
> y
    [3, 2, 1]
> x === y
    true

A: The problem is that [].reverse() doesn't behave as you expect.
reverse changes the value of the array itself, so the array is being reversed, just you're examining both variables whatever and yup after this has happened.
So the array itself is reversed and you've just made 2 references to that object.


text:
Q: What is the difference between using round braces "()" and not using it in instance declaration of php? I see some people use braces "()" when creating a new instance of a class using new. Some do not.
Is there any difference?


text:
Q: Java: prevent auto-decoding of encoded String I have an encoded String like this:
17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu

and want to split it on the "/".
In the last part, there is a encoded "/" as "%2F".
The result is
[17298457,abcdef , 17298529,ghijklm , 17298562,opq , rstu]

The problem is, that Java decodes the string on the fly as soon as i pass it to another method (split method e.c.)
Do someone have a good idea how to work around that?
thanks a lot!
monk

A: Not for me....
import java.util.Arrays;
public class Test {
    public static void main(String[] args) throws Exception {
        String s = "17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu";
        System.out.println(Arrays.toString(s.split("/")));
    }
}

gives
[17298457,abcdef, 17298529,ghijklm, 17298562,opq%2Frstu]

A: public static void main(String[] args) {

    String test = "17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu";

    String[] args2 = test.split("/");

    for (int i = 0; i < args2.length; i++) {

        String[] args3 = args2[i].split("%2F");

        for (int j = 0; j < args3.length; j++) {

            if(!args3[j].trim().startsWith(",") && j != 0)
            System.out.print(" ,");
            System.out.print(args3[j]);
        }

    }

OUT PUT - AS U WRITTEN -
17298457,abcdef17298529,ghijklm17298562,opq ,rstu


text:
Q: Users are getting access denied message when group they are in has access? Hello
We have a document library that a group of users is given Read access to.  Checking the effective permissions on a member of the group confirms this.  We also have 2 documents that inherit the parent permissions (both .mht files).  Sending a link to the sharepoint document via email users can access one document but not the other.  Checking effective permissions confirms they have access to one but not the other even though both are inheriting from the parent and neither have any custom permissions.
Has anybody seen this before?

A: Could it be that the site in which this document library is situated has given no access to the group for whom is getting the access denied message?

A: I doubt this is the solution, Dan, but I wonder if the .mht's are similar in nature or not.  Does the one that doesn't work, perhaps, reference another artifact on the portal to which the users do not have permission?


text:
Q: SQL - Nested select statement? I have 2 tables, ticket and ticket_custom.
Here are how the tables are set up.
I have a web interface where I can change the state (value in the table ticket_custom) The web interface adds a new entry instead of updating the original entry.
ticket  name    value
1   state   Ready for Final Verification
2   state   Ready for Final Verification
1   state   Verified

The last row is added
So I need to modify the queries.
   SELECT p.value AS __color__,
   id AS ticket, summary, component, version, c.value AS state, milestone, t.type AS type,
   owner, status,
   time AS created,
   changetime AS _changetime, description AS _description,
   reporter AS _reporter
  FROM ticket t,  ticket_custom c
  LEFT JOIN enum p ON p.name = t.priority AND p.type = 'priority' AND id = c.ticket
  WHERE status <> 'closed' AND id = c.ticket
  ORDER BY CAST(p.value AS int), milestone, t.type, time, c.ticket

The query now returns both entries. I tried to add a nested select in the where clause.
SELECT g.ticket
FROM ticket_custom g
WHERE g.ticket = id
ORDER BY g.ticket DESC LIMIT 1

So -
SELECT p.value AS __color__,
   id AS ticket, summary, component, version, c.value AS state, milestone, t.type AS type,
   owner, status,
   time AS created,
   changetime AS _changetime, description AS _description,
   reporter AS _reporter
  FROM ticket t,  ticket_custom c
  LEFT JOIN enum p ON p.name = t.priority AND p.type = 'priority' AND id = c.ticket
  WHERE status <> 'closed' AND id = c.ticket and (
         SELECT g.ticket
         FROM ticket_custom g
         WHERE g.ticket = id
         ORDER BY g.ticket DESC LIMIT 1 )
  ORDER BY CAST(p.value AS int), milestone, t.type, time, c.ticket

Clearly I'm doing something wrong.

A: This appears to be more of a design issue than a query issue.  While it is possible to return only a single record from the ticket_custom table there is not a way to determine which record that will be.  In you sample table ticket 1 has a value of "Ready for..." and "Verified" but nothing that shows which happened first.  Logically, the "Ready for..." happened first.
The easiest way for you to fix this issue would be to add a timestamp or incrementing ID field.  Then your subquery could select the most recent entry (latest timestamp or highest ID).

A: Assuming at least one ticket, you could do this instead:
SELECT MAX(g.ticket)
FROM ticket_custom g
WHERE g.ticket=id
You can convert that to a JOIN or nested SELECT etc.
so change id=c.ticket id=MAX(c.ticket)
but check your WHERE & LEFT JOIN there's some strange stuff in there.

A: Don't make your database schema dynamic (i.e. "table-driven").  It isn't a sensible design pattern (I know from experience).  It saves only a little effort upfront in creating additional attributes, but incurs additional overhead thereafter, both in writing queries and in the database processing required to execute them.
Just add a state id column to the ticket table and update it when the state changes.  Create a reference table to store the state names.  Then your queries become quite simple, and requires less effort for database engine to do an indexed join to a small reference table.


text:
Q: Simple apache mod_rewrite URL Alright, I have a seemingly simple thing that I am trying to do that I would love some help on.
I have a URL like this:
http://www.example.com/api/?q=sometask&paramX=somevalue&paramY=someothervalue
And I would like it to accessed through:
http://www.example.com/api/sometask/?paramX=somevalue&paramY=someothervalue
The "q" value could be as simple as "sometask" or as complex as "sometask/123/otherthing/y" but it will always be the value of "q".  And the rest of the parameters (paramX and paramY, for example) should just be tacked on at the end of the URL.
For example, I would like:
http://www.example.com/api/?q=sometask/123/otherthing/y&paramX=somevalue&paramY=someothervalue&paramZ=somethirdvalue
To be accessible through:
http://www.example.com/api/sometask/123/otherthing/y/?paramX=somevalue&paramY=someothervalue&paramZ=somethirdvalue
I have setup some really really basic mod_rewrite rules in the past (pageA redirects to pageB, etc.), but I'm not really familiar enough with it to even write this (seemingly) simple rule.  So, any help (answer) would be appreciated!
Thanks!

A: Add this to your .htaccess in your web root / directory
Options +FollowSymLinks -MultiViews
RewriteEngine on

RewriteRule ^api/(.+)/$ /api/?q=$1 [NC,L,QSA]


text:
Q: How to get only some informations from json response? Openweatherapi returns json like this:
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}

But i need only informations for class like this:
export class WeatherInfo{
    constructor(
                public name: string,
                public description: string,
                public temperature: number){
                      this.name = name;
                      this.description = description;
                      this.temperature = temperature;

  }

}
This is my api service:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import {environment} from '../environments/environment';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  getWeatherByCity(city): Observable<any>{
    const httpParams: HttpParams = new HttpParams().set('q',city).set('appid',environment.ApiKey).set('units',environment.ApiUnits);

    return this.http.get(environment.ApiUrl, {params: httpParams});

  }

  private handleError (error: any) {
    let errMsg: string;
      errMsg = error.message ? error.message : error.toString();

    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

I can see the response in console log, but i cant display it in the browser

And my app.component.class
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
import { WeatherInfo } from './weather-info';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  weather: WeatherInfo;

  data: string;

  title = 'Pogoda';

  constructor(private api: ApiService) {}

  ngOnInit(){
    this.getWeather();
  }

  getWeather(){
    this.api.getWeatherByCity('Bydgoszcz').subscribe(
      res => {
        this.data = res;
        console.log(this.data);
      }
    );
  }

My goal is to get json data and parse it to the weather-info object. I need only information in this class.

A: You can project the return value of your api call with the rxjs map method. You usually should to this in your service:
 return this.http
      .get(environment.ApiUrl, {params: httpParams})
      .pipe(map((data: any) =>
       {
          /** Build your custom object to return **/
          /** const customObject = { id: data.id };
          /** return customObject;
       });

See https://www.learnrxjs.io/operators/transformation/map.html for further information


text:
Q: Self assigned IP address 169.254... on Panasonic TV I have a Netgear router using DHCP, Windows 7 Laptop, Panasonic WiFi tv and iphone 3 on my home network. If I power up all items everything works fine. If power down the Laptop the tv stops working on the network and returns the 169.254... IP address. If I reboot the router the tv returns a good IP and works fine. Is this normal?
I've tried a static IP address for the tv inside and outside the DHCP range and the tv always works on the internet but the iPhone app to control the tv does not and I can't ping the tv when using a static IP.
I would like to avoid rebooting the router when I switch the laptop off. Is this possible or is this the way things work?

A: Try reserving the IP Addresses to the MAC Addresses that is connecting. This way everytime the device connects it will have the same IP and any new device will get  an unassigned IP Address. What model is your router?.

A: This sounds like either your ISP is handing out public IPs to your devices (which is unnecessary - and you are probably paying extra for this) or your ISP has some sort of configuration on the router to only allow up to X devices.
My advice is always take the router the ISP gives you and put it in the trash. Go out and buy a Linksys (or other router) that is compatible with DD-WRT.
Or if your ISP insists on requiring that router - you can just plug a router into that router and that should solve IP issues.
Edit:
Why was this downvoted? I have multiple IPs from my ISP and the only way to reallocate them is to power cycle the modem. And if you plug in another device it gets a local 169 address.


text:
Q: Using Oauth 2.0 with Next js I want to use Google OAuth 2.0 with my React/Next.js app. I've set up my OAuth Client IDs on the Google Developer console, and set up a route in my server.js node file. When I try to GET request https://localhost:3000/auth/google I get the Next js 404 Not Found page. It's obviously looking for a page called auth in my Next js pages directory. Tried using the next/Router, wrapping my button in an anchor element, fetch API GET requesting https://localhost:3000/auth/google, all failed.
I've managed to successfully implement passport user authentication, salting, hashing and sessions but it's just the Oauth that's giving me trouble.
If it were a standard node application https://localhost:3000/auth/google would redirect to the interface where users could login with their google credentials.
I've tried search the nextjs examples github for implementations of oauth but there doesn't seem to be any. Anyone know how I can use OAuth 2.0 with Next JS?
Route
server.get("/auth/google", (req, res) =>{
   passport.authenticate("google", { scope: ['profile']});
})

Button that's supposed to take me to the google login/register page
<button className="btn btn-block btn-social btn-google" style={{'color': '#fff'}} onClick={() => Router.push("/auth/google")}>
<FontAwesomeIcon icon={faGoogle} className="google-social-button" /> Sign Up with Google
</button>

A: You can simply try this,
const app = next({ dev });
const server = express()

server.get('/auth/google/callback*',
    passport.authenticate('google'),
(req, res) => {
    res.redirect('/dashboard');
});

server.get('/auth/google*', (req, res) => {
    return app.render(req, res, req.path, req.query)
});

server.get('/api/logout', (req, res) => {
    req.logout();
    res.send(req.user);
})

server.get('/api/current_user', (req, res) => {
    res.send(req.user);
});

server.get('*', (req, res) => {
   return handle(req, res)
});

Just make sure the google reqs are above the server.get('*') route as it catches all requests.
More help: https://github.com/zeit/next.js/blob/canary/examples/custom-server-express/server.js

A: Not sure if you're still looking for an answer here, but if are, you can do something like the following under the latest Next.js version (9+), https://nextjs.org/blog/next-9#api-routes
//--- PART 1: DEFINE YOUR GOOGLE OAUTH STRATEGY ALA PASSPORT
// This would be in its own passport.js file (the filename doesn't matter), the key thing being that you define your Google Strategy
import passport from 'passport'
import {
  Strategy as GoogleStrategy,
} from 'passport-google-oauth20'

passport.use(new GoogleStrategy({
  ...getGoogleKeySecret(), // a utility for grabbing your secret keys
  callbackURL: `/api/authorize/google/callback`,
  passReqToCallback: true, // http://www.passportjs.org/docs/authorize/
}, async function(req, accessToken, refreshToken, profile, done) {
    // Do any user lookup/mapping you need here
    return done(null, profile)
}))

//--- PART 2: DEFINE THE END-POINT
// This would be in your pages/api/auth/google.js file
import nextConnect from 'next-connect'
import middleware from '../any/custom/middleware/stuff/you/may/have'

const handler = nextConnect()

handler.use(middleware)

handler.get(passport.authenticate("google", {
  scope: ['profile', 'email', 'openid'], // tailer the scope to fit your needs
}))

export default handler

To try it out, direct a user to /api/auth/google via your UI or hit the URL directly, and you should be taken through the Google OAuth 2.0 flow.
Hope this helps - good luck!


text:
Q: How to access a specific camera device using HTML5 and JavaScript? I wrote some HTML5 and JS code that render a video stream, from a webcam, on a canvas but I don't know the method to specify which camera device to open.
Infact, if I access the webpage where my code runs with my Android, it shows only the "selfie-cam". How can I specify to use the main camera of the phone? Is there a method to do it?
If I access the webpage from my laptop, it opens the built-in webcam. But how can I connect to a (secondary) USB camera?
This is the "main" of my script:
var video, canvas, context;

window.onload = Initialize;

Initialization function:
function Initialize()
{
    video = document.getElementById("videoElement");

    canvas = document.getElementById("canvasElement");
    canvas.width = parseInt(canvas.style.width);
    canvas.height = parseInt(canvas.style.height);

    context = document.getCSSCanvasContext("2d", "mask", 640, 480);

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;// || navigator.msGetUserMedia || navigator.oGetUserMedia;

    if(navigator.getUserMedia)
    {
        navigator.getUserMedia({video: true}, VideoCapture, Error);
        requestAnimationFrame(IdleFunc);
    }
    else
    {
        alert("Error: your browser is not supported.");
    }
}

Success callback:
function VideoCapture(stream)
{
    video.src = window.URL.createObjectURL(stream);
}

Failure callback:
function Error(e)
{
    alert("Error: " + e);
}

Idle function:
function IdleFunc()
{
    requestAnimationFrame(IdleFunc);

    if(video.readyState === video.HAVE_ENOUGH_DATA)
    {
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
    }
}

Any help?
Thank you.
And sorry for my English :)
PC: Windows 8.1, Chrome (v41).
Smartphone: Android 4.2.2, Chrome (v41).


text:
Q: Splitting the array with / slash From debugger in my string of arrays I am getting this:
"/mercedes-benz/190-class/1993/" class="canonicalLink" data-qstring="?sub=sedan">1993

I wish to split text after each '/' and get it in string[], here is my effort:
Queue<string> see = new Queue<string>(); //char[] a = {'\n '};
       List<car_facts> car_fact_list = new List<car_facts>();
       string[] car_detail;

       foreach (string s in car)
       {

            MatchCollection match = Regex.Matches(s, @"<a href=(.+?)",
            RegexOptions.IgnoreCase);

            // Here we check the Match instance.
            foreach(Match mm in match)
            {
                // Finally, we get the Group value and display it.
                string key = mm.Groups[1].Value;
                //key.TrimStart('"');
                //key.Trim('"');
                key.Trim();

                // @HERE: I tried with string.Split as well and tried many combinations of separators
                car_detail = Regex.Split(key, "//");

                see.Enqueue(key);
            }
}

In car_detail[0] I get this "$[link]">$[title]
from this string:
"/mercedes-benz/190-class/1993/" class="canonicalLink" data-qstring="?sub=sedan">1993

A: It's not clear why you're using a double slash here...
string[] details = key.Split('/');

should work fine. (Note that forward-slashes don't have to be escaped in C#.) For example:
using System;

class Test
{
    static void Main()
    {
        string text = "/mercedes-benz/190-class/1993/";
        string[] bits = text.Split('/');
        foreach (string bit in bits)
        {
            Console.WriteLine("'{0}'", bit);
        }
    }
}

Output:
''
'mercedes-benz'
'190-class'
'1993'
''

The empty strings are due to the leading and trailing slashes. If you want to avoid those, you can use
string[] details = key.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);

Notes:

*

*car_facts is a highly unconventional name in C#. Normally you'd have something like CarFacts (or potentially just Car, CarInfo etc). Likewise car_fact_list would normally be carFactList or something similar.

*This code doesn't do what you expect it to:
key.Trim();

Strings are immutable in .NET - so Trim() returns a reference to a new string rather than changing the contents of the existing one. You may want:
key = key.Trim();

*You're currently assigning a value to car_detail but never using it. Why?

*Parsing HTML using regular expressions is a really bad idea in general. Consider using HTML Agility Pack or something similar.


text:
Q: Ubuntu 14.04 won't update packages After installing the Chrome plugin 'Chrome Remote Desktop', Ubuntu fails to update its packages. I get a pop-up with the message:
Requires installation of untrusted packages

When I click 'OK' nothing further happens.
Do I have to uninstall 'Chrome Remote Desktop' or is there some work around?

A: You are trying to install a package whose repository your Ubuntu does not trust.
Possibility 1
Run
sudo apt-get update

and find the missing key and install with
sudo apt-key adv --keyserver hkp://subkeys.pgp.net --recv-keys <your_missing_key>

Possibility 2
But you can also use y-ppa-manager
sudo add-apt-repository ppa:webupd8team/y-ppa-manager
sudo apt-get update
sudo apt-get install y-ppa-manager

*

*Run y-ppa-manager

*Click Advanced

*Click Try to import all missing GPG keys

A: This happens when there is a problem with an apt source. Running sudo apt-get update should display what the error is, even when the system updater does not.
After you see what apt source is causing the error, you can fix that error or remove it from the configuration to allow the system to upgrade normally.

A: I use synaptic package manager to deal with all the extra downloads that the software sources (if not configured correctly) aren't working properly. It also gives an option to mark all upgrades for every program you have in your computer (and driver), so I'd rather pick the lazy way and use synaptic..
If you'd like to check it out, its basically a graphical version of APT. https://apps.ubuntu.com/cat/applications/synaptic/


text:
Q: Getting Request Timeout from stored procedure? Only sometimes, I get request timeout (means my stored procedure is not responding within a specified time-period which is 90 seconds).
Here is my stored procedure:
ALTER PROCEDURE [dbo].[Insertorupdatedevicecatalog]
                (@OS                NVARCHAR(50)
                ,@UniqueID          VARCHAR(500)
                ,@Longitude         FLOAT
                ,@Latitude          FLOAT
                ,@Culture           VARCHAR(10)
                ,@Other             NVARCHAR(200)
                ,@IPAddress         VARCHAR(50)
                ,@NativeDeviceID    VARCHAR(50))
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @TranCount INT;
    SET @TranCount = @@TRANCOUNT;

    DECLARE @OldUniqueID VARCHAR(500) = ''-1'';
    SELECT @OldUniqueID = [UniqueID] FROM DeviceCatalog WHERE (@NativeDeviceID != '''' AND [NativeDeviceID] = @NativeDeviceID);

    BEGIN TRY
        IF @TranCount = 0
            BEGIN TRANSACTION
        ELSE
            SAVE TRANSACTION Insertorupdatedevicecatalog;

        DECLARE @Geo GEOGRAPHY = geography::STGeomFromText(''POINT('' + CONVERT(VARCHAR(100), @Longitude) + '' '' + CONVERT(VARCHAR(100), @Latitude) + '')'', 4326);

        IF EXISTS(SELECT 1 FROM DeviceCatalog WHERE [UniqueID] = @UniqueID)
        BEGIN
            DECLARE @OldGeo     GEOGRAPHY
                    ,@OldCity       NVARCHAR(100)
                    ,@OldCountry    NVARCHAR(100)
                    ,@OldAddress    NVARCHAR(100);

            SELECT  @OldGeo = [LastUpdatedLocationFromJob]
                    ,@OldCity = [City]
                    ,@OldCountry = [Country]
                    ,@OldAddress = [Address]
            FROM    DeviceCatalog
            WHERE   [UniqueID] = @UniqueID;

            UPDATE  DeviceCatalog
                SET [OS] = @OS
                    ,[Location] = @Geo
                    ,[Culture] = @Culture
                    ,[Other] = @Other
                    ,[IPAddress] = @IPAddress
            WHERE   [UniqueID] = @UniqueID;

                            IF (@OldGeo IS NULL OR @OldAddress IS NULL OR @OldCity IS NULL OR @OldCountry IS NULL OR ISNULL(@Geo.STDistance(@OldGeo) / 1000,0) > 50)
            BEGIN
                UPDATE  DeviceCatalog
                    SET [Lastmodifieddate] = Getdate()
                WHERE   [UniqueID] = @UniqueID;
            END

        END
        ELSE
        BEGIN
            INSERT INTO DeviceCatalog
                        ([OS]
                        ,[UniqueID]
                        ,[Location]
                        ,[Culture]
                        ,[Other]
                        ,[IPAddress]
                        ,[NativeDeviceID])
                VALUES  (@OS
                        ,@UniqueID
                        ,@Geo
                        ,@Culture
                        ,@Other
                        ,@IPAddress
                        ,@NativeDeviceID);
                IF(@OldUniqueID != ''-1'' AND @OldUniqueID != @UniqueID)
                BEGIN
                    EXEC DeleteOldAndroidDeviceID @OldUniqueID, @UniqueID;
                END
        END
LBEXIT:
        IF @TranCount = 0
            COMMIT;

    END TRY
    BEGIN CATCH
        DECLARE @Error INT, @Message VARCHAR(4000), @XState INT;
        SELECT  @Error = ERROR_NUMBER() ,@Message = ERROR_MESSAGE() ,@XState = XACT_STATE();

        IF @XState = -1
            ROLLBACK;
        IF @XState = 1 AND @TranCount = 0
            rollback
        IF @XState = 1 AND @TranCount > 0
            ROLLBACK TRANSACTION Insertorupdatedevicecatalog;

        RAISERROR (''Insertorupdatedevicecatalog: %d: %s'', 16, 1, @error, @message) ;
    END CATCH
END


text:
Q: In C#, how do you check if between two times? So I'm trying to figure out if a DateTime is between two Dates as well as two times.
For example,
if DateTime.Now >= January && DateTime.Now < August && DateTime.Now >= 9am && DateTime.Now < 12pm
     //do something

I'm not really sure how to go about this, any help is appreciated :')

A: if (DateTime.Now.Month < 8 && DateTime.Now.Hour >= 9 && DateTime.Now.Hour < 12) {
 // do your thing
}

A: From the documentation at https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.8#properties:
if (DateTime.Now.Month >= 1 && DateTime.Now.Month < 8
    && DateTime.Now.Hour >= 9  && DateTime.Now.Hour < 12)

where DateTime.Month is a number between 1 and 12, and DateTime.Hour is a number between 0 and 23.


text:
Q: Display images in PyroCMS depending on its {{ name }}-tag I need to display some images from a folder depending on its {{ name }}.
The names of my files look like this:

*

*foo.jpg

*foo_blur.jpg

*bar.png

*bar_blur.png

Now I need to do something with the blurred-image. This is what I tried, but no success:
{{ files:listing folder='1' }}
    {{ if { helper:strpos haystack='[[ name ]]' needle='_blur' } }}
        {{ files:image id='{{ id }}' }}
    {{ endif }}
{{ /files:listing }}

Currently it just does nothing. It seems that the strpos returns allways false. Any ideas what I'm doing wrong?

A: You should use the same curly braces for the name variable as you are for the id:
{{ files:listing folder='1' }}
    {{ if { helper:strpos haystack='{{ name }}' needle='_blur' } }}
        {{ files:image id='{{ id }}' }}
    {{ endif }}
{{ /files:listing }}

A: Got it by myself, thanks to Leon Stafford:
Just remove the brackets [[ ]] and its surrounding quotes
{{ files:listing folder='1' }}
    {{ if { helper:strpos haystack=name needle='_blur' } }}
        {{ files:image id='{{ id }}' }}
    {{ endif }}
{{ /files:listing }}


text:
Q: Missing values in a csv file after having dumped a dictionary I have dumped a dictionary to a csv file, but the last ~400 rows are missing form the file. The dictionary has 10000 values and this is what it looks like:
dict={'0':252, '1':61, '2':38. '3':91, ..., '9999':17}. The keys are sorted 0 to 9999 by construction (the dict comes from the application of the networkx package).
This is what I have used to do the dumping:
import csv
dict=G.edges() #The dictionary comes from an application of the networkx package
writer = csv.writer(open('myfile.csv', 'wb'))
for key, value in dict.items():
    writer.writerow([key, value])

My csv file reports the values until the 9631st row, after which there are no more values. How to fix this?
This is what my csv file looks like: you clearly see that the 9632nd row is truncated, and there is nothing after it. How to deal with this?
0     252
1     61
2     38
3     91
...   ...
9630  4
963

A: You haven't closed your output file. Try this structure instead:
with open('myfile.csv', 'w') as f:
    writer = csv.writer(f)
    for key, value in dict.items():
        writer.writerow([key, value])

The with keyword will automatically close your output file after the block completes.


text:
Q: Authentication Cookie I'm writing a database authentication system for my web application which is wrriten in ASP.NET MVC. When someone authorize, it should save his username in cookies. Is it safe to just use HttpResponse.Cookies` for saving a cookie that its value is username? Wouldn't it forgeable?
Saving only the username... Is it the right and safe way? Or should I save the whole User object (if this actually possible)?
Thank you and sorry for my English.

A: No, saving the username is very insecure, because it can be easily faked.  Here are my guidelines:

*

*Use a token.

*Hash the token when it is stored in the database.

*Make the cookie HttpOnly.

Tokens can be generated by a CSPRNG to ensure that the auto-login cookie can not be faked.
Hashing the tokens in the database prevents user account stealing in the case that you database is compromised.  (Remember, the token at this point is a password-equivalent.)
HTTP-Only cookies prevent XSS attacks that could potentially steal the cookie.

A: No, saving the user name in a cookie to flag that the user it authorizes is not the right way, and it's definitely not safe.
It would be quite easy to edit the cookie to be someone else's user name, and voila! you are now authorized as that user.
Instead you should store some information in the cookie that is not specific to the user, but is specific to the user session. You could create a value from the browser string (scrambled in some way to make it less obvious) and store the value both in the cookie and in the session data on the server. When the user sends the next request, you can verify that the value comes from the same session and the same browser configuration.
It's of course not totally safe, as you can spoof both cookie data and browser string, but it's a lot safer than putting the user name in a cookie, and somwhat safer than only relying on the session id.
To get an authentication that is really safe, you have to use SSL.

A: If you store the username in the cookie then its very easy for someone to change that.
A better approach would be to store a session id (which you have generated) in the cookie and hang things like the username off that in your server.

A: Use the built-in forms authentication framework to handle the HTTP transport end of the world and avoid reinventing the wheel.
PS: before someone downvotes, remember that FormsAuthentication != using the SqlMembershipProvider.


text:
Q: Return results from multiple list choice in Applescript This script is for use in Capture One where I am assigning people's names to the EXIF data.
I am trying to return the results of a list that could be one or more choices made by the user. I can get it to work with using item 1 in the list but I can't figure out how to deal with someone choosing 2 or more names from anywhere in the list?
Thanks for any help you can offer.
tell application "Capture One 11"
set peopleChoices to {"Abbie", "Charlie", "De-Arne", "Dean", "Jason", "Marlene", "Peta ", "Phoenix", "Rod", "Vanessa", "Yvonne"}
set peopleList to choose from list peopleChoices with prompt "Select your keyword/s:" with multiple selections allowed
if the result is not false then
set exif_keywords to item 1 of the result
end if
set selectedVariants to get selected variants
repeat with i from 1 to number of items in selectedVariants
    set this_item to item i of selectedVariants
    set theID to id of (parent image of this_item)
    do shell script "/usr/local/bin/exiftool -Subject='" & exif_keywords & "' -m -overwrite_original_in_place " & quoted form of theID
    reload metadata this_item
end repeat
display dialog "EXIF data has been updated"
end tell

A: You are constraining the list to one item in this line
set exif_keywords to item 1 of the result

Just change it to
set exif_keywords to result

I don't know how the keywords are supposed to be passed in the exiftool line, you might flatten the list with text item delimiters, this example joins the list comma separated. Replace "," with space if the parameters have to be space separated.
set {ASTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ","}
set exif_keywords to exif_keywords as text
set AppleScript's text item delimiters to ASTID

A: I have included the whole working script below in case anyone else is looking for something similar. The "-sep" is part of exiftool and splits the string depending on what you put after it. I had to escape it for the shell script line but it nromally does not have the back slashes.
tell application "Capture One 11"
    set peopleChoices to {"Abbie", "Charlie", "De-Arne", "Dean", "Jason", "Marlene", "Peta", "Phoenix", "Rod", "Vanessa", "Yvonne"}
    set peopleList to choose from list peopleChoices with prompt "Select your keyword:" with multiple selections allowed
    if the result is not false then
        set exif_keywords to result
        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ","}
        set exif_keywords to exif_keywords as text
        set AppleScript's text item delimiters to TID
    end if
    set selectedVariants to get selected variants
    repeat with i from 1 to number of items in selectedVariants
        set this_item to item i of selectedVariants
        set theID to id of (parent image of this_item)
        do shell script "/usr/local/bin/exiftool -sep \",\" -Keywords='" & exif_keywords & "' -m -overwrite_original_in_place " & quoted form of theID
        reload metadata this_item
    end repeat
    display dialog "EXIF data has been updated"
end tell


text:
Q: Is it possible to develop an app for Ubuntu with C (not C++)? I just want to know if i can write GUI apps for Ubuntu using C--again, not C++. It's just that I hate having to learn a new language entirely (I know that they are similar in some ways but still). Just want to know thanks in advance.

A: You can develop apps for Ubuntu with just about any language. If there are particular libraries you need your app to use, then as mdpc says that's the only thing that would likely impose any restrictions. Some libraries can only be used from certain languages.
But Ubuntu apps can be developed in C, and a lot of Ubuntu software is written in C, including many programs and libraries installed by default in almost every Ubuntu system.
Programs that are installed by default in Ubuntu or otherwise very popular, and are written in C, include: bash, Brasero, dash, Disks, most of the Document Viewer, Empathy, Evolution, the Eye of GNOME image viewer (src), the File Roller archive manager, GCalctool, GIMP, GNOME Terminal, LightDM, the Nautilus file browser, Pidgin (except some plugins), Rhythmbox, Seahorse (src), Totem, Upstart, and X.org.
So yes, you can definitely develop for Ubuntu in C. Many people do.
With that said, the Ubuntu SDK uses Qt. Qt has bindings for many languages but not C. So you probably cannot create programs with the Ubuntu SDK, by coding solely in C. (You could still often code most of your software in C.)
That may make it difficult to write mobile apps (for Ubuntu Touch) in just C. But there's no need to use the Ubuntu SDK for desktop apps. Many desktop apps (all but 4 apps listed above are desktop apps in the usual sense) that are packaged for and run well in Ubuntu don't use the Ubuntu SDK.
Furthermore, using the Ubuntu SDK may not be the best way to create portable apps that run well on other desktop operating systems besides Ubuntu. The Ubuntu SDK is good for many purposes, but even if it did support writing apps in C, you'd still likely not use it under a variety of circumstances.
One popular way to write GUI applications in C is to use Gtk+. There are other alternatives for GUI toolkits with C bindings, including WxWidgets (via WxC), IUP, and possibly Clutter (GObject is accessible from C but sometimes writing for its object model--or any object model--is difficult in C).


text:
Q: Contact Form 7 watermark for select menu im searching for a way to put a watermark on select fields.
that is not working ->
[select* c_type class:ic watermark "choose type" "a" "b" "c"]

to put a not valid value that fail validation, i had to put include_blank
[select* c_type class:ic include_blank "a" "b" "c"]

but the problem is that i have --- as watermark, thats what i want to change..

A: Try this:
[select* menu-206 first_as_label "Select doctor" "David Mikaberidze" "Sophio Gelashvili" "Maya Dolidze"]

A: You can do it with one line of jQuery.

To replace the – - – with the placeholder text I wanted, I first of
  all gave the fields an ID in the Contact Form 7 options. Following
  this, I added the following in my themes footer between script tags.

$("#typeofinjury option:first:contains('---')").html('How Were You Injured?');//Replace ---

The code simply looks for the first option inside the dropdown menu
  which has the ID 'typeofinjury'. It then replaces it with the text
  'How Were You Injured?'.

The blog post for this solution with screenshots is Here

A: If you find string replacement unefficient, you could simply use this:
jQuery(function($) {
    $("select option:first").attr('disabled', 'disabled');// Disable the first value/label ---
  });

I also made sure that the first alternative is the "label" i want to use, by adding 'first_as_label' to the shortcode in wcf7, like this:
[select name first_as_label 'label' 'alt1' 'alt2' 'alt3']

By making the first option disabled, wcf7 won't confirm the form until this an enabled alternative is chosen.

A: More recent versions of Contact Form 7 allow the use of first_as_label to create placeholder text that does not validate as an entry if users do not make a selection. Simply make your placeholder text be the first label in the list of options.
[select* food-choice first_as_label "Preferred food?" "Cake" "Pizza" "Burger" "Salad" "Donut"]

A: After hard searching i found this script that is working and replacing the "---" when targeting to that element
this one is changing all the "---"s
function my_wpcf7_form_elements($html) {
    $text = 'Please select...';
    $html = str_replace('<option value="">---</option>', '<option value="">' . $text . '</option>', $html);
    return $html;
}
add_filter('wpcf7_form_elements', 'my_wpcf7_form_elements');

this code, replacing with targeting
function my_wpcf7_form_elements($html) {
    function ov3rfly_replace_include_blank($name, $text, &$html) {
        $matches = false;
        preg_match('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $html, $matches);
        if ($matches) {
            $select = str_replace('<option value="">---</option>', '<option value="">' . $text . '</option>', $matches[0]);
            $html = preg_replace('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $select, $html);
        }
    }
    ov3rfly_replace_include_blank('menu-569', 'Choose language', $html);
    ov3rfly_replace_include_blank('menu-614', 'Choose country', $html);
    return $html;
}
add_filter('wpcf7_form_elements', 'my_wpcf7_form_elements');

hope that will save for some of you a headache
(source here)


text:
Q: why i am getting 500 internal error in ajax code Here is my code where I am getting error what m doing wrong there :
Ajax Call back Code:
    $(document).ready(function(){
    $('#btn2').click(function(e){
            e.preventDefault();
                var cate=$( "#cate option:selected").val();
                var sub_cat=$( "#myselect option:selected").val();
                var price=$('#price').val();
                var dprice=$('#dprice').val();
                var fprice=$('#fprice').val();
                var payment=$('input[name=payment]:checked').val();
                 var url="<?php echo base_url();?>cat_cntrl/submitalldata";
                $.ajax({
                type:'post',
                url:url,
                data:{cate :cate, sub_cat:sub_cat,price :price,dprice:dprice,fprice:fprice,payment:payment},
                dataType:"JSON",
                success:function(response){
    alert(response);
                }

    })
    })
        })

Controller funcation to get data and return data :
 public function submitalldata(){

          $cate=$this->input->post('cate');
          $sub_cat=$this->input->post('sub_cat');
          $price=$this->input->post('price');
          $dprice=$this->input->post('dprice');
          $fprice=$this->input->post('fprice');
          $payment=$this->input->post('payment');
          $data=array(
                 'category'=>$cate,
                 'subcat'=>$sub_cat,
                 'price'=>$price,
                 'discount'=>$dprice,
                 'finalprice'=>$fprice,
                 'paymentmode'=>$payment,
                 'createddate'=>time()
                     );

$get=$this->cat_model->insert('task',$data);
echo $this->db->last_query();
         // print_r($get);exit;
      $data['result']=$get;
     //print_r($data['result']);exit;
      echo $this->db->last_query();

     echo json_encode(array('result'=>$data['result']));
 }

On console m getting error 500 Internal Server Error what I am doing wrong there can anyone pls help me related this

A: I found the answer: it was my mistake in the controller file. Sorry to all of you.
$get=$this->cat_model->insert('task',$data); instead of this i used

$get=$this->db->insert('task',$data);


text:
Q: Symfony doctrine:generate:entities How to find is and has methods I have an entity called Member with a boolen property called "active". When I generate the getters and setters with doctrine:generate:entities I get the methods getActive() and setActive(). Now I rename the getter to isActive. When I now call doctrine:generate:entities on this entity again, the process generates a new method getActive as he does not find the method isActive.
Is there a way to tell it to search for is and has getter methods too?

A: No, this is not possible at the moment. You can vote for this feature here: http://www.doctrine-project.org/jira/browse/DDC-2287. However it is not recommended to use the "doctrine:generate:entities"-command to update entities. The command was built to generate the entities for the first time and not to update them. You should maintain your entities with your ide.


text:
Q: how to remove push notification badge while installing an app my app uses push notification. When I install the app to my device the app icon shows a push notification badge. The badge number remains the same and doesn't update with new notifications.
Is there any way not to show the badge just after installing the app and only when my app receives an actual push notification?

A: func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    application.applicationIconBadgeNumber = 0

}

A: Since there is not call made to you app after installing you can not do this.
You might be able to do it in the application:didFinishLaunchingWithOptions: method.
Here you could make a check if you apps is update or something and clear the icon badge.


text:
Q: Automatic ActiveJDBC instrumentation in VSCode I use VSCode as editor and I need to make automatic running instrumentation of my model classes.
To run it manually I run in shell mvn org.javalite:activejdbc-instrumentation:2.0:instrument

A: I use following VSCode extension to develop on Java: https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack
solved:
1. create .vscode/tasks.json
{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
      {
          "label": "Run instrumentation",
          "type": "shell",
          "command": "mvn org.javalite:activejdbc-instrumentation:2.0:instrument"
      }
  ]
}

*add "preLaunchTask": "Run instrumentation" in .vscode/launch.json


text:
Q: Xamarin Datapages - Getting XamlParseException I started playing a bit with Xamarin DataPages.
I followed the instructions from this page, and everything compiled, but when I started the application I got a XamlParseException upon instanciateing the datapage (new SessionDataPage();) :

Position 7:15. No Property of name StyleClass found

I'm aware that Datapages are still in the preview channel, but still - this should work.

Additional Information:
Xaml:
<?xml version="1.0" encoding="utf-8" ?>

<p:ListDataPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:p="clr-namespace:Xamarin.Forms.Pages;assembly=Xamarin.Forms.Pages"
             x:Class="HoloTour.Pages.SessionDataPage"
              StyleClass="Events" Title="Sessions" >

  <p:ListDataPage.DataSource>
    <p:JsonDataSource Source="http://demo3143189.mockable.io/sessions" />
  </p:ListDataPage.DataSource>

</p:ListDataPage>

StackTrace:

  at Xamarin.Forms.Xaml.ApplyPropertiesVisitor.SetPropertyValue(Object xamlelement, XmlName propertyName, Object value, BindableObject rootElement, INode node, HydratationContext context, IXmlLineInfo lineInfo)

at Xamarin.Forms.Xaml.ApplyPropertiesVisitor.Visit(ValueNode node, INode parentNode)
     at Xamarin.Forms.Xaml.ValueNode.Accept(IXamlNodeVisitor visitor, INode parentNode)
     at Xamarin.Forms.Xaml.RootNode.Accept(IXamlNodeVisitor visitor, INode parentNode)
     at Xamarin.Forms.Xaml.XamlLoader.Load(BindableObject view, String xaml)
     at Xamarin.Forms.Xaml.XamlLoader.Load(BindableObject view, Type callingType)
     at Xamarin.Forms.Xaml.Extensions.LoadFromXaml[TView](TView view, Type callingType)
     at HoloTour.Pages.SessionDataPage.InitializeComponent()
     at HoloTour.Pages.SessionDataPage..ctor()
     at HoloTour.App..ctor()
     at HoloTour.UWP.MainPage..ctor()
     at HoloTour.UWP.HoloTour_UWP_XamlTypeInfo.XamlTypeInfoProvider.Activate_4_MainPage()
     at HoloTour.UWP.HoloTour_UWP_XamlTypeInfo.XamlUserType.ActivateInstance()

Edit:
If i remove the StyleClass from the Xaml file I get a TypeLoadException:

Method 'CanConvertFrom' in type 'Xamarin.Forms.Pages.JsonSourceConverter' from assembly 'Xamarin.Forms.Pages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

A: It turns out that the issue was with the references to Xamarin.Forms and Xamarin.Forms.Pages.
Initially, I have installed the nuget packages as described in the manual using the following commands:
Get-Project -all | Install-Package Xamarin.Forms.Pages -Version 2.3.0.107
Get-Project -all | Install-Package Xamarin.Forms.Theme.Base -Pre
Get-Project -all | Install-Package Xamarin.Forms.Theme.Light -Pre

After this did not work - I went into the Manage Packages for Solution (Right click on Solution -> Manage NuGet Packages for Solution), and updated the packages to the latest version.
I'm sure this is something that will be resolved once DataPages are no longer in the preview channel


text:
Q: Soft start for fridge compresser I live in an off grid property running on 6 12v batteries. We have a 2000w inverter and are trying to get a fridge to run on our system. We have enough power to run it however the issue I am having is on the initial start up the compressor draws around 100amps for around a second. This draw drops the voltage of the batteries to the point that anything else we were using (TV, computer) turns off and has to be rebooted.
I am looking into a soft start device to distribute that instant 100amp draw over a few seconds (such as this one https://www.jaycar.co.nz/240v-10a-motor-speed-controller-kit-with-soft-start/p/KC5526
I was wondering if anyone has any experience with this and if they believe that it will work or any other suggestions. My main concern is that the soft start will mess up the timing of the electric motor of the fridge and it will just stall out.
Thanks in advance!

A: The linked speed controller clearly states that it is for a universal motor and only a universal motor. A universal motor is a series-field type DC motor with brushes, that has been designed to run on either AC or Dc power. It is unlikely that a refrigerator will have a universal motor. If you can not see brushes and a commutator inside, or two round insulated covers for changing brushes, it is not a universal motor.
There are variable-voltage AC speed controllers that are designed to power fans and centrifugal pumps. The torque required to drive a fan or centrifugal pump increases in proportion to speed squared. They require very little torque to start and reach their maximum torque requirement at full speed. One of those might be able to to start a refrigerator, but it is rather unlikely.
Your best alternative is probably to buy an inverter that is designed to start an AC motor that has a hard-starting load. The fridge may need its own inverter. If the inverter you have can start the inverter, buy a second inverter for everything else.

A: If you mean 100 amps from the 12 volt batteries (in parallel, I assume), ~1,000 W out from the inverte, that is to be expected for a full-sized household refrigerator. The initial current draw for a refrigerator is high because the motor must turn over the compressor against gas pressure. There is no way to distribute that initial load over time, because enough force must be applied against the "springy" gas. In addition, household refrigerators consume a lot of energy over time, perhaps 1 kWh/day for a small, highly-efficient ("Energy Star") appliance to 5kWh for older models. How are you keeping those batteries charged?
Most likely, you need a smaller, more efficient refrigerator, e.g. one designed for a recreational vehicle, or more batteries, or perhaps a separate inverter with its own batteries.

A: The average household refrigerator uses a hermetically sealed single phase AC induction motor that uses a capacitor for starting. It is the charging of that capacitor that you are seeing as that 10x spike in current and after that, the motor will pull approximately 6x current until it gets to around 80-90% speed. That entire process usually takes a second or less, but if your system cannot supply it, you have the problem you are seeing.
An AC soft starter is not going to work for this, in fact there really isn't a solution because anything that interferes with that capacitor starting routine ultimately interferes with the motor starting at all. Even VFDs designed for SOME types of single phase motors will not work for this type, the capacitor charging current looks and acts like a short circuit to the VFD transistors and the VFD harmonics gets trapped in the starting capacitor, so it is a race to see which one fails first.
The viable solution, as mentioned by DrMoishe Pippik at the end of his first response, is to attain a new refrigerator designed to operate off-grid.

A: Just a thought, you might try a UPC backup (for computers) inline for the fridge.  These units have batteries and power conditioners. I believe that an APC1500 UPS can provide about 900 watts, which is about half of what a refrigerator requires to start.
Conversely, you could run your television and other sensitive equipment with the UPC inline.

A: A "soft start", even if appropriate for the motor, will only lead to a stall of the compressor. You will need an inverter (and batteries) capable of handling the start-up surge.
It's possible that there are special fridges that have less start-up surge designed for your application and similar ones such as RVs.

A: Soft starter is the one which slowly changes the applied voltage  to an induction motor which results in reduction of electrical surge current of motor during starting.
The product is an Universal motor speed controller.
soft starting is just an another method of starting an induction motor. it will not change any of its operating parameters

A: No it won't cost I tried it ....your best bet and it's the only possible way is to add an 12v capacitor bank before your inverter.
Checkout lasersaber's youtube channel ~ he uses high induction power tools directly from portable solar panels via a super capacitor bank and inverter.....that system could also be incorporated into your existing system too.
https://youtu.be/eJ1OztoGprU


text:
Q: Use of present participles and past tense in literature I'm interested in stylistic differences between the use of participles and the past tense in literary writing. Here's a simple example phrase:
"Since becoming a chef..."
"Since he became a chef..."
Does the participle connote more movement and action? Is that the only stylistic difference?

A: In a comment John Lawler wrote:

The participle connotes a shorter phrase, with no subject (which must be located in context), while the clause indicates the subject and relates it to the verb. There is no difference otherwise; the distinction is entirely one of individual style, with no consequences except differentiation of one style from another.


text:
Q: Make leading and trailing spaces in an input field visible In an input field used for filtering, I want to honor leading and trailing spaces as they're relevant. In angularjs, this is easily done with ng-trim=false, but how can I make them visible, so that the user doesn't get confused by a forgotten space?
Explanations:
Trailing spaces are obviously relevant for filtering as "in " doesn't match the "input", while plain "in" does.
A trailing space in an input field is invisible as you can easily find out. I'd like something like colored background for the text part or any other not too intrusive way of highlighting.

A: You can keep differently styled divs side by side in a container overlapped by a transparent input. Modify the widths of the styled divs on the basis of your input entry.

  <input id="inpt" type="text" ng-model="input.text" ng-trim="false" placeholder="Add leading/trailing spaces" ng-change="inputChanged()" maxlength="20" />

The three divs inside the container will change their width with input change and you can color the divs for leading and trailing spaces differently.
Working Angular example in jsfiddle: http://jsfiddle.net/TalhaAwan/8b3xzd38/ (tested with chrome only)


text:
Q: Angular / Firebase / Typescript Interfaces - How to manage interface type of firebase.firestore.FieldValue with toDate() I have an interface where the date is set to work with firestores timestamps.
    export interface Album{
        album_name: string,
        album_date: firebase.firestore.FieldValue;
    }

If I wanted to add a new item, this works perfectly fine
    this.albumsCollection.add({
        album_name: "My Album",
        album_date: firebase.firestore.FieldValue.serverTimestamp(),
     })

Getting the album document from firestore
However, upon retrieving an album Document from firestore, the code below will work fine if i exclude the album_date. However, I'm attempting to use toDate so that it appears in the Angular Material Date Picker
  public getAlbum(): Observable<Album> {
    this.itemDoc = this.afs.doc<Album>(`albums/1`);
    return this.itemDoc.snapshotChanges()
      .pipe(map(collectionDoc => {
        const data = collectionDoc.payload.data();
        return {
          ...data,
          album_date: (data.album_date as firebase.firestore.Timestamp).toDate(),
        } as Inspection;
      }),
        shareReplay()
      );
  }

The error received on the line: album_date: (data.album_date as firebase.firestore.Timestamp).toDate(), is the following:

Conversion of type '{ album_Date: Date; }' to type 'Album` may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Types of property 'album'_date are incompatible.
Property 'isEqual' is missing in type 'Date' but required in type 'FieldValue'.

What's the best way to manage using 'toDate' on a returned firestore timestamp, when the interface is also configured for firestore?

A: There are at least two ways you manage this.  Since questions seeking opinion are off-topic for Stack Overflow, you can decide for yourself which one is best for your case.
You could have two different Album interfaces, one for reading and one for writing.  The one for writing can use the FieldValue type, and the one for reading can use the Timestamp type.
You could also use TypeScript's union type to say that album_date can be either a FieldValue or a Timestamp.
album_date: firebase.firestore.FieldValue | firebase.firestore.Timestamp

That should allow you to cast the individual field as you see fit.


text:
Q: How do I make a form submit work when button disappears on onBlur event? React, next js I have a form which performs an event on submit.
The form contains a textarea, that when you click on it, the submit button appears, and when you click out it disappears (using onFocus and onBlur for this to flag variable 'showSubmit'):

<form id="commentsForm" onSubmit={handleSubmitForm}>
      ...
         <textarea
             onFocus={onFocusShowSubmit}
             onBlur={onBlurHideSubmit}
             id="comment" name="comment" type="text" required></textarea>

         {showSubmit
             ?
             <button type="submit">Post Comment</button>
             : null}
</form>

The onBlur event is blocking the button to be clicked and therefore to submit the form.
I read about using onMouseDown event in the button, and it does work, but it does not capture the form event. And I really need to pass the form event to the "handleSubmitForm" to be able to retrieve the form data..
Does anybody know how I could work this out?
Thanks!

A: I reproduced this and solved it this way:
import React, { useState } from "react";

function Q1() {
  const [showSubmit, setShowSubmit] = useState(false);
  const [text, setText] = useState();

  const onFocusShowSubmit = () => {
    setShowSubmit(true);
  };

  const handleSubmitForm = (e) => {
    alert("Form Sent");
  };
  return (
    <div>
      <form id="commentsForm" onSubmit={handleSubmitForm}>
        ...
        <textarea
          onFocus={onFocusShowSubmit}
          onBlur={
            text && text.length >= 1
              ? () => setShowSubmit(true)
              : () => setShowSubmit(false)
          }
          id="comment"
          name="comment"
          type="text"
          required
          onChange={(e) => setText(e.target.value)}
        >
          {text}
        </textarea>
        {showSubmit ? <button type="submit">Post Comment</button> : null}
      </form>
    </div>
  );
}

export default Q1;


text:
Q: What is the equivalent tensorflow operation of this numpy array operation? So, for example, y_pred is a numpy array and I want this operation.
result = []
for i in y_pred:
    i = np.where(i == i.max(), 1, 0)
    result.append(i)

The maximum number of each row in y_pred will become 1 and the rest will become 0.
How can I implement this operation if y_pred is a tensor?

A: Not sure if there is a vectorized function already available that does all these things together.
Assume this is your array.
a = tf.Variable([[10,11,12,13],
             [13,14,16,15],
             [18,16,17,15],
             [0,4,3,2]], name='a')

top = tf.nn.top_k(a,1) gives the indices of the maximum values in each row. Now we start with ones acopy = tf.Variable(tf.zeros((4,4),tf.int32), name='acopy')  which is the same shape as the original array.
After that we just stitch the rows together after replacing zeros in the positions where maximum values were found.
import tensorflow as tf

a = tf.Variable([[10,11,12,13],
                 [13,14,16,15],
                 [18,16,17,15],
                 [0,4,3,2]], name='a')

acopy = tf.Variable(tf.zeros((4,4),tf.int32), name='acopy')

top = tf.nn.top_k(a,1)

sess = tf.Session()

sess.run(tf.global_variables_initializer())

values,indices = sess.run(top)

shapeofa = a.eval(sess).shape

print(indices)

sess.run(tf.global_variables_initializer())

for i in range(0, shapeofa[0] ) :
    oldrow = tf.gather(acopy, i)
    index = tf.squeeze(indices[i])
    b = sess.run( tf.equal(index, 0) )
    if not b  :
        o = oldrow[0:index]
        newrow = tf.concat([o, tf.constant([1])], axis=0)
        c = sess.run(tf.equal(index, (tf.size(oldrow) - 1)))
        if not c:
            newrow = tf.concat([newrow, oldrow[(index+1):(tf.size(oldrow))]], axis=0)
    else :
        o1 = oldrow[1:tf.size(oldrow)]
        newrow = tf.concat([tf.constant([1]), o1], axis=0)
    acopy = tf.scatter_update(acopy, i, newrow)
    print(sess.run(acopy))

The output is this.

[[0 0 0 1]
[0 0 1 0]
[1 0 0 0]
[0 1 0 0]]

You may test this yourself.


text:
Q: SQL column maximum input values hi please how do i give sql column maximum input example if i want max_num column to take only three(3) result sets or inputs

A: It's mostly the same in other rdbms. You need to specify right after the column type
MYSQL
CREATE TABLE TestTable(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
three_char_demo VARCHAR(3) NOT NULL,
)

PostgreSQL
CREATE TABLE TestTable(
   ID INT PRIMARY KEY     NOT NULL,
   three_char_demo CHAR(3) NOT NULL,
);


text:
Q: Extract certain files from .zip Is there a way to selectively extract from a .zip archive those files with names matching a pattern?
For example, if I want to use all .csv files from the archive and ignore other files.
Current approach:
zipped_file_names <- unzip('some_archive.zip') # extracts everything, captures file names
csv_nms <-  grep('csv', zipped_file_names, ignore.case=TRUE, value=TRUE)
library('data.table')
comb_tbl <- rbindlist(lapply(csv_nms,  function(x) cbind(fread(x, sep=',', header=TRUE,
                                                               stringsAsFactors=FALSE),
                                                         file_nm=x) ), fill=TRUE )

Instead of just selecting which ones to read (csv_nms), I'm looking for a way to choose which ones to extract in the first place.
I'm currently on v3.2.2 (Windows).

A: Thanks to comment from  @user20650.
Use two calls to unzip.  First with list=TRUE just to get the $Name for the files.  Second with files= to extract only the files whose names match the pattern.
  zipped_csv_names <- grep('\\.csv$', unzip('some_archive.zip', list=TRUE)$Name,
                           ignore.case=TRUE, value=TRUE)
  unzip('some_archive.zip', files=zipped_csv_names)
  comb_tbl <- rbindlist(lapply(zipped_csv_names,
                               function(x) cbind(fread(x, sep=',', header=TRUE,
                                                       stringsAsFactors=FALSE),
                                                 file_nm=x)), fill=TRUE )


text:
Q: How can I use ListLogLinearPlot to plot wildly different functions? I have two sets of points I need to ListLogLinearPlot plot:
{{1,10},{10,-20},{100,55},{1000,5000}}
{{1,0.8},{10,2},{100,-0.58},{1000,15}}

How can I plot them together with ListLogLinearPlot? The second will be an almost flat line around 0.

A: Update: Combining all steps in a function that works like ListLogLinearPlot:
ClearAll[listLogLinearPlot]

listLogLinearPlot = Module[{r1 = MinMax[#[[1, All, 2]]], r2 = MinMax[#[[2, All, 2]]]},
  ListLogLinearPlot[{#[[1]], Transpose[{#, Rescale[#2, r2, r1]} & @@ Transpose[#[[2]]]]},
   Frame -> True, FrameTicks -> {{Automatic, Charting`FindTicks[r1, r2]},
      {Automatic, Automatic}}, ##2]] &;

Example:
listLogLinearPlot[{l1, l2}, Joined -> True, PlotStyle -> {Thickness[.015], Thick},
   PlotLegends -> {"l1", "l2"}, ImageSize -> 500]

Original answer:
l1 = {{1, 10}, {10, -20}, {100, 55}, {1000, 5000}};
l2 = {{1, 0.8}, {10, 2}, {100, -0.58}, {1000, 15}};

Find the vertical ranges of l1 and l2:
{vrange1, vrange2} = MinMax[#[[All, 2]]] & /@ {l1, l2};

Rescale the second column of l2 to the vertical range of l1:
l2b = Transpose[{#, Rescale[#2, vrange2, vrange1]} & @@ Transpose[l2]];

Use ListLogLinearPlot with {l1, l2b} as input and the function Charting`FindTicks[vrange1, vrange2] to get the ticks for the right frame:
ListLogLinearPlot[{l1, l2b}, Joined -> True, Frame -> True,
 PlotStyle -> {Directive[Thickness[.02], Red], Blue},
 FrameTicks -> {{Automatic, Charting`FindTicks[vrange1, vrange2]}, {Automatic, Automatic}},
 PlotLegends -> {"l1", "l2"}, ImageSize -> Medium]

A: Here's a quick hack borrowed from the how-to on two-axis plotting:
list1 = {{1, 10}, {10, -20}, {100, 55}, {1000, 5000}};
list2 = {{1, 0.8}, {10, 2}, {100, -0.58}, {1000, 15}};

Module[{f = Interpolation[list1, InterpolationOrder -> 1],
  g = Interpolation[list2, InterpolationOrder -> 1]},
 LogLinearPlot[f[x], {x, Min@list1, Max@list1}];
 LogLinearPlot[f[x], {x, Min@list2, Max@list2}];
 TwoAxisPlot[{f[x], g[x]}, {x, 0, Max@list2}]]

TwoAxisPlot[{f_, g_}, {x_, x1_, x2_}] :=
 Module[{fgraph, ggraph, frange, grange, fticks,
   gticks}, {fgraph, ggraph} =
   MapIndexed[
    Plot[#, {x, x1, x2}, Axes -> True,
      PlotStyle -> ColorData[1][#2[[1]]]] &, {f, g}]; {frange,
    grange} = (PlotRange /.
        AbsoluteOptions[#, PlotRange])[[2]] & /@ {fgraph, ggraph};
  fticks = N@FindDivisions[frange, 5];
  gticks =
   Quiet@Transpose@{fticks,
      ToString[NumberForm[#, 2], StandardForm] & /@
       Rescale[fticks, frange, grange]};
  Show[fgraph,
   ggraph /.
    Graphics[graph_, s___] :>
     Graphics[
      GeometricTransformation[graph,
       RescalingTransform[{{0, 1}, grange}, {{0, 1}, frange}]], s],
   Axes -> False, Frame -> True,
   FrameStyle -> {ColorData[1] /@ {1, 2}, {Automatic, Automatic}},
   FrameTicks -> {{fticks, gticks}, {Automatic, Automatic}}]]

A more straightforward approach might be to normalize and scale the data to a common range and add custom FrameTicks to the left and right sides. Check out Standardize.


text:
Q: Curl command not working properly on Robot Framework with Process Library I have to program an automated test for a POST request, i'm using curl command because said post needs a CSV file to include or exclude fields to search, the thing is that, although the following command works fine on Ubuntu terminal, in Robot Framework this happens:

OSError: [Errno 2] No such file or directory

My Robot Framework code is (it's just a test to familiarize with the method):
*** Settings ***
Library     Process

*** Variables ***
${command}  curl -X POST "http://10.0.0.85:7173/v1/performance/custom/games?gameId=2019101308&isExclusion=false&teamId=2510" -H  "accept: */*" -H  "Content-Type: multipart/form-data" -F "file=@file;type=text/csv"s

*** Test Cases ***
Test Get endpoint
    ${test}=    run process     ${command}

The command is generated by Swagger (i do my manual tests there), i dont know where i can be failing, the file is in the same directory as the .robot file