text:
Q: Using Scrollbar plugin with DIVs having 100% height I tried to use the jQuery Scrollbar plugin with my 3-column-layout (Update: Switched to slimScroll plugin now). The 3 columns shall use 100% browser height. The idea is that the scrollbars only appear when hovering the corresponding column.
With my layout the scrollbar is not working fine. I already call the function each time the window is resized (what I initially tried to avoid because its - from my point of view - a hack):
$(window).resize(function()

Here  is the fiddle.
The code to initialize the scrollbar is in line 226 (before I pasted the jquery.slimscroll.js).

function setFrameSizes() {
  console.log("Set scrollbar");
  $('.inner').slimScroll({
    height: $(window).height() - 46
  });
}

$(document).ready(function() {
  setFrameSizes();
});
$(window).resize(function() {
  setFrameSizes();
});

A: Assuming that every div has the same height:
var myHeight = $('.myDiv').height();
$(".myDiv").slimscroll({
    wheelStep: 20,
    color: '#fff',
    height: myHeight
});

If that's not the case then you could maybe try referencing to the each div by ID, or something like this:
$(".myDiv").each(function(){
     var myHeight = $(this).height();
     $(this).slimscroll({
        wheelStep: 20,
        color: '#fff',
        height: myHeight
      });

});


text:
Q: Kill and restart ngrok within a shell script I need to kill and restart my ngrok server every 24 hours, so I thought about using a cronjob to run a shell script. The issue I am facing is that when I restart ngrok within the shell script, it starts it within that given shell session.
How can I go about starting ngrok in a different session, so that I can continue to do other checks within the same script?
The code I have so far:
# grabs the PID for the current running ngrok
ngrok_pid=$(pgrep ngrok)
echo "Current ngrok PID = ${ngrok_pid}"

# kills ngrok
kill_ngrok_pid=$(kill -9 $ngrok_pid)

# get exit status code for last command
check=$?

# check if the exit status returned success
if [ $check -eq 0 ]; then
    # re-start ngrok
    $(./ngrok http 5000 &)
    # do more checks below...
else
    echo "NO ngrok PID found"
fi

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't open folders with spaces I have the following code to read items from my FTP-Server:
internal List<FtpItem> OpenFolder(string folderName)
{
   FtpWebRequest request = CreateFtpWebRequest("ftp://myserver.com", folderName);
   request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
   List<FtpItem> ftpItems = GetFtpItemsFromRequest(request);
   return ftpItems;
}

private List<FtpItem> GetFtpItemsFromRequest(FtpWebRequest ftpWebRequest)
{
   List<FtpItem> ftpItems = new List<FtpItem>();
   WebResponse webResponse = ftpWebRequest.GetResponse();
   StreamReader reader = new StreamReader(webResponse.GetResponseStream());
   string line = reader.ReadLine();
   while (line != null)
   {
      ftpItems.Add(new FtpItem(line));
      line = reader.ReadLine();
   }
   reader.Close();
   webResponse.Close();
   return ftpItems;
}

private FtpWebRequest CreateFtpWebRequest(params string[] url)
{
   FtpWebRequest webRequest = (FtpWebRequest)WebRequest.Create(string.Join("/", url));
   webRequest.KeepAlive = false;
   webRequest.UseBinary = true;
   webRequest.Credentials = this.networkCredential;
   return webRequest;
}

As long as I try to open a folder like root/sub/subsub everything works fine. But if the foldername contains a space, I get the error-message
No such file or directory

I tried to replace the space-character by %20, but this doesn't work.
What do I have to do to open folders which contains spaces?

A: You forgot a closing "/" at the end of your url request. So either append it to the end of the request:
FtpWebRequest webRequest = (FtpWebRequest)WebRequest.Create(string.Join("/", url)+"/");

or add an empty string as url parameter:
FtpWebRequest request = CreateFtpWebRequest("ftp://myserver.com", folderName,"");


text:
Q: Print the best thresholds of multiple ROC curves in one plot I am trying to print the best threshold in the pROC package and combine multiple ROC curves in one plot at the same time. I succeeded in doing each separately, but couldn't do both together.
library(ggplot2)
library(pROC)
dataframe<-data.frame (
  response= c("0","1","0","1","1","0","1","0","1","1"),
  predictor1= c(".3",".9",".2",".6",".7",".5",".5",".3",".7",".8"),
  predictor2= c(".4",".8",".1",".5",".6",".6",".4",".4",".8",".6"),
  predictor3= c(".2",".7",".3",".4",".7",".7",".3",".3",".9",".7"))

A single ROC curve with best threshold:
plot.roc(dataframe$response, as.numeric(dataframe$predictor1),
         percent=TRUE,
         ci=TRUE, of="thresholds",
         thresholds="best",
         print.thres="best")

multiple ROC curves:
ggroc(list(
  roc(dataframe$response, as.numeric(dataframe$predictor1)),
  roc(dataframe$response, as.numeric(dataframe$predictor2)),
  roc(dataframe$response, as.numeric(dataframe$predictor3))),
  aes="color")

I could not add the print.thres bits inside the list, and I also did not succeed in putting it into a coord() argument. How can I print the best threshold of multiple ROC curves in one plot?


text:
Q: Can MySQL query include HTML values? REVISED QUESTION:
How can I reference a row of MySQL data while a form is being filled out.  In other words, with my ('Select * FROM... how can I specify the row to pull the fields from without having to process the form to get the PHP fields?
Desired Process 1) User inputs first value, 2) Sidebar MySQL query looks up that value and fills div with data from that row, 3) User continues to fill out form while able to see div filed with MySQL data
ORIGINAL QUESTION:
I am curious if you can include a reference to an HTML input in a MySQL query.
Take the following for an example.
('SELECT * FROM MyTableName WHERE MyColumnID="MyHTMLInputValue"');

I would like to reference all the fields in the row based on the value of an input field and not sure of how to reference such a query.
Thank you!

A: Ajax is the way to go.
This example uses jQuery.
First we need to setup a php script to get our value and search for it, then return our data.
PHP myPhpScript.php
<?php
 $search_value = $_POST["field1"]; //Get our value from the post.
 //Make sure to do some authentication on the value so that bad values dont get through
 $connection = new mysqli(Stuff here);
 $rows = $connection->query(
 "SELECT * FROM someTable where searchColumn LIKE %".$search_value."%"
 );

 //Now all we need to do is send out our data. Lets use json.
 $out = $rows[0];//Get the first row. NOTE: Make sure to remove any columns that you dont want the client to see.

 echo json_encode($out); //Send the client the data.
?>

Javascript Some script on the page.
var textbox = $("#mySearchBox"); //This is the jQuery object for our text box.
var viewbox = $("#myViewer"); //This is the jQuery object for the div that holds the results

textbox.on("input", function () {
$.ajax({
  url: "myPhpScript.php", //This is the php script that we made above.
  method: "POST", //This set our method to POST.
  data: {field1: textbox.val()}, //set the textbox value to field1
  dataType: "json", //So jquery formats the json into an object.
  success: function (phpDataObject) { //Now its up to you to decide what to do with the data. Example below
    viewbox.html("");//Clear the viewbox.
    viewbox.append("Id: "+phpDataObject["id"]); //Show the id of row that was found.
  }
});
});

This code may not work. Just fix whatever syntax errors that show up.
Hope this helps.
Comment if you need any more help.

A: This does not sound like a good idea. Usually you want some separation between your site and database. You could take in "MyHTMLInputValue", process it, then you can complete your query.
var myValue = MyHTMLInputValue;
//validate input
('SELECT * FROM MyTableName WHERE MyColumnID="' + myValue + '"')


text:
Q: How would i interprete smiles in a python string? Well, I came back to writing a bot for vk on python.
It shows first signs of life and first obstacles.
One of these are smiles that may arrive in a private message or chat.
I have a function that disassembles every incoming message into string using my own functions and json library.
#getting a message

def getmessage(out, count):
    payload['out']=str(out)
    payload['count']=str(count)
    return json.loads(requests.get(api+'messages.get', payload).text)    ['response']['items'][0]

#disassembling a message

def messageanalysis(message):
    m=message
    mes={
    'date':m['date'],
    'id':m['id'],
    'user_id':m['user_id'],
    'body':m['body']}
    return mes

So, then I .split() the string mes['body'] and compare every word from it to a set of templates and based on the result decide what to answer.
So just now I've received a smile in private messages and the program crashed, not knowing what to do with a .png file. It's interesting that unlike a regular attachment that has its own parameters in the object "message", received by vk server, the smile is directly integrated into the body of the message. What should I do to at least prevent the program from crashing because of smiles, or, which is better, make it recognize that a smile was sent?
======
Error:
Traceback (most recent call last):
  File "C:\BOT\Body.py", line 24, in <module>
    print('User_id: '+str(m['user_id'])+'\nMessage: '+str(m['body'])+'\n')
  File "C:\Users\Арсений\AppData\Local\Programs\Python\Python35-32    \lib\idlelib\PyShell.py", line 1344, in write
    return self.shell.write(s, self.tags)
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 28-28:     Non-BMP character not supported in Tk

A: The code that is in your question is not the problem. You are using IDLE (based on the error message), which doesn't support displaying the characters outside of the "Basic Multilingual Plane" of Unicode (emojis are outside of the BMP). You should switch to using a command prompt, or replace the non-BMP characters with something else before printing them.


text:
Q: Свойство зависимости из UserControl в MainWindow Не работает свойство зависимости
UserControl.cs:
    // private double Radius = 100;
    private void DrawScale()
    {
        double bigTick = 9;
        for (double i = 0; i <= 90; i = i + bigTick)
        {
            Point p = new Point(0.5, 0.5);
            Rectangle r = new Rectangle
            {
                Height = 5,
                Width = 15,
                Fill = new SolidColorBrush(Colors.Aqua),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                RenderTransformOrigin = p
            };

            TransformGroup trGp = new TransformGroup();
            RotateTransform rTr = new RotateTransform();
            double iRadian = (i * Math.PI) / 180;
            rTr.Angle = i;
            trGp.Children.Add(rTr);
            TranslateTransform tTr = new TranslateTransform();
            tTr.X = (int) ((Radius) * Math.Cos(iRadian));
            tTr.Y = (int) ((Radius) * Math.Sin(iRadian));
            trGp.Children.Add(tTr);
            r.RenderTransform = trGp;
            gr.Children.Add(r);
        }
    }

    public double Radius
    {
        get { return (double)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("Radius", typeof(double), typeof(RoundScale), null);

userControl.xaml
  <Grid x:Name="gr"/>

MainWindow.xaml
 <Grid>
    <local:RoundScale Radius="90" />
 </Grid>

Если переменную Radius в UserControl.cs разкомментировать и удалить из кода свойство зависимости то все работает как надо.

A: Вы неправильно определили dependency property. CLR-свойство должно называться так, как ваше dependency property, минус суффикс Property. В вашем случае dependency property называется MyPropertyProperty, а CLR-свойство — Radius.
Переименуйте dependency property в RadiusProperty.

Документация: https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/custom-dependency-properties#checklist-for-defining-a-dependency-property:

When you create the identifier field, name this field by the name of the property as you registered it, plus the suffix Property.

Ещё одна проблема — опрос dependency property из конструктора. Дело в том, что значение dependency property, заданное непосредственно в XAML, устанавливается в InitializeComponent, а привязки могут сработать ещё позже. Поэтому имеет смысл либо читать значение на событии Loaded, либо подписаться на изменения.

Если вам нужно подписаться на изменения, проще всего указать callback в определении dependency property:
public double Radius
{
    get { return (double)GetValue(RadiusProperty); }
    set { SetValue(RadiusProperty, value); }
}

public static readonly DependencyProperty RadiusProperty =
    DependencyProperty.Register(
        "Radius", typeof(double), typeof(RoundScale),
        new PropertyMetadata(0.0, OnRadiusChangedStatic));

static void OnRadiusChangedStatic(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
    ((RoundScale)d).OnRadiusChanged();

void OnRadiusChanged()
{
    // тут у вас поменялся радиус, реагируйте
}


text:
Q: How to Console.log elements of an array I am currently console logging:
Array(2)
0: {id: '0p1a3', name: 'Ligue 1'}
1: {id: '0s7a9', name: 'La Liga'}
length: 2
[[Prototype]]: Array(0)

I would just like to console log the name of each competition, i have tried
  let comps = this.state.competitions.name;
    console.log(comps)


text:
Q: How to change UILabel frame on the basis of its child frame in Auto Layout environment I am customizing UILabel. All I want to do is set a custom view inside UILabel. I added the label's width and height constraint to greater than 100. Now when I add sub view to label, I want to update the label's frame according to its child's frame. How can I achieve this?
Any help will be thankful.

A: First, lower the priority of the width and height constraint to 800 or so. Then, add constraints so that the label is always at least as tall and wide as its subview:
[self.label addSubview:otherView];
[self.label addConstraints:
 [NSLayoutConstraint
  constraintsWithVisualFormat:@"|-0-[otherView]->=0-|"
  options:0
  metrics:nil
  views:@{@"otherView" : otherView}]];
[self.label addConstraints:
 [NSLayoutConstraint
  constraintsWithVisualFormat:@"V:|-0-[otherView]->=0-|"
  options:0
  metrics:nil
  views:@{@"otherView" : otherView}]];

A: I have implemented the other way. As I am looking for a way in which I do not need to deal with constraints and It will behave as it was configured. For that I have Derived UILabel and created a Custom Label. Then I implemented addSubView and intrinsicSize methods as below:
@implement MxCustomLabel

@synthesize dummyView;

- (void) addSubView:(UIView*)view
{
    self.dummyView = view;

    [self invalidateIntrinsicSize];

    dispatch_async(dispatch_get_main_queue(), ^{

        [super addSubView:view];

        });

}

-(CGSize) intrinsicSize
{
   return CGSizeMake(self.dummyView.frame.size.width, self.dummyView.frame.size.height);
}

@end

Only thing to take care is to set Label's width and height constraints to greater than or equal in interface builder. If it is set to equals then this implement will respect constraint and will not enlarge. However, if you set either height OR width to greater than or equal then this implement will expand the size for corresponding constrain.
In this similar manner we can design custom component from all basic components which are derived from UIView.
Although, it has limitation that, it will grow parent UIView from center. we can not control the growing direction. If this also can be achieved then it will be awesome.


text:
Q: How do you stop users directly accessing files on a website in IIS I want to stop users on the internet being able to enter this URL into a browser and access these files directly. How can I do this?
note: application developed in asp.net
for example: mysite/uploadedfiles/file1.txt
is there any iis rule? Please help me.

A: Try to use the requestFiltering and hidden segments security feature in web.config.
<configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <hiddenSegments applyToWebDAV="false">
               <add segment="uploadedfiles" />
            </hiddenSegments>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

A: My advice would be not to store these files in a location which is accessible via a URL in the first place. Then the problem is solved without worrying about permissions etc.
Once the user has uploaded the file, you can store it in some other place on the server's disk - no need for it to be within the web application.
And if the file must be downloadable again later, you can write an action method to find the necessary document on disk and transmit a copy of it in the response, without the webserver ever having direct access to it.


text:
Q: if Y1 and Y2 are independent, does it follow that U and X are independent, where U = f1(Y1, Y2) and X= f2(Y1, Y2) If X, Y are iid rvs, and U and Z are r.v.s that can each be written in terms of X and Y, does that mean that U and Z are independent?

A: No. Consider i.i.d. standard normal random variables, $\,X,Y\sim\mathcal{N}\left(0,1\right)\,.$ Let $\,\,U{}={}a_1X+a_2Y\,\,$ and $\,\,Z{}={}b_1X+b_2Y$ for non-zero real numbers $a_1, a_2, b_1$ and $b_2$.
Then, see that

$$
\mathbb{C}ov\left(U,Z\right){}={}a_1b_1+a_2b_2\ne0\,,
$$

therefore $U$ and $Z$ can't be independent.

A: No, and there's a trivial counterexample (or example, depending on how you interpret it): $U=Z=X+Y$ (or any other expression, even a constant, instead of $X$ and $Y$).

A: Even more trivial:  Let $U = Z$ be the same function of $X$ and $Y$.  Then $U$ and $Z$ are obviously dependent.  Or let $U = g(Z)$ for some non-degenerate function $g$.


text:
Q: Bootstrap button outline remain highlighted after click I have the following bootstrap 4 button code.What I am finding is that only on my mobile device, the button remains highlighted after clicked. The color of it is exactly the same as if I hovered it over with a mouse on my desktop device
<button class="btn btn-outline-primary d-inline">
  Search
  <i class="fa fa-search float-right" aria-hidden="true"></i>
</button>

Or in other words, it is pretty much the same as if I clicked on the button on my desktop mouse and dont hover away.
To me, it seems like one of the following occurred

*

*On the mobile device, the click on the button simulates moving the mouse to that point and trigger the click event. However, the "invisible" mouse on the mobile device never hover away??

*Something else?
How can I get rid of this behaviour?

A: Its because mobile browsers (modern ones) support hover state.
 what you can do is override it for case of mobile with
button.btn:hover {
    background-color: inherit || < your color >;
}


text:
Q: Can a PDA with two stacks accept RE Language? So, I was having a bit of difficulty figuring what exactly is meant by a String on which Turing Machine does not halt. I read somewhere that a Turing Machine is equivalent to a deterministic automata with 2 stacks. But how will a deterministic automata with 2 stacks accept a string that doesn't halt when for any finite string it is determined to halt... Am I missing something??

A: A PDA with two stacks is equivalent to a Turing machine. To show a TM is at least as powerful as a two-stack PDA, we can use the fact that a TM is exactly as powerful as a two-tape TM. In a two-tape TM, we can restrict usage of the tapes to simulate their being stacks. So, certainly a TM can do whatever a two-stack PDA can do.
To show a PDA with two stacks is at least as powerful as a two-stack TM is a little trickier, but basically the idea is that you can simulate a single tape using the two stacks as follows:

*

*Call one stack L and the other R

*The contents of L represent everything to the left of the tape head (including the current symbol)

*The contents of R represent everything to the right of the tape head

*To overwrite the current symbol: pop from L and push to L

*To move left in the tape: pop from L and push to R

*To move right in the tape: pop from R and push to L

So, we can move left and right and overwrite symbols. This lets us simulate a tape, which is all a TM can do anyway.


text:
Q: appendTo not working for this function yet append works Ok, So I have over 1000 lines of jQuery code, and other functions are also using appendTo and it works.
However it seems that the following function appendTo wont work, while append does work.
I think it is because I am creating the DIV in the jquery file and the asking another function to fill that div. but am not sure if that is the reason.
here is the function that is playing up.
function getmessage(e) {
    $('#loadmessage').html("");
    $.getJSON('sys/classes/usermessage.php?task=fetch&subkey=' + e + '&userid=' + sessionparts[1], function(getmessage) {
        // get line status
        $.each(getmessage, function(i, item) {

            $('#loadmessage').append(item.subkey);
        });
    });
};

A: The reason is that .appendTo() will not work in this case because your item.subkey is not a dom element. You have 2 choices.
1) Use .append() as your code is now
2) For using .appendTo() put your item.subkey in a dom node, as the following:
$.each(getmessage, function(i, item) {
    $("<span />").text(item.subkey).appendTo('#loadmessage');
});

Hope this helps. Cheers


text:
Q: cs50 pset7 houses roster My roster.py function in pset7 works as it should except for the fact that it returns 4 or 5 copies of the name and birthyear instead of just one. Through debugging you can see that the problem is with the results variable. It stores all of the copy pasted names instead of one name.
Heres my code:
import sys
from cs50 import SQL

if len(sys.argv) != 2:
    print("Needs two command-line argument")
    exit(1)

db = SQL("sqlite:///students.db")

house = sys.argv[1]

results = db.execute("SELECT * FROM students WHERE house = ? ORDER BY last ASC, first ASC", house)

for row in results:
    if row["middle"] != None:
        print(f'{row["first"]} {row["middle"]} {row["last"]}, born {row["birth"]}')
    else:
        print(f'{row["first"]} {row["last"]}, born {row["birth"]}')

A: Go into your students.db,
go in students table,
empty your table,
Then Run Following Command and make sure to run import.py once
$ python import.py characters.csv
$ python roster.py Gryffindor

if you run more than once import.py then there will be more copies and you will need to empty the table


text:
Q: How do I get udev to mount certain USB disks when they are plugged in, or after a reboot? I've just upgraded to Fedora 15.  I've used Bacula for backup for some years now, and it works fine.  But now I've just run into a problem, probably because Bacula is now running as user bacula rather than as root.
My backup media is two USB disk drives (I keep one offsite and swap them over once a month or so).  However Fedora auto-mounts the USB drive with its mount point owned by my UID with mode 700, presumably because I am logged in and this would be the Right Thing for most USB storage.  However in this case it is not because Bacula can't access it.
If I understand the sequence of events correctly, udev creates the /dev/sdb and /dev/sdb1 device nodes, and these are then automounted by udisk (which is a Gnome component).  It's udisk that decides what the mount parameters are.
What I want is for any disk labelled "BACKUP*" to be mounted with its mount point owned by bacula:bacula, mode 700.  I think I need a custom udev rule file in /etc/udev/rules.d.  I've read the udev(7) page and "Writing udev rules".  Here is what I have come up with so far, in a file called "10-backup-disk.rules".  It's being parsed by udev OK, but isn't working: the disk still winds up being owned by me.  Can someone tell me what I am doing wrong?
Thanks.
KERNEL!="sd[a-z][0-9]", GOTO="backup-disk_auto_mount_end"
ENV{ID_FS_LABEL}!="BACKUP*", GOTO="backup-disk_auto_mount_end"

# Import FS infos
IMPORT{program}="/sbin/blkid -o udev -p %N"

# Get disk label
ENV{dir_name}="%E{ID_FS_LABEL}"

# Global mount options
ACTION=="add", ENV{mount_options}="relatime,rw"
# Filesystem-specific mount options
ACTION=="add", ENV{mount_options}="$env{mount_options}"

# Mount the device
ACTION=="add", RUN+="/bin/mkdir -p /media/%E{dir_name}", RUN+="/bin/mount -o $env{mount_options} /dev/%k /media/%E{dir_name}"

# Clean up after removal
ACTION=="remove", ENV{dir_name}!="", RUN+="/bin/umount -l /media/%E{dir_name}", RUN+="/bin/rmdir /media/%E{dir_name}"

# Exit
LABEL="backup-disk_auto_mount_end"

A: I know nothing about udev, but since you're using Fedora 15 you can accomplish the same thing with systemd much more simply.
Assuming you have a USB drive labeled BACKUP_ONE, create the following file:
/etc/systemd/system/mnt-backup1.mount:
[Mount]
What=/dev/disk/by-label/BACKUP_ONE
Where=/mnt/backup1
Options=uid=bacula,gid=bacula,mode=0700

Note the filename must end in .mount and have a name that matches the mount point (in the Where= line of the unit file), with slashes (/) changed to dashes (-).  For more information, see man systemd.unit.
Additionally, you can prevent it from mounting the drive until Bacula actually runs a backup (or you try to access the drive) by creating /etc/systemd/system/mnt-backup1.automount:
[Automount]
Where=/mnt/backup1
[Install]
WantedBy=remote-fs.target

Repeat this for your other drive, and then run systemctl enable mnt-backup1.automount and systemctl daemon-reload to inform systemd of the changes.  (I'd make sure they're unplugged at this time so it doesn't get confused.)
udisks will now defer to your systemd configuration and mount it with the options you defined.


text:
Q: Detecting user abort/navigation websockets I'm experimenting with websockets and would like to detect if a user has navigated away from the page to the PHP stream script from running. Everything else is working fine.
Everything I try to do does not stop the PHP script from running (using Xampp locally).
I'm currently working with javascript's beforeunload, and PHP's connection_aborted(), connection_status() and even file_exists() (which is the only one that works currently!!!).
Until the script exists or I restart apache I cannot reload the page but it's the abort detection that I have to get working. Firebug reports the socket script has aborted but PHP just keeps ion running. Any help appreciated.
My javascript looks like this
function socket_open(){
    if(!!window.EventSource){
        var websocket = new EventSource('./ajax/progress.php');
        websocket.addEventListener('message', function(e){
            var data = JSON.parse(e.data);
            console.log(data);
        },false);
        $(window).bind('beforeunload', function(){
            websocket.onclose = function(){};
            websocket.close();
        });
    }
}

And my PHP is like this.
./ajax/progress.php
function get_task_progress(){
    $output = array();

    //conditionally create some output

    if(!empty($output)){
        echo 'data: '.json_encode($output)."\n\n";
        ob_flush();
        flush();
    }
    sleep(1);
    if(!connection_aborted() && connection_status()==0 && file_exists('1.txt')){
        get_task_progress();
    }
}

A: I seem to have solved it but echoing and flushing a no updates status on every request before the test for a live connection
if(!empty($output)){
    $tasks_state = $tasks_new;
    echo 'data: '.json_encode($output)."\n\n";
}else{
    echo 'data: '.json_encode(array('e'=>0))."\n\n";
}

ob_flush();
flush();
sleep(1);
if(!connection_aborted() && connection_status()==0){
    get_task_progress();
}


text:
Q: Django models, referencing and storing model id I have a model by name Order, I want to create and invoice_number field on this same model and store order id and some other generated text to make up  order invoice_number and I can't figure it out, I think there is a short and neat way to achieve this and I will appreciate any help Thanks.
This code throws and error that self is not defined
here is my code
import datetime
YEAR = datetime.datetime.today().year

class Order(models.Model):
    customer_contact = models.IntegerField()
    paid = models.BooleanField(default=False)
    date = models.DateTimeField(auto_now=True)
    salesman = models.CharField(db_index=True, max_length=20)
    discount = models.IntegerField(default=0)
    price =  models.IntegerField(default=0)
    customer_name = models.CharField(db_index=True, max_length=20)
    apartment_name = models.CharField(db_index=True, max_length=20)
    flat_number = models.IntegerField()
    invoice_number = models.CharField(max_length=20,
    default=f'{YEAR}/INV/000{self.pk}')


text:
Q: Insert Textbox values in Array in Jquery / Javascript I have a textbox in which user can add some values one by one. Now, when user click on add button I want to insert value that user enter into array one by one. I am doing this but I am getting the wrong result. The length of array is not increasing. Say If I entered 2 values then the length of array remain 1. I don't know what's the error. Below is my code:-
HTML
<input type="text" class="form-control input_add_prod_grp" name="input_add_prod_grp" placeholder="Enter Group Name" />

<button class="btn default btn-xs btn_add_input_prod_grp" name="btn_add_input_prod_grp" id="add_group">Add</button>

Javascript
$(".btn_add_input_prod_grp").click(function(){

var add_input_grp = $("input[name$='input_add_prod_grp']").val();

var newArray = [];
newArray.push('Ungrouped');
$( "input[name='input_add_prod_grp']" ).each(function() {
    newArray.push($( this ).val());

});
console.log(newArray.length);
});

Now, If I enter more than 1 value then length of array remain 1. I don't know why.. Please help me out.. Thanks in advance..

A: Take you array outside:
var newArray = [];
$(".btn_add_input_prod_grp").click(function(){

   var add_input_grp = $("input[name$='input_add_prod_grp']").val();

  newArray.push(add_input_grp);
  console.log(newArray.length);
});

JSFIDDLE:https://jsfiddle.net/c19u6fa2/1/

A:

var newArray = [];
$(".btn_add_input_prod_grp").click(function() {

  var add_input_grp = $("input[name$='input_add_prod_grp']").val();

  newArray.push('Ungrouped');
  $("input[name='input_add_prod_grp']").each(function() {
    newArray.push($(this).val());

  });
  console.log(newArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control input_add_prod_grp" name="input_add_prod_grp" placeholder="Enter Group Name" />

<button class="btn default btn-xs btn_add_input_prod_grp" name="btn_add_input_prod_grp" id="add_group">Add</button>

Put the initialization outside of click event. Inside click event it is always reinitialize over and over.

A: You are making newArray empty when you click on button so the old values are deleting from that array to avoid this you have to move that to outside of your function along with default values you have only one input box you no need to write each you can get directly that value from your variable
            var newArray = ['Ungrouped'];

            $(".btn_add_input_prod_grp").click(function(){

                var add_input_grp = $("input[name$='input_add_prod_grp']").val();

                newArray.push(add_input_grp);

                console.log(newArray.length);

            });


text:
Q: How to get the angle from quartnenion value? Using android phone, I am able to get quarternion value x,y,z from TYPE_ROTATION_VECTOR
However, I do not know how to get the angle.
Anyone have any idea on this? Thank you.

A: Taken from here
    /**
     * Returns the heading, attitude and bank of this quaternion as euler angles in the double array respectively
     *
     * @return An array of size 3 containing the euler angles for this quaternion
     */
    public double[] toEulerAngles() {
        double[] ret = new double[3];

        ret[0] = Math.atan2(2 * points[1] * getW() - 2 * points[0] * points[2], 1 - 2 * (points[1] * points[1]) - 2
                * (points[2] * points[2])); // atan2(2*qy*qw-2*qx*qz , 1 - 2*qy2 - 2*qz2)
        ret[1] = Math.asin(2 * points[0] * points[1] + 2 * points[2] * getW()); // asin(2*qx*qy + 2*qz*qw)
        ret[2] = Math.atan2(2 * points[0] * getW() - 2 * points[1] * points[2], 1 - 2 * (points[0] * points[0]) - 2
                * (points[2] * points[2])); // atan2(2*qx*qw-2*qy*qz , 1 - 2*qx2 - 2*qz2)

        return ret;
    }


text:
Q: Bash - Return value from subscript to parent script I have two Bash scripts. The parent scripts calls the subscript to perform some actions and return a value. How can I return a value from the subscript to the parent script? Adding a return in the subscript and catching the value in the parent did not work.

A: I am assuming these scripts are running in two different processes, i.e. you are not "sourcing" one of them.
It depends on what you want to return.  If you wish only to return an exit code between 0 and 255 then:
# Child (for example: 'child_script')
exit 42

# Parent
child_script
retn_code=$?

If you wish to return a text string, then you will have to do that through stdout (or a file).  There are several ways of capturing that, the simplest is:
# Child (for example: 'child_script')
echo "some text value"

# Parent
retn_value=$(child_script)

A: Here is another way to return a text value from a child script using a temporary file. Create a tmp file in the parent_script and pass it to the child_script.  I prefer this way over parsing output from the script
Parent
#!/bin/bash
# parent_script
text_from_child_script=`/bin/mktemp`
child_script -l $text_from_child_script
value_from_child=`cat $text_from_child_script`
echo "Child value returned \"$value_from_child\""
rm -f $text_from_child_script
exit 0

Child
#!/bin/bash
# child_script
# process -l parm for tmp file

while getopts "l:" OPT
do
    case $OPT in
      l) answer_file="${OPTARG}"
         ;;
    esac
done

read -p "What is your name? " name

echo $name > $answer_file

exit 0

A: return a value from the subscript and check the variable $? which contain the return value


text:
Q: The project plan suggestions I have coursework to do and I am still not sure about some planning parts of my project.
So, let me explain, I've got a SQL file (a big database with dummy data) and my task is to setup and connect to the database and write Java code and satisfy a few requirements which will check if my connection with the database is valid. The database consists of tables such as customers, payments, orders, products, etc. My task is to do some calculations with those tables, also the focus is on coding, not on queries.
Here is what I came up with: (let's focus on the payment table and calculations) I have 5 classes: Main class, MySQLAccess class and one class for each table(payment, orders, customers).
Class diagram
Please have a look at the diagram above
My biggest concern is where and when should I populate my lists, in the test classes, or in the main class when the app is run, also do i need Main class or it could be control class.
Please feel free to submit any reasonable suggestion - class diagram changes


text:
Q: remove bottom panel in xfce How remove the bottom panel in xfce
I am using vmware VM debian-10.0.0-amd64-xfce-CD-1

A: To remove the bottom panel, right click in the panel, then click the - button.

A: Just click control + right click on the panel then go to panel then click panel preferences.At the top of the window choose panel 2 then click  symbol which is in the right end of panel 2


text:
Q: how can i use jalali calendar (persian calendar) in react-big-calendar I create a project with react-big-calendar (code) and I want to use jalali calendar in this project instead of georgian.
I found a jalali-react-big-calnedar repo but its based on old version of react-big-calendar.
how can i change the default lib calendar to jalali?

A: I haven't tried this, but you may be able to use the momentLocalizer using a decorated moment with moment-jalaali, and the proper culture prop. Being unfamiliar with the culture used, you may also require the rtl prop.
Again, not sure if this would work for you or not. Think I would fork the Big Calendar CodeSandbox and do some testing first, if I were you.

A: /*
If I understood correctly, you want to change your calendar to Farsi;  This is a React component for Khayyam's calendar. (Jalali):
*/

const Jalali = () => {
    const date = new Date();
    const option = {
        weekday: "long",
        year: "numeric",
        month: "numeric",
        day: "numeric",
        };
    return (
        <>
            <div>
                {date.toLocaleDateString("fa-IR", option)}
            </div>
        </>
    );
};

export default Jalali;


text:
Q: Hangfire run background job only once I have one hangfire server running.
I created a background job as follows
  BackgroundJob.Enqueue(() => new MyJob().Execute(path));

This job should run just once but in the processing jobs part of the web portal  i see it running multiple times at once. How do I prevent this and ensure that the job is only ever kicked off once?

A: Every time you make that call, it will add another job to the DB.  If you have that going on in Startup and your app frequently restarts, that will cause the behavior you're reporting.  You could use the attribute DisableConcurrentExecution on your method call, or you can enter the jobinto the DB as a timed recurring job via Hangfire.RecurringJob.AddOrUpdate instead of BackgroundJob.Enqueue

A:    var options = new BackgroundJobServerOptions { WorkerCount =1 };
            app.UseHangfireServer(options);

I hope this will help you


text:
Q: checking if date is between range I have a custom calendar setup using a UICollectionView and I have an array that hold dates through 30 days.  What I am trying to do is find out if a value is between the current date and 7 days before it.  If it is I need it to do something.  I cannot figure out what I am doing wrong.  Here is what I have so far:
    NSDateFormatter *df = [NSDateFormatter new];
    [df setDateFormat:@"MM-dd-yy"];
    NSdate *date = [NSDate date];
    NSDate *newCurrentDate = [date dateByAddingTimeInterval:+14*24*60*60];
    NSDate *sevenDaysBeforeCurrent = [date dateByAddingTimeInterval:-7*24*60*60];

    if([[df stringFromDate:[days objectAtIndex:indexPath.item]] compare:[df stringFromDate:newCurrentDate]] == NSOrderedAscending && [[df stringFromDate:[days objectAtIndex:indexPath.item]] compare:[df stringFromDate:sevenDaysBeforeCurrent]] == NSOrderedDescending )
    {

            UIImage *buttonImage = [UIImage imageNamed:@"dates.png"];
            [myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];

    }

What it does is change the image of every date before the newCurrentDate instead of just the previous 7.  Can anyone see what I am doing wrong?
Heres the initialization of the array:
myDays = [[NSMutableArray alloc] init];
    NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
    NSDate *today = [NSDate date];
    date = [NSDate date];

    for (int i = 0; i < 31; i++)
    {
        NSDateComponents *comps = [[NSDateComponents alloc]init];
        [comps setDay:i];
        [myDays addObject:[cal dateByAddingComponents:comps toDate:today options:0]];
    }

A: You don't need to be using the dateFormatter.
if([dateInQuestion compare:newCurrentDate] == NSOrderedAscending && [dateInQuestion compare:sevenDaysBeforeCurrent] == NSOrderedDescending){
    // do something
}

A: Try something along these lines:
NSDate *currentDate = [NSDate date];
NSDate *dateSevenDaysPrior = [currentDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)];
NSDate *someDate = [currentDate dateByAddingTimeInterval:-(3 * 24 * 60 * 60)]; // adjust as you like

if (([dateSevenDaysPrior compare:someDate] != NSOrderedDescending) &&
    ([someDate compare:currentDate] != NSOrderedDescending))
{
    NSLog(@"date is in range");
}
else
{
    NSLog(@"date is not in range");
}

This assumes that what you're providing (what someDate is standing for in this example) really is an instance of NSDate.


text:
Q: jQuery Tablesorter - initial sort rows from array i'm trying to inital sort a table by it's row-numbers from an array/variable like
$list: row0=id2;row1=id0;row2=id1...

...

...

...

How can i handle with tablesorter that the rows will be sorted like in $list?
thanks for any tipp or workaround :)

A: This is a possible duplicate of: How to sort DOM elements while selecting in jQuery?

$('#myt tr').sort(function(a, b) {
  if (parseInt(a.id) > parseInt(b.id)) return 1;
  else return -1;
}).each(function() {
  $('#myt').append($(this));
});
td {
  border: 1px solid grey;
  padding: 10px;
}

    8

    1

    21

    5

A: maybe not what was originally intended but it's a workaround :)
var sortTable = [1,5,2,3,4];
$.each(sortTable, function(){
   $("table#productList").append($("#" + this));
 })

thanks for the responses and help!!


text:
Q: Office add-in for save location When you open office 2013 and click "Open", you have 3 choices by default (Recent, OneDrive and Computer) and the possibility to "Add a Place".
I would like to create a add-in to add a custom place...
See, I develop a Electronic Document Manager software, and I provide a add-in to office suit, this would be another feature of the add-in.
Instead of "saving-locally-and-uploading-the-file-to-the-site" and/or "downloading-document-and-read", the user would just open and/or save to the site... I would use the Save/Open event to check if everything is right and the user has access and etc...

A: It kind of depends what you mean by 'office add-in'. Microsoft rather confusingly renamed the modern 'office store apps' to 'add-ins' at the Build 2015 event. However we also still have the old style VSTO 'add ins'.
If you mean a modern store add-in, then no, those only have limited access to read/edit the document via the office JS library.
If you mean the old style VSTO add-in, then I am not sure.


text:
Q: Prestashop Webservice Image Upload Hello and thanks in advance, now I'm trying to upload a image to a prestashop 1.7 via webservice and I'm unable to insert a image in a product. I don't know what fails, because I don't get any response of the webservice, even with the debug enabled (I get the xml responses of the rest of the files, but not the ones from curl).
The variable $idProduct is a value passed to the function and is defined.
My code is the following:
$url = PS_SHOP_PATH."api/images/products/".$idProduct;
$dir_path_to_save = 'img/import/';

$img_path = getFile($remoteImageURL, $dir_path_to_save);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, PS_WS_AUTH_KEY.':');
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => '@'.$img_path));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
echo print_r($response);
curl_close($ch);

The getFile function downloads the image to the server where is installed the prestashop and returns the path (returns a string with the real path where the image is stored, already tested).
I tried to make a form to upload the image (just for testing), but it returns "code 66 - unable to save this image". I don't know if this helps.
Thanks
UPDATE
A fellow programmer told me to use curl_file_create()
So I changed the $img_path declaration this way:
$img = curl_file_create($dir_path_to_save.'/'.basename($img_path));

Now everything works as intended.


text:
Q: Should I create an extra user (other than root) for my web server? I want to host a small homepage via node.js from an DigitalOcean Debian droplet. I added SSH-keys for my personal MacBook and I'm able to connect via SSH (only my MacBook is registered otherwise you are instantly kicked out and not even asked for an SSH password).
I'm currently connecting via something like: ssh root@MY-IP-ADDRESS on a fresh Debian 8.6 x64 installation. This is the first time I'm setting up a real node.js server with the purpose of actually serving something.
Many times I read that you should definitely not run the server process (in this case node) as root. I think I'll need another user (other from root), something like server with just enough permission to handle the server.
I'm currently asking myself, if I even should work via root - should I even add a fancy .bashrc or .vimrc? Or is it preferred to spend as little time as root as possible?
What is the recommended approach here?

A: Yes, you absolutely should. In fact in many systems you never log on as root ever. SSH root logins should be disabled and key based authentication set up.There's a lot of bad actors who attempt to brute force root and other common usernames in order to get access to anything.
As I recall the 'usual' way to do this is to have a 'proper' web server acting as a proxy - say ngnix, passing traffic to your node.js server running on a higher port.
Alternately you could set firewall to forward ports.
You certainly should avoid being root as much as possible.
What I typically do is to have one account with sudo powers, and set up one account per 'standalone' app. I store anything to do with the application in one place, and use the crontab for that account to start the application on reboot. YMMV


text:
Q: Create Range of Numbers in if Statement I have a range of values 1768 to 1815 and I have my if statement
if (location.x = 1768 to 1815)
{
    //perform code
}

Do i create an array or how can I do this?  Sorry I am new to programming

A: if (location.x >= 1768 && location.x <= 1815)


text:
Q: Why do we need argument name in typescript function type definition? Imagine we want to define a function that takes a string and returns a number.
Why couldn't we define it as
type Foo = string => number

but instead we are forced to write
type Foo = (arg: string) => number

Seems like an overhead


text:
Q: how to execute ajax output script I'm getting an ajax output success data.
Where the data contains some html text and a script.
But the script is not executing, how can I execute the script.
Let's say Ajax response obj is

something....

the above code is my Ajax response.The div is getting rendered, but the alert is not working.

A: Assuming you are not using JSON or jQuery, or any other library, and your AJAX call returns some HTML and/or javascript which is being added to your existing document (eg. using innerHTML), any javascript returned using AJAX will not execute in the browser - except for events on elements in the HTML.
So if your AJAX call returns <input type="button" value="Click me" onclick="alert('hello');" />, the js alert will work ok, but if your AJAX call returns  it will not execute. In that case, you would have to parse the result to extract the javascript and execute it, using a function such as this:
function extract_and_execute_js(output_to_parse)
{
    if(output_to_parse != '')
    {
        var script = "";
        output_to_parse = output_to_parse.replace(/


text:
Q: Signature of PostgreSQL Installers (sha1, sha256, MD5 etc.) I cannot find any reference which clearly shows the signatures of an installer of any PostgreSQL tool in order to verify it. Even looking at the official site (https://www.postgresql.org/download)! It feels very strange to me, but I lost at least one hour looking for them and I was not able to find anything!
Does anyone know where to find those signatures (any official sha, md5 etc. will be OK for me), in general? I'd like to find those before using any installer!


text:
Q: Closing a popup box in Google Translate I am new to NUNIT and am stumped on how to close a dialog box.
The site I am experimenting with is Google Translate.  Part of the code "clicks" on the "Send Feedback Link".
Below is the function I am using:
public void CloseModalWindow(string className)
{
    WebController wPage = new WebController(driver);
    wPage.waitUntilExistsByXPath(className);
    wPage.waitUntilVisibleByXPath(className);
    IWebElement clickButtonXPATH = driver.FindElement(By.XPath(className));
    clickButtonXPATH.Click();
}

The basic logic is that I am trying to simulate is to click the "X" on the upper right hand side of the Google Feedback popup that appears.
Please note that:

*

*The web driver is FireFox.

*I am sending the XPath value (derived from Google Translate directly using FireBug) /html/body/div[3]/div/span[2].

*I've also tried using the CSSSelector method instead of XPATH, sending the value span[class='modal-dialog-title'] into the function.

Nunit will in complete without any errors, but the popup does not close as I am anticipating.
Thank you in advance for your input and insight.

A: From your XPath I see that the "X" is not a natively clickable element - like <a> or <button> are. I experienced that calling Click() on such elements does not what one expects. Instead you could try using the action builder functionality which will simulate a general mouse or keyboard input. Replace
clickButtonXPATH.Click();

with
new Actions(driver).Click(clickButtonXPATH).Build().Perform();


text:
Q: Bootstrap modal interfering with droppable I have draggables and droppables on a page with a bootstrap modal.  They work fine on page load.  However, if the modal is opened and closed, they no longer work.  For this reason, I have placed them inside an init() function which I run after modal close.  This works for the draggables, but not the droppables.  To be clear, after draggableInit() runs the second time, I can drag, but not drop.
$(document).ready(function () {
    draggableInit();
});

// Reinitialize draggables after modal close
$('#gallery-modal').on('hidden.bs.modal', function () {
    draggableInit();
});

function draggableInit() {
    // Draggable
    $('.block-grab').draggable({
        containment: 'document',
        stack: '.edit-container',
        revert: true,
        refreshPositions: true,
        start: function(event, ui) {
            ui.helper.data('not-dropped', true);
        },
        stop: function(event, ui) {
            if (ui.helper.data('not-dropped')) {
                $('.dz').hide();
            }
        }
    });
    // Droppable
    $.each($('.dz-container'), function() {
        var hbid = $(this).data('hbid');
        var position = $(this).data('position');
        $('#dz-'+position+'-container-'+hbid).droppable({
            over: function() {
                $('#dz-'+position+'-'+hbid).show().droppable({
                    accept: '.block-grab',
                    drop: blockDropped
                });
            },
            out: function() {
                $('#dz-'+position+'-'+hbid).hide();
            },
        });
    });
    function blockDropped(event, ui) {
        ui.helper.data('not-dropped', false);
        ui.draggable.draggable('disable');
        $(this).droppable('disable');
        ui.draggable.draggable('option', 'revert', false);

        var hbid = $(this).data('hbid');
        var position = $(this).data('position');
        var type = ui.draggable.data('type');
        $('#dz-'+position+'-'+hbid).show()
        $.post('/controller/drop-block', { hbid : hbid, position : position, type : type });
    }
}

Edit:
It must have something to do with conflicting jquery-ui:
On page load, it loads jquery-ui.min.js
On modal open, it loads jquery-ui.js
Another Edit:
After creating a jQuery modal, I discovered my problem is not a conflict between Bootstrap and jquery, but something in the gallery plugin that I am placing in the modal.


text:
Q: Unnecessary lines appearing between image-links I'm using three images side-by-side, and adding a Url.Action to each one of them.  The code works fine, but the images are being displayed w/ some sort of line between them.  Here is my code:

Edit - This is also happening when I tried an alternate, non-Url.Action method:

Here is how the images are displaying:

A: Try to put each image in one line:

It seems to be the underline of an space in your link. You can also add 'text-decoration: none;' in the style of those links.


text:
Q: How to parse every IP from the Apache access log and count each unique request from them in a CSV file in a bash script? I've been trying to create a bash script to create a CSV file with every IP from an Apache access log, and count how many unique requests that IP made, along with the actual requests.
So far I have this:
#!/bin/bash

# Print the headers to the CSV file
printf "\tRequests\tIP\t\n" > memory.csv

# Create a text file named .access_log.tmp.2 with the IPs and how many requests they made in total - .access.log.tmp is the Apache access log in this case
awk '{ print $1 }' .access_log.tmp | sort -n | uniq -c | sort -nr | head -20 > ".access_log.tmp.2"

# Make it a CSV file
sed 's/[[:space:]]\+/;/g' .access_log.tmp.2 >> memory.csv

# Remove the leftover files
rm .access_log.tmp .access_log.tmp.2

That gives an output like this:

Requests          IP
20                10.0.0.1
15                10.0.0.2

This is how I would want it to look like:
IP              Requests
10.0.0.1        12 "GET / HTTP/1.1" 403 490 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                8 "GET /favicon.ico HTTP/1.1" 403 489 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"

10.0.0.2        13 "GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
                2 "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
etc.

I have no clue where to go from now.
Can someone please help?

Edit: Adding the input and output files below, as requested:
What I have right now
10.0.0.7 - - [17/Nov/2019:14:21:48 +0100] "GET / HTTP/1.1" 403 490 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.7 - - [17/Nov/2019:14:21:48 +0100] "GET /favicon.ico HTTP/1.1" 403 489 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.7 - - [17/Nov/2019:14:22:39 +0100] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.7 - - [17/Nov/2019:14:22:39 +0100] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.7 - - [17/Nov/2019:14:22:39 +0100] "GET /favicon.ico HTTP/1.1" 404 486 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.6 - - [17/Nov/2019:19:07:46 +0100] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:46 +0100] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:47 +0100] "GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:51 +0100] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:51 +0100] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:51 +0100] "GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:52 +0100] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:52 +0100] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:52 +0100] "GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"

^ Input
Requests            IP
9                   10.0.0.6
5                   10.0.0.7

^ Output
What I want to have
Input is the same
IP                            Requests
10.0.0.6                      3 "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
                              3 "GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
                              3 "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"

10.0.0.7                      1 "GET / HTTP/1.1" 403 490 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                              1 "GET /favicon.ico HTTP/1.1" 403 489 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                              1 "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                              1 "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                              1 "GET /favicon.ico HTTP/1.1" 404 486 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"

^ Output

A: Two possible path: single awk program, or combining sort/uniq/awk pipeline. Second is simpler to write:

*

*Eliminate unwanted attributes (timestamp, and 2 '-' fields)

*Sort by IP, Request information

*Count unique IP/Request info

*Sort lines in descending request count

*Format output with awk

cat input |
    awk '{ $2 = $3 = $4 = $5 = "" ; print }' |
    sort |
    uniq -c |
    sort -k2.2nr -k1.1 |
    awk '
{
    printf "%-20s %d", $2 != p ? $2 : "", $1 ;
    p=$2 ; for (i=3 ; i<=NF ; i++) printf " %s", $i ;
    printf "\n"
}'

The alternative pure awk solution is much longer: Run with prog.awk < input
#! /usr/bin/awk -f
{
        ip = $1
        body = $6
        for (i=7 ; i<=NF ; i++) body = body " " $i
        n[ip, body]++
}

function sort_id_count(i1, v1, i2, v2)
{
        ip1 = substr(v1, 1, index(v1, SUBSEP))
        ip2 = substr(v2, 1, index(v2, SUBSEP))

        if ( ip1 < ip2 ) return -1
        if ( ip1 > ip2 ) return +1 ;

        # Descending freq
        return n[v2]-n[v1]
}

BEGIN { OFS="," }

END {
        na=0
        for (k in n) a[++na] = k ;
        asorti(a, ai, "sort_id_count") ;
        p="" ;
        for (ki in ai) {
                k1 = ai[ki]
                k2 = a[k1]
                ip = substr(k2, 1, index(k2, SUBSEP)-1)
                body = substr(k2, index(k2, SUBSEP)+1)
                if ( ip == p ) ip = "" ; else p=ip ;
                printf "%-20s %d %s\n", ip, n[k2], body
        }
}

A: Here is another shortened awk solution (standard Linux gawk).
One file sweep, sort once, no string substitutions, reduced to only 3 fields.
script.awk
BEGIN {FS="( -)|(] \")"} # define field separator " -" or "] "
{ # read each input line
    ipLogsArr[$1,$4]++; # store array counting appearance IP+Log combination
    ipArr[$1]++; # store array counting appearance of IP
    ipLogsArrVal[$1,$4]=sprintf("%s&&&%03d&&&%s", $1, ipLogsArr[$1,$4], $4); # store array of IP+count+Log combination
}
END { # post processing after reading all input
    printf("%-14s %3s %s\n", "IP", "#", "log"); # output header
    count = asort(ipLogsArrVal); # sort array of IP+count+Log combination
    for (i = count; i >= 1; i--) { # for each element of the sorted array, iterate backward
        split(ipLogsArrVal[i],arr,"&&&"); # separate IP+count+Log to into array arr
        ipOut = (currIp == arr[1]) ? "" : arr[1]; # ignore printed IP
        printf("%-14s %3d %s\n", ipOut, arr[2], arr[3]); # print current log
        currIp = arr[1]; # remember current IP, in order to prevent repeated output
    }
}

input.txt
10.0.0.7 - - [17/Nov/2019:14:21:48 +0100] "GET / HTTP/1.1" 403 490 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.7 - - [17/Nov/2019:14:21:48 +0100] "GET /favicon.ico HTTP/1.1" 403 489 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.7 - - [17/Nov/2019:14:22:39 +0100] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.7 - - [17/Nov/2019:14:22:39 +0100] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.7 - - [17/Nov/2019:14:22:39 +0100] "GET /favicon.ico HTTP/1.1" 404 486 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.6 - - [17/Nov/2019:19:07:46 +0100] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:46 +0100] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:47 +0100] "GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:51 +0100] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:51 +0100] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:51 +0100] "GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:52 +0100] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:52 +0100] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
10.0.0.6 - - [17/Nov/2019:19:07:52 +0100] "GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"

running:
awk -f script.awk output.txt

output:
IP               # log
10.0.0.7         1 GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                 1 GET /favicon.ico HTTP/1.1" 404 486 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                 1 GET /favicon.ico HTTP/1.1" 403 489 "http://10.0.0.6/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                 1 GET / HTTP/1.1" 403 490 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
                 1 GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"
10.0.0.6         3 GET /icons/ubuntu-logo.png HTTP/1.1" 200 3623 "http://10.0.0.6/" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
                 3 GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
                 2 GET /favicon.ico HTTP/1.1" 404 486 "-" "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"


text:
Q: Toggling UITextAutoCorrectionType WHEN a UITextField is being edited I want to turn auto-correction on/off based on the content in the text field.
For example, if the user is typing a phrase like "Machine tools" I want auto-correction to be on (for the rest of the words she's gonna type) but if I sense the beginnings of - say - a web address like "www.mach.." I want to turn auto-correction off.
I tried doing this on receiving the UITextFieldTextDidChangeNotification, by toggling autoCorrectionType on the textfield based on the content typed. While the actual value of this property on the text field changes (verified this with an NSLog) the actual correction behaviour does not get affected. So if auto-correction was on at the beginning of the editing session, it continues to be so even AFTER I have set the text field to UITextAutoCorrectionTypeNo. So "www.foogle..." gets corrected to "www.google.." which may not always be desirable in my book.
So has anyone found a way to enable/disable auto-correction on the fly (when editing) in a text field?
Thanks.

A: UITextView has to reload something internally which it doesn't do automatically, so we have to trigger it from the outside. A way I found is to resign and become first responder again:
[textView resignFirstResponder];
// UITextAutoCorrectionType change
[textView becomeFirstResponder];

This works. Remember to restore the selected range.
Raphael

A: I was able to run [textField reloadInputViews] after setting the autocorrection type.
Be aware that this resets the state of the keyboard. If you were viewing symbols (instead of letters), after calling reloadInputViews the keyboard will be reset to letter.


text:
Q: Why was a correct answer deleted and converted to a comment? Please refer to the following question (on SO):
How to list all the files changed by a perforce change list
One of the answers to the question was deleted and converted to a comment:

Although many perforce users might not be aware, this is a correct answer.  I would even go on to say that is better than the accepted answer in the thread.
Unfortunately, it was converted to a comment.

The reference to the (deleted) answer can be observed in another answer:

and also in a comment:

Was it deleted simply due to the fact that to err is human?  Was it removed because the reviewers without a minimal understanding voted to delete it?

EDIT: It is worthwhile to state that this was a first post (link to user's profile) and a late answer.  So it would have featured in both the relevant review queues.  Moreover, it might have appeared in the Low Quality Posts queue too given it's length.

A: As @ShaWizDowArd said, I'd suspect it's because the entire answer is "Probably the easiest way:" with absolutely no explanation of why that is "probably" the best way.
Code-only answers are discouraged on SO, because they offer no information in addition to the code. SO isn't a "Find me code I can copy/paste" site; it's a collection of information and knowledge, and that answer doesn't impart the knowledge to go with the code.
It's fine to think something is "probably the best way", but the answer also needs to explain why that's the case, and provide enough information to do so. I'd have flagged that as "Other", with a reason that it's a comment and not an answer as well.

A: Probably because it started with the word Probably.


text:
Q: Oracle converting date to number causes it to become 7 digits long instead of 8 I am currently converting a date to number using Oracle query. However for certain dates such as 08122019, it is becoming as 8122019
How can i tweak my query to show 0 in the beginning:
TO_NUMBER(TO_CHAR(MyDate, 'DDMMYYYY'))

A: Here it is (though I have no idea why you would want the 3rd one, if what you're asking for is the first):
    SQL> select to_char(sysdate,'ddmmyyyy')  from dual;

    TO_CHAR(
    --------
    08122019

    SQL> select to_number(to_char(sysdate,'ddmmyyyy')) from dual;

    TO_NUMBER(TO_CHAR(SYSDATE,'DDMMYYYY'))
    --------------------------------------
                                   8122019

    SQL> select to_char(to_number(to_char(sysdate,'ddmmyyyy')),'09999999') from dual;

    TO_CHAR(T
    ---------
     08122019


text:
Q: Is $x^8 + x^5 + x^3 + x^2 + 1$ an irreducible polynomial or not in GF $2^8$ Is $x^8 + x^5 + x^3 + x^2 + 1$ an irreducible polynomial or not in Galois Field $2^8$? Thanks in advance.

A: The question is a bit unclear. If you are truly asking whether this polynomial
$$
p(x)=x^8+x^5+x^3+x^2+1
$$ is irreducible in the ring $GF(256)[x]$, then the answer is trivially NO! This is because:

*

*Either it is reducible over $GF(2)$ in which case it is reducible over the extension field also,

*Or it is irreducible over $GF(2)$ in which case $GF(2)[x]/\langle p(x)\rangle$ is a field of 256 elements, and thus isomorphic (or equal to) $GF(256)$. In this case $p(x)$ has 8 distinct zeros in the field, namely the cosets $x^{2^i}+\langle p(x)\rangle$, $i=0,1,2,\ldots,7$. Consequently $p(x)$ would split into linear factors over $GF(256)$.

But this was a bit naughty of me, because I took your phrasing of the question literally. Presumably you would not ask things like: "Is $x^2+1$ irreducible over the complex numbers?", because you know that it factors as $(x+i)(x-i)$ in $\Bbb{C}[x]$. The only sensible guess is that you are inquiring whether $p(x)$ is irreducible over $GF(2)$.
As pointed out in the comments you need to show that $p(x)$ has no factors of degree 4 or lower. The usual suspects are $x,x+1,x^2+x+1,x^3+x+1,x^3+x^2+1,x^4+x+1,x^4+x^3+1$ and
$x^4+x^3+x^2+x+1$. If you were given this as an exercise, your teacher/book must have produced this at some earlier point (otherwise it would a bit naughty of them - barring introduction of a general algorithm like Berlekamp's).

*

*Because $p(x)$ has five terms including $1$ we can immediately rule out the linear factors.

*The quadratic factor is a factor of $x^3+1$. But $x^8+x^5=(x^3+1)x^5$, so
$$p(x)\equiv x^2\pmod{x^2+x+1}.$$ Thus no irreducible quadratic factor.

*Both the cubic irreducible polynomials are factors of $x^7+1$ (the multiplicative group of the field $GF(8)$ is cyclic of order seven). We see that $x^8\equiv x\pmod{x^7+1}$, so $p(x)\equiv x^5+x^3+x^2+x+1\pmod {x^7+1}$. If this were divisible by $x^3+x+1$ then so would $x^5+x^2=x^2(x^3+1)=x^2(x+1)(x^2+x+1)$ which is absurd. Likewise, if it were divisible by $x^3+x^2+1$, then so would $x^5+x=x(x^4+1)=x(x+1)^4$ again violating uniqueness of factorization.

This leaves the possibility that $p(x)$ could be a product of two irreducible quartics, i.e. a product of two of $f_1(x)=x^4+x+1$, $f_2(x)=x^4+x^3+1$, $f_3(x)=x^4+x^3+x^2+x+1$.
Could $f_1(x)$ be a factor? We have $f_1(x)^2=x^8+x^2+1$, so
$$
p(x)\equiv x^5+x^3\pmod{f_1(x)}.
$$
As in the cubic case this leads to a contradiction as $x^5+x^3=x^3(x+1)^2$ is not divisible by $f_1(x)$.
Because $p(x)$ contains odd degree terms, it is not a square of a polynomial. The only remaining possibility is
$$
p(x)=f_2(x)f_3(x).
$$
Leaving it to you to rule out this possibility. Either by brute force or by using one of the techniques outlined here.

A: I'll say at the beginning that I'm not very familiar with this area, I just thought I'd take a shot at this since there hasn't been much.  Please correct me if I'm misunderstanding something.
Suppose you have the polynomials
$$ P_0(x) = x^8 + x^5 + x^3 + x^2 + 1$$
$$ P_1(x) = A_7\,x^7 + A_6\,x^6 + A_5\,x^5 + A_4\,x^4 + A_3\,x^3 + A_2\,x^2 + A_1\,x^1 + A_0\,x^0 $$
$$ P_2(x) = B_7\,x^7 + B_6\,x^6 + B_5\,x^5 + B_4\,x^4 + B_3\,x^3 + B_2\,x^2 + B_1\,x^1 + B^0\,x^0 $$
Now, if $P_0(x) \equiv P_1(x)\cdot P_2(x) \pmod{256}$, then $P_0(x) \equiv P_1(x)\cdot P_2(x) \pmod{2}$ since $2 \mid 256$.  So we can check:
$$\begin{align}
0 & \equiv A_7\,B_7\pmod{2} \\
0 & \equiv A_6\,B_7 + A_7\,B_6\pmod{2} \\
0 & \equiv A_5\,B_7 + A_6\,B_6 + A_7\,B_5\pmod{2} \\
0 & \equiv A_4\,B_7 + A_5\,B_6 + A_6\,B_5 + A_7\,B_4\pmod{2} \\
0 & \equiv A_3\,B_7 + A_4\,B_6 + A_5\,B_5 + A_6\,B_4 + A_7\,B_3\pmod{2} \\
0 & \equiv A_2\,B_7 + A_3\,B_6 + A_4\,B_5 + A_5\,B_4 + A_6\,B_3 + A_7\,B_2\pmod{2} \\
1 & \equiv A_1\,B_7 + A_2\,B_6 + A_3\,B_5 + A_4\,B_4 + A_5\,B_3 + A_6\,B_2 + A_7\,B_1\pmod{2} \\
0 & \equiv A_0\,B_7 + A_1\,B_6 + A_2\,B_5 + A_3\,B_4 + A_4\,B_3 + A_5\,B_2 + A_6\,B_1 + A_7\,B_0\pmod{2} \\
0 & \equiv A_0\,B_6 + A_1\,B_5 + A_2\,B_4 + A_3\,B_3 + A_4\,B_2 + A_5\,B_1 + A_6\,B_0\pmod{2} \\
1 & \equiv A_0\,B_5 + A_1\,B_4 + A_2\,B_3 + A_3\,B_2 + A_4\,B_1 + A_5\,B_0\pmod{2} \\
0 & \equiv A_0\,B_4 + A_1\,B_3 + A_2\,B_2 + A_3\,B_1 + A_4\,B_0\pmod{2} \\
1 & \equiv A_0\,B_3 + A_1\,B_2 + A_2\,B_1 + A_3\,B_0\pmod{2} \\
1 & \equiv A_0\,B_2 + A_1\,B_1 + A_2\,B_0\pmod{2} \\
0 & \equiv A_0\,B_1 + A_1\,B_0\pmod{2} \\
1 & \equiv A_0\,B_0\pmod{2} \\
\end{align}$$
This is fairly simple to check with a computer, my search turned up that it is irreducible.


text:
Q: Cassandra pagination: start from a given / random position? Is it possible to start pagination from a specified or random position?
Why do I need this?
On my production nodes I have a couple of parallel service jobs that iterate over circa 200 000 000 items and update information for them. New versions of software are often pushed to servers and with each push, service jobs are restarted. So all jobs start from beginning again and again. Of course I use locks, but it would be better, if I could instruct those parallel job to start from different pages.

A: Paging is done via Apache Cassandra and client drivers by communicating a pagingState as described in section 8 of the native protocol specification:

However, if some results are not
    part of the first response, the Has_more_pages flag will be set and the result
    will contain a paging_state value. In that case, the paging_state value
    should be used in a QUERY or EXECUTE message (that has the same query as
    the original one or the behavior is undefined) to retrieve the next page of
  results.

As you query data, this paging state can be accessed and stored for later use, in a way like you describe in starting a job from a previous position.
This can be accomplished using the DataStax java-driver as described in the manual on the 'Paging' page under the 'Saving and Reusing the paging state' section:

The driver exposes a PagingState object that represents where we were in the result set when the last page was fetched:

ResultSet resultSet = session.execute("your query");
// iterate the result set...
PagingState pagingState = resultSet.getExecutionInfo().getPagingState();

This object can be serialized to a String or a byte array:

String string = pagingState.toString();
byte[] bytes = pagingState.toBytes();

This serialized form can be saved in some form of persistent storage to be reused later. In our web service example, we would probably save the string version as a query parameter in the URL to the next page (http://myservice.com/results?page=<...>). When that value is retrieved later, we can deserialize it and reinject it in a statement:

PagingState pagingState = PagingState.fromString(string);
Statement st = new SimpleStatement("your query");
st.setPagingState(pagingState);
ResultSet rs = session.execute(st);

Other drivers should have a similar mechanism for paging in this way.


text:
Q: Как добавить генетический алгоритм к Direction API? Интересно, есть ли способ реализовать простой генетический алгоритм, который решает проблему TSP (имеется в виду, что он находит кратчайший путь из одного места в другое, не посещая то же самое место снова). Я использовал Direction API, однако он уже автоматизирован, и его использование стоит денег. Мне нужен генетический алгоритм, который будет выполнять ту же работу, но я запутался и не знаю, как использовать с Directions API. Я получил файл API JSON с данными о расстоянии и продолжительности. Могу ли я использовать его в качестве параметров для генетического алгоритма и, наконец, но самое главное, как я могу отобразить это на карте.
На данный момент у меня есть экран того, что я могу сделать с помощью Directions API. Я хочу того же, но используя генетический алгоритм. Приложение, которое я создаю, предназначено для Android, поэтому я использую только JAVA. Thx!
Какие-либо идеи на этот счет?

Directions API Screenshot


text:
Q: How to develop this layout in AngularJS and/or AngularJS Material? I have following code:
div
    div Test1
    div(flex)
    div 12
    div(ng-show="someCondition", class="triangleLeft")

If the triangle is shown, it will push the 12 to the left. Is it able to hide/show the triangle without pushing the 12 to the left using AngularJS and/or AngularJS Material?
Here is my Plunk :)

A: Here is a forked version of your plunk
The parent div should be relatively positioned like this
position: relative;

The triangle or the chevron must be absolutely positioned and should be placed at right: 0px like this
position: absolute;
right: 0px;

Now you can see that the triangle does not push the text 12to the left. But you can see that it hides the text. You could add a right/left padding to the parent div like below so it looks better
 padding: 0 10px;


text:
Q: Where can I find "Install Mac OS X Lion" in the App Store? I'm trying to follow the directions on the Apple Support Page regarding Mass Deployment
Step 2 of the process says

On the server, install the app named "Install Mac OS X Lion" from the Mac App Store (a network connection is required for this process).

The problem here is that when I do a search for Install Mac OS X Lion in the App Store, I get no results found.
Where can I find this app in order to enable me to do mass deployment of OS X Lion across my network?

A: What you're probably looking for is a copy of the OS X Lion installer. If you saved a copy when you first installed Lion, great. If not, you'll need to re-download it from the Mac App Store.

*

*Launch the App Store and ⌥-click the Purchases tab. An "Install" button should appear next to Lion. Click it to re-download the installer.

*Once the installer finishes downloading, go to your Applications folder to find the installer itself. It is called Install Mac OS X Lion.
Further steps to get the DMG image:

*

*Right-click the installer and choose Show Package Contents from the contextual pop-up.

*Navigate to .../Contents/SharedSupport. There you'll find a disk image called InstallESD.dmg.

A: I still see "Mac OS X Lion" on the homepage of the Mac App Store. Can't you see it there?
Did you try to search Mac OS X Lion or Lion?

You can re-download Lion from the App Store by clicking on "Purchase" with the alt key pressed. Only then will you be able to download. Otherwise, it's just noted as "installed".

Do you use the Mac App Store app and not the App Store from iTunes?


text:
Q: How to fill the entire FloatingActionButton with icon I am trying to create a FAB button that has a circle icon in it. I want to fill the entire button with the icon as shown in the image, but Android seems always to add space between icon and button.
Can someone please explain how to get rid of the space? I have multiple FAB buttons in my app, and I only want to do this with one of them. How can I do this by setting the attributes of the button or programmatically?


text:
Q: AttributeError: 'LogisticRegressionTrainingSummary' object has no attribute 'areaUnderROC' I want to run area under ROC test for my machine learning model, but the attribute error pops up. Below is my complete code with the error details include. I already have string indexer, one hot encoder and vector assembler on the flight. Please refer to the full code below:
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
import pyspark.sql.types as T

spark = SparkSession.builder.getOrCreate()

df=spark.read.csv("2018-2010_import.csv",inferSchema=True,header=True)

train, test = df.randomSplit([0.7, 0.3], seed=7)

print(f"Train set length: {train.count()} records")
print(f"Test set length: {test.count()} records")

train.dtypes

catCols = [x for (x, dataType) in train.dtypes if dataType == "string"]
numCols = [
    x for (x, dataType) in train.dtypes if ((dataType == "double") & (x != "HSCode"))
]

print(numCols)
print(catCols)

train.agg(F.countDistinct("Commodity","Country")).show()

train.groupBy("Commodity","Country").count().show()

from pyspark.ml.feature import (
    OneHotEncoder,
    StringIndexer,
)

string_indexer = [
    StringIndexer(inputCol=x, outputCol=x + "_StringIndexer", handleInvalid="skip")
    for x in catCols
]

one_hot_encoder = [
    OneHotEncoder(
        inputCols=[f"{x}_StringIndexer" for x in catCols],
        outputCols=[f"{x}_OneHotEncoder" for x in catCols],
    )
]

from pyspark.ml.feature import VectorAssembler

assemblerInput = [x for x in numCols]
assemblerInput += [f"{x}_OneHotEncoder" for x in catCols]

vector_assembler = VectorAssembler(
    inputCols=assemblerInput, outputCol="VectorAssembler_features", handleInvalid="skip"
)

stages = []
stages += string_indexer
stages += one_hot_encoder
stages += [vector_assembler]

from pyspark.ml import Pipeline

pipeline = Pipeline().setStages(stages)
model = pipeline.fit(train)

pp_df = model.transform(test)

pp_df.select(
    "HSCode", "Commodity", "value", "Country", "VectorAssembler_features",
).show(truncate=False)
from pyspark.ml.classification import LogisticRegression

data = pp_df.select(
    F.col("VectorAssembler_features").alias("features"),
    F.col("HSCode").alias("label"),
)

model = LogisticRegression().fit(data)

model_summary.areaUnderROC

AttributeError                            Traceback (most recent call last)
C:\Users\AZMANM~1\AppData\Local\Temp/ipykernel_4856/3039136250.py in
----> 1 model_summary.areaUnderROC
AttributeError: 'LogisticRegressionTrainingSummary' object has no attribute 'areaUnderROC'
model.summary.pr.show()

AttributeError                            Traceback (most recent call last)
C:\Users\AZMANM~1\AppData\Local\Temp/ipykernel_4856/3388404637.py in
----> 1 model.summary.pr.show()
AttributeError: 'LogisticRegressionTrainingSummary' object has no attribute 'pr'

A: There's no code that tells us how you are getting the model_summary variable.
Did you maybe forget to use model.summary.areaUnderROC instead of model_summary.areaUnderROC?
The following example works for me:
from pyspark.sql import Row, SparkSession
from pyspark.ml.linalg import Vectors
from pyspark.ml.classification import LogisticRegression

if __name__ == "__main__":

    spark = SparkSession.builder.getOrCreate()
    sc = spark.sparkContext
    bdf = sc.parallelize(
        [
            Row(label=1.0, weight=1.0, features=Vectors.dense(0.0, 5.0)),
            Row(label=0.0, weight=2.0, features=Vectors.dense(1.0, 2.0)),
            Row(label=1.0, weight=3.0, features=Vectors.dense(2.0, 1.0)),
            Row(label=0.0, weight=4.0, features=Vectors.dense(3.0, 3.0)),
        ]
    ).toDF()
    blor = LogisticRegression(weightCol="weight")
    blorModel = blor.fit(bdf)
    summary = blorModel.summary
    aur = summary.areaUnderROC

A: You will need to use BinaryClassificationEvaluator. After the train test split, I have named the training set as train_set and testing data as test_set.  Here input_columns are all the columns apart from the label column.
from pyspark.ml.evaluation import BinaryClassificationEvaluator
assembler= VectorAssembler(inputCols=input_columns,outputCol='features')

And call on the vector assembler to transform your dataframe
    final_data = assembler.transform(your_dataframe)
    print("Train test Split...")
    train,test = final_data.randomSplit([0.7,0.3], seed=4000)
    lr = LogisticRegression(labelCol="label",
    featuresCol="features",maxIter=10 ,threshold=0.5)
    lr_model=lr.fit(train_set)
    predict_train=lr_model.transform(train_set)
    predict_test=lr_model.transform(test_set)

    evaluator = BinaryClassificationEvaluator()
    print("Test Area Under ROC: " + str(evaluator.evaluate(predict_test, {evaluator.metricName: "areaUnderROC"})))


text:
Q: Independent set of formulas of the sentential logic A set $\Gamma$ of well formed formulas of the sentential logic is called independent if for each $\varphi\in\Gamma$, $\Gamma-\{\varphi\}\nRightarrow\varphi\\$.
1 when $\Gamma=\{\varphi\}$ is independent?
2 Is $\{A\rightarrow B, B\rightarrow C, C\rightarrow A\}$ independent? ($A,B,C$ are sentencial letters).
In the first case I guess that $\varphi$ should be a tautology but I get confused because $\emptyset\Rightarrow\varphi$ has a meaning?
And for the second I said no, because I can easily find valuation that make two of them true but not the third one.
If it is useful $\alpha\Rightarrow\beta$ holds iff $\alpha\rightarrow\beta$ is a tautology.

A: You haven't said whether $\implies$ is semantic or syntactic entailment, but the same goes either way. I'll assume you mean semantic entailment, but you can easily adjust the answer if you meant syntactic entailment.

*

*$\{\varphi\}$ is independent [on your definition] iff $\emptyset \nvDash \varphi$,  i.e. iff $\varphi$ is not a tautology. But why does $\emptyset \vDash \varphi$ say that $\varphi$ is a tautology? Recall: $\Delta \vDash \varphi$ says that any valuation which makes $\varphi$ false must make some wff in $\Delta$ false. So: $\emptyset \vDash \varphi$ says that any valuation which makes $\varphi$ false must make some wff in $\emptyset$ false. But there are no wffs in the empty set to make false, so that's equivalent to saying no valuation makes $\varphi$ false, i.e. $\varphi$ is a tautology.

*Yes, except you need three valuations since you need to consider the three different cases where you extract in turn one of the propositions from the given set and see if the extracted set follows from the remainder.


text:
Q: Showing legend for multiple grouped geom_hline in a geom_line plot I'm trying to generate a grouped geom_line plot with two grouped geom_hline overlaid. The groupings are the same in all 3 cases. The issue is that the legend only appears for geom_line (+ geom_point), but not for the two geom_hline commands. The ideal result would be 3 legends, each with 3 lines representing each group (with relevant dashed/dotted lines for geom_hline). Alternatively additional legends showing a black dashed and dotted line labelled as I have in the color variable for the geom_hline commands would also work. Data, code and plot as it stands below, thanks in advance for any assistance!
Data (dput):
acc.df <- structure(list(intersect.nn = structure(c(1L, 2L, 3L, 1L, 2L,
3L, 1L, 2L, 3L), .Label = c("CD4", "CD8", "Treg"), class = "factor"),
    prop = c(0.689912280701754, 0.999746643020015, 0.779661016949153,
    0.671249111163783, 0.988757981832899, 0.769230769230769,
    0.666112680737909, 0.981778644271146, 0.776223776223776),
    K = c("k 1", "k 1", "k 1", "k 2", "k 2", "k 2", "k 3", "k 3",
    "k 3")), row.names = c(NA, -9L), class = "data.frame")
acc.exp <- structure(list(intersect.exp = structure(1:3, .Label = c("CD4",
"CD8", "Treg"), class = "factor"), prop = c(0.689912280701754,
0.999746610921069, 0.779661016949153)), row.names = c(1L, 5L,
9L), class = "data.frame")
acc.clust <- structure(list(seurat_clusters = structure(1:3, .Label = c("CD4",
"CD8", "Treg"), class = "factor"), prop = c(0.666275954454119,
0.981845461365341, 0.774647887323944)), row.names = c(1L, 5L,
9L), class = "data.frame")

Code:
ggplot(acc.df, aes(x = K, y = prop, group = intersect.nn)) +
  geom_line(aes(color = intersect.nn)) +
  geom_point(aes(color = intersect.nn)) +
  geom_hline(data = acc.exp, aes(yintercept = prop, color = intersect.exp), show.legend = T, linetype = "dashed") +
  geom_hline(data = acc.clust, aes(yintercept = prop, color = seurat_clusters), show.legend = T, linetype = "dotted")

A: Managed to work this out myself. Very quickly for someone in the same situation: don't use a dataframe for each geom_hline. I simply merged the dataframes (acc.df and acc.exp) together (adding a column variable to distinguish between them), then in a single geom_hline command setting the "color" and "linetype" aesthetics to my groupings.


text:
Q: open modal after sign-up with firebase - vuejs I am wanting the user to complete a "wizard/profile" after they sign up through authentication. My code for registering the user is below.
async registerUser(email, password) {
        this.loadingUser = true;
        try {
            const { user } = await createUserWithEmailAndPassword(
                auth,
                email,
                password
            );
            this.userData = { email: user.email, uid: user.uid };
            router.push("/onboarding");
        } catch (error) {
            console.log(error);
            this.userData = {};
        } finally {
            this.loadingUser = false;
        }
    },

I have created a modal component that will open and i can push the user to the route after completion of authentication but i would rather have it opened to when the user is pushed to the home page and to new users (modal to open once user is redirected to home page). At the moment the modal opens when the route is pushed to /onboarding. Any direction or help would be great.


text:
Q: How should PHP receiving end look like when using JS Fetch just a quick question.
eventReceive: function(info) {
        //get the bits of data we want to send into a simple object
        var eventData = {
          title: info.event.title,
          start: info.event.start,
        };
        //send the data via an AJAX POST request, and log any response which comes from the server
        fetch('<?php \E::get('obj_curr_module')->build_action_path('dev_guideline_ui_calendar','add_event'); ?>', {
            method: 'POST',
            headers: {
              'Accept': 'application/json'
            },
            body: encodeFormData(eventData)
          })
          .then(response => console.log(response))
          .catch(error => console.log(error));
      },

My eventData is set as JS format. After using the function encodeFormData, i was wondering how should my php receiving end file looks like in order to retrieve the eventData pass on in the body?
My encodeFormData function is as below,
const encodeFormData = (data) => {
      var form_data = new FormData();

      for (var key in data) {
        form_data.append(key, data[key]);
      }
      return form_data;
    };


text:
Q: How to write test class for LWC apex class Apex Class
public class WorldEnergyServicesController {
@AuraEnabled
public static List<Location__c> getLocationwithKeys() {
    return [SELECT Id,Location_Name__c,Count_Keys__c,Notes__c FROM Location__c where Count_Keys__c>0 Order by CreatedDate DESC];
}
@AuraEnabled
public static ID createLocation(Location__c Location) {
    insert Location;
    return Location.id;
}
@AuraEnabled
public static ID createLocationKey(Add_Location_Key__c LocationKey) {
    insert LocationKey;
    return LocationKey.id;
}

}
TestClass
 @isTest
public class WorldEnergyServicesControllerTest{
    public static testMethod void TestMethod1()
    {
        Location__c Loc=new Location__c();
        Loc.Location_Name__c='Room 1';
        Loc.Notes__c='ABSCDSSSS';
        insert Loc;
    }
}

I wrote this but when i run this it is running succesfully but not showing any progress in percentage

A: To test the Apex class, you need to call its methods in the testmethod
static void myTest() {

   Id result = WorldEnergyServicesController.createLocationKey(new Add_Location_Key__c(..) );
   System.assertEquals(Add_Location_Key__c.SObjectType,result.getSobjectType(),'should insert rec');

   ... then next static method ...

}

I strongly suggest you take the Trailhead on Apex testmethods.


text:
Q: How to generate URI inside a controller in Spring 3 I use spring 3.0 and I have a really simple question but didn't find any answer on the internet. I want to generate a path (an URI) just like in my JSPs:
<spring:url value="/my/url" />

But inside a controller. What is the related service to use?
Thanks!
Edit: May it be related with this: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/resources.html#resources-resourceloader ?
Ain't there a better solution for this?

A: Rossen's suggestion is gold.
There's also the ServletUriComponentsBuilder class from 3.1 that builds URLs from current request in static fashion. For example:
ServletUriComponentsBuilder.fromCurrentContextPath().path("/my/additional/path").build().toUriString();

It's the closest thing to <spring:url> in servlet.

A: In Spring MVC 3.1 you can use the UriComponentsBuilder and its ServletUriComponentsBuilder sub-class. There is an example of that here. You can also read about UriComponentsBuilder in the reference docs.

A: I would say
request.getRequestURL() + "/my/url"

makes the job. There is no such built in functionality, spring:url calls UrlTag.class that has the below method to generate URL, you can use it as an insőiration for your code:
private String createUrl() throws JspException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
    StringBuilder url = new StringBuilder();
    if (this.type == UrlType.CONTEXT_RELATIVE) {
        // add application context to url
        if (this.context == null) {
            url.append(request.getContextPath());
        }
        else {
            url.append(this.context);
        }
    }
    if (this.type != UrlType.RELATIVE && this.type != UrlType.ABSOLUTE && !this.value.startsWith("/")) {
        url.append("/");
    }
    url.append(replaceUriTemplateParams(this.value, this.params, this.templateParams));
    url.append(createQueryString(this.params, this.templateParams, (url.indexOf("?") == -1)));

    String urlStr = url.toString();
    if (this.type != UrlType.ABSOLUTE) {
        // Add the session identifier if needed
        // (Do not embed the session identifier in a remote link!)
        urlStr = response.encodeURL(urlStr);
    }

    // HTML and/or JavaScript escape, if demanded.
    urlStr = isHtmlEscape() ? HtmlUtils.htmlEscape(urlStr) : urlStr;
    urlStr = this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr;

    return urlStr;
}


text:
Q: django view function code runs after return I have a django view that looks like...

    def add_user(request):
        if User.objects.get(username__exact = request.POST['username']):
            context = { 'message': "Username already taken"}
            return render_to_response("mytemplate.html", context, RequestContext(request))

        newUser = User(username="freeandclearusername")
        newUser.save()

        #then other code that is related to setting up a new user.

The other code that is related to setting up the user is still ran even if the initial conditional statement fails and the "return render_to_response()" is called.
The page is rendered with the correct context but other information is added to the database after the initial return.   I thought that the code after the "return render_to_response()" would not run.
Can anyone confirm or explain this?
UPDATE....
Ok so if I add a conditional....
def add_user(request):
    if User.objects.get(username__exact = request.POST['username']):
        bad_user = True
        context = { 'message': "Username already taken"}
        return render_to_response("mytemplate.html", context, RequestContext(request))

    newUser = User(username="freeandclearusername")
    newUser.save()

    if bad_user != True:
        #then other code that is related to setting up a new user.
        context = { 'message': "Username is great!!!!!"}
        return render_to_response("mytemplate.html", context, RequestContext(request))

This behaves as expected.  Also if I remove the RequestConext() it seems to behave correctly as well.
Any ideas? I think the problem lies in how I'm using RequestContext.

A: The return statement will indeed terminate the function. So if you see other code being executed, you either

*

*don't execute the return statement, and thus produce the output somehow differently, or

*have other code (before the function is called, or in a middleware) that makes the database changes.

A: You are correct, assuming your conditions are met, the view will exit on your return statement.  The only other thing I can think of that hasn't already been mentioned is indentation -- double-check that you do not have a mix of tabs and spaces.  That can sometimes result in the unexpected.


text:
Q: How to find hidden columns in Telerik Radgridview using Linq expression How to find invisible columns from Telerik Radgridview.I tried with following expression
RadGridView radGridView = dependencyObject as RadGridView;
var columns = radGridView.Columns.Where(x => x.IsVisible == false);

I got following exception

Error   1   'Telerik.Windows.Controls.GridViewColumnCollection' does not
  contain a definition for 'Where' and the best extension method
  overload
  'Telerik.Windows.Data.QueryableExtensions.Where(System.Linq.IQueryable,
  Telerik.Windows.Data.FilterDescriptorCollection)' has some invalid
  arguments

Can anyone help on this

A: var columns = new List<Telerik.Windows.Controls.GridViewColumn>(gridView.Columns);
var filteredList = columns.Where(o => o.IsVisible == false);

Cheers