text:
Q: What is the equivalent of  with Django form I am trying to input results from Autocomplete in (a.js file) into a Django form (html).
Currently the html file looks like this:
Template:
<input class="field" id="street_number" disabled="true" />

Obvioulsy, I cannot input directly {{form.street_number}}. I have found a few posts on the topic, (in particular this one: How to get form fields' id in Django), but I am not too sure to understand how this solves the problem.
.js file
 function initAutocomplete(){
      autocomplete = new google.maps.places.Autocomplete(document.getElementById("autocomplete"),{
        componentRestrictions: {'country':['uk']},
        fields: ['name','geometry','address_components'],
        types:['establishment','geocode']
      });

       autocomplete.addListener('place_changed', fillInAddress );
    }

    function fillInAddress(){
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();
        //showsdiffrent address components (click on 'inspect' on webpage to see)
        console.log(place);

         document.getElementById('business').value = place.name;
            //loop through address components detailed in consol
            for (let i = 0; i < place.address_components.length; i++) {
              for (let j = 0; j < place.address_components[i].types.length; j++) {
                ...
                if (place.address_components[i].types[j] === "street_number") {
                document.getElementById('street_number').value = place.address_components[i].short_name;
                } ...

I suppose the question is how do I translate <input id="id"> into django form terms? Maybe there is a possibility to apply an id in the django form.py itself?
I tried a solution found on here, but I am getting an error saying TextInput is not defined.
forms.py:
 class VenueForm(ModelForm):
        address = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput())

        class Meta:
            model = Venue
            fields = ['address']

        def __init__(self, *args, **kwargs):
                super(VenueForm, self).__init__(*args, **kwargs)
                self.fields['address'].widget = TextInput(attrs={
                    'id': 'street_number'})

A: I believe you are using id wrong:
<input class="field" name="my_test_name" value="my_test_value" id="street_number" disabled="true" />

in this example above:
id works for your html, css, and javascript to identify this particular input. You dont need id atribute with django, only with frontend.
In case you want to recieve data in django, for example you use this input in a form with POST request, you can identify this input via name, and recieve its value (from value atribute)
def my_function_name(request):
    my_value = request.POST['my_test_name']
    print(my_value)
    #output will be >> my_test_value

Also you don't need to override your ModelForm, you can add this input below your form, and it will be working

A: Ok, so here is the solution I worked out.
Reading different posts, there is probably more sophisticated ways to address the problem, but this one worked for me. It might also be more beneficial for other beginners like me, as this solution is easy to understand.
I basically created an id for each form field in the forms.py. Without this id in the forms, django did not make the link between the assigned ID in the .js file and the form field in the template.
forms.py
class VenueForm(ModelForm):
    street_number = forms.CharField(max_length=100, label = '', widget = forms.TextInput(attrs={'id':"street_number"}))

template
 <form id="venueform" method="POST">
    {% csrf_token %}
    {{ form|as_crispy_errors }}

    <td class="label">Street Number </td>
    {{form.street_number| as_crispy_field}} </form>

.js file (not changes)
function initAutocomplete(){
      autocomplete = new google.maps.places.Autocomplete(document.getElementById("autocomplete"),{
        componentRestrictions: {'country':['uk']},
        fields: ['name','geometry','address_components'],
        types:['establishment','geocode']
      });

       autocomplete.addListener('place_changed', fillInAddress );
    }

    function fillInAddress(){
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();
        //showsdiffrent address components (click on 'inspect' on webpage to see)
        console.log(place);

         document.getElementById('business').value = place.name;
            //loop through address components detailed in consol
            for (let i = 0; i < place.address_components.length; i++) {
              for (let j = 0; j < place.address_components[i].types.length; j++) {
                ...
                if (place.address_components[i].types[j] === "street_number") {
                document.getElementById('street_number').value = place.address_components[i].short_name;
                } ...


text:
Q: Unreadable text at native resolution 2560x1440 I have a BenQ GW2765HT monitor (specifications) connected to an AMD Radeon R5 230 graphics card (specifications, driver: 15.200.1046.0). When I change the resolution to the native monitor resolution of 2560x1440 the text is unreadable. Why? Do I have to change the graphics card? If yes, what should I look for?
OS: Windows 7 Professional Service Pack 1. Cable: DVI-D Single Link.

A: You're using a Single-Link DVI cable. This is not enough for 2560×1440@60Hz:

Single link DVI employs a single 165 MHz transmitter that supports resolutions up to 1920 × 1200 at 60 Hz.

(Wikipedia)
You'll have to get a Dual-Link cable. IIRC there's no way of detecting the cable type, so the monitor just won't receive all the data, resulting in a corrupted image.

A: Use another cable.
Duel link DVI or DisplayPort
DVI single link support
(1440 × 900) @ 60 Hz.

A: I have found an article
(Dutch) where it says this about your graphic adapter:
Maximale resolutie:     2560x1600 (WQXGA)

According to Wikipedia in Digital Visual Interface, WQXGA is a display mode available in dual link
only.
If you are using a single-link DVI cable, and your card can only achieve
the resolution of 2560x1440 using WQXGA which is a dual-link mode,
then it is clear where is the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Perl remove multiple line that match regex I have a file that looks like this:
*
TEST CASE1,
$ some text unque633
PLACEMENT 123
*
TEST CASE2,
$ some text unque759
PLACEMENT 321
*
TEST CASE3,
$ some text unque966
PLACEMENT 856
*

I want to remove multiple lines that match regex. For example, need to remove starting from TEST CASE2 until the line begining with *. How can this be done within perl script.
Also, how would I edit text from TEST CASE2 if I only know unque759.
Much appreciated.

A: Desired goal can be easily achieved with following algorithm: read all data into a variable, substitute block 'TEST CASE2.....' before next '*' to nothing, output result
use strict;
use warnings;
use feature 'say';

my $data = do { local $/; <DATA> };     # read all data at once

$data =~ s/TEST CASE2[^*]*//s;          # substitute requested block with nothing

say $data;

__DATA__
*
TEST CASE1,
$ some text
PLACEMENT 123
*
TEST CASE2,
$ some text
PLACEMENT 321
*
TEST CASE3,
$ some text
PLACEMENT 856
*

Output
*
TEST CASE1,
$ some text
PLACEMENT 123
*
*
TEST CASE3,
$ some text
PLACEMENT 856
*

A: This will remove blocks beginning with TEST CASE2,, ending with * and containing unque759
cat file.txt
*
TEST CASE1,
$ some text unque633
PLACEMENT 123
*
TEST CASE2,
$ some text unque759
PLACEMENT 321
*
TEST CASE2,
$ some text unque999
PLACEMENT 321
*
TEST CASE3,
$ some text unque966
PLACEMENT 856
*

perl -0777 -ape 's/TEST CASE2,[^*]+?\bunque759\b[^*]+?\*(?:\R|\z)//' file.txt
*
TEST CASE1,
$ some text unque633
PLACEMENT 123
*
TEST CASE2,
$ some text unque999
PLACEMENT 321
*
TEST CASE3,
$ some text unque966
PLACEMENT 856
*

Explanation:
-0777            # "slurp" mode, read the file in a single string
s/               # substitute
    TEST CASE2,     # literally
    [^*]+?          # 1 or more non asterisk, not greedy
    \b              # word boundary
    unque759        # literally
    \b              # word boundary
    [^*]+?          # 1 or more non asterisk, not greedy
    \*              # an asterisk
    (?:\R|\z)       # non capture group, end of line OR end of string
//               with nothing


text:
Q: Cordova cannot find plugins in Netbeans I used nodejs to install cordova version '3.5.0-0.2.7'.  The app compiles fine in netbeans.  I have a plugins folder at the same level as the www folder.  When I run the app I get a message for all of my plugins.
Failed to load resource: net::ERR_EMPTY_RESPONSE (11:09:29:715 | error, network)
  at
http://localhost:8383/AppName/plugins/de.appplant.cordova.plugin.local-notification/www/local-notification.js

It is looking for the plugins folder, but the files are in the js folder.  How do I have it point to this folder?


text:
Q: Вывод переменной при условии в Smarty - как оптимальней? Есть меню навигации

Необходимо вывести active при условии, если url = 123

Эта запись оптимальна?


text:
Q: Use a directive or component in the content prop using Tippy.js I am trying to figure out how to incorporate a directive or component with corresponding styling and data into the content prop of a Tippy.js object. I want to have this to give me the flexibility on working on the content and behavior as well as the styling of the respective tooltips. I want to setup a tooltip for each node of a graph I built using Cytoscape.js.
I have found this page here explaining me how I can incorporate Tippy.js into Cytoscape.js Nodes.
I have followed this example, but instead of adding inline elements inside of the content prop of a Tippy object, I wanted to add a directive or component.
So instead of creating inline elements here, as shown in the example on the page mentioned above:
content: () => {
  let content = document.createElement('div');
  content.innerHTML = 'Tippy content';
  return content;
}

I want it something along the lines of this, creating a directive or component:
content: '<input tippy [tippyOptions]="{}" class="search-input" type="text">',

I have found an example on SO which shows such an approach, it is this page.
I followed this example, and create now for each Tippy.object a dynamic directive inside of the content prop:
  const nodeReference = node.popperRef(); // used only for positioning
  // A dummy element must be passed as tippy only accepts dom element(s) as the target
  // https://atomiks.github.io/tippyjs/v6/constructor/#target-types
  const domElement = document.createElement('div');

  node.toolTip = Tippy(domElement, {
      getReferenceClientRect: nodeReference.getBoundingClientRect, // https://atomiks.github.io/tippyjs/v6/all-props/#getreferenceclientrect
      content: '<input tippy [tippyOptions]="{ arrow: true, createPopperInstanceOnInit: true }" class="search-input" type="text" (keyup)="searchInputKeyDown($event)">',
      allowHTML: true,
      appendTo: document.body
  });

My directive looks like this as in the example above on mentioned SO page:
import { Directive, Input, OnInit, ElementRef } from '@angular/core';
import tippy from 'tippy.js';

@Directive({
  /* tslint:disable-next-line */
  selector: '[tippy]'
})
export class GraphTooltipDirective implements OnInit {

  @Input('tippyOptions') public tippyOptions: Object;

  constructor(private el: ElementRef) {
    this.el = el;
  }

  public ngOnInit() {
    tippy(this.el.nativeElement, this.tippyOptions || {});
  }
}

This seems to be working, it does add the directive correctly, however, it only shows me an empty input field when hovering over the respective area, as it can be seen here:

What I would like to understand is now. How do I use styling with this directive now inside of the directive to style the tooltip appropriately? Also, how do I use the Tippy.js props correctly inside of the directive?


text:
Q: cookies, sessions , and security I came up with my own way to protect the moderators on my site. First, I know that a hacker could hijack my session. So what I did was to add a cookie to the moderator and set my algorithm on how to set and unset those cookies.
First, precaution that I took is this when the moderator logs in:
        if('Moderator'==is_monitor($name))//function finds who is the user
        {
            ini_set('session.use_only_cookies',true);
            session_start();
            $password_hash = hash('sha256',$salt.hash('sha256', $pass));
            $_SESSION['mod_identify']=$password_hash;
            if(!isset($_Cookie['adderss']))
            {
              setCookie("adderss",$ip_address,time()+60*60*24*365*5,"/");
            }

Then I use this to reset the sessions on every page:
if(!isset($_SESSION))
{
   start_session(); // all sessions should be reset with a new id
}

The question is whether setting a cookie for many pages is a burden on the moderator?!?
Do you think that my way is secure enough against session/cookie hijacking?

A: No. Use HTTPS - which uses SSL - if you want to prevent session hijacking. Also, never store the password of some user's account in the session if that's what $pass is.
Alternatively, you could use a Session wrapper class like this one. Note that this will not protect against session hijacking, rather it simply encrypts the data stored therein.
Also, unless you've created your own custom function named "start_session()", then session_start() is the function you want to call to start sessions.
If you want to redirect users to HTTPS, you can do it with apache's mod_rewrite in your .htaccess file like so:
RewriteCond %{REQUEST_URI} =/admin
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}%{REQUEST_URI}

Or something similar, depending on where you want users to be using secure sockets layer.


text:
Q: $watch in an array to avoid duplicates I have a form where with ngmodel I do an array,
I want to watch ngmodel (array) to avoid that between input text would have duplicates

this would be an input
<md-input-container md-theme="default" class="col-xs-3 col-sm-3 col-md-3 col-lg-3" style="padding:0; margin-top: 0;">
            chairs
            <input
            type="text"
            name="chairs"
            id="chairs"
            ng-model="data.home.chairs"
            required
            changeinput
            ng-maxlength="10"
            ng-minlength="10"
            maxlength="10"
            md-maxlength="10"
            ng-pattern="/^[2]{0,1}[m|M]{0,1}[2]{0,1}[a-zA-Z0-9]{0,7}$/"
            />

Required 2M26123200

        </md-input-container>

this wolud be the watch
,$scope.data will be bounded to ngmodel
$scope.data = {};

        $scope.$watch('data', function (newValue, oldValue) {
          // check duplicates in ngmodel
        }, true);

but I dont know in deep how to use $watch to this case


text:
Q: Counting Overlaps of Integer Ranges I've been stumped on this algorithm for quite a bit.
Say there are four ranges of integers.  Each range has a Start and an End value.
Range A: 0,5
Range B: 4,12
Range C: 2,10
Range D: 8,14

From these values I would like to get a new set which counts of the number of the ranges that fall in a particular span of ints.  Each of these would have Start, End and Count values, producing something like this:
(Start, End, Count)
0,1,1   (Only 1 range (A) falls between 0 and 1 inclusive)
2,3,2   (2 ranges (A,C))
4,5,3   (3 ranges (A,B,C))
6,7,2   (2 ranges (B,C))
8,10,3  (3 ranges (B,C,D))
11,12,2 (2 ranges (B,D))
13,14,1 (1 range (D))

Does that make sense?  What's a good way to approach the algorithm?

A: You can solve this in O(N ln N) time (for sorting) followed by the same amount of time for outputting results.  If the number range is large,  O(N ln N) is better than the O(M·N) time of the method suggested in a comment (where M = total range of numbers covered by the ranges).
Sort the N ranges into ascending order, keyed by Start value, say in array S.  Initialize an empty priority queue P.  Initialize a depth-count D to zero, and the current  "reach" to R = S[0].Start.
While S[i].Start=R, push S[i].End on P and advance i and D.  When S[i].Start>R, yield the tuple (R, p.top, D).  Pop P to R and then decrease D by one and pop P while P.top==R.
Repeat the above paragraph while i<N.

A:

const ranges = {
  A: [10, 12],
  B: [20, 30],
  C: [29, 31],
  D: [15, 95],
  E: [195, 196]
};

let overlaps = {},
    keys = Object.keys(ranges),
    values = Object.values(ranges),
    i, j;

for (i = 0; i < values.length; i++)
  for (j = 0; j < values.length; j++)
    if (keys[i] !== keys[j] &&           // skip same item
        values[i][0] < values[j][1] &&   // overlap check
        values[j][0] < values[i][1])     // overlap check
      overlaps[keys[i]] = 1;

console.log( Object.keys(overlaps) )

A: A range x intersects the input range y if:
x.End >= y.Start AND y.End >= x.Start

So, for a given input, just loop through your collection of ranges and see which satisfy the above condition.
If your given collection of ranges doesn't change very often, and your collection of ranges gets much larger than the 4 you stated in the problem description, then sort them first so that you can more efficiently search for the ranges that intersect your input, rather than looping through all of them.
If the given collection of ranges changes often, the sorting could be too expensive, and it would then be smarter to just loop through all of them each time.


text:
Q: vbscript for executing oracle procedure I have a script (not my own) for executing oracle procedure in vbscript. It doesn't work. I set my DSN, user, password etc. ... script run, but procedure didn't run. Please can you correct this script?

'Vbsript to execute a Oracle PL/SQL Procedure

Rem Name of the PROCEDURE
Dim strProc  : strProc ="POPULATE_EMP_DATA"
Rem Name of the DB SCHEMA
Dim strSchema : strSchema = "bhive_report"

'########## TARGET DB DSN
Dim TargetDSN : TargetDSN  = "devDSN"
Dim TargetDBuser : TargetDBuser = "devUSER"
Dim TargetDBpwd : TargetDBpwd = "devPASS"

Call runPROC(TargetDSN,TargetDBuser,TargetDBpwd,strProc,strSchema)

Rem Sub Routine to Execute Stored Procedure
Rem Generic accepts DSN name, username, password and procedure name.
Sub runPROC(vDSN,vUser,vPass,vProc,vSchema)
On Error Resume Next
Const adCmdStoredProc = 4
Dim strTargetConnection : strTargetConnection = "DSN=" & vDSN & ";uid=" & vUSER & ";pwd=" & vPASS&";"
Set objConn = CreateObject("ADODB.Connection")
objConn.Open strTargetConnection : Rem [ opening Target ORACLE connection ]
Set CmdStoredProc = CreateObject("ADODB.Command")
With CmdStoredProc
Set .ActiveConnection=objConn
  .CommandText= vSchema & "." & vProc
  .CommandType=adCmdStoredProc
  Set rsProc = .Execute
  If Err.Number  0 then
      msgbox "[ERROR]" & Err.Description
    Else
      msgbox "Executed Procedure Succesfully - " & .CommandText
  End If
End With
End Sub


text:
Q: "Possible duplicate"-comments removed after closure, even when edited I close-voted this question and edited the auto-generated comment after that.
Now the question is closed and the comment is removed. I read here on meta that such comments would stay if EditCount is not null, but that doesn't seem to be the case anymore since at least a few weeks.
Was this change intentional?
While on the subject: can the generated comment be made to look more like a proper sentence, especially with a capital P for Possible and a period on the end?

A: I have never heard of the edit count affecting comment removal.
When a question is closed as a duplicate, any comments containing a link to the closed question are removed. Additionally, such a comment is only generated when none exists in the comments already.
Those are the only two rules I've heard of concerning possible duplicate comments. The claim you are referring to is talking about comment, not question edits. This means that the comment is not deleted if it has been edited, but if the question was edited, it will still be deleted.


text:
Q: how to do an iterative process for a fortran subroutine I have a fortran code that computes the solution vector using the thomas algorithm subroutine.
I want the solution vector to run in a loop for a certain number of time.
How do i call this subroutine in the loop?
my subroutine is the thomas algorithm subroutine.
It returns the solution vector u but I want it to use the vectors NN times in a loop. So the old u becomes the new u to use in the subroutine.
How do I do this?
Below is the what i tried
program thomasalg2
implicit double precision(A-H,O-Z)

real*8, dimension(9,1) :: a,b,c,r,u,uold!the dimension is subject to change depending on the size of the new matrix
!real*8, dimension(9,50) :: W
real*8 :: pi
real*8 :: h,k,lm,l,T
integer :: i,j,al,NN,n

l = 1!right endpoint on the X-axis
n = 9 !number of rols/cols of the coefficient matrix with boundaries included
T = 0.5 !maximum number of the time variable
NN = 50!number of time steps
np = n

h = l/n
k = T/NN
al = 1.0D0 !alpha
pi = dacos(-1.0D0)
lm = (al**2)*(k/(h**2)) !lambda

do i = 1,n
    r(i,1) = sin(pi*i*h) !this is W_0
end do

a(1,1) = 0.0D0
do i = 2,n
    a(i,1) = -lm
end do

do i = 1,n
    b(i,1) = 1 + (2*lm)
end do

c(9,1) = 0.0D0
do i = 1,n-1
    c(i,1) = -lm
end do

!the 3 diagonals are stored in the 1st, 2nd, 3rd & 4th files respectively.
open(10, file = 'thom1.txt')
open(11, file = 'thom2.txt')
open(12, file = 'thom3.txt')
open(13, file = 'thom4.txt')

write(10,*)
do i = 1,n
    write(10,*) a(i,1)
end do

write(11,*)
do i = 1,n
    write(11,*) b(i,1)
end do

write(12,*)
do i = 1,n
    write(12,*) c(i,1)
end do

write(13,*)
do i = 1,n
    write(13,*) r(i,1)
end do

open(14, file = 'tridag2.txt')

write(14,*)

n = 9

do i = 1,n
    write(14,*) a(i,1),b(i,1),c(i,1),r(i,1) !write the given vectors in the file in the form of a column vector
end do

call tridag(a,b,c,r,u,n)

!solve the given system and return the solution vector u
do i = 1,NN
    call tridag(a,b,c,r,u,n)
    !write(15,*) u
    r = u
end do

open(15, file = 'tridag2u.txt')

write(15,*)
!write the solution vector in the form of a column vector
do i = 1,n
    write(15,*) u(i,1)
end do

!print *, "Your data has been written in 'tridag2.txt'"

end program thomasalg2
subroutine tridag(a,b,c,r,u,n)
    implicit double precision (A-H, O-Z)
integer n, NMAX
real*8 a(n), b(n), c(n), r(n), u(n)
parameter (NMAX = 500)

integer j
real*8 bet, gam(NMAX)
if(b(1).eq.0.) stop "tridag: rewrite equations"
bet = b(1)
u(1)=r(1)/bet
do j = 2,n
    gam(j) = c(j-1)/bet
    bet = b(j)-a(j)*gam(j)
    if (bet.eq.0.) stop "tridag failed"
    u(j) = (r(j)-a(j)*u(j-1))/bet
end do
do j = n-1,1,-1
    u(j) = u(j)-gam(j+1)*u(j+1)
end do
!print *, "The solution is", u
return

end subroutine


text:
Q: Removing variable if not filled out I'm trying to make a reference generator. People fills in some information, and then the generator sets up the text in the right way. Here's what I've got so far:
    $('#ref-button1').click(function () {
    var authorname = $('#bookAuthor').val();
        if (authorname == "") {
             $('.error').show();
             return false;
         }
    var booktitle = $('#bookTitle').val();
        if (booktitle == "") {
             $('.error').show();
            return false;
         }
    var year = $('#bookYear').val();
        if (year == "") {
             $('.error').show();
            return false;
         }
    var place = $('#bookPlace').val();
        if (place == "") {
            $('.error').show();
            return false;
         }
    var publisher = $('#bookPublisher').val();
        if (publisher == "") {
             $('.error').show();
            return false;
         }
    var edition = $('#bookEdition').val();
    var page = $('#bookPage').val();
    var completeString1 = authorname + ' ' + '(' + year + '),' + ' ' + '' + booktitle + '' + ', ' + edition + ' ed., ' + place + ': ' + publisher + ', ' + page;

    $('.error').hide();
    $('#output').empty();
    $('#output').append(completeString1);
});

As you see, I have 5 variables that have to be filled out, and 2 that don't. I create the entire string in completeString1, where I also put in the commas and so on. I know this is probably not the easiest way to do, but it is how I could do it. My problem now, is that my completeString1 will still contain and print "ed.," even if I don't fill out the variable.
So my question is: How can I leave out that bit of the variable, given that it is not filled out?

A: What I got is that you have problem with "edition" variable. So you need to change the way you assign the value to it:
var edition = $('#bookEdition').val() != "" ? ($('#bookEdition').val() + ' ed., ') : "";

And then, update completeString1 setting to:
var completeString1 = authorname + ' ' + '(' + year + '),' + ' ' + '' + booktitle + '' + ', ' + edition + place + ': ' + publisher + ', ' + page;

A: You can use the conditional operator:
(edition?' ed., ':'')

If edition is true it will return the first value after the questionmark, else the value after the colon.
This will work since "" (an empty string) evaluates as false.

A: You already have the if-blocks which only operate when a value is filled in, just create your string in there:
var resultstring = "";
$('#ref-button1').click(function () {
var authorname = $('#bookAuthor').val();
    if (authorname == "") {
         $('.error').show();
         resultstring = authorname + ' ' + '(' + year + '),' + ' '
    }

Just build the string in the 5 steps, and no text will be added if the if-evaluation is false.


text:
Q: disable autocorrectionType is not working with UITextfield I have created RegisterViewController with email, password and confirm password fields.
In email field, it always show suggest email on QuickType's keyboard bar but other fields not show anything.
How it know which field is email or not ? I swear I didn't set anything to textfield.
I already set autocorrectionType = .no on my base class text field but it still show suggest on bar.
Can anyone help me about this ?

A: Here's what you can try -
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
textField.spellCheckingType = .no

A: try textField.textContentType = .none

A: You can try this:
textField.disableAutocorrection(true)
textField.disableAutocorrection(false)

Or this:
textField.autocorrectionType = .yes
textField.autocorrectionType = .no

To hide the bar (predictive bar), use this code:
if #available(iOS 9.0, *) {
    var item = textFeild.inputAssistantItem
    item.leadingBarButtonGroups = [];
    item.trailingBarButtonGroups = [];
}

This also may help in your case:
self.passwordField.isSecureTextEntry = true

if #available(iOS 11.0, *) {
    self.emailField.textContentType = .username
    self.emailField.keyboardType = .default
}

if #available(iOS 12.0, *) {
    self.passwordField.textContentType = .password
    self.passwordField.keyboardType = .default
}

A: this is not autocorrection. this is suggestion
Use below code to disable suggestion
if #available(iOS 12, *) {
    // iOS 12 & 13: Not the best solution, but it works.
    passwordTextField.textContentType = .oneTimeCode
} else {
    // iOS 11: Disables the autofill accessory view.
    // For more information see the explanation below.
    emailTextField.textContentType = .init(rawValue: "")
    passwordTextField.textContentType = .init(rawValue: "")
}


text:
Q: Call jquery method on desktop I have the following jquery call on my website and I would only like it to be actioned if the visitor is using a desktop device (screen size over 767px). How can this be achieved?
SCRIPT
<script>$("#sidebar").stick_in_parent();</script>

A: You can check the window width, but keep in mind, there are handhelds with over 767px width. So this is not a "desktop check".
if( $(window).width() >= 767 )
    $("#sidebar").stick_in_parent();

A: Use navigator.platform to get OS Name vs. using screen size.
What is the list of possible values for navigator.platform as of today?


text:
Q: How to fetch data from a nested array May I know how to get the "product" value with foreach loop in PHP?
Array
(
    [0] => Array
        (
            [product] => "Sony"
        )

    [1] => Array
        (
            [product] => "Toshiba"
        )

    [2] => Array
        (
            [product] => "A4Tech"
        )

)

This is my code and I know it is not working after I tried it.
foreach($response as $key => $value){

    foreach($key as $pic_small => $value2){

    echo $pic_small;
    }
}

A: foreach($response as $item)
   echo $item['product'];

ps: ok, foreach statement takes every first level element of $response array and set $item variable equal to it (you do not need indexes of the elements, so instead of the $key => $value only $value could be used). at the first loop it is the same as $item = array('product' => 'Sony');, at the second loop it is the same as $item = array('product' => 'Toshiba'); and so on..
you may, of course, use the second foreach loop to deal with those arrays, but if you need the value of only one associative element with key product then you can access it directly through the value of $item['product'].
otherwise, as it is shown in another answer, you can done it as
// $item1 means element of the first level in the original array
// $key2 and $value2 are keys and values of the second level elements
foreach($response as $item1)
     foreach($item1 as $key2 => $value2) // you may remove '$key2 =>' here
        echo $value2;

A: foreach($response as $key => $value){

    foreach($value as $title => $value2){

        echo $value2;
    }
}


text:
Q: Drop in Numbers while comparing Real-time vs Behavior reports - Google Analytics We are tracking form registrations and the count of users who registered using the form that is put up in our website.
So we did a bit of testing, and when we registered 10 users within 30 minutes, under Realtime -> Behavior it showed me the exact number as 10 users.
Whereas when I pulled the report from Behaviour -> Site Content -> All Pages, I see that there is a significant drop (showed me the number as only 6 people registered).
The users are redirected to a 'thank you/successful registered' page after the registration is a success. In this case, I view the count of the thank you pages under real-time in order to see how many have registered.
Could someone please help me out here. Why is there a drop in number between the real-time and behaviour report?
Thanks!


text:
Q: Question about the definition of toric varieties I am reading Fulton's introduction to toric varieties.
A toric variety $X=X(\Delta)$ is an algebraic variety specified by a rational fan $\Delta$ in $N_{\mathbb{R}}=N \otimes_{\mathbb{Z}}\mathbb{R}$ for a lattice $N \cong \mathbb{Z}^n$.
My questions is about $N_{\mathbb{R}}=N \otimes_{\mathbb{Z}} \mathbb{R}$. My understanding is $N_{\mathbb{R}}\cong \Bbb{Z}^n \otimes_{\mathbb{Z}} \mathbb{R}\cong \bigoplus (\Bbb{Z}\otimes_{\Bbb{Z}}\Bbb{R})\cong \Bbb{R}^n,$ so I don't quite understand why writing the notation   $N_{\mathbb{R}}=N \otimes_{\mathbb{Z}} \mathbb{R}$ instead of just $\Bbb{R}^n$. Is it in order to emphasize that $N_{\mathbb{R}}$ is obtained from $N$?


text:
Q: Set action when an item from combobox is selected I am working on a project where I have ComboBox in a pane, which has "Games", "Albums", and "Movies".
I want to open another Pane when one of these is selected.
How can I do that?
Here is my code:
GridPane select = new GridPane();
select.setAlignment(Pos.CENTER);
select.setHgap(6.5);
select.setVgap(6.5);
select.add(new Label("Media Type"), 0, 1)

ComboBox<String> comboBox = new ComboBox<String>();

comboBox.getItems().add("Movies");
comboBox.getItems().add("Albums");
comboBox.getItems().add("Games");

HBox hbox = new HBox(comboBox);

Scene thirdScene = new Scene(hbox, 500, 500);
Stage thirdStage = new Stage();

thirdStage.setScene(thirdScene);
thirdStage.setTitle("Media Menu");
thirdStage.show();

A: I strongly suggest you to go through the API (java doc) of controls you use to have a quick idea of what they are capable of.
You can either listen to the valueProperty or selectedItemProperty or you can set an action.
comboBox.setOnAction(e->{
  String value= comboBox.getValue();
  ... // Do the stuff with value
});

or
comboBox.valueProperty().addListener((obs,old,value)->{
    ... // Do the stuff with value
});

or
comboBox.getSelectionModel().selectedItemProperty().addListener((obs,old,value)->{
    ... // Do the stuff with value
});


text:
Q: Java FX Tableview not loading data from MYSQL DB I fairly new to Java and JavaFX am trying to write a program that will pull user data from a MYSQL database.  My connection works, but I am unable to pull the information into the TableView.  Now I have reworked this so many times that now I have no idea where I am especially since I am not getting errors.
Can someone please show me how to make this work properly.
Here is the Users Class
public class Users {

    public Integer userID;
    public String userName;
    public String password;

    public Users(Integer userID, String userName, String password) {
        this.userID = userID;
        this.userName = userName;
        this.password = password;
    }

    private static final ObservableList<Users> allUsersList = FXCollections.observableArrayList();

        /** This method adds Users to the all Users observable list.
        * @param Users */
        public static void addUsers(Users users) {
         allUsersList.add(users);
        }

        /** This method gets Users from the all Users observable list.
        * @return all Users*/
        public static ObservableList<Users> getAllUsers() {
            return allUsersList;
        }

        /** This method modifies Users on the Users observable list
         * @param newUsers.*/
        public void modifyUsers(Users newUsers) {
        }

        /** This method deletes Users from the Users observable list
        * @param selectedUser.*/
        public void deleteUsers(Users selectedUser) {
        }

        public int getUserID() {
        return userID;
        }

        public void setUserID(int userID) {
        this.userID = userID;
        }

        public String getUserName() {
        return userName;
        }

        public void setUserName(String userName) {
        this.userName = userName;
        }

        public String getPassword() {
        return password;
        }

        public void setPassword(String password) {
        this.password = password;
        }

        public void setUser(int userID, String userName, String password) {
        }

    }

Here is the Controller Class
public class UsersScreenController implements Initializable {

    @FXML
    public TableView<Users> userTable;
    @FXML
    private TextField userID;
    @FXML
    private TextField userName;
    @FXML
    private TextField password;
    @FXML
    private TableColumn<Users, Integer> usernameIDCol;
    @FXML
    private TableColumn<Users, String> userNameCol;
    @FXML
    private TableColumn<Users, String> passwordCol;
    @FXML
    private Button Dashboard;
    @FXML
    private Button editUser;
    @FXML
    private Button newUserBtn;
    @FXML
    private Button saveUserBtn;
    @FXML
    private Button resetUserBtn;

    public UsersScreenController() {

    }

    /**
     * Initializes the controller class.
     */

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        userTable.setItems(Users.getAllUsers());

        usernameIDCol.setCellValueFactory(new PropertyValueFactory<>("User_ID"));
        userNameCol.setCellValueFactory(new PropertyValueFactory<>("User_Name"));
        passwordCol.setCellValueFactory(new PropertyValueFactory<>("Password"));

    }

    // Generates unique id for each new user as added

    AtomicInteger count = new AtomicInteger(4);

    /** This method adds a new user to the Users table
     * @param actionEvent
     */

    @FXML
    public void newUser(ActionEvent actionEvent) throws IOException {
        int userIDS = count.incrementAndGet();
        String userNameS = userNameCol.getText();
        String passwordS = passwordCol.getText();

    //    Users.addUser(new User(int userID, String userName, String password));

        Parent root = FXMLLoader.load(getClass().getResource("/View/UsersScreen.fxml"));
            Stage stage = (Stage)((Node)actionEvent.getSource()).getScene().getWindow();
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

    }

    /**Sets modified users to show in user table
    * @param users
    **/
    @FXML
    public void setUser(ActionEvent event){
        String userIDS=userID.getText();
        String userNameS=userName.getText();
        String passwordS=password.getText();

        userTable.setItems(Users.getAllUsers());

        usernameIDCol.setCellValueFactory(new PropertyValueFactory<>("User_ID"));
        userNameCol.setCellValueFactory(new PropertyValueFactory<>("User_Name"));
        passwordCol.setCellValueFactory(new PropertyValueFactory<>("Password"));

    }

    public void editUser(ActionEvent actionEvent) throws IOException {

        TableViewSelectionModel<Users> selectionModel = userTable.getSelectionModel();

        ObservableList<Users> selectedItems = selectionModel.getSelectedItems();

        Users users = null;

        users = userTable.getSelectionModel().getSelectedItem();

        if (users == null) {
            Alert errorAlert = new Alert(AlertType.ERROR);
            errorAlert.setTitle("Missing Selection Error");
            errorAlert.setContentText("Missed item selection. Can you select the user you want to modify?");

            errorAlert.show();
            return;
        }

        int userIDS = users.getUserID();
        String userNameS = users.getUserName();
        String passwordS = users.getPassword();

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/View/UsersScreen.fxml"));

        Parent root = loader.load();
        Users user = loader.getController();
        Stage stage = (Stage)((Node)actionEvent.getSource()).getScene().getWindow();
        stage.setScene(new Scene(root));

        stage.show();

        }

    @FXML
    private void deleteUser(ActionEvent actionEvent) {
       Alert alert = new Alert(AlertType.CONFIRMATION);
       alert.setTitle("Delete User");
       alert.setContentText("Are you sure you wish to delete user?");

       if(alert.showAndWait().get() == ButtonType.OK) {
       userTable.getItems().remove(userTable.getSelectionModel().getSelectedItem());
       }

    }

    public void saveUser(ActionEvent actionEvent) throws IOException {

        TableViewSelectionModel<Users> selectionModel = userTable.getSelectionModel();

        ObservableList<Users> selectedItems = selectionModel.getSelectedItems();

        Users users = null;

        users = userTable.getSelectionModel().getSelectedItem();

        if (users == null) {
            Alert errorAlert = new Alert(AlertType.ERROR);
            errorAlert.setTitle("Missing Selection Error");
            errorAlert.setContentText("Missed item selection. Can you select the user you want to modify?");

            errorAlert.show();
            return;
        }

        int userIDS = users.getUserID();
        String userNameS = users.getUserName();
        String passwordS = users.getPassword();

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/View/UsersScreen.fxml"));

        Parent root = loader.load();
        Users user = loader.getController();

        Stage stage = (Stage)((Node)actionEvent.getSource()).getScene().getWindow();
        stage.setScene(new Scene(root));

        stage.show();

        }

    /** This method brings user back to main screen when clicking cancel button.
     * @param actionEvent
     */
    @FXML
    private void resetUser(ActionEvent event) throws IOException {

    }

    /** This method brings user back to Dashboard screen when clicking Dashboard button.
     * @param actionEvent
     */
    @FXML
    private void goToDashBoard(ActionEvent event) throws IOException {
         Stage primaryStage = new Stage();
                   Parent root = FXMLLoader.load(getClass().getResource("/View/Dashboard.fxml"));
                   Scene scene = new Scene(root);
                   primaryStage.setScene(scene);
                   primaryStage.setTitle("SCHEDULER");
                   primaryStage.show();
    }

I think this might be the one causing the issue, where I call the prepared statement.
public class DBUsers {

    private static ObservableList<Users> getAllUsers(){

        ObservableList<Users> userData = FXCollections.observableArrayList();

        try{
            String sql = "SELECT * from users";

            PreparedStatement ps = DBConnection.getConn().prepareStatement(sql);

            ResultSet rs = ps.executeQuery(sql);

            while (rs.next()) {
                int userID = rs.getInt("User_ID");
                String userName = rs.getString("User_Name");
                String password = rs.getString("Password");
                UsersScreenController.userTable.getColumns().addAll(users);
            }
        }

        catch (SQLException e) {
            e.printStackTrace();
        }

        return userData;
    }

}

Finally the Main
public class Main extends Application {

    /**
     *
     * @param primaryStage
     * @throws Exception
     */
     @Override
    public void start(Stage primaryStage) throws Exception  {

            Parent root = FXMLLoader.load(getClass().getResource("/View/LoginForm.fxml"));
            Scene scene = new Scene(root);
            primaryStage.setScene(scene);
            primaryStage.setTitle("SCHEDULER");
            primaryStage.show();
        }

    /**
     * runs args then calls closeConn() to close database connections
     * @param args
     * @throws java.lang.Exception
     */
    public static void main(String[] args) throws Exception {
    Locale.setDefault(new Locale("fr", "FR"));
      System.out.println(Locale.getDefault());

     DBConnection.openConnection();

     launch(args);

      DBConnection.closeConnection();

    }

    }


text:
Q: How to most compactly implement the code on DRF ORM def read_rate(self, id):

    cursor = self.db.cursor()

    cursor.execute('SELECT volume FROM rate WHERE cur_id = ' + str(id) + ' ORDER BY id DESC LIMIT 10')
    volume = cursor.fetchall()

    cursor.execute('SELECT rate FROM rate WHERE cur_id = ' + str(id) + 'ORDER BY id DESC LIMIT 1')
    (get,) = cursor.fetchone()
    rate = str(get)
    average = str(sum([float(x[0]) for x in volume])/len(volume))

    cursor.close()
    return {'rate': rate, 'average_volume': average}

Need to implement the code on DRF ORM, where queryset will return 'cur id', 'last rate' and 'average volume in the last 10 days'
Model
class Rate(models.Model):
    cur = models.ForeignKey(Cur, on_delete=models.CASCADE)
    date = models.DateField(auto_now=True)
    rate = models.FloatField()
    volume = models.FloatField()

    def __str__(self):
        return self.cur

    class Meta:
        ordering = ['-id']

and how I tried to implement
class RateView(ListAPIView):

    serializer_class = RateSerializer

    def get_queryset(self):
        return Rate.objects.values(
            cur__id__in=[self.kwargs['id']]).order_by(
                '-id')[:10].annotate(Avg('volume'), 'rate', self.kwargs['id'])

A: So, it looks like you have your base queryset setup slightly off.
I'm not sure you need to order by the ID, because you ae filtering on one id. So every ID in the retruned filtered QuerySet<> object will be the same - so technically, it's already ordered.
The values() method is a way to extract the QuerySet<> for iterative manipulation ... so you will need to filter first on the cur__id being equal to self.kwargs['id'].
Next, extract only the values you want - which looks to me like id, rate and volume (needed for the proceeding annotation).
Then, utilise the Avg aggregator as shown.
Then limit? (I think - I'm not sure if this works for less than 10 entries off hand).
So, all in all, I would implement it in this way:
class RateView(ListAPIView):

    serializer_class = RateSerializer

    def get_queryset(self):
        return Rate.objects.all()

    def list(self):
        queryset = self.get_queryset().filter(
            cur__id=self.kwargs['id']
        )

        queryset = queryset.values(
            'id',
            'rate',
            'volume'
        ).annotate(
            average_volume=Avg('volume'),
        )[:10]

        ...

I've also changed up your base class method "get_queryset()" to return all() objects - the only filtering I would do on this level is very basic filtering, such as if the view was for showing all female Users (for whatever reason)...so a User.objects.filter(gender='female') would make sense as your base query to build from.
The point at which it is evaluated by the DB, is on the final values() call.


text:
Q: Upload file in angularjs e2e protractor test I would like to know why testing the upload file (with absolutePath) works fine but it doesn't close the file selection dialog.
This is my code:
var path = require('path');
it('Upload file', function() {
  var button = element(by.css('button')).click();
  expect(button.isEnabled()).toBe(true);
  var test= ['../file/1.pdf','../file/2.pdf','../file/3.pdf'];
  for (var i=0;i<test.length;i++)
  {
  var absolutePath = path.resolve(__dirname, test[i]);
  element(by.css('input[type="file"]')).sendKeys(absolutePath);
  element(by.buttonText("Submit")).click();
  }
  element.all(by.css('span[ng-show="upload.complete"]')).each(function(complete){
    var text = complete.getText();
  expect(text).toEqual("Upload Complete");
});

Thank you in advance!

A: You can't control windows dialog boxes with Protractor since it uses webdriver.
The code above will not enter the file path into the windows dialog box but rather it is sending the absolute file path directly to the file upload element on the page. Thus you don't need to open the windows dialog box at all to upload a file.
If you are interested in interacting with windows dialogs there are some packages that could help you such as https://github.com/octalmage/robotjs


text:
Q: How to configure Firebase Security Rules based on user profile? I have read the Firebase Security Rules documentation. I have implemented authentication through Firebase (Firebase Auth), but I can't understand how to properly configure security Rules in Firebase based on each user's profile.
Consider the following data structure
{
    "company": {
        "idCompany1": {
            "data": {
                "address": "",
                "companyName": "Company 1",
                "logo": "assets/ApliansLogo.png",
                "nit": "",
                "phone": ""
            },
            "users": {
                "idUser1": {
                    "idCompany": "idCompany1",
                    "idUser": "idUser1",
                    "name": "Charlie",
                    "profile": "Admin"
                },
                "idUser2": {
                    "idCompany": "idCompany1",
                    "idUser": "idUser2",
                    "name": "John",
                    "profile": "Basic"
                },
                "idUser3": {
                    "idCompany": "idCompany1",
                    "idUser": "idUser3",
                    "name": "Jack",
                    "profile": "Basic"
                }
            }
        },
        "idCompany2": {
            "data": {
                "address": "",
                "companyName": "Company 2",
                "logo": "assets/ApliansLogo.png",
                "nit": "",
                "phone": ""
            },
            "users": {
                "idUser3": {
                    "idCompany": "idCompany2",
                    "idUser": "idUser3",
                    "name": "Jack",
                    "profile": "Admin"
                }
            }
        }
    },
    "users": {
        "idUser1": {
            "data": "user1@test.com",
            "empresas": {
                "idCompany1": true
            }
        },
        "idUser2": {
            "data": "user2@test.com",
            "empresas": {
                "idCompany1": true
            }
        },
        "idUser3": {
            "data": "user3@test.com",
            "empresas": {
                "idCompany1": true,
                "idCompany2": true
            }
        }
    }
}

As you can see, Charlie is the Company1's Admin, John has a Basic profile in the same company and Jack can access both companies (Company1 with a Basic profile and Company2 with an Admin profile).
idUserX are Firebase Auth Generated UIDs. idCompanyX are unique IDs generated by Firebase.
The rules I would like to implement are the following:
Rule #1
A user can only read or write information in the companies to which it belongs (users/$idUser/companies/$idCompany == true)
Rule #2
Only the Admin user of a company X can give another user access to his company, for which the idCompanyX: true is created from the App within users/$idUser/companies.
Rule #3
The same user or an Admin are the only ones who can create or modify the user's data within users
I have read Use conditions in Realtime Database Rules, but I am not sure how to do it.
The App's alghoritms handles the different roles, but I would like to add the database security layer and I don't know how to do it. At this moment I have only configured:
{
  "rules": {
    "company" : {
      ".read": "auth != null",
      ".write": "auth != null",
        }
      }
    },
    "users" : {
      "$user_id" : {
        ".read": "auth != null",
        ".write": "auth.uid === $user_id"
  }
}

How can I configure the Firebase security rules based on the authentication and profile of each user?
APPEND:
The way I'm using in Flutter to read data is:
Future<EmpresaDatosModel> cargarEmpresaDatosListado(String idCompany) async {

   Query resp = db.child('company/$idCompany/data');
   resp.onChildAdded.forEach((element) {
      final temp = EmpresaDatosModel.fromJson(Map<String,dynamic>.from(element.snapshot.value));
    });
    await resp.once().then((snapshot) {});
    return temp;
}

And to write...
db.child('company/$idCompany/data')
    .update(Map<String, dynamic>.from(_map));

A: The most important thing to realize is that rules don't filter data.
This mean that this read won't work for your use-case:
Query resp = db.child('company');
resp.onChildAdded.forEach((element) {
  ...

The reason is that this requires that the user has full read permission on /company, which your use-case doesn't allow.

There are usually two options:

*

*Only read a specific child node (e.g. /company/idCompany1) that you need to display in the app. In that case, you can use security rules on /company/$companyId to secure access to that node.

*Query for specific child nodes, and then use security rules to validate that query.

I don't think securely querying is possible here, because your use-case depends on reading from /user/... and you can't read from another location in a query.

So it seems that you can't allow your security requirements on your current data structure. That means you likely have to modify you data structure to allow the security model you want. This may mean duplicating data about who is in a company  under that company's JSON in the database.


text:
Q: Replace character string elements by indices efficiently in R I would like to efficiently replace elements in my character object with other particular elements in particular places (these places are indices which I know as they are results of the gregexpr function).
I would like some foo function that works like:
foo("qwerty", c(1,3,5), c("z", "x", "y"))

giving me:
[1] "zwxryy"

I searched the stringr package cran pdf but nothing hit my mind. Thank you in advance for any suggestions.

A: For example:
xx <- unlist(strsplit("qwerty",""))
xx[c(1,3,5)] <- c("z", "x", "y")
paste0(xx,collapse='')
[1] "zwxryy"

A: You could also try the one below, if you don't have that many characters to replace
  st1 <- "qwerty"
 gsub("^.(.).(.).","z\\1x\\2y", st1)
#[1] "zwxryy"

A: In stringi package there is stri_sub function that works like this:
a <- "12345"
stri_sub(a, from=c(1,3,5),len=1) <- letters[c(1,3,5)]
a
## [1] "a2345" "12c45" "1234e"

it's almost what you want. Just use this in loop:
a <- "12345"
for(i in c(1,3,5)){
    stri_sub(a, from=i,len=1) <- letters[i]
}
a
## [1] "a2c4e"

Be aware that this kind of function is on our TODO list, check:
https://github.com/Rexamine/stringi/issues?state=open


text:
Q: Supermicro H8DGU-F hangs with CentOS7 I try to fix our old failing blade replacing nodes with old Supermicro 1U servers that are cheap now. I do it for my own money so price matters (company doesn't want to buy new equipement). Servers contain Supetmicro PSU with good caps from good brands, not Ablecom (I checked values and ESR of 3 of them and they are good), Supermicro H8DGU-F boards (SR5670 + SP5100 chipset), 2x Opteron 6238 12 core CPUs, 2 Intel Kawela LANs. Infiniband ConnectX2 or ConnectX3 card is inserted in the only PCIE slot of this board (infinibands are different, problem persists). We use CentOS-7 from 2019 autumn as an operating system but the shop where I bought servers say that the problem is also appeae in Windows. They say they selected best items they have and made some tests but today I faced this nasty problem again on this hardware...
The problem is that an operating system hangs spontanously mainly when CentOS starting (while initializing hardware, before Welcome... text) or when the system is under load (scientific calculation, all cores). Machine becomes inaccessible vis ssh, screen is blank, no reaction on keyboard or mouse. If it hangs while loading OS and you didn't press Esc to show messages, the bottom bar continues to move sometime, than stops. If you press Esc you may see that it hang while cheching HDD or initializing Infiniband... BIOS is updated to newest 3.5c, CMOS cleared, optimal defaults loaded. I monitored temperarures with IPMI and just with my finger, nothing bad. Voltages in IPMI and BIOS are good. Ripple at high load at 12 V rail is maximom 200 mV, I don't think it can cause hangs, and there ere different supplies.
I bought 4 servers and 6 H8DGU-F boards. Two of boards with 1.01 revision hang identically (after 2 days of load, after hours of load, or when the calculation started, or during boot), one of 1.01 revision from the same stock worked for 7 days under maximum load and was successifully rebooted about 10 times, one of 2.00 revision has all memory slots of CPU2 dead (it's not relevant, replacement was sent), one of 2.00 revision worked successifully for 9 days and started sucsessifully approximately 10 times.
What can be the reason? I can't believe serverboards are that bad. It's really frustrating. They are expensive when new, shouldn't they be reliable and durable according to their price?
Can someone, please, suggest what can be the reason?
(Sorry, it's about IPMI version of the board, so I corrected topic)

A: Looks strange that there are no answers, maybe just too old board. SO answering (partially) my question. I had a talk with one of companies I bought rhese board in. They say that this model (rev. 1.01, 2.00) is problematic, other shop confirms for rev. 1.01. From 4 boards with 2.00 revision one doesn't see memory in CPU2 slots, one reboots and has network problems, two are being tested under full load now. From 1.01 revision two boards hang (while booting, immediately after high load starts, after hours or ~2 days of high load), one board worked for 2.5 weeks under high load, one board worked for ~2 days under high load (usually, 15...20 CentOS-7 boot tests are done before puttinig the server in operation because it sometime helps to identify the hanging earlier that just putting under load).
So avoid H8DGU-F, they seem to be very undurable/unreliable, although cheap. In my situation I can't see other option because of high prices of other Opteron 6000 boards so I will check if there are 3...4 good boards to use, may be with one H8DGi or H8DG6 (they are dual-chipset versions and has onboard RAID controller so they are 2...5 times more expensive).


text:
Q: pandas cannot find csv file to load I am trying to do some tutorial on Edx. The file I am working with is csv. I have pandas imported and I have the working directory set to where the file is store but it always says:

Files does not exist

or

Error tokenizing data. C error: Expected 1 fields in line 108, saw 3

what do I have to do in order to not put the full file path for importing in pycharm?

A: That is an error that can occur if your file is not comma delimited or if you have some field in your data that also contains commas. For example if you have numerical data in your file that contains commas as thousands separators.
This will fail with pd.read_csv(filename):
108
1
2
108,109,104

Likewise this will also fail pd.read_csv(filename):
108, [23]
2, [15]
3, [15, 17]

If your data is not comma separated you need to specify the separator with the sep= kwarg. For example:
some_file.csv
108|[23]
2|[15,17]

Trying to load this with pd.read_csv('some_file.csv') will fail on line 2 as it expects only one column based on the first line, and finds two values on line 2. The correct way to read this file is pd.read_csv('some_file.csv', sep='|').


text: Q: Connection works on Visual Studio 2015 but not on 2019 I have created an Oracle connection in Visual Studio 2015 and it works but the same details do no work in Visual Studio 2019. Do we need to change anything when we move to the new version?


text:
Q: Using NoSQL/MongoDB in Visual Studio Express or Professional Our company is planning on purchasing a copy of Visual Studio Professional 2013 for some features that are absent from the Express edition, mainly, the ability to create installers, plugin functionality, and likely the ability to use NoSQL databases. We only plan on buying one copy as our budget is tight, where the rest of the developers when not needing to use the Professional features can use the Express edition.
I know that Express has a database explorer, so that still allows basic SQL functionality, but we are interested in exploring object-oriented databases, mainly MongoDB or other NoSQL databases. My question is - can you use MongoDB (or other object-based databases) with the Express edition, or does it require the Professional edition?
From my research so far, MongoDB compiles to 32-bit and 64-bit, but because VSE can only do 32-bit builds, there will be issues with using it in VS Express.
Next, if the Professional edition is necessary to work with MongoDB, would we then be able to open solutions/projects created with the Professional edition in Express?
Thank you.

A: If you mean that you want to use MongoDB for queries, updates or inserts, the answer is yes, you can use Visual Studio Express.
You only need the  MongoDB C# driver in your project and configure the connection to the database. But it is the same with Oracle, SQL Server, MySQL or whatever database you want. You don't need a Pro version of VS.
If you mean that you want to develop a plugin for explore MongoDB databases, then you need  VS Professional or better, or use an external tool.


text:
Q: INSTEAD OF INSERT does not display changes This is my table:
CREATE TABLE [MyTable]
(
    [GroupId]     INT        NOT NULL,
    [ItemId]      INT        NOT NULL,
    [Data]        INT        NOT NULL,
    PRIMARY KEY CLUSTERED ([GroupId], [ItemId]),
    CONSTRAINT [FK_MyTable_tblGroup] FOREIGN KEY ([GroupId]) REFERENCES [tblGroup] ([Id])
);

I used this trigger to generate ItemID on insert:
CREATE TRIGGER [Trigger_MyTable_OnInsert]
ON [MyTable]
INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO MyTable([GroupId], [ItemId], [Data])
    SELECT [GroupId],
        ISNULL((SELECT MAX(ItemId)
                FROM MyTable
                WHERE MyTable.GroupId = GroupId), 0) + 1,
        [Data]
    FROM  inserted i
END

At insert time, the new ItemId value is inserted into the table but is not displayed:

This problem also exists when working with the Entity Framework and I found the problem with this part of the database.
I'm trying to get an ItemId sequence for each GroupId. ItemId is unique to each group, not the table, that's why I can't use IDENTITY.

A: To answer the question directly, the problem is:
WHERE MyTable.GroupId = GroupId

You haven't specified which GroupId you mean on the right hand side of that expression.
The SQL standard dictates that SQL Server must resolve it to the innermost scope, so you have effectively written:
WHERE MyTable.GroupId = MyTable.GroupId

You should instead write:
WHERE MyTable.GroupId = i.GroupId

db<>fiddle demo
The trigger has other problems, such as not handling multi-row inserts properly, and not being safe under concurrency.
A related article of mine: Sequence Tables.

A: Finally i found the point that i have to use OUTPUT command.

Using OUTPUT in an INSTEAD OF trigger

This is Fixed SQL Trigger:
CREATE TRIGGER [Trigger_MyTable_OnInsert]
ON [MyTable]
INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO MyTable([GroupId], [ItemId], [Data])
    OUTPUT INSERTED.[ItemId] as [ItemId]
    SELECT [GroupId],
        ISNULL((SELECT MAX(ItemId)
                FROM MyTable
                WHERE MyTable.GroupId = GroupId), 0) + 1,
        [Data]
    FROM  inserted i
END

And as I said, this problem exists when using EntityFrameworkCore. To solve this problem, we must tell Entity Framework that this value will change after call the Add() method.
To solve this problem, it is enough to add the following method in the DbContext class:
entity.Property(table => table.ItemId).ValueGeneratedOnAdd();

To be clear, the result of the code is as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyTable>(entity =>
    {
        entity.HasKey(e => new { e.GroupId, e.ItemId });
        entity.Property(table => table.ItemId).ValueGeneratedOnAdd();
        entity.ToTable("MyTable");
    });
}


text:
Q: How to resize a drawable from the layout I am trying to customize the layout of a dialog. I want to have a logo in the top left corner and in the right of it, the title of the dialog. I wrote the layout below, but the editor in eclipse gives me the layout shown below, and I do not know why the logo is so wide? and the title should be to the right of it.
please let me know what I am doing wrong?
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TableLayout
    android:id="@+id/tl_MainTable"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <TableRow
        android:id="@+id/tr_Logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/iv_Logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_launcher"/>
    </TableRow>
    <TableRow
        android:id="@+id/tr_Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true">
        <TextView
            android:id="@+id/tv_Title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Discovering Neigbouring Devices"
            android:/>
    </TableRow>

</TableLayout>

A: First of all use android:src instead android:background
So finally your ImageView
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:src="@android:drawable/sym_def_app_icon"
    android:layout_weight="1"
    android:adjustViewBounds="true"/>

FYI : Use Linear Layout Instead Table Layout .

A: You have so wide logo, because you use TableRow.
Try to add android:layout_weight="1" for ImageView.

A: You need to use RelativeLayout or LinearLayouts. TableLayout is not good for this.
This is an example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:background="@color/material_deep_teal_500">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:src="@android:drawable/sym_def_app_icon"
        android:layout_weight="1" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="LOGONAME"
        android:id="@+id/textView"
        android:layout_weight="8"
        android:gravity="center_vertical"
        android:paddingLeft="@dimen/abc_action_bar_overflow_padding_end_material" />
</LinearLayout>


text:
Q: 403 CSRF verification failed Django when refresh url? I have create a view that takes in a post request from my /login route, but after accepting the login post request and redirecting to /, when the user refresh the browser, I get a 403 CSRF failure code.
How can i optimize my code so that if the user refreshes the browser it doesn't prompt the error?
view

def index(request):
    username = password = ''

    if request.method == 'POST':
        HttpReferrer = request.session.get('HttpReferrer')
        if  HttpReferrer == '/login':
            username = request.POST['username'].lower().strip()
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                login(request, user)
                return index_(request)
            else:
                err = {"err_login": {"code": 404, "message": "The username and password combination do not match our records. Please double-check and try again."}}
                return render(request, 'auth/auth.html', err)

A: Why do you want to post to an index page?
It is the login page (the login view) , that is supposed to handle the login, right?
If the login view handles login, then just get the user in your index view with user = request.user
you shouldn't have to reauthenticate in the index view.
If on the other hand the index view is your login view, then why do you check the referer?


text:
Q: java drawing a rainbow The program can run but it's not outputting what I want it to output. See, I want 7 concentric arcs which colored as a rainbow. What I'm getting is 7 concentric arcs colored red and yellow. I need the colors in this order:
red, yellow, pink, green, purple, orange, blue
What do I need to add or change? I'm using if else statements to alternate between colors. Which is why it's alternating between red and yellow. I added another set of if else within the other if else statements, I am thinking that I can use them to further alternate.
I'm pretty new to java and loops. I was thinking I could use for, while, if else or do loops for the colors.
import javax.swing.JPanel;
import java.awt.*;
public class rainbowpanel extends JPanel
{

private final int MAX_WIDTH = 300, NUM_RINGS = 7, RING_WIDTH = 20;

public rainbowpanel ()
{
setBackground (Color.white);
setPreferredSize (new Dimension(300,300));
}

    public void paintComponent (Graphics page)

    {
        super.paintComponent (page);
        int x = 0, y = 0, diameter = MAX_WIDTH;
        page.setColor (Color.yellow);
     for (int count = 0; count < NUM_RINGS; count++)

        {
            if (page.getColor() == Color.yellow) // alternate colors
            page.setColor (Color.red);
            else
            page.setColor (Color.yellow);
            page.fillArc (x, y, diameter, diameter, 0, 180);

            diameter -= (2 * RING_WIDTH);
            x += RING_WIDTH;
            y += RING_WIDTH;
            }

            {
            if (page.getColor() == Color.yellow) // alternate colors
                page.setColor (Color.pink);
            else
                page.setColor (Color.orange);
                   page.fillArc (x, y, diameter, diameter, 0, 180);

            //diameter -= (2 * RING_WIDTH);
            //x += RING_WIDTH;
            //y += RING_WIDTH;
}

            page.setColor (Color.white);
            page.fillArc (x, y, diameter, diameter, 0, 180);
}
}

You have to run it from this file:
import javax.swing.JFrame;
public class rainbow

{

public static void main (String[] args)
{
JFrame frame = new JFrame ("Rainbow");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

rainbowpanel panel = new rainbowpanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

A: Try something like this:
public void paintComponent (Graphics page)
{
    super.paintComponent (page);
    int x = 0, y = 0, diameter = MAX_WIDTH;

    Color myColors[] = { Color.red, Color.yellow, Color.pink, Color.green, Color.purple, Color.orange, Color.blue };

    for (int count = 0; count < NUM_RINGS; count++)
    {
        page.setColor (myColors[count%NUM_RINGS]);
        page.fillArc (x, y, diameter, diameter, 0, 180);

        diameter -= (2 * RING_WIDTH);
        x += RING_WIDTH;
        y += RING_WIDTH;
    }
}

You should suffice with just one for cycle with all the drawing. The count%NUM_RINGS will prevent array out of bounds error if you set more rings than you have colors, they will cycle from beginning.

A: please try this code. This code is little bit tricky .I know this is not the professional  way to code .
public class rainbowpanel extends JPanel{
private final int MAX_WIDTH = 300, NUM_RINGS = 7, RING_WIDTH = 20;

public rainbowpanel ()
{
    setBackground (Color.white);
    setPreferredSize (new Dimension(300,300));
    }
public void paintComponent (Graphics page)
{
super.paintComponent (page);
int x = 0, y = 0, diameter = MAX_WIDTH;
page.setColor (Color.red);
for (int count = 0; count < 2; count++)
{
if (page.getColor() == Color.yellow) // alternate colors
page.setColor (Color.red);
else
page.setColor (Color.yellow);
page.fillArc (x, y, diameter, diameter, 0, 180);

diameter -= (2 * RING_WIDTH);
x += RING_WIDTH;
y += RING_WIDTH;
}
for (int count = 0; count < 2; count++)
{
if (page.getColor() == Color.blue) // alternate colors
page.setColor (Color.green);
else
page.setColor (Color.blue);
page.fillArc (x, y, diameter, diameter, 0, 180);

diameter -= (2 * RING_WIDTH);
x += RING_WIDTH;
y += RING_WIDTH;
}
for (int count = 0; count < 2; count++)
{
if (page.getColor() == Color.pink) // alternate colors
page.setColor (Color.LIGHT_GRAY);
else
page.setColor (Color.pink);
page.fillArc (x, y, diameter, diameter, 0, 180);

diameter -= (2 * RING_WIDTH);
x += RING_WIDTH;
y += RING_WIDTH;
}
for (int count = 0; count < 1; count++)
{
if (page.getColor() == Color.cyan) // alternate colors
page.setColor (Color.LIGHT_GRAY);
else
page.setColor (Color.cyan);
page.fillArc (x, y, diameter, diameter, 0, 180);

diameter -= (2 * RING_WIDTH);
x += RING_WIDTH;
y += RING_WIDTH;
}

}
}


text:
Q: Detecting Last View UIViewController I am trying to program a page so that when I click the 'Return' button I got the the last visited UIViewController.
Last Page Code:
[[NSUserDefaults standardUserDefaults] setObject:NSStringFromClass([self class]) forKey:@"currentViewController"];
[[NSUserDefaults standardUserDefaults] synchronize];

Return Button Code:
    - (IBAction)Return:(id)sender {
        NSString *savedClassName = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentViewController"];
UIViewController *screen = (UIViewController *)NSClassFromString(savedClassName);
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:screen animated:YES];
            }

The problem is it keeps returning the error:
+[SAVEDVIEWNAME setModalTransitionStyle:]: unrecognized selector sent to class 0x59b98
2013-12-14 12:47:27.462 Friends+[16358:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[Calander setModalTransitionStyle:]: unrecognized selector sent to class 0x59b98'

I understand what it's trying to say, but it's not making sense as that is perfectly acceptable in this instance!!!
Any help appreciated, thnx.

A: You need to instantiate an objcet from the class, like so:
NSString *savedClassName = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentViewController"];
Class cls = NSClassFromString(savedClassName);
UIViewController *screen = (UIViewController *)[cls new];
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:screen animated:YES completion:nil]; //You should use this instead of presentModalViewController:animated: !


text:
Q: SQL top 5 records algorithm Let me be the first to admit that I am not the greatest with SQL and this issue has be slightly stumped.
I need to create an algorithm that will return the top 5 records from a table. The Top 5 records should be worked out by summing 3 columns together and the top 5 with the greatest score should be returned.
Can anyone give me some pointers in how I would do this kind of statement please.
I have been messing around with some code for a while and I am not getting anywhere fast.
Regards
Mark

A: I just tried the following in SQL Server Management Studio and it seems to do what you want:
SELECT TOP 5 * FROM
(
     SELECT Value1, (Col1 + Col2 + Col3) AS Rank FROM MyTable
) tmp
ORDER BY Rank DESC

EDIT
Just noticed that you actually don't need the outer select and can write:
SELECT TOP 5 Value1, (Col1 + Col2 + Col3) AS Rank FROM MyTable
ORDER BY Rank DESC

This was tested in SQL Server 2008.

It selects the value of a column and the sum of three other columns from a table called MyTable in the inner select. The outer select orders these by the selected sum and takes the top 5.
Example: The source table contains the following data
Value1    Col1    Col2    Col3
  V0        0       0       0
  V1        1       0       0
  V2        2       0       0
  V3        3       9       0
  V4        4       9       0
  V5        5       9       0
  V6        6       9       10
  V7        7       9       10

The inner select would create
Value1    Rank
  V0        0
  V1        1
  V2        2
  V3        12
  V4        13
  V5        14
  V6        25
  V7        26

And the outer select would return
Value1    Rank
  V7        26
  V6        25
  V5        14
  V4        13
  V3        12

A: This might give you the desired effect:
MySQL
SELECT Value1, (Col1 + Col2 + Col3) AS Rank
FROM MyTable
ORDER BY Rank DESC
LIMIT 5;

SQL
SELECT TOP 5 Value1, (Col1 + Col2 + Col3) AS Rank
FROM MyTable
ORDER BY Rank DESC;

A: SQL Server uses TOP to limit the number of records return on the SELECT statement.
SELECT TOP 5 Column1, (Column1 + Column2 + Column3) totalSum
FROM   TableName
ORDER  BY totalSum  DESC

if you want to handle tie, add WITH TIES in the TOP clause,
SELECT TOP 5 WITH TIES Column1,
       (Column1 + Column2 + Column3) totalSum
FROM   TableName
ORDER  BY totalSum  DESC

*

*TSQL TOP

A: Try a combination of 'order by' and 'limit'.
select *, (col1 + col2 + col3) as total
  from MyTable
  order by total desc
  limit 5;

Note, this is the syntax for mysql, not sql-server


text:
Q: Delete files inside a folder, but not delete folders How do I delete all the files in a folder, except the folders inside?
I have a folder named here.
And i have 10 folders inside here named 1 to 10, and different files that are not folders.
How i can only delete that files?
I try but i can only delete all.
yeha, i try
path = 'C:\\teste'
imagesToTrain = os.listdir(path)
for f in imagesToTrain:
     if not os.path.isdir(f):
         os.remove(f)

but dont find the file

A: I didn't understand really well your problem but I here is a code I made with the two possible options:
from pathlib import Path
from shutil import rmtree

def delete_folders(path: Path):
    """
    Delete all folders in a folder.
    """
    for folder in path.glob('*'):
        if folder.is_dir():
            rmtree(folder)

def delete_files(path: Path):
    """
    Delete all files in a folder.
    """
    for file in path.glob('*'):
        if file.is_file():
            file.unlink()

if __name__ == '__main__':
    folder_path = Path('/path/to/folder/')
    # This is for deleting only the folders inside folder_path.
    delete_folders(folder_path)
    # This is for delte only the files inside folder_path.
    delete_files(folder_path)


text:
Q: pymedtermino sqlite database not found I am new to python and trying to use the module pymedtermino but keep getting teh below error
from pymedtermino.snomedct import *

File
  "C:\Users\\AppData\Local\Continuum\Anaconda3\lib\site-packages\pymedtermino__init__.py",
  line 790, in connect_sqlite3
      raise IOError('Database %s not available. Please build, or set pymedtermino.DATA_DIR correctly' % path)
OSError: Database
  C:\Users\AppData\Local\Continuum\Anaconda3\lib\site-packages\pymedtermino\snomedct.sqlite3
  not available. Please build, or set pymedtermino.DATA_DIR correctly

i have successfully installed the module

Collecting PyMedTermino   Downloading PyMedTermino-0.3.3.tar.gz
  (34.0MB)
      100% |████████████████████████████████| 34.0MB 25kB/s Building wheels for collected packages: PyMedTermino   Running setup.py
  bdist_wheel for PyMedTermino ... done   Stored in directory:
  C:\Users\administrator\AppData\Local\pip\Cache\wheels\71\01\91\f3ec03bdc7c10c11093b77f8a5ecef4f855327c1b29107d4dd
  Successfully built PyMedTermino Installing collected packages:
  PyMedTermino Successfully installed PyMedTermino-0.3.3

Thanks!

A: After installing PyMedTermino if you try the following code there will be no error:
from pymedtermino import *

It is clearly mentioned in the documentation that "For SNOMED CT and ICD10, the data are not included (because they are not freely redistributable) but they can be downloaded for free in XML format, for research / academic purpose"
In order to use SNOMED or ICD you have to download SNOMED CT data. Please see the following link for download and installation procedure.
https://pythonhosted.org/PyMedTermino/tuto_en.html
https://pythonhosted.org/PyMedTermino/tuto_en.html#installation

A: You have to set the global parameter using
pymedtermino.DATA_DIR = <path to the SQLite3 files>

A: There are two issues with setup.py script in pymedtermino resolving them solves the problem.

*

*To set the directory path of data directories one has to directly hard code in setup.py. Using export DATA_DIR="<path>" doesn't help.

*In ICD10_DIR the code by default looks for a file with the name 'icd102010en.xml' which has got changed to  'icd102016en.xml' in the recent version


text:
Q: Wireguard working on phone but not laptop I have a wireguard server setup in docker on my home server.  It has generated configuration for my laptop, phone and tablet.  I took those files and put them in my google drive, and downloaded them to my phone and laptop.  I am trying to use my laptop to connect to my Sunshine server on my home desktop remotely from laptop so I can stream my games.  This works perfectly from my phone, I just installed the wireguard app, imported the config, turned it on, and immediately my Sunshine server shows up in Moonlight app.  I can also bring up other things on my network at home through wireguard no problem.
From my laptop, however, it doesn't seem to be able to connect to anything on my home network. Running curl ifconfig.me from my terminal does show my desktop/home IP address, so the wireguard connection works.
What am I missing here?  How can I get access to other services on my home network?  Why would it be different than the phone when the configs are almost identical (other than the private key, preshared key and ip address obviously).
Laptop running Pop_OS 22.04, wireguard 1.0.20210914-1ubuntu2
Output of wireguard:
 ip link add peer_laptop type wireguard
 wg setconf peer_laptop /dev/fd/63
 ip -4 address add 10.13.13.2 dev peer_laptop
 ip link set mtu 1420 up dev peer_laptop
 resolvconf -a tun.peer_laptop -m 0 -x
 /etc/resolvconf/update.d/libc: Warning: /etc/resolv.conf is not a symbolic link to /run/resolvconf/resolv.conf
 wg set peer_laptop fwmark 51820
 ip -6 route add ::/0 dev peer_laptop table 51820
 ip -6 rule add not fwmark 51820 table 51820
 ip -6 rule add table main suppress_prefixlength 0
 nft -f /dev/fd/63
 ip -4 route add 0.0.0.0/0 dev peer_laptop table 51820
 ip -4 rule add not fwmark 51820 table 51820
 ip -4 rule add table main suppress_prefixlength 0
 sysctl -q net.ipv4.conf.all.src_valid_mark=1
 nft -f /dev/fd/63

Running wireguard on my laptop with sudo wg-quick up peer_laptop, and I expected to not only tunnel internet traffic (works) but also access my internal services on my home network (not working)


text:
Q: Load data from MongoDb to Elasticsearch through python I have some json data loaded in MongoDb. e.g. doc1 = {"id": 1,"name": "x1"},doc2 = {"id": 2,"name": "x2"},doc3 = {"id": 3,"name": "x3"}. Now I want this data to import from MongoDb to Elasticsearch. I wrote this piece of code.

mgclient = MongoClient()
db = mgclient['light-test']
col = db['test']

es1 = Elasticsearch()
print ("Connected", es1.info())

es1.indices.create(index='light-test', ignore=400)

# Pull from mongo and dump into ES using bulk API
actions = []
for data in tqdm(col.find(), total=col.count()):
    data.pop('_id')
    action = {
        "_index": 'light-test',
        "_type": 'test',
        "_source": data
    }
    actions.append(action)
    print("complete")

# Dump x number of objects at a time
    if len(actions) >= 100:
        deque(parallel_bulk(es1, actions), maxlen=0)
        actions = []

print("done")

a = es1.search(index='light-test', body={
  'query': {
    'match_all': {
     }
  }
})
print(a)

The problem is in the query returned. The hits shows blank whereas it should had returned the json files.
results
Help me in importing the data from MongoDb to Elasticsearch.

A:

app = Flask(__name__)

MONGO_URL = '...'
mgclient = MongoClient(MONGO_URL, ssl=True, ssl_cert_reqs=ssl.CERT_NONE)
db = mgclient['light']
col = db['task']

doc1 = {...}
doc2 = {...}
doc3 = {...}
post_id = col.insert_many([doc1, doc2, doc3])

print(col.count())

es1 = Elasticsearch(...)
ESinfo=(es1.info())

# Pull from mongo and dump into ES using bulk API
actions = []
for data in tqdm(col.find(), total=col.count()):
    data.pop('_id')
    action = {
            "index": {
                    "_index": 'light',
                    "_type": 'task',
                    }
    }
    actions.append(action)
    actions.append(data)

#delete = es1.indices.delete(index = 'light')
request_body = {
    "settings" : {
        "number_of_shards": 1,
        "number_of_replicas": 0
    }
}
es1.indices.create(index='light', body = request_body, ignore=400)
res = es1.bulk(index = 'light', body = actions, refresh = True)

result = col.find()
names = []
for obj in col.find():
    name = obj['name']
    names.append(name)
    print(names)

@app.route('/query')
def Query():
    a = es1.search(index='light', body={
      'query': {
        'match': {
          'name': '...',
         }
      }
    })
    return jsonify(query=a)

if __name__ == "__main__":
 app.run(host='0.0.0.0', port=1024)

This has helped. thank you :)


text:
Q: c# - how to pass function as parameter (with parameters as values) without invoking it I want to pass a function as a parameter to another function (with actual values) and later execute it. Here is JavaScript code:
function functionToPass1 (x,y) {
    console.log(x, y);
}

function functionToPass2 (x,y,z) {
    console.log(x, y, z);
}

function mainFunction(param1, param2, functionToPass){
  console.log(param1, param2);
  functionToPass();

}

mainFunction("a", "b", function(){
    functionToPass2(1, 2, 3) ;
});

How to write this in C#  (or VB.Net)?

A: Func<> Delegates are what you are looking for to pass methods in another method.
I wrote a small example below, you can apply it according to your needs. Func<> is a generic delegate. It can be Func<int,string> Func<int,int,bool> and so on. The last one represents the return type and the others represent the input parameter types of method.
        static void Main(string[] args)
        {
            MethodB(MethodA);
            Console.ReadLine();
        }

        static string MethodA(string message) //Func<string,string>
        {
            return message;
        }

        static void MethodB(Func<string, string> method)
        {
            Console.WriteLine(method("I am MethodA"));
        }

For more detailed information, you can check this link => https://www.tutorialsteacher.com/csharp/csharp-func-delegate

A: Thank you all for contributing, your help meant all to me. The only thing I needed to figure out that is an anonymous function to be passed. C# equivalent is like this:
string functionToPass1(int i, string x, string y)
{
  return string.Join(',', new[] { i.ToString(), x, y });
}

string functionToPass2(int i, string x, string y, string z)
{
  return string.Join(',', new[] { i.ToString(), x, y, z });
}

string mainFunction(string param1, string param2, Func<int,string>? functionToPass)
{
  Console.WriteLine(param1);
  Console.WriteLine(param2);
  var res = "";
  int i = 5;
  if (functionToPass != null)
    res = functionToPass(i);
  return res;
}

var res = "";

res = mainFunction("a", "b", (x) =>
{
  return functionToPass2(x, "1", "2", "3");
});

Console.WriteLine(res);
Console.WriteLine("---------------");

res = mainFunction("a", "b", (x) =>
{
  return functionToPass1(x, "1", "2");
});

Console.WriteLine(res);
Console.WriteLine("---------------");

res = mainFunction("a", "b", null);

Console.WriteLine(res);
Console.WriteLine("---------------");
Console.ReadLine();

A: I didn't delete the first comment in case it might be useful to other people in the future. I made some changes for the code you refreshed. I tried to create a generic structure as much as possible. However, Javascript is much more flexible than C#. In other words, even if the structure is generic, at some points we have to break this genericity.
        static void Main(string[] args)
        {
            MainFunction<string, string, int>("a", "b", FunctionToPass2<int, int, int>);
            Console.ReadLine();
        }

        static void FunctionToPass1<T1, T2>(T1 x, T2 y)
        {
            Console.WriteLine(x + " " + y);
        }

        static void FunctionToPass2<T1, T2, T3>(T1 x, T2 y, T3 z)
        {
            Console.WriteLine(x + " " + y + " " + z);
        }

        static void MainFunction<T1, T2, T3>(T1 param1, T2 param2, Action<T3, T3, T3> functionToPass)
        {
            Console.WriteLine(param1 + " " + param2 + "\n");
            FunctionToPass2(1, 2, 3);
        }

If our parameter types are certain, I believe we will come up with a much simpler solution by not writing it generic. For example, I assume that T3 for Action<T3, T3, T3> delegate is int for this solution because your arguments are integer. Here we have to break the 'generic' structure a bit.


text:
Q: How to add addTextChangedListener to listview values from sqlite database as source in editText for Android? I would like to have editText addTextChangedListener to listview values for sqlite database values.Kindly provide me a snippet or example to do this or is it not possible to do it.Kindly provide a snippet to achieve this.Thank you.

A: You have to create a custom adapter and in the getView method add the text change listener to you edit text.


text:
Q: Passing method with list of base type in return type as a parameter causes wrong method signature error I'm trying to create generic method to filter results from  several method returning lists of types that are deriving from same base type. I prepared a simplified version of my problem:
using System;
using System.Collections.Generic;
using System.Linq;

public class Animal
{
    public string Name { get; set; }
}
public class Cat : Animal { }
public class Dog : Animal { }

public class Program
{
    public static void Main()
    {
        Console.WriteLine(GetFilteredAnimals("Pe", GetCats));
    }

    private static List<Cat> GetCats()
    {
        return new List<Cat>() { new Cat { Name = "Sphinx" }, new Cat { Name = "Persian" } };
    }

    private static List<Dog> GetDogs()
    {
        return new List<Dog>() { new Dog { Name = "Bulldog"}, new Dog { Name = "Dalmatian" } };
    }

    private static List<Animal> GetFilteredAnimals(string f, Func<List<Animal>> method)
    {
        var animals = method();

         return animals.Where(a => a.Name.StartsWith(f)).ToList<Animal>();
    }
}

The method
GetFilteredAnimals("Pe", GetCats)

does not work because GetCats does not return list of Animal. Is it possible to do such generic method for lists? As far as I know, if I used single objects instead of lists it would work.
The working code for this is here on .NET Fiddle

A: Assuming you're using C# 4+ and .NET 4+, you can get this to work using generic covariance:
private static List<Animal> GetFilteredAnimals(string f, Func<IEnumerable<Animal>> method)

A List<Cat> can't be treated as a List<Animal> - but it can be treated as an IEnumerable<Animal> because IEnumerable<T> is covariant in T.
Likewise Func<T> is covariant in T, so a Func<List<Cat>> can be treated as a Func<IEnumerable<Animal>>... so it then compiles.


text:
Q: Error when submitting a sitemap through Google Webmaster Tools I keep getting an "Unsupported File Format" error when I submit a sitemap to Google Webmaster Tools.  I always use hwww.xml-sitemaps.com to create my sitemaps and I've never had an issue before, so I have no idea how to fix this.  Your advice is appreciated!
Here's the specific error I'm getting from Webmaster Tools :
XML Parsing Error: junk after document element
Location: http://www.joshgoodman.com/sitemap.xml
Line Number 3, Column 1:http://www.joshgoodman.com/main.phpweekly0.85
Here is the beginning and end code of my sitemap:

<?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<!-- created with Free Online Sitemap Generator www.xml-sitemaps.com -->

<url>
  <loc>http://www.joshgoodman.com/</loc>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/main.php</loc>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/blog/</loc>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/faqs.html</loc>
  <lastmod>2014-05-20T01:13:17+00:00</lastmod>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/il-cielo-wedding.html</loc>
  <lastmod>2014-05-20T01:13:19+00:00</lastmod>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/inland-empire-wedding-photographer.html</loc>
  <lastmod>2014-05-20T01:13:19+00:00</lastmod>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/palm-springs-wedding-photographer.html</loc>
  <lastmod>2014-05-20T01:13:28+00:00</lastmod>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/blog/niko-and-joshuas-sls-hotel-wedding/</loc>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/blog/ashley-and-walters-four-seasons-il-cielo-wedding/</loc>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/blog/four-seasons-beverly-hills-wedding-emilia-and-anthony/</loc>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/oviatt-penthouse-wedding.html</loc>
  <lastmod>2014-05-20T01:13:28+00:00</lastmod>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/blog/get-out-and-vote/</loc>
  <changefreq>weekly</changefreq>
</url>
<url>
  <loc>http://www.joshgoodman.com/blog/?s=powershot&searchsubmit=Search</loc>
  <changefreq>weekly</changefreq>
</url>
</urlset>

A: You've missed a beginning <urlset> tag. And the sitemap.xml on your website differs from the XML sitemap you've specified in your question.


text:
Q: GetSystemTimeZones missing GMT Standard Time I have been trying to use TimeZoneInfo.GetSystemTimeZones in .net4 to replace our old method which uses COM to call into some MFC code. However, I've had to revert to the COM method because GetSystemTimeZones doesn't return all time zones. Being based in the UK and not including GMT Standard Time in our list of options is a problem.
When I look in the registry, I find that GMT Standard Time has a Dynamic DST subkey with no rules defined. I downloaded the .net4 source code and, in TimeZoneInfo.cs,  GetSystemTimeZones eventually calls TryCreateAdjustmentRules which appears to return false if the Dynamic DST key has no FirstEntry or LastEntry defined.
            //
            // loop over all of the "<time_zone_name>\Dynamic DST" hive entries
            //
            // read FirstEntry  {MinValue      - (year1, 12, 31)}
            // read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
            // read LastEntry   {(yearN, 1, 1) - MaxValue       }

            // read the FirstEntry and LastEntry key values (ex: "1980", "2038")
            Int32 first = (Int32)dynamicKey.GetValue(c_firstEntryValue, -1, RegistryValueOptions.None);
            Int32 last = (Int32)dynamicKey.GetValue(c_lastEntryValue, -1, RegistryValueOptions.None);

            if (first == -1 || last == -1 || first > last) {
                rules = null;
                return false;
            }

As TryCreateAdjustmentRules returns false, TryGetTimeZoneByRegistryKey throws an InvalidTimeZoneException which means GMT Standard Time doesn't get added into the time zone collection. I've tried deleting the empty Dynamic DST subkeys but something adds them back in again (probably Windows Update).
I've done alot of searching but haven't seen anyone else report this problem. I'm not sure whether there is a GetSystemTimeZones fix or whether I can stop the empty Dynamic DST subkey appearing in the first place. Any ideas?

A: I'm guessing this is just a registry issue.
Something similar is outlined here for WinXP /  Server 2003 SP1.
Please see if the following helps:
http://blogs.technet.com/b/dst2007/archive/2007/03/06/missing-time-zones-in-registry.aspx
My guess is you could export the entire registry Key from another machine, and apply it to your problematic box(es).

A: It turns out that the problem is with our COM object and not with the .NET code. The code to read the registry should only be reading but it mistakenly calls RegCreateKey to optimise multiple calls to the same registry branch.
When the COM object is registered (with admin rights) because of a new version, it loads the time zones and creates Dynamic DST for the local time zone which in my case is GMT/UTC.
Administrators, I guess this question should be marked for deletion.

A: After looking it over your problem and even running the code you provided in the comments to print out a list of Time Zones I am not able to get GMT to show up on my system. I am running Windows 7 Professional and selecting GMT is just not an option. I know that doesn't solve your problem and you - like a lot of other people - sound like you really need to get this to work with GMT.
However if at all possible, if you see a way to use UTC then I would check out these links:
Windows 7 Lack of Support for GMT
Converting UTC to GMT
Just another possible answer to your problem, is there anyway you can create a wrapper around the UTC values to display GMT? I ask because this problem doesn't seem like it is going to go away anytime soon. Even if you get it to work now - in the future it might break again. If I come up with a method for this I will update my answer.