text:
Q: Deleted Ubuntu from dual boot system, now can't boot into Windows Can't boot into Windows after Ubuntu partition was deleted. Fixmbr did not solve the problem. Cannot figure out what the actual problem is.

A: When your computer boots try constantly pressing F11 Del F1 and try to reach boot options, even better if you can reach boot options in the BIOS.  You'll need to google what the buttons to press for your computer make and model if those keys I recommended don't work.  You'll need to constantly be jabbing them soon as you press the power button.  Then you should be able to pick Windows Boot Loader or UEFI type options.

A: (If I were u)I would try the Trinity rescue kit has options to repair booting here
Another shot would be to actually reinstall Ubuntu on that partition which would probably reinstall grub but then you can run the boot-repair which is a utility, can also be run as a live cd.
Also take a look at reFind


text:
Q: RAID 10 Замена диска Всем привет! Имеется сервер на Windows Server 2008 R2 c Intel RS2BL040 на борту. Был собран RAID 10. Один из 4-х дисков полетел. Заменили вышедший из строй диск. Теперь не понимаю что сделать, чтобы запустить диск в работу.
До замены диска было так:

Теперь стало так:

P.S. Прошу описать последовательность действий подробно, т.к. с таким сталкиваюсь впервые.

A: Заходим во вкладку Physical , затем, выбираем наш Raid контроллер.
Идем на вкладку Go to. Выбираем Controller -> Scan Foreign Configuration

Появится окно с импортом конфигурации. Выбираем Import....

Жмем Yes

redpajama_set_name: RedPajamaStackExchange


text:
Q: Class Field Towers Let k a number field whose $p$-class group $C_k$ of type $(p,p)$ i.e $C_k \cong \mathbb{Z}/p\mathbb{Z}\times \mathbb{Z}/p\mathbb{Z}$. Let $k^{(1)}$ be the Hilbert class field of $k$ and $k^{(2)}$ the Hilbert class field of $k^{(1)}$, for a positive integer $n$, we define $k^{(n)}$ is the Hilbert class field of $k^{(n-1)}$...
We define the class fields tower of k as: $k \subset k^{(1)} \subset k^{(2)}\subset k^{(3)} \subset.....\subset k^{(n)}\subset.....$
I need to prove that the class field tower of $k$  terminate in the second step i.e $k^{(2)} = k^{(3)}= k^{(4)}=....$

A: This is only known to be true for $p = 2$. For odd $p$, Wingberg (On the maximal unramified p-extension of an algebraic number field, J. Reine Angew.
Math. 440 (1993), 129–156) claims to have proved that there exist infinite $p$-class field towers for certain fields with class group of type $(p, p)$. I seem to remember that there were problems with some of his claims but at least it shows that the problem is not exactly of the homework type.
For examples in which the towers have length $3$ see
https://arxiv.org/abs/1601.00179 .


text:
Q: Why the grid view appear different in the emulator? Why does the emulator have different sizes of buttons other than the designed ones here is the XML? This is a serious problem with the grid views and I've encountered it many times but I can't find the answer.
Where is the problem?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.life.braintrainer.MainActivity">

    <Button
        android:id="@+id/startButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="#26eb47"
        android:onClick="start"
        android:padding="40dp"
        android:text="Go!"
        android:textSize="70sp"
        android:visibility="invisible" />

    <TextView
        android:id="@+id/timerTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="#e6ff26"
        android:padding="10dp"
        android:text="30s"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/pointsTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/timerTextView"
        android:background="#fe8a0e"
        android:padding="10dp"
        android:text="0/0"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/sumTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/pointsTextView"
        android:layout_centerHorizontal="true"
        android:padding="15dp"
        android:text="30 + 12"
        android:textColor="#312e2e"
        android:textSize="25sp" />

    <GridLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/sumTextView"
        android:layout_alignParentStart="true"
        android:columnCount="2"
        android:rowCount="2">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_columnWeight="1"
            android:layout_gravity="fill"
            android:layout_row="0"
            android:layout_rowWeight="1"
            android:background="#27f13f"
            android:onClick="chooseAnswer"
            android:tag="0"
            android:text="3"
            android:textSize="80sp" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_columnWeight="1"
            android:layout_gravity="fill"
            android:layout_row="0"
            android:layout_rowWeight="1"
            android:background="#0a2ef9"
            android:onClick="chooseAnswer"
            android:tag="1"
            android:text="3"
            android:textSize="80sp" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_columnWeight="1"
            android:layout_gravity="fill"
            android:layout_row="1"
            android:layout_rowWeight="1"
            android:background="#f43ffb"
            android:onClick="chooseAnswer"
            android:tag="2"
            android:text="3"
            android:textSize="80sp" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_columnWeight="1"
            android:layout_gravity="fill"
            android:layout_row="1"
            android:layout_rowWeight="1"
            android:background="#2cdefe"
            android:onClick="chooseAnswer"
            android:tag="3"
            android:text="3"
            android:textSize="80sp" />

    </GridLayout>

    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/startButton"
        android:layout_centerHorizontal="true"
        android:text="Correct!"
        android:textSize="40sp" />

</RelativeLayout>


text:
Q: Как перевести клиенту "резиновая верстка" на англ.язык? Речь, конечно не о буквальном переводе, а о реальном опыте

A: Виды верстки:
Статический (Static) - использует заданный размер страницы и не изменяется в зависимости от ширины браузера.
Жидкий, резиновый (Liquid, Fluid) - использует в CSS-стилях относительные единицы измерения вместо фиксированных. Обычно в «жидких» макетах шаблона используются проценты вместо пикселей.
Адаптивный (Adaptive) - страницы использует CSS медиа-запросы, чтобы определить ширину браузера и соответствующим образом изменить макет страницы.
Отзывчивый (Responsive) - для построения шаблона страницы используются как относительные единицы измерения, так и медиа-запросы CSS. Что подразумевает под собой использование преимуществ и «жидкого», и адаптивного макета.


text:
Q: No Settings -> Window Manager in XFCE4 I am under Ubuntu 20.04, using XFCE4.
When I click Menu (Upper left cross) -> Settings in the Applications Menu (added to the panel via this)

I expected to have Window Manager available (PS: I needed that to setup keyboard shortcuts for window tiling, which were not set by default).

But I don't have that menu entry, this is what I have.

I can go to the Window Manager via CLI with xfwm4-settings (source, and related old post).
By typing xfce4-+Tab (for tab completion), and likewise for xfwm4-, I realized there are quite a few other settings that do not show under Menu (Upper left cross) -> Settings.
Of all tab completion alternatives (shown below), I checked executing some of them at the CLI, and then if they show in the menus. None of them were present (and perhaps none of the others as well!).
These are marked with an asterisk.
xfce4-about
xfce4-accessibility-settings
*xfce4-appearance-settings
xfce4-appfinder
xfce4-color-settings
xfce4-display-settings
xfce4-find-cursor
*xfce4-keyboard-settings
xfce4-mime-settings
*xfce4-mouse-settings
xfce4-notifyd-config
xfce4-panel
xfce4-popup-applicationsmenu
xfce4-popup-directorymenu
xfce4-popup-windowmenu
xfce4-session
xfce4-session-logout
xfce4-settings-editor
xfce4-settings-manager
xfce4-session-settings
xfwm4
*xfwm4-settings
*xfwm4-tweaks-settings
*xfwm4-workspace-settings

The CLI settings available above seem a completely disjoint set compared to the menu entries.
So:

*

*Why are these menu entries not present? (I guess they should be automatically included)

*How can I have them shown?

A: As per comment by @Artem S. Tashkinov,
the XFCE Whisker Menu applet is an alternative menu that can be installed with sudo apt install xfce4-whiskermenu-plugin, and added to the panel.
It then gives the menu in the left figure.
   ..........
It contains essentially the same items as the Applications Menu, but it shows a small icon (circled in red) that leads to the menu in the right figure, with access to the missing settings.
Besides this providing a solution to the problem,
I still wonder:

*

*What tells apart these last settings from the previous.

*If these settings could also be added to Applications Menu (perhaps via an extra icon/submenu).


text:
Q: Passing vba variable date to sql statement As a newbie in vba-sql, I am trying to populate a table using a for loop in vba and the Docmd.runsql to populate the table. The code works fine but then the values in the table are: 12/30/1899 for all the records. I used a message box to check and dt works fine. It gives me the date in the loop and moves to the next but in the table it only gives me one date: 12/30/1899.
Function dateTblUpdate()

    DoCmd.SetWarnings False
    DoCmd.RunSQL "DELETE FROM [date-table]"
    Dim dt As Date

    For dt = #1/1/2010# To DateSerial(Year(Now), Month(Now), Day(Now))
       'MsgBox DateSerial(Year(Now), Month(Now), Day(Now))
       'MsgBox dt
        DoCmd.RunSQL "Insert into [date-table] (the_date) values(" & dt & ")"

   Next
   DoCmd.SetWarnings True
End Function

date-table current outcome
the_date
----------
12/30/1899
12/30/1899
12/30/1899
12/30/1899
12/30/1899
12/30/1899

But Expected outcome:
the_date
------------
01/01/2010
01/02/2010
01/03/2010
01/04/2010

My date column is of date type and I believe sql is thinking dt is not a date so it is not saving it and saving the default date.... Any ideas?

A: Include # characters before and after your literal date value.  Otherwise the db engine will interpret something like 26/5/2015 as 26 divided by 5 divided by 2015 ... IOW as a math expression, not the date you intended.
"Insert into [date-table] (the_date) values(" & Format(dt, "\#yyyy-m-d\#") & ")"

However if you use a parameter query, you wouldn't need to bother about those # characters in the SQL statement:
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim dt As Date
Dim strInsert As String

strInsert = "INSERT INTO [date-table] (the_date) VALUES (pDate)"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strInsert)

'For dt = #1/1/2010# To DateSerial(Year(Now), Month(Now), Day(Now))
For dt = #1/1/2010# To Date
    qdf.Parameters("pDate").Value = dt
    qdf.Execute dbFailOnError
Next

Note using the QueryDef.Execute method removes the motivation for DoCmd.SetWarnings False.  Turning SetWarnings off suppresses information, including information which could be useful for troubleshooting.

A: Since the SQL you're building is:
Insert into [date-table] (the_date) values(1/1/2010)

The interpreter may be doing integer division and saving a 0 value, which is the default date.  Enclose the value in pound signs instead:
DoCmd.RunSQL "Insert into [date-table] (the_date) values(#" & dt & "#)"


text:
Q: Regex to split Camel case - with Numbers I want to split a camelCase name to individual names using regex, for performing a spell check.
The split should be as follows:
1) extendedStructureForNUB  --> extended, Structure, For, NUB
2) extendedStructureFor2004 --> extended, Structure, For, 2004
Using the answer from the below question , i am able to split for the 1st condition.
Question : RegEx to split camelCase or TitleCase (advanced)
But for a string containing number (2nd condition), it is not returning as per format.
extendedStrctureFor2004 --> extended, Structure, For2004

Please suggest a way by which i can reuse this regex to split numerals also.

A: public static void main(String[] args)
{
    for (String w : "camelValue".split("(?<!(^|[A-Z0-9]))(?=[A-Z0-9])|(?<!^)(?=[A-Z][a-z])")) {
         System.out.println(w);
    }
}

Edit: Correcting the case for UPPER2000UPPER the regex becomes:
public static void main(String[] args)
{
    for (String w : "camelValue".split("(?<!(^|[A-Z0-9]))(?=[A-Z0-9])|(?<!(^|[^A-Z]))(?=[0-9])|(?<!(^|[^0-9]))(?=[A-Za-z])|(?<!^)(?=[A-Z][a-z])")) {
         System.out.println(w);
    }
}

A: public static void main(String[] args)
{
    for (String w : "extended2004FeeStructure".split("(?<!(^|[A-Z0-9]))(?=[A-Z0-9])|(?<!^)(?=[A-Z][a-z])")) {
        System.out.println(w);
    }
}

corrected one

A: What I see is answer from your previous question was almost pervect. If I ware you i would just add another split opperation, but this time before first digit in middle in each word.
Here is example:
String data="2Hello2000WORLDHello2000WORLD";
//your previois split
String[] myFirstSplit=data.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])");

//I will store split results in list (I don't know size of array)
List<String> list=new ArrayList<>();
for (String s:myFirstSplit){
    //if splited word contains digit after letter then split
    for (String tmp:s.split("(?<=[a-zA-Z])(?=[0-9])"))
        list.add(tmp);
}
System.out.println(list);
//out [2, Hello, 2000, WORLD, Hello, 2000, WORLD]

A: After you seperate this
extendedStrctureFor2004 --> extended, Structure, For2004
Store it in some array like "arr"
Use this Regex
var numberPattern = /[0-9]+/g;
var numMatch= arr[i].match(numberPattern);
now numMatch will contain the numerals u want..


text:
Q: Error in Implementing singleton pattern I am trying to implement singleton pattern and i am getting the following error

Fatal error: Access level to Database::__construct() must be public
  (as in class PDO) in /config/database.php on line 29

<?php

class Database extends PDO
{
    private static $instance;

    private function __construct()
    {

            return parent::__construct(
                    "mysql:host=localhost;dbname=live",
                    "root",
                    "root"
            );

    }

    public function getInstance() {
        if(self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

    public function __clone()
    {
        die(__CLASS__ . ' class cant be instantiated. Please use the method called getInstance.');
    }
}

$mySingleton = Database::getInstance();

var_dump($mySingleton);

?>

A: By declaring the __construct() function as private like private function __construct() you are effectively disallowing PHP from automatically calling it upon object creation.
Instead, you should always have your __construct() as well as other magic methods declared public.
public function __construct()
{
   // Now PHP can access me
}

As far as making your Database class follow a singleton pattern, it doesn't make sense to extend a class that doesn't (i.e. PDO). Instead, do something like this:
<?php

class Database
{
    private static $instance;

    public function __construct()
    {
        // Check to see if static PDO instance
        // has already been created, so we create only one (singleton)
        if(!self::$instance)
        {
            self::$instance = new PDO(
                "mysql:host=localhost;dbname=live",
                "root",
                "root"
            );
         }
    }

    public function getInstance() {
        if(self::$instance === null) {
            self::__construct();
        }
        return self::$instance;
    }

    public function __clone()
    {
        die(__CLASS__ . ' class cant be instantiated. Please use the method called getInstance.');
    }
}

$mySingleton = Database::getInstance();

var_dump($mySingleton);

?>

A: As PDO's __construct() function is public, you cannot extend it with a private __construct() function.
So a "real" singleton is not possible.
You have to set public function __construct().

A: You can't change the Access level for a override method.
Instead of extending PDO, you could just have a PDO instance in Database.
Composition is more flexible than inheritance.

A: You should
1) disable constructor by setting it to private.
2) create single PDO object by calling the static method only. Static method have to return the instance of PDO object.
In Silex or Symfony you will have to prefix class name with "\" or use "use \PDO;". Which means nothing more that this is a global class.
Ps. if you set the __constructor to public and use return functino note that it will not generate any exception or warning but you will get an class object returned and not actual value of return statement.
So $db = new Database() would return object of class Database. Then from there you would have to access your PDO using class method. $pdo = $db->getInstance()
Which is not the right way to build proper singleton.
If you interested in reading more about singletons pros and cons and some use cases read this Best practice on PHP singleton classes, you will find more information about this pattern design.
/**
 *  Singleton pattern
 */
class Database
{

    /**
     *  holds the only PDO instance
     */
    private static $_instance;

    /**
     *  private __constructor not accesible
     */
    private function __construct()
    {

        self::$instance = new PDO(
            "mysql:host=localhost;dbname=live",
            "root",
            "root"
        );

    }

    /**
     *  clone will not duplicate object
     */
    public function __clone()
    {

        die(__CLASS__ . ' class cant be instantiated. Please use the method called getInstance.');

    }

    /**
     *  the only public function to access or create PDO object
     */
    public static function getInstance()
    {

        if(!self::$_instance instanceof PDO){
            new self;
        }

        return self::$_instance;

    }

}

A: The need to have different access level between parent and child constructors is perfectly lecit, apart from technical difficulties involving the PHP source code.
In fact, it has been filed as a bug (#61970).
In this commit made on march 2017, if I am not wrong, the developer says it has been closed:
http://git.php.net/?p=php-src.git;a=commitdiff;h=5324fb1f348f5bc979d9b5f13ac74177b73f9bf7
I use PHP 7.0.24 released on july, but I still see it has not been fixed.


text:
Q: In express-jwt is there any way option similar to req.isAuthenticated() similar to passportjs? I want to find whether the user is authenticated 'jwt' inside middleware. Is there any way like req.isAuthenticated() similar to passportjs?

module.exports = function(app){
 return function(req, res, next){

        // How to implement the below step?
  var isAuthenticated = app.use(jwt({secret: app.get('jwtTokenSecret')}))

        if(isAuthenticated){
          // do some logic
        }

    }
}

A: Yes there is!
1) You can use use the express-jwt module. Check out https://github.com/auth0/express-jwt
2) You can do it this way:
  //get the authorization token from the request headers, or from a cookie
  if (req.headers && req.headers.authorization) {
    var parts = req.headers.authorization.split(' ');
    if (parts.length == 2) {
      var scheme = parts[0];
      var credentials = parts[1];

      if (/^Bearer$/i.test(scheme)) {
        token = credentials;
      }
    }
  }
  else if(req.cookies && req.cookies.token)
  {
    token = req.cookies.token;
  }
...
  jwt.verify(token, config.secrets.session, function(err, decoded) {
     //isAuthenticated is in here
  });


text:
Q: Drupal 6 Views - how to sort on # of comments for a node I'm using Drupal (6) Views (6.2) to render a list of items, one of which is the number of comments that the particular item has (along with another calculated field for the star rating for the item).
I have been banging my head trying to add an ORDER BY that would be very simple with a plain SQL query - namely the count of comments. I want to sort by star rating  and then count of comments.
I have tried using a calculated field, but it always comes up empty.
Thanks for any suggestions.

A: *

*Make sure you have Drupal 6.25 (there were some updates related to this in 6.25 release).

*Create a View on node table.

*add new sort criteria: Node: Comment count.

Not sure what you meant by star ratings though. If you want to get FiveStar or Rate module's data (Voting API's data actually), add a relationship to voting results first.


text:
Q: Apex class query error I am trying to write a query to get a lead's contact information back from a phone number.
The code is:
global class AccountRetrieval{

webService static String getAccount(String phone_number) {
List<Lead> leads = new List<Lead>();
for (Lead lead : Database.query('Select Id, Name, phone, email from Lead where phone like\"' + phone_number + '%\"')){
   leads.add(lead);
}

   String JSONString = JSON.serialize(leads);
   return JSONString;
}
}

The error I get is:
System.QueryException: line 1:56 no viable alternative at character '"'

Class.AccountRetrieval.getAccount: line 5, column 1

A: You could reduce this method to one line
global class AccountRetrieval{

  webService static String getAccount(String phone_number) {
    return Json.serialize([select id,name,phone,email from Lead
                            where phone LIKE :phone_number + '%']);
  }
}

I'm a bit puzzled why you are searching Leads in a method named getAccount but I assume you have a valid business use case here


text:
Q: Check browser width after resize, without reload (Javascript) I have a small piece of Javascript that checks what the browser's width is on load and, depending on the result, runs a piece of jQuery. This to display a different menu on mobile devices
However, it CAN happen a user starts with a very small browser on his desktop, running the jQuery (and therefore the mobile menu). If he then resizes to full-screen, the menu doesn't change, because the check on the browser's width doesn't run again.
The question: How do I adapt the Javascript so it checks every time the browser is resized?
My code:
if (window.innerWidth <= 992) {
    jQuery(document).ready(function($) {
        $(".main-menu").hide();
        $(".mobile-nav-button").click(function() {
            $(".main-menu").slideToggle(500);
        });
    });
}
else {
    jQuery(document).ready(function($) {
        $(".mobile-nav-button").hide();
        $(".mobile-cart-button").hide();
    });
}

A: You can use a resize function wrapper like this:
function resize(){
    // do all your stuff here
}

And then call it once on page load, and recall it on every resize event:
$(document).ready(function(){
    resize();
    $(window).resize(resize);
});

Instead of the wrapper you could also use an anonymous function ($(window).resize(function(){/*Do stuff here*/})), but then you can't call your function on page load and you'd have to repeat yourself.
Your specific case
In your specific case you'd have to take out the document readys. Heres how it should look:
function resize(){
    // First we need to show all, then we will selectively hide based on page width
    $(".main-menu, .mobile-nav-button, .mobile-cart-button").show();
    if (window.innerWidth <= 992) {
        $(".main-menu").hide();
        // also, because you bind a click event here, you'll need to unbind it every time
        // otherwise it will be executed multiple times after a couple of resizes
        // (you could also do what @david does and move this into the document.ready below)
        $(".mobile-nav-button").off("click").click(function() {
            // slideToggle will toggle display of an element, but because its wrapped in click()
            // it only gets executed onclick, not resize. Also, you don't want animation on resize.
            $(".main-menu").slideToggle(500);
        });
    } else {
        $(".mobile-nav-button").hide();
        $(".mobile-cart-button").hide();
    }
}

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

A snippet
Below is a snippet with the code working. I reduced the width to 700 pixels so I could see the effects at a smaller screen difference (because that how the snippet editor looks) but it all works.

<!DOCTYPE html>

Mobile Nav Button

Mobile CART Button

MAIN MENU</dov>

A: you can use
jQuery(document).ready(function($) {

    $(".mobile-nav-button").click(function() {
        $(".main-menu").slideToggle(500);
    });

    $(window).resize(function()
    {
        if (window.innerWidth <= 992) {
            $(".main-menu").hide();
        }
        else {

           $(".mobile-nav-button").hide();
           $(".mobile-cart-button").hide();

       }
    ));

    $(window).resize();

));

A: Just call resize function  on pageLoad
$(document).ready(function($) {
    $(window).resize(YourFunctionName);
    $(window).resize();
 });

 function YourFunctionName() {
          // Here is your code which you want to run automatically on page resize.
  }


text:
Q: "Go to" option in jquery pagination Created pagination in jquery,
Now I am trying to have it more user-friendly by adding input box Go To (See the top of the resulted snippet). I am not able to decide how would it be done? I need on onKeyPress (that means no submit button for it):

$(document).ready(function() {
  var totalRows = $('#tblData').find('tbody tr:has(td)').length;
  var recordPerPage = 18;
  var totalPages = Math.ceil(totalRows / recordPerPage);
  var $pages = $('

');
  for (i = 0; i < totalPages; i++) {
    $(' ' + (i + 1) + '').appendTo($pages);
  }
  $pages.appendTo('#tblData');

  $('.pageNumber').hover(
    function() {
      $(this).addClass('focus');
    },
    function() {
      $(this).removeClass('focus');
    }
  );

  $('table').find('tbody tr:has(td)').hide();
  var tr = $('table tbody tr:has(td)');
  for (var i = 0; i <= recordPerPage - 1; i++) {
    $(tr[i]).show();
  }
  $('span').click(function(event) {
    $('#tblData').find('tbody tr:has(td)').hide();
    var nBegin = ($(this).text() - 1) * recordPerPage;
    var nEnd = $(this).text() * recordPerPage - 1;
    for (var i = nBegin; i <= nEnd; i++) {
      $(tr[i]).show();
    }
  });
});
.focus {
  background-color: green;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
}

#pages {
  position: fixed;
  bottom: 0;
  background-color: blue;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
}

.pageNumber {
  padding: 5px;
}

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>KBC</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <input type="number" placeholder="Go to.." />

        Question 1

        Question
        मुनि हिंसा आदि पापों का त्याग कितनी कोटि से करता है  ?

        Option A
        6

        Option B
        7

        Option C
        8

        Option D
        9

        Right Answer
        D

        <button type="submit" name="save" class="btn btn-default">
           Alter this question
        </button>

     Question 2

     Question
        'अभिमान  से बंधने वाला कौनसा पाप है  ?

     Option A
        क्रोध

     Option B
        मान

     Option C
        माया

     Option D
        लोभ

     Right Answer
        B

        <button type="submit" name="save" class="btn btn-default">
           Alter this question
        </button>

     Question 3

     Question
        तिर्यञ्च जीवों के दण्डक कितने है  ?

     Option A
        7

     Option B
        8

     Option C
        9

     Option D
        10

     Right Answer
        C

        <button type="submit" name="save" class="btn btn-default">
           Alter this question
        </button>

     Question
        नाग कुमार का दण्डक कौनसा है  ?

     Option A
        तीसरा

     Option B
        चौथा

     Option C
        पांचवां

     Option D
        छठा

     Right Answer
        A

        <button type="submit" name="save" class="btn btn-default">
           Alter this question
        </button>

Now I am trying to have it more user-friendly by adding input box Go To (See the top of the resulted snippet). I am not able to decide how would it be done? I need on onKeyPress (that means no submit button for it).

A: You can add a keypress event listener to the input and if event.which is equal to 13 (enter), you can execute a function.

$(document).ready(function() {
  var numOfPages = 2;
  var totalRows = $('#tblData').find('tbody tr:has(td)').length;
  var recordPerPage = 18;
  var totalPages = Math.ceil(totalRows / recordPerPage);
  var $pages = $('

');
  for (i = 0; i < totalPages; i++) {
    $(' ' + (i + 1) + '').appendTo($pages);
  }
  $pages.appendTo('#tblData');

  $('#goTo').keypress(function(e){
     var value = parseInt($(this).val());
     if(e.which==13&&!isNaN(value)&&value>0&&value<=numOfPages){
       alert("Going to "+value+"...!")
       $('.pageNumber')[value-1].click();
     }
  });

  $('.pageNumber').hover(
    function() {
      $(this).addClass('focus');
    },
    function() {
      $(this).removeClass('focus');
    }
  );

  $('table').find('tbody tr:has(td)').hide();
  var tr = $('table tbody tr:has(td)');
  for (var i = 0; i <= recordPerPage - 1; i++) {
    $(tr[i]).show();
  }
  $('span').click(function(event) {
    $('#tblData').find('tbody tr:has(td)').hide();
    var nBegin = ($(this).text() - 1) * recordPerPage;
    var nEnd = $(this).text() * recordPerPage - 1;
    for (var i = nBegin; i <= nEnd; i++) {
      $(tr[i]).show();
    }
  });
});
.focus {
  background-color: green;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
}

#pages {
  position: fixed;
  bottom: 0;
  background-color: blue;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
}

.pageNumber {
  padding: 5px;
}

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>KBC</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <input type="number" placeholder="Go to.." id="goTo"/>

        Question 1

        Question
        मुनि हिंसा आदि पापों का त्याग कितनी कोटि से करता है  ?

        Option A
        6

        Option B
        7

        Option C
        8

        Option D
        9

        Right Answer
        D

        <button type="submit" name="save" class="btn btn-default">
           Alter this question
        </button>

     Question 2

     Question
        'अभिमान  से बंधने वाला कौनसा पाप है  ?

     Option A
        क्रोध

     Option B
        मान

     Option C
        माया

     Option D
        लोभ

     Right Answer
        B

        <button type="submit" name="save" class="btn btn-default">
           Alter this question
        </button>

     Question 3

     Question
        तिर्यञ्च जीवों के दण्डक कितने है  ?

     Option A
        7

     Option B
        8

     Option C
        9

     Option D
        10

     Right Answer
        C

        <button type="submit" name="save" class="btn btn-default">
           Alter this question
        </button>

     Question
        नाग कुमार का दण्डक कौनसा है  ?

     Option A
        तीसरा

     Option B
        चौथा

     Option C
        पांचवां

     Option D
        छठा

     Right Answer
        A

        <button type="submit" name="save" class="btn btn-default">
           Alter this question
        </button>

A: If you wrap the <input ...> inside a <form ...>, you can just hit enter to go, no submit button needed.
<form action="#" id="gotoForm">
    <input type="text" placeholder="Go to ..." name="goto" id="goto">
</form>

Then attach the jQuery to the form to handle the submit-event. This saves you from having to decode key-codes, and saves you running an event handler for every keypress.
$("#gotoForm").on("submit", function(event){
    event.preventDefault();
    showPage($("#goto").val());
}

Also, you'll need to refactor the click handler for the span, and extract the function so you can call that from the submit handler as well.
$('span').click(function(event) {
    showPage($(this).text());
});

function showPage(page){
    $('#tblData').find('tbody tr:has(td)').hide();
    var nBegin = (page - 1) * recordPerPage;
    var nEnd = page * recordPerPage - 1;
    for (var i = nBegin; i <= nEnd; i++) {
      $(tr[i]).show();
    }
  };


text:
Q: Islands and Gaps Issue Backstory:  I have a database that has data points of drivers in trucks which also contain the.  While in a truck, the driver can have a 'driverstatus'.  What I'd like to do is group these statuses by driver, truck.
As of now, I've tried using LAG/LEAD to help.  The reason for this is so I can tell when a driverstatus change occurs, and then I can mark that row as having the last datetime of that status.
That in itself is insufficient, because I need to group the statuses by their status and date.  For this, I've got something such as DENSE_RANK, but I can't manage to get that right concerning the ORDER BY clause.
Here is my test data, and here is one attempt of many of me floundering with ranking.
/****** Script for SelectTopNRows command from SSMS  ******/
DECLARE @SomeTable TABLE
(
    loginId VARCHAR(255),
    tractorId VARCHAR(255),
    messageTime DATETIME,
    driverStatus VARCHAR(2)
);

INSERT INTO @SomeTable (loginId, tractorId, messageTime, driverStatus)
VALUES('driver35','23533','2018-08-10 8:33 AM','2'),
('driver35','23533','2018-08-10 8:37 AM','2'),
('driver35','23533','2018-08-10 8:56 AM','2'),
('driver35','23533','2018-08-10 8:57 AM','1'),
('driver35','23533','2018-08-10 8:57 AM','1'),
('driver35','23533','2018-08-10 8:57 AM','1'),
('driver35','23533','2018-08-10 9:07 AM','1'),
('driver35','23533','2018-08-10 9:04 AM','1'),
('driver35','23533','2018-08-12 8:07 AM','3'),
('driver35','23533','2018-08-12 8:37 AM','3'),
('driver35','23533','2018-08-12 9:07 AM','3'),
('driver35','23533','2018-06-12 8:07 AM','2'),
('driver35','23533','2018-06-12 8:37 AM','2'),
('driver35','23533','2018-06-12 9:07 AM','2')
;
SELECT *, DENSE_RANK() OVER(PARTITION BY
  loginId, tractorId, driverStatus
ORDER BY messageTime ) FROM @SomeTable
;

My end result would ideally look something like this:
loginId tractorId   startTime           endTime            driverStatus
driver35    23533   2018-08-10 8:33 AM  2018-08-10 8:56 AM      2
driver35    23533   2018-08-10 8:57 AM  2018-08-10 9:07 AM      1
driver35    23533   2018-08-12 8:07 AM  2018-08-12 9:07 AM      3

Any help on this is greatly appreciated.

A: WITH drivers_data AS
(
    SELECT *,
           row_num =     ROW_NUMBER()
                         OVER (PARTITION BY loginId,
                                            tractorId,
                                            CAST(messageTime AS date),
                                            driverStatus
                               ORDER BY messageTime),

           row_num_all = ROW_NUMBER()
                         OVER (PARTITION BY loginId,
                                            tractorId
                               ORDER BY messageTime),

           first_date =  FIRST_VALUE (messageTime)
                         OVER (PARTITION BY loginId,
                                            tractorId,
                                            CAST(messageTime AS date),
                                            driverStatus
                               ORDER BY messageTime),

           last_date =   LAST_VALUE (messageTime)
                         OVER (PARTITION BY loginId,
                                            tractorId,
                                            CAST(messageTime AS date),
                                            driverStatus
                               ORDER BY messageTime
                               ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    FROM @t
)
SELECT loginId, tractorId, first_date, last_date, driverStatus
FROM drivers_data
WHERE row_num = 1
ORDER BY row_num_all;

OUTPUT:

+==========+===========+=====================+=====================+==============+
| loginId  | tractorId | first_date          | last_date           | driverStatus |
|==========|===========|=====================|=====================|==============|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:56:00 | 2            |
|----------|-----------|---------------------|---------------------|--------------|
| driver35 | 23533     | 2018-10-08 08:57:00 | 2018-10-08 09:07:00 | 1            |
|----------|-----------|---------------------|---------------------|--------------|
| driver35 | 23533     | 2018-12-06 08:07:00 | 2018-12-06 09:07:00 | 2            |
|----------|-----------|---------------------|---------------------|--------------|
| driver35 | 23533     | 2018-12-08 08:07:00 | 2018-12-08 09:07:00 | 3            |
+----------+-----------+---------------------+---------------------+--------------+

I will try to explain what's going on here:

*

*row_num This is for numbering rows which are restricted by date and status of the driver. We need casting since we need date part without time.

*row_num_all This is the key attribute since it allows us in the end to sort rows by occurrence. This window is not restricted by status since we need numbering across whole driver's data.

*first_date The FIRST_VALUE is handy function for our purpose. It just retrieves the first datetime occurrence.

*last_date It's correct to assume that for the last date we need LAST_VALUE window function. But using it is tricky and requires more explanation. As you can see I explicitly use special framing ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING. But why? Let me explain. Let's take a part of output for date 10/8/2018 and status 2 with default framing. We get the following results:

+==========+===========+=====================+=====================+==============+
| loginId  | tractorId | first_date          | last_date           | driverStatus |
|==========|===========|=====================|=====================|==============|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:33:00 | 2            |
|----------|-----------|---------------------|---------------------|--------------|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:37:00 | 2            |
|----------|-----------|---------------------|---------------------|--------------|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:56:00 | 2            |
+----------+-----------+---------------------+---------------------+--------------+

As you can see, the last date is incorrect! This happens because LAST_VALUE uses default frame RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW- it means that last row is always current row in window. Here's what happens under the hood. Three windows get created. Each row gets its own window. Then it retrieves the last row from window:
Window for 1-st row

+==========+===========+=====================+=====================+==============+
| loginId  | tractorId | first_date          | last_date           | driverStatus |
|==========|===========|=====================|=====================|==============|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:33:00 | 2            |
+----------+-----------+---------------------+---------------------+--------------+

Window for 2-nd row

+==========+===========+=====================+=====================+==============+
| loginId  | tractorId | first_date          | last_date           | driverStatus |
|==========|===========|=====================|=====================|==============|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:33:00 | 2            |
|----------|-----------|---------------------|---------------------|--------------|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:37:00 | 2            |
+----------+-----------+---------------------+---------------------+--------------+

Window for 3-rd row

+==========+===========+=====================+=====================+==============+
| loginId  | tractorId | first_date          | last_date           | driverStatus |
|==========|===========|=====================|=====================|==============|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:33:00 | 2            |
|----------|-----------|---------------------|---------------------|--------------|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:37:00 | 2            |
|----------|-----------|---------------------|---------------------|--------------|
| driver35 | 23533     | 2018-10-08 08:33:00 | 2018-10-08 08:56:00 | 2            |
+----------+-----------+---------------------+---------------------+--------------+

So, the solution for this is to change framing: we need to move not from beginning to current row, but from current row to the end. So, UNBOUNDED FOLLOWING just means this - last row in current window.

*Next is WHERE row_num = 1. This is all simple: since all rows has same information about first date and last date, we just need first row.

*The final part is ORDER BY row_num_all. This is where you  get your correct ordering.
P.S.

*

*Your desired output in question is incorrect.
For date 8/10/18 8:57 AM and status 1 the last date must be 10/8/2018 9:07 AM - not 10/8/2018 9:04 AM, as you mentioned.

*Also there's missing output for date 12/6/2018 and status 2.
UPDATE:
Here are illustrations of how FIRST_VALUE and LAST_VALUE work.
All three figures have following parts:

*

*Query data This is result of query.

*Original query Original source data.

*Windows These are intermediate steps for calculations.

*Frame Mentions which frame is used.

*Green cell Window specification.

Here's what's happening under the hood:

*

*First, SQL Server creates partitions for all mentioned fields. On figure it is partition column.

*Each partition can have a frame: either default or custom. The default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. This means that the row gets window between the start of partition and current row. If you don't mention a frame, the default frame comes into play.

*Each frame creates window for each row. On figures these windows are in columns row 1 to row 2 and marked with color. The row number corresponds to row_num_all field.

*A row operates only in bounds of its window.

1. FIRST_VALUE

To get first date, we can use handy FIRST_VALUE window function.
As you can see, we use default frame here. This means that for each row the window  will be between the start of window and current row. For getting first date this is just what we need. Each row will fetch the value from first row. The first date is in "first_date" field.
2. LAST_VALUE - incorrect frame

Now we need to calculate last date. The last date is in the last row of partition, so we can use LAST_VALUE window function.
As I mentioned earlier, if we don't mention frame, the default frame is used. As you can see on figure, the frame always ends in the current row - this is incorrect, because we need the date from last window row. The last_date field shows us incorrect results - it reflects the date from current row.
3. LAST_VALUE - correct frame

To fix the situation with fetching last date, we need to change the frame upon which LAST_VALUE will operate on: ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING. As you can see, the window for each row now is between current row and the end of partition. In this case LAST_VALUE will correctly fetch the date from last row of window. Now the result in last_date field is correct.

A: The below solution identifies each time an island starts (when a driverStatus changes) within each loginID / tractorID combination, and then assigns an "id" number to that island.
After that, its a simple min/max to find when that island starts and ends.
Answer:
select b.loginId
, b.tractorId
, min(b.messageTime) as startTime
, max(b.messageTime) as endTime
, b.driverStatus
from (
    select a.loginId
    , a.tractorId
    , a.messageTime
    , a.driverStatus
    , a.is_island_start_flg
    , sum(a.is_island_start_flg) over (partition by a.loginID, a.tractorID order by a.messageTime asc) as island_nbr --assigning the "id" number to the island
    from (
        select st.loginId
        , st.tractorId
        , st.messageTime
        , st.driverStatus
        , iif(lag(st.driverStatus, 1, st.driverStatus) over (partition by st.loginID, st.tractorId order by st.messageTime asc) = st.driverStatus, 0, 1) as is_island_start_flg --identifying start of island
        from @SomeTable as st
        ) as a
    ) as b
group by b.loginId
, b.tractorId
, b.driverStatus
, b.island_nbr --purposefully in the group by, to make sure each occurrence of a status is in final results
order by b.loginId asc
, b.tractorId asc
, min(b.messageTime) asc

When you leave off the last three records of the sample data (as this is not in the expected output of the question, just like JohnyL said), this query produces the exact output from the question.

A: SELECT
  t.loginId,
  t.tractorId,
  startTime = MIN(messageTime),
  endTime   = MAX(messageTime),
  driverStatus
FROM @someTable t
GROUP BY loginId, tractorId, driverStatus
ORDER BY MIN(messageTime);

Results:
loginId        tractorId  startTime               endTime                 driverStatus
-------------- ---------- ----------------------- ----------------------- ------------
driver35       23533      2018-10-08 08:33:00.000 2018-10-08 08:56:00.000 2
driver35       23533      2018-10-08 08:57:00.000 2018-10-08 09:07:00.000 1
driver35       23533      2018-12-08 08:07:00.000 2018-12-08 09:07:00.000 3


text:
Q: JOOQ - map a single record using RecordMapper I am not able to use a RecordMapper mapper to map a single record retrieved via fetchOne/fetchAny.
If I use for example (like in the manual)
List<Something> list =  create.selectFrom(TABLE).fetch().map(mapper);

it works,
but if i use the same mapper for:
Something pojo = create.selectFrom(TABLE).fetchOne().map(mapper);

it doesn't compile.
Thanks for the help

A: This probably has to do with generics. While Result.map() takes a RecordMapper<? super R,E> argument type, Record.map() takes RecordMapper<Record,E>, because Record has no recursive generic type definition for R.
In other words, if you want to reuse the same mapper for both Result.map() and Record.map(), unfortunately, you will need to make it a RecordMapper<Record, E>, which means you'll lose some of the type safety on the record type.
A workaround would be to create a new result just for the sake of mapping:
Result<TableRecord> result = DSL.using(configuration).newResult(TABLE);
result.add(record);
Something pojo = result.map(mapper).get(0);

A: An alternative workaround to the one provided by Lukas Eder could be to use the mapper directly:
TableRecord record = create.selectFrom(TABLE).fetchOne();
Something pojo = mapper.map(record);


text:
Q: Place "Favorite Tags" above the ad instead of below it, at least after privilege gain of "reduce ads" It would be great to show the "Favorite Tags" above the ad in the right side of the window instead of below it when showing a list of questions screens

Because, the "Favorite Tags" are something we use to switch between different set of question lists as we are interested specifically in some areas only.
It is a tedious task to scroll each time we need to click the next tag once we didn't find any new question in the current tag. It will be great help for regular users.
Instead if the "Favorite Tags" are on top, we can have quick click on each tags and have a quick check of each tag updates and move on.


text:
Q: Pandas dataframe math.isnan faster than boolean check I was wondering if you have a df and filter for example like the following
df = df[math.isnan(df.columnA)]

is it faster than for same number of true/false evaluations as
df = df[df.columnB == True] #(or df = df[df.columnB])

I thought null checks are faster than true/false checks but I'm not sure in this case.
I'm not sure if python Not A Number is equally not cpu intensive as null check in for example C#


text:
Q: What is the meaning of the decision tree algorithm name "c4.5"? I'm learning Machine Learning. In this subject, I see a decision tree name "c4.5" but I do not know "c4.5" stand for what. Is there anyone help me? I search about it a lots but I still do not have the answer :D

A: In the book "C4.5: Programs for Machine Learning" by Quinlan I wasn't able to quickly find an description of why that name was chosen (it's about 300 pages including appendices with lots of source code though, so didn't read all that).
The story I heard is that the "C" simply indicates that the algorithm was implemented in C, and that Quinlan was maybe very proud of the fact that he was able to program in C. Then I suppose the "4.5" is simply a version number of the software.
Note that a Java implementation of the same / a similar algorithm in Weka is named "J48".


text:
Q: Is it normal for Software & Updates to always show I'm up to date? For the last month on my Ubuntu 13.10 system, Software and Updates always shows that the laptop is up to date. I tried to change the server for updates but with the same result.
So is it normal?

A: This is often to be expected, especially if updates are being installed automatically behind the scenes (which you can configure in the Software Updater). And sometimes, a month or more goes by without any updates being released.
Why does so much time sometimes pass with no new updates? With default settings, it is intended that users of stable releases only get updates for security bugs and serious stability/usability bugs; in Ubuntu, updates to provide new features are not typically rolled out after the end of a release's beta phase.
It's a good idea to check to make sure updates are working properly on your system, though.
Check Your Update Settings
To check your settings, run the Software Updater [Update Manager for people using old versions of Ubuntu] and click Settings.... You might have to wait for it to automatically check for updates, before being able to do that.

The Software & Updates window is shown (called some different things on some other versions of Ubuntu). Under "Install updates from:", there are checkboxes for the different kinds of updates that can be installed. At least "Important security updates" should be checked, and you probably want "Recommended updates" as well.
Under that, you can choose how often to check automatically for updates, what to do when new security updates are found, and what to do when other (non-security) updates are found. If you have something relatively frequent chosen for "Automatically check for updates" and you have "Download and install automatically" chosen for "When there are security updates:", then most likely any important security updates are being installed behind the scenes for you.
But if you have "Never" selected for "Automatically check for updates," then you're not getting updates installed or even checked for automatically.

After making sure your settings are however you want them, click Close. Then I recommend checked your Ubuntu's systems record of what updates have been installed recently. That should answer the question as to whether or not you're getting updates.
Checking If Updates Are Being Installed
If your settings look good, then you should check to see if the updates you'd expect to get are really being installed automatically.
To see when updates were last installed, you may be able to see a list of everything installed recently (including updates) in the Software Center.
Or you can look at the package manager's logs, especially history.log in the /var/log/apt folder. You can view that file by double-clicking on it in Nautilus (the graphical file browser), or in the Terminal with:
less /var/log/apt/history.log

If the file is empty, there's still typically no need to worry; in that case, look at history.log.1.gz, the most recently "old" log. To examine it graphically, you can double-click it, drag the .log file inside anywhere (e.g. the desktop), and double-click the extracted file (since a .gz file is compressed).
Or you can easily view it in the Terminal with:
zless /var/log/apt/history.log.1.gz

If the dates in the log(s) show updates installed in the last couple of months, then most likely everything is fine.
If they do not, then maybe something isn't working. In that case, please edit your question to include the full contents of sources.list in the /etc/apt folder. You can view that graphically, or have its contents shown on (and copyable from) the Terminal with:
cat /etc/apt/sources.list

(For readers with this or a similar problem other than the poster of this question, of course you shouldn't edit this question. Instead, you should post your own question, fully describing your situation; you can include the contents of that file in your question.)

A: reinstalling the ubuntu 13.10 solved the issue


text:
Q: how to prevent SQL injection in ruby on rails with post request I am getting a security error in my ROR code that SQL injection may be possible in one post request when I run The OWASP Zed Attack Proxy (ZAP) tool on my code.
I have a get_auth_token method which does not take any parameters , ZAP tool adds a query parameter in this request and on executing the modifier request the page loads fine  which is an issue
Below is the modified url with added query param
https://example.com/api/sessions/get_auth_token?query=query+AND+1%3D1+--+
get_auth_token implementation looks like this
def get_auth_token
  user = User.find_by(id: session[:user_id], disabled: false)
 if session[:user_id]
  if user
  token = AuthToken.issue(user_id:user.username)
  session[:user_id] = user.id
  session[:username] = user.username
  session[:project_id] = user.get_setting('xyz', nil)
  User.update(user.id, :token=>token)

I do not want to convert this request to GET. I have gone through many examples for SQL injection prevention , they all focus on methods which accept some param. My method does not accept any param. How can I make sure that it does not accept any external param to prevent this SQL injection


text:
Q: VSCode debugger - 'node' not found error when launching I'm trying to step through my Typescript project with VSCode debugger. However, I encounter this error on launch:
/usr/bin/env: 'node': No such file or directory

*

*Node is available from the VSCode terminal - which node returns /home/user/.nvm/versions/node/v14.15.5/bin/node

*The launch conf is as follows:

{
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/src/index.ts",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": ["${workspaceFolder}/dist/**/*.js"],
      "skipFiles": ["<node_internals>/**"]
}

Why does VSCode claim node is not available?


text:
Q: github, are pull requests auto-generated for bumping up a dependency version always safe? I have noticed that some MRs get auto created for bumping dependencies like
Bump axios from 0.18.0 to 0.18.1 in xxx
Bump ini from 1.3.5 to 1.3.7 in xxx
What are these and is it always safe to simply accept the change?

A: Ideally, if the code is semantically versioned and the version is just a patch version, then generally they're pretty safe.  But there are always risks to bumping versions:

*

*The new dependency could actually be incompatible in some subtle way and break things.

*The new dependency could contain new bugs that impact the functionality of the program.

*The new code could contain additional security vulnerabilities.

These are the same risks as happen with any new code, so they are not any riskier than introducing other new code.
You may also want to distinguish between bumping versions just because there's a new version and bumping versions because there's a bug or security vulnerability.  The former is a bit hostile to other users of your package, especially if they need to use an older toolchain or environment or your package is a dependency, whereas the latter is generally useful, and in the case of security vulnerabilities, responsible.

A:
What are these?

These are security updates generated by Dependabot. It monitors your dependencies for security problems. When it finds one it suggests an upgrade based on recommendations by the developers and security experts.
You can find details about the security issue in your Security tab. This usually includes a link to the CVE post about the issue, and the developer's commentary and recommended action.
See About Dependabot security updates for more.

and is it always safe to simply accept the change?

The tl;dr is yes.
The long answer is you have to weigh the security risk vs the risk it could introduce new bugs and incompatibilities, but with the knowledge this has been reviewed by experts and the action recommended by the developers. To mitigate this, Dependabot makes the smallest possible upgrade which resolves the security issue. If you have a solid test suite for your project it should catch any problems caused by the update.
If you're relying on undocumented features, such as monkey patching, upgrading always has a risk. You can mitigate this by configuring those dependencies to stay within a version range, and by having good tests to ensure the undocumented features continue to work. However, you should minimize your use of undocumented features.
In your case, 0.18.0 to 0.18.1 and 1.3.5 to 1.3.7 indicate they are patch releases which contain only bug fixes to version 0.18.x and 1.3.x respectively. They should be safe. This is Semantic Versioning adopted by projects to give you a better idea of what changes are in each version.
For example, in one of my projects Dependabot has found a low priority security issue in a dependency that I don't use directly (a dependency of a dependency). The dependency is a very important one for many projects, so I have a lot of trust in their updates. Dependabot did not generate a PR, only a security alert which recommended an upgrade. However, there is not yet a stable release which fixes the problem, only a release candidate, and it is a minor update from 1.1 to 1.2, not just a bug fix release. After reading the security alert I've judged it does not put us at risk. The risks of using a minor update release candidate are greater than a low priority security issue, so I'm waiting for a stable release.


text:
Q: CREATE TABLE errors out after 1st use? This piece of code creates the first table with no problems, but then throws "Error Querying Database 2" which is the error for the second CREATE TABLE query. Syntax looks right, but I'm relatively new to this...
$dbc = mysqli_connect("localhost", "$dbuser", "$dbpass") or die('Error connecting to MySQL server.');
mysqli_select_db($dbc, "autoim9_codeaic");

$content = "CREATE TABLE content (id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), page varchar(255), html longtext)";
mysqli_query($dbc, $content) or die('Error querying database1');

$events = "CREATE TABLE events (id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name varchar(255), date varchar(255), time varchar(255), location varchar(255), html longtext, img varchar(255), link varchar(255), target varchar(255), order int)";
mysqli_query($dbc, $events) or die('Error querying database2');

$spotlight = "CREATE TABLE spotlight (id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), title varchar(255), img varchar(255), link varchar(255), target varchar(255), order int)";
mysqli_query($dbc, $spotlight) or die('Error querying database3');

A: date, time, and order are reserved keywords in MySQL. You either need to change their names or use backticks (`) to escape them.
$events = "CREATE TABLE events (id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name varchar(255), `date` varchar(255), `time` varchar(255), location varchar(255), html longtext, img varchar(255), link varchar(255), target varchar(255), `order` int)";

FYI, if you're using varchar(255) for every field you probably are doing it wrong. Date and time fields have their own data types and should be used accordingly.

A: "Order" is a reserved word, so you need to enclose in back-ticks (or preferably, choose a slightly different field name).
So it's actually an error in your SQL.


text:
Q: Doing X when an Image is clicked on my ASP.Net project How can I program a Click event on an image?

A: Javascript Method:
Create a function
function myFunction() {
    //Do Something
}

Create event handler for your image:
<img OnClick="myFunction()" />

If you want to trigger a server side method then use asp:ImageButton which has an OnClick event.


text:
Q: How can I check if every word in a sentence starts with a capital letter and ends with ", "? I have an input type text where I would like to allow the user to type profession names. I want to be in this scheme "Profession1, Profession2, Profession3".That is, start with a capital letter and if there are other values then the word should be followed by a "," and a single space. I've tried html patterns and php functions but unfortunately it doesn't work as I would like.  The important thing is that the user can only enter one value, then it should look like "Profession1" without the spaces after the word and the "," symbol. The last condition also applies to the previous example.
Thanks in advance

A: For simplicities sake, the below solution does not use regex.
function match(str) {
    let list = str.split(' ');
    for (let i = 0; i < list.length; i++) {
        if (list[i].charCodeAt(0) > 90 || list[i].charCodeAt(0) < 65) {
            return false;
        }
    }
    for (let i = 0; i < list.length - 1; i++) {
        if (!(list[i][list[i].length - 1] == ",")) {
            return false;
        }
    }
    return list;
}

When passed a string containing words separated by commas, with each word starting with a capital letter, it returns the list. Otherwise, it returns false.
Edit: After the clarification of requirements in the comments, below is the updated function.
function match(str) {
    let list = str.split(',');

    // Checks for capital letters at the start of each profession
    for (let i = 0; i < list.length; i++) {
        if (list[i].trim().charCodeAt(0) > 90 || list[i].trim().charCodeAt(0) < 65) {
            return false;
        }
    }

    // Checks for spaces after every comma
    for (let i = 1; i < list.length; i++) {
        if (!(list[i][0] == " ")) {
            return false;
        }
    }

    // Trim whitespace on each profession
    l = list.map((profession) => {
        return profession.trim();
    })
    return l;
}


text:
Q: Big locale files in rails, is it ok? I couldn't really find an answer for this on the internet. I am currently developing a relatively big web application in Rails. And my locale file is growing rapidly.
My question is, does it matter if my locale file gets really big? If it doesn't matter, how does Rails handle this? If it does, what would be a good solution to this? I found in the rails documentations that you can name your files respectively to their language e.g. index.en.html.erb. But that would mean I'd have to edit each view for each language individually when a change has to be made.
Thanks!

A: Locales are loaded into memory when the server is started (not on every request). Rails handles all locales internally as one big nested hash. Therefore Rails does not care if there are one big or many small locale files.
What you need to consider: What works well for you. I had to work with an app with ~ 5000 locales once. I was very happy that they were organized into one folder for each language and splited into multiple files: One for every model or controller. The locales were clearly arranged and easy to find. Later we used a webservice to maintain the locales (webtranslateit.com) what also helped a lot when working with external (not technical) translators.

A: You can try to break up your locales file into separate files.  More info:
http://guides.rubyonrails.org/i18n.html#organization-of-locale-files


text:
Q: Best memory type for data logging I'm gonna design a board which data logging it's mandatory! I don't think that i have sufficient space in pcb for large parts but i want an embedded flash (dedicated IC). For handling unexpected power downs the system must storing data every time which is determined by some interval value (seconds). Data have string format with undefined lenth. And i need to store that data in an embedded flash memory. Data comes from, sensors and other peripherals such as power supply monitoring.

*

*Who memory type is best for that purpose? (NAND or NOR)?

I will glad with a >4MB memory capacity.
In a little research i find that NAND flash have small amount of pages with large capacitance and this will consumes more W/E cycles.
-Thanks!

A: If you're looking for something which can withhold many write cycles you might want to to look at FRAM (e.g. from Cypress). Basically unlimited Write/Erase cycles. Of course, this comes at a cost. If you're looking for large storage, go for NAND but make sure that you do not write to the same sector/page again and again.

A: I realize you mentioned using a dedicated IC, but I believe the easiest way to add a device for data logging in a reasonably small space is to use a microSD card.  The connection to the microcontroller is a four wire SPI bus (CLK, SDI, SDO, and CS).  Because of their high volume, they are very inexpensive -- 8 GB for $5 on Amazon, probably less on eBay.  These happen to use NAND flash, but that's transparent to the user.
You don't need an operating system, you can just write to it as individual sectors.  Because the space is so huge, there is no issue of wearing out the card. The spec for the SPI interface to SD cards is publicly available, and there's also lots of code for writing and reading to the card around.
If you want to add the code to implement a FAT file system, then you could remove the card and read it in a PC.  There's a lot of code around to do that also.


text:
Q: Is it possible to use a delimiter with Will_Paginate pagination? In a Rails 4 app, I'm using the will_paginate and will_paginate-bootstrap gems:
=will_paginate @things, renderer: BootstrapPagination::Rails

Is it possible to specify a comma-delimiter in the pagination, so the higher pages would be listed as 30,115 and 30,116?
I'm aware of number_with_delimiter but I don't know how to use this with will_paginate.

A: You can give the below code a try (put it in ApplicationHelper)
def page_entries_info(collection, options = {})
  raw super(collection, options).gsub(/\<b\>\d*\<\/b\> in total/, "<b>#{number_with_delimiter(collection.total_entries)}</b> in total")
end


text:
Q: Dtexec ISSERVER returns is not a valid server package path I am executing a SSIS package via master..xp_cmdshell from a stored procedure and I am always getting the error

"Description:
  '\SSISDB\Main\Projects\ProjectName\Packages\PackageName.dtsx' is not a
  valid server package path."

I tried various kinds of permutations and combinations on the path, but it is not helping. This package was migrated from SQL 2008(MSDB) to SQL 2016(SSISDB) and I am leveraging the dtexec command (that was earlier using MSDB and now updated to point to SSISDB). What am I doing wrong?
dtexec /ISSERVER "\SSISDB\Main\Projects\ProjectName\Packages\PackageName.dtsx"
/SERVER SERVERNAME /CONFIGFILE "D:\WorkSpace\Configurations.dtsConfig"
/CHECKPOINTING OFF /REPORTING E /SET
"\Package.Variables[User::LogId].Properties[Value]";718801

This is how it looks like in SSMS-2016 tree view of the package

Thanks,
Arvind

A: I figured out that you need to remove "Projects" and "Packages" from the folder path. (Found about this after running the package manually and verifying the Folder Location mentioned in the Package Name from execution report).
So it should be called as given below:
dtexec /ISSERVER "\SSISDB\Main\ProjectName\PackageName.dtsx" /SERVER SERVERNAME
 /CONFIGFILE "D:\WorkSpace\Configurations.dtsConfig" /CHECKPOINTING OFF
/REPORTING E /SET "\Package.Variables[User::LogId].Properties[Value]";718801


text:
Q: HTML5 Video background not showing for Safari or IE I've tried applying the fixes from other forum posts but none resolved this puzzle.
This video background does not work on Safari or IE.  This is the current code:
<video controls preload="preload" id="video" autoplay="autoplay" loop="loop" muted >
  <source src="<?php echo get_stylesheet_directory_uri(); ?>/video/pike.webm" type="video/webm">
  <source src="<?php echo get_stylesheet_directory_uri(); ?>/video/pike.mov" type="video/mov">
  <source src="<?php echo get_stylesheet_directory_uri(); ?>/video/pike.mp4" type="video/mp4">
    Your browser does not support the video tag.
</video>

A: Check if you are using a higher version of IE and Safari, because the tag video works only on version 3.5 above on Safari and a version above 9.0 in IE.


text:
Q: How to fix wget download file name when the url is redirected Wget can't detect filename when 301/302 redirections.  For example, to download the MySQL source code from http://www.mysql.com/downloads/mirror.php?id=408580
wget http://www.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.25a-linux2.6-x86_64.tar.gz/from/http://cdn.mysql.com/

The file will be save as index.html
wget http://cdn.mysql.com/Downloads/MySQL-5.5/mysql-5.5.25a-linux2.6-x86_64.tar.gz

The file will be save as mysql-5.5.25a-linux2.6-x86_64.tar.gz
but the first url is only a redirection for second URL as it is shown in:
curl -I http://www.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.25a-linux2.6-x86_64.tar.gz/from/http://cdn.mysql.com/

HTTP/1.1 302 Found
Date: Mon, 09 Jul 2012 06:11:50 GMT
Server: Apache/2.2
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: mirror=http%3A%2F%2Fcdn.mysql.com%2F; expires=Sat, 08-Jul-2017 06:11:50 GMT; path=/
Location: http://cdn.mysql.com/Downloads/MySQL-5.5/mysql-5.5.25a-linux2.6-x86_64.tar.gz
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8

How can wget save http://www.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.25a-linux2.6-x86_64.tar.gz/from/http://cdn.mysql.com/ as ".tar.gz" automatically (without using -O argument)?

A: Try the following command:
wget --content-disposition http://www.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.25a-linux2.6-x86_64.tar.gz/from/http://cdn.mysql.com/

When this is set to on, the experimental (not fully-functional) support for "Content-Disposition" header is enabled. This can result in extra round-trips to the server for a "HEAD" request and is known to suffer from a few bugs, which is why it is not currently enabled by default.
This option is useful for some file-downloading CGI programs that use "Content-Disposition" header to describe what the name of a downloaded file should be.


text:
Q: VS Code - Extension Details Blank post "disable gpu" fix I apologize if this question has been answered somewhere else, but so far I am unable to locate it if it was.
Background:
As many folks have suffered the dreaded blank screen on VS Code, I deployed the recommended fix for --disable-gpu.  This fix worked just fine for me and I have been using it ever since.
Issue:
Since this fix has been deployed, I'm unable to view the details page when viewing an Extension.  The page/tab just shows up as blank.  This happens with any extension, regardless of if I've installed it or not.  This in and of itself is not a deal breaker for me, but I was hoping to use the Jupyter Notebook extension, but this seems to be impacting this as well.
If anyone has any guidance, please let me know.
Screenshot showing lack of details

A: I was able to get this corrected by creating a .bat file that I use to open VS Code.  The code file was set up like the following:
cd C:\Program Files\Microsoft VS Code\
Code.exe --disable-software-rasterizer --disable-gpu --no-sandbox


text:
Q: error compilation, function pointer i have a simple program like this :
#include<stdio.h>

void add(int *nb)
{
    *nb += 1;
}

int f(int nb, void (*add)(int *))
{
    if (nb < 5)
        f(nb, add(&nb));
    return (nb);
}

int main() {
    int b = 5;
    int a = f(b, add);
    printf("%d\n", a);
}

i want to call f recursively until nb become greater or equal to 5, but when i compile the program , the gcc compiler show something like this :
error: passing 'void' to parameter of incompatible type 'void (*)(int *)'

can anyone help me please?

A: I'm not completely certain as to what you are trying to do with your function, but I took a stab at what I think you might be attempting to do:
#include<stdio.h>

void add(int *nb)
{
    *nb += 1;
}

int f(int nb, void (*function)(int *))
{
    function(&nb);
    if (nb < 5)
        f(nb, function);
    return (nb);
}

int main() {
    int b = 5;
    int a = f(b, add);
    printf("%d\n", a);
}

Now your function f accepts a function-pointer to a void function that takes an int * as an argument (I renamed this argument to function so it doesn't conflict with your existing function add).  It proceeds to call said function and pass in a pointer to nb to function.
What you were doing was passing in the result of add(&nb) into the function f as an argument (which said function is a void so it does not return anything) instead of passing in a pointer to the function.

A: The line f(nb, add(&nb)); doesn't make sense. You need to call the function somewhere, but not on the same line as where you pass the function pointer on, recursively.
Overall the program doesn't make much sense. I have no idea what you are trying to do, perhaps something similar to this?
#include<stdio.h>

void add(int *nb)
{
    *nb += 1;
}

void f(int* nb, void (*add)(int *))
{
    add(nb);

    if (*nb < 5)
    {
        f(nb, add);
    }
}

int main() {
    int a = 5;
    f(&a, add);
    printf("%d\n", a);
}

Will print 6 since the add is called once. The name add as function parameter to f is also mighty confusing, so better come up with another name for it.

A: Passing add(&nb) as an argument passes the returned value of add with the argument &nb. The function signature for f requires a function pointer, which can be passed as:
f(nb, add)

Also, even if you were actually trying to pass the returned value of add, that would be undefined behavior since it is of type void.

A: As Christian pointed out in the comments, the problem is on the recursive call line:
 f(nb, add(&nb));

If I understand correctly you are trying to increase nb using the function you receive as a pointer; here however you first pass nb unchanged (and as a value, not by reference), and then call the add function.
In the second argument the compiler is expecting a function pointer, but instead it receives the return value of the add(&nb) function call, which is void.
Also, in case nb is < 5 you need to return the recursive call.
The correct procedure would be:
#include<stdio.h>

void add(int *nb)
{
    *nb += 1;
}

int f(int nb, void (*add)(int *))
{
    if (nb < 5) {
        add(&nb);
        return f(nb, add);
    }
    return (nb);
}

int main() {
    int b = 1;
    int a = f(b, add);
    printf("%d\n", a);
}

It almost seems like you're trying to use lazy evaluation, but C doesn't have that!


text:
Q: What is the difference between null and System.DBNull.Value? Is there any difference between null and System.DBNull.Value? If yes, what is it?
I noticed this behavior now -
while (rdr.Read())
{
    if (rdr["Id"] != null) //if (rdr["Id"] != System.DBNull.Value)
    {
        int x = Convert.ToInt32(rdr["Id"]);
    }
}

While I retrieve data from the database using a sql datareader, though there is no value returned if(rdr["Id"] != null) returned true and eventually threw an exception for casting a null as integer.
But, this if I use if (rdr["Id"] != System.DBNull.Value) returns false.
What's the difference between null and System.DBNull.Value?

A: DBNull.Value is what the .NET Database providers return to represent a null entry in the database.  DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.
http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx

A: DataRow has a method that is called IsNull() that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.
DataRow["col"]==null will allways be false.
use
DataRow r;
if (r.IsNull("col")) ...

instead.

A: Null is similar to zero pointer in C++. So it is a reference which not pointing to any value.
DBNull.Value is completely different and is a constant which is returned when a field value contains NULL.

A: From the documentation of the DBNull class:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.

A: Well, null is not an instance of any type. Rather, it is an invalid reference.
However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.
*We would normally say null, but I don't want to confound the issue.
So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).
Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

A: DBNull.Value is annoying to have to deal with.
I use static methods that check if it's DBNull and then return the value.
SqlDataReader r = ...;
String firstName = getString(r[COL_Firstname]);

private static String getString(Object o) {
   if (o == DBNull.Value) return null;
   return (String) o;
}

Also, when inserting values into a DataRow, you can't use "null", you have to use DBNull.Value.
Have two representations of "null" is a bad design for no apparent benefit.


text:
Q: how to set a fiexd hostname for azure container app service I'd like to know if it's possible to specify a fixed hostname for an azure container app service? Just like what we did using the command "docker run --name xxx -h {fixed-hostname} ...", thanks.

A: No matter the Azure Container Instance or the Azure Web App for Container, they both do not support to change the containers' hostname, the hostname is set by Azure.


text:
Q: How to cast object from C# in Visual Basic I have a class library project in Visual Basic with a class like:
Public Class Test
    Public Vaule As Integer
    Public Str As String
    .
    .
    .
End Class

And a Function which gets an object from C#.
How to cast the object from C# in Visual Basic?
Neither DirectCast nor CType work.
Public Class Calculate
    Public Function CalculateTest(test As Object)
        Dim t As Test = New Test
        Dim tt = DirectCast(test, Test) '(Ctype do not work either)
        t.Vaule = tt.Vaule * 2
        t.Str = "Hello " + tt.Str
        Return t
    End Function
End Class

Code in C# (the DLL from the class library project in Visual Basic is as reference):
    public class Test
    {
        public int Value { get; set; }
        public string Str { get; set; }
        .
        .
    }

   public SubmitData()
    {
         Calculate cal = new Calculate();

        Test t = new Test() { Value = 4, Str = "Johan" };

        Object obj = cal.CalculateTest(t);
       .
       .
   }

A: *

*You don't need to create the Test object in your vb.net project unless it will encapsulate new functionalities and features. If this is the case then consider subclassing. Otherwise, you already have the object created in the c# project.

*In your vb.net code, you are trying to cast from and to unrelated objects. You can do that only if the vb.net Test object inherits the c# Test object. Nonetheless, consider specifying the full namespace of the target object if you insist to use identical objects names. Better to rename the Test object in your active project to something else to avoid the ambiguous-exceptions.
Regards

A: You shouldnt cast the object, but recreate an object with an embedded class with all primitive member.
In your case it could be simpler to implement some function with more parameters.
Always remember: the cast will give you access to memory of a different runtime. And so provide some strange behaviour.


text: Q: How to retrieve a record with a binary id We have a table in SQL Server.  Some genius made the identify field the type binary(8).  Whatever anyone else may say, that's a bad idea.  I've been trying for over an hour to get a record out of the table in Entity Framework using Linq.  I can do it in SQL Management Studio using the criteria "WHERE Contact_Id = 53147", but in EF the field is declared as type byte[] so it won't take an int parameter.  I found a way to convert my int to byte[], but it still can't find the record.  How can I construct a query in Linq that will retrieve this simple record?


text:
Q: How to modify JavaScript file on Drupal Site Here is my problem:
I am in freelance and for a job on a Drupal site, I have to fix a JavaScript bug.
I find it, but I don't know how to "compile" my JavaScript file for the online site.
I mean that a find the right file, and modify the code and send it to the SFTP server but when I check the online site nothing change (even when a look at the file in the inspector, the program isn't modified.
I already try grunt command but nothing change.

A: First thing to check is if your changes are reflected in your local development machine (view the file locally). For changes in Drupal JavaScript or css to be reflected, make sure you're editing the right file (right subtheme).

*

*Check exactly what file you edited by doing view source and seeing the path.

*Clear cache at Drupal (if you are on Drupal 7 check performance->cache and google where exactly the path is on Drupal 8).
CSS and js are aggregated and cached so cache clear re-creates them.

*Clear the browser cache


text:
Q: Error message if deleting a comment fails is misleading I get a "An error occurred during voting" error message in a red popup when deleting a comment fails. But that message is misleading as I wasn't voting the comment but deleting it. It should be "An error occurred during deleting".
Steps to reproduce:

*

*Post a comment, say, 'Blah blah bladdeddy blah!'

*Disconnect your device from the internet

*Press the delete button X next to the comment

*You get "An error occurred during voting" which is misleading


text:
Q: Is there a way to custom Marshaling Protobuf in golang? Is there a way to custom marshal/unmarshal protobuf just like how encoding/json provides way to custom marshal/unmarshal json in golang?

A: Update :
The proto3 go library (https://google.golang.org/protobuf/proto) does not support custom marshalling anymore.

Deprecated:
GoDoc mentions Marshaler and Unmarshaler interfaces.
type Marshaler interface {
    Marshal() ([]byte, error)
}

type Unmarshaler interface {
    Unmarshal([]byte) error
}


text:
Q: Best practice using JWT refresh token in nodejs I'm using JSON Web Tokens for authentication in my react-native app. When a user signs in, a token is created and send to the user to store in the local storage. The token is valid for 24 hours. Whenever the server (nodejs) is called, the token is send in a header.
The problem is, after 24 hours, the user has to sign in again. I don't want this, so I started searching for solutions. The solution I found: refresh tokens.
My approach so far. Please correct me if I'm doing something wrong.
1) A user signs in. An auth token and a refresh token are both send to the user to store in the local storage. (Is this safe enough?)
2) The user wants to change his profile. I send a request to the server with the auth token in a header.
3) The server receives the auth token. If the auth token is still valid, do whatever you have to do. If the auth token is expired, check if the user has a refresh token (that's still valid). At this point, I'm stuck. Should I send a new request from the server to the user with the question "do you have a refresh token?" and if so, send this refresh token to the server to create a new auth token?
The problem for me is the following:
Let's say the user wants to get the last 10 messages from a list. A request with the auth token is send to the server.
=> the auth token is valid: the response is a list of 10 messages
=> the auth token is invalid: the response is a new request from the server to the client for the refresh token
These are 2 different responses. Wouldn't that mess up my code at the client side? How should I handle this?
An alternative could be to send the auth token AND the refresh token in every request. But would that make sense?

A: Do you mean refresh tokens as in OAuth2? If so, these are usually only used with server clients (not browser apps). Using a refresh token requires client authentication in order to retrieve a new access token, which makes it different from just sending the access token to a resource (which usually gives access just by itself).
As such it's not clear that using refresh tokens adds anything here. If you think it's safe enough to keep people logged in to your app for more than 24 hours, why not just make the session last longer and extend the lifetime of the token you issue?
With respect to storage, keeping secure information in local storage is generally frowned on. If you are certain that you have no vulnerable external Javascript and you are using a very strict Content Security Policy header with your site to prevent any inline Javascript or undesired sources, and your app isn't super high risk, then it may be OK.


text:
Q: Whats wrong with the sql statement? startD is a date and endD is a date and type is a string
 String sqlStatement = "SELECT Booking.* FROM Booking INNER JOIN Room USING (RoomID) BETWEEN " + startD + ", " + endD+ " AND RoomSize = " + type;

This is my error:
 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BETWEEN 2016-03-01, 2016-03-01 AND RoomSize = Medium' at line 1

A: see manual Between Clause
replace , with AND in between clause

A: the SQL statement is not correct, should this be:  String sqlStatement = "SELECT Booking.* FROM Booking INNER JOIN Room USING (RoomID) WHERE someDateColumn BETWEEN " + startD + " AND " + endD+ " AND RoomSize = " + type;

A: The Syntax is wrong:
Try the below one:
String sqlStatement = "SELECT Booking.* FROM Booking INNER JOIN Room USING (RoomID) WHERE BETWEEN " + startD + " AND " + endD+ " AND RoomSize = " + type;

You are missing WHERE clause, also, you are missing an AND(you have put a comma instead) which is required when you provide a range using BETWEEN keyword.


text:
Q: Another random tree generator I would like to construct a random tree: for each node, there a random number of leaves is created.
I am almost there, but I don't understand why recursion is done only at the first leaf of a branch.
This is my code:
# init, total_staff is the leaves counter
g = nx.DiGraph()
g.add_node(0)
total_staff = 0

# help function to create a group of leaves
# (the number of leaves will follow a given prob distribution)

def makeTeam():

    global total_staff

    # number of people reporting to root
    team_size = random.choices(team_population, weights = optimal_size_weight, k=1)[0]

    team = []
    for _ in range(team_size):
        total_staff += 1
        team_id = total_staff
        team.append(team_id)

    return team

# function to create a tree (representing an organisation)
def buildOrganisation(root):

    global total_staff
    if total_staff > 25:
        return g

    team = makeTeam()

    for team_id in team:
        print('creating sub ', root, team_id, team)
        g.add_edge(root, team_id)
        buildOrganisation(team_id) # this is the point I don't get: I expect recursion to be done for each team_id...

    return g

The result I have, though, is this:
note that recursion is only at the first node of each branch, instead I want it for all nodes of the each branch.

Can you help me fix it and understand why ?


text:
Q: Change the numbering so that it follows the numbering of the containing section I use the following code to mark the end of definitions but I can't see how to adapt it so that the numbering follows the section numberring.

\documentclass[]{article}

%opening
\author{}

\makeatother
\usepackage{graphicx}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{hyperref}
\usepackage[margin=0.75in]{geometry}
\usepackage{amsthm}
%lists
\usepackage{enumitem}
\setcounter{secnumdepth}{5}

\begin{document}

\theoremstyle{definition}
\newtheorem{defi/}{Definition}

\newenvironment{defi}
{\renewcommand{\qedsymbol}{$\triangle$}%
    %\numberwithin{equation}{section}
    \pushQED{\qed}\begin{defi/}}
    {\popQED\end{defi/}}
%
%\usepackage{chngcntr}
%\counterwithin*{definition}{section}

\section{Introduction}
\subsection{Subsection Examples}
I am a subsection
\begin{defi}
    A definition
\end{defi}

\subsubsection{Sub Subsection Example}
I am a sub subsection

\end{document}

As you can see there is a problem with the numbering in Definition 1.

Thank you for your help.

A: The \newtheorem command has three different modes. See the amsthm manual section 3 for an explanation.
Here
\newtheorem{...}{...}[section]

Will be enough


text:
Q: Range of possible value returned by cksum I am looking for the range of possible values that could be returned by cksum.  E.g.
echo -n '/my/path/filename' | cksum | cut -d' ' -f1

returns 2379496500.  What is the range (min and max) of the possible values that can be returned?
BTW, the parameter above is the string value of a fully qualified file path, not the contents of the file specified thereby.

A: The POSIX standard specifies the CRC algorithm used by cksum. I quote the relevant part here (emphasis mine):

The encoding for the CRC checksum is defined by the generating polynomial:
G(x)=x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1
Mathematically, the CRC value corresponding to a given file shall be defined by the following procedure:
The n bits to be evaluated are considered to be the coefficients of a mod 2 polynomial M(x) of degree n-1. These n bits are the bits from the file, with the most significant bit being the most significant bit of the first octet of the file and the last bit being the least significant bit of the last octet, padded with zero bits (if necessary) to achieve an integral number of octets, followed by one or more octets representing the length of the file as a binary value, least significant octet first. The smallest number of octets capable of representing this integer shall be used.
M(x) is multiplied by x32 (that is, shifted left 32 bits) and divided by G(x) using mod 2 division, producing a remainder R(x) of degree <= 31.
The coefficients of R(x) are considered to be a 32-bit sequence.
The bit sequence is complemented and the result is the CRC.

So there you go, the CRC of cksum is a 32-bit sequence, so it ranges in value from 0 to 232-1 = 4294967295 (thank you Google!)


text:
Q: modx revo friendly urls Just started to use MODX Revo.
When I make new document in MODX(Revo), fill its alias (for example 'TESTALIAS') and trying to get mydomain/TESTALIAS I'm receiving mistake 404.
Using nginx and php-fpm, FURLs are ON in .htaccess
So what am I doing wrong? Thank you very much

A: The only thing that disturbs me is NGINX & .htaccess... htaccess is meant to be used with Apache web server. I guess having a look at http://rtfm.modx.com/display/revolution20/Nginx+Server+Config might be of any use :)
Hope that'll help.

A: If you have built the site, browsed around a bit and THEN turned on furls, clear your modx cache. [actually delete all the files]
Also make sure that not only furls are enabled in modx but that:
Use Friendly Alias Path = on
Check for Duplicate URIs Across All Contexts = on
Automatically generate alias = on [not necessary, just handy]
Are you getting the modx 404 error page or the apache 404?
But it sounds like you have not enabled furls in modx system->settings->freindly urls

A: Remember
Options +FollowSymlinks
RewriteEngine On
RewriteBase /

Or
Options +FollowSymlinks
RewriteEngine On
RewriteBase /your-path-from/

I've had no problems with friendly URLs in any of my...50 modx-pages over the years.


text:
Q: RDS Connection String in PHP I'm frantically beginning the move from Xeround to Amazon RDS. I've been unable to connect to RDS via PHP. I've tried a number of variations of the following:
$connection = @mysql_connect('host:port','uname','password')

Nothing seems to go through. I'm using the same port value as I had used previously with Xeround, so that's not the issue. I'm certain the host is the endpoint and the username and password are correct. I've tried using the same parameters in C# and the MySQL workbench, but to no avail. What should I do to troubleshoot this problem?
Thanks!

A: I resolved the problem. I needed to edit the security group and add a CIDR exception for the current IP address. The connection string I initially posted was correct.
Thanks!


text:
Q: How to add class-level custom method to angular rails resource I am using angular-rails-resource for the ajax calls from Angular
and I want to create custom method in my resource which should behave in
the same way as .query() method. Here is the code for the resource:
 angular.module('mymodule').factory('Posts', ['railsResourceFactory',
   function(railsResourceFactory) {
     var resource = railsResourceFactory({
       url: 'api/v1/users/{{userId}}/posts',
       name: 'post'
     });

     resource.feed = function(userId, timestamp, page) {
       return resource.$get('api/v1/users/' + userId + '/posts/feed', {timestamp: timestamp, page: page});
     };

     return resource;
   }
 ]);

There are two problems with this code:

*

*I have to define API route in two places in two different ways. I
would like to utilize resource url which is defined the first time.

*I cannot call this like I would call .query() method since I have
userId as parameter directly, and not as an object.

How to improve this code to be more .query() method already defined in
angular-rails-resource?
I would like to invoke this method .feed() in the following way:

Posts.feed({userId: $scope.userId}, {timestamp: new Date(), page:  1}).then(function success(posts){ /*...*/ }, function error() { /*...*/ });

A: There is convenient method in angular rails resource called .resourceUrl() which accepts url parameters object and builds URL with it. You just have to change .feed() to look like this:
resource.feed = function(context, params) {
  return resource.$get(resource.resourceUrl(context) + '/feed', params);
};

So the complete service will have the following form:
angular.module('mymodule').factory('Posts', ['railsResourceFactory',
  function (railsResourceFactory) {
    var resource = railsResourceFactory({
      url: 'api/v1/users/{{userId}}/posts',
      name: 'post'
    });

    resource.feed = function(context, params) {
      return resource.$get(resource.resourceUrl(context) + '/feed', params);
    };

    return resource;
  }
]);

Now you will be able to use Posts.feed() in the same way as you would've used Posts.query().


text:
Q: Make Selenium wait until text inside web element changes I'm using Selenium to upload an excel file to a website automatically. To make sure upload is complete before proceeding i use time.sleep(60) but i want to make the code a bit smarter.
after the upload field, there's a label element.
only .xlsx files will be accepted.

this label changes after upload is finished to
100 entries were detected.

can i use the text inside the label to tell if the upload has finished?

A: Yes, you can use text_to_be_present_in_element expected_conditions.
This should work:
WebDriverWait(driver, 100).until(EC.text_to_be_present_in_element((By.ID, "upload_status"), "entries were detected"))

These imports should be used here:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

A: First find label element by ID, then check for keyword to (dis)appear:
from selenium import webdriver
from selenium.webdriver.common.by import By
...
el = driver.find_element(By.ID, 'upload_status')
while 'entries were detected' not in el.get_attribute('innerHTML'):
    time.sleep(1)
...