text:
Q: How to overload operator<< for qDebug I'm trying to create more useful debug messages for my class where store data. My code is looking something like this
#include <QAbstractTableModel>
#include <QDebug>

/**
  * Model for storing data.
  */
class DataModel : public QAbstractTableModel {
    // for debugging purposes
    friend QDebug operator<< (QDebug d, const DataModel &model);

    //other stuff
};

/**
  * Overloading operator for debugging purposes
  */
QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}

I expect qDebug() << model will print "Hello world!". However, there is alway something like "QAbstractTableModel(0x1c7e520)" on the output.
Do you have any idea what's wrong?

A: You implemented only the << operator for a reference. If your model variable is a pointer, it will use another implementation (not yours).
To use your implementation you can do:
qDebug() << *model

By the way, the correct way to implement a QDebug operator<<(QDebug dbg, const T &data) overload is to use the QDebugStateSaver class:
QDebug operator<<(QDebug dbg, const QDataflowModelOutlet &outlet)
{
    QDebugStateSaver stateSaver(dbg);
    dbg.nospace() << ...;
    return dbg;
}

In this way the settings (i.e. wether to insert or not spaces between prints) will be correctly restored when exiting the function.

A: I know it long time now, but just to be documented and to help any other people who eventually come here having the same doubt, the easiest way to get qDebug() << working with your own class printing something like "Hello World" or whatever else, is to implement implicit conversion of your class to a printable type, like QString (which is well supported by QDebug).
class Foo {
public:
   Foo() { }
   operator QString() const { return <put your QString here>; }

};

A: I found this answer on the QT Forum by raven-worx (giving credit where credit is due!)
In the .h file:
QDebug operator<<(QDebug dbg, const MyType &type);

where MyType is your class, like DataModel and type is the instance you will display.
And in the .cpp file:
QDebug operator<<(QDebug dbg, const MyType &type)
{
    dbg.nospace() << "MyType(" << .... << ")";
    return dbg.maybeSpace();
}

and you can use the QDebug's space(), nospace(), and other methods to control the exact display of the stream.
So for the OP, we would use:
// in the .h file:
class DataModel : public QAbstractTableModel {
// stuff
};
QDebug operator<<(QDebug dbg, const DataModel &data);

// in the .cpp file:
QDebug operator<<(QDebug dbg, const DataModel &data)
{
    dbg.nospace() << "My data {" << data.someField << ',' << data.another << "}";
    return dbg.maybeSpace();
}

// in some .cpp user of the class:
DataModel myData;

. . .

QDebug() << "The current value of myData is" << myData;

A: In your example, qDebug() prints the address of your variable, which is the default behavior for unknown types.
In fact, there seem to be two things you have to take care of:

*

*Get the item by value (and eugen already pointed it out!).

*Define the overloading operator before you use it, put its signature in the header file, or define it as forward before using it (otherwise you will get the default "qDebug() <<" behavior).

This will give you:
QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}
DataModel m;
qDebug() << "m" << m;

or
QDebug operator<< (QDebug d, const DataModel &model);

DataModel m;
qDebug() << "m" << m;

QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}

I've learned it the hard way, too...

A: After an hour of playing with this question I figured out model is pointer to DataModel and my operator << takes only references.


text:
Q: Array to string conversion error in Magento logs My Magento system.log is full with this error:
Notice: Array to string conversion in /app/code/core/Mage/Core/Block/Abstract.php on line 1232.
I've added the code here: (rule 1232 is $key = implode('|', $key);)
   /**
      * Get Key for caching block content
      *
      * @return string
      */
     public function getCacheKey()
     {
         if ($this->hasData('cache_key')) {
             return $this->getData('cache_key');
         }
         /**
         * don't prevent recalculation by saving generated cache key
          * because of ability to render single block instance with different data
          */
         $key = $this->getCacheKeyInfo();
         //ksort($key);  // ignore order
         $key = array_values($key);  // ignore array keys
         $key = implode('|', $key);
         $key = sha1($key);
         return $key;
    }

Do you know what's going wrong, and what I need to change?
Thank you in advance!

A: Well this is magento core code so i do expect some wrong value getting into $key variable from outside of this code.
You can try to log the $key variable and check if it is an array.
Something like:
Mage::log(print_r($key,true), null, 'mycustomerror.log', true);
or
Mage::log($key, null, 'mycustomerror.log', true);
If you want a better answer you should tell us when this notice is generated and the modules you are using.
After extra info
Well it is a guess because the information you gave me is not much. But your logs shows the following:
2013-01-17T16:52:36+00:00 DEBUG (7): Array
(
    [0] => CATALOG_PRODUCT_HIGHLIGHT
    [1] => 1
    [2] => default
    [3] => a058
    [4] => 0
    [5] => highlight/product/grid.phtml
    [6] => 8
    [7] => 4
    [8] => Array
        (
        )

    [9] => Array
        (
        )

    [10] => Array
        (
        )

    [11] => Aanbiedingen
    [12] => highlight-special
    [13] => special_from_date,special_to_date
    [14] => -special
    [15] => product_special
)

I think the problem is:
[8] => Array()
[9] => Array()
[10] => Array()

When they are imploded they will give the notice.
SEE:
http://codepad.viper-7.com/qb5tIW
I would check the CATALOG_PRODUCT_HIGHLIGHT (highlight/product/grid.phtml)
You can navigate your site so that the highlight/product/grid.phtml is loaded and see if this call is indeed putting that notice in your log files.
good luck !

A: After noticing one visit to my site's homepage made 90+ lines of this warning in system.log, I tackled the problem of nested arrays inferred in khoekman's answer. My Magento version is 1.7.0.1
Step 1
Create the path: app/code/local/Mage/Core/Block and then cd to that directory.
Step 2
Copy Abstract.php from core to local:
cp ~/public_html/app/code/core/Mage/Core/Block/Abstract.php .
This is how you "override the core file" for your custom edits.
Step 3
Open the new file ~/public_html/app/code/local/Mage/Core/Block/Abstract.php in your favorite editor, scroll down to line 1232:
Change from this:
    $key = implode('|', $key );
to:
    $key = $this->implodeRecursive('|', $key );
Step 4
Scroll above this current function public function getCacheKey() and then in the free space above it, add in the recursive implode function:
//  ckck: fix of system.log Notice: Array to string conversion in app/code/core/Mage/Core/Block/Abstract.php on line 1232
private function implodeRecursive( $_glue, $_arrIn ) {
    $_arrTmp=Array();
    if( count( $_arrIn ) > 1 ) {
        foreach( $_arrIn as $key => $value ) {
            if( is_string($value) || is_null($value) )
                $_arrTmp[] = $value;
            else
                $_arrTmp[] = $this->implodeRecursive( $_glue, $value );
        }
    }
    $_strReturn = implode( $_glue, $_arrTmp );
    return $_strReturn;
}

Through trial and error, the only reliable test was if $value is a string. My usual tricks of is_array() or testing for count() > 0 did not work. Fixing this bug was an interesting endeavor.
Step 5
Save then close Abstract.php and then check in the new file into your version control system.
I use git with merge --no-ff branching.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Birfucation Points I have the following ODE: $$\dot x=y+ax(x^2+y^2), \dot y=-x+ay(x^2+y^2)$$
I used polar coordinates and I got $$\dot r=ar^3,\dot \theta=-1$$.
I have the equilibrium point (0,0) and calculate the jacobian matrix
and i got eingevalue $λ_1=i$ and $λ_2=-i$.
But i can not understand how to find the birfucation points of this ODE.


text:
Q: Javascript variables conflict in different files I have declared two variables with the same name using the const keyword in two different javascript files. But still I get an error when I import both the files together to a web page.
I know that var declares global scope variables which would conflict but I had heard that const and let do not bahave like that.
How do I fix this.

A: If you're just looking for an easy solution, having code blocks in the files will work, either as a self executing function or just a plain block:
// On both files
(function(){
    const x = 123;
})();

// or just a code block
{
    const x = 456;
}

However, this is usually fixed by using a preprocessing tool like webpack (and organizing your code into modules to keep things separate), or at least having different classes and functions.


text:
Q: python оптимизация циклов Как мне оптимизировать цикл, чтобы он работал намного быстрее?
import keyboard
import pyscreenshot as ImageGrab
from Xlib import display

def move_left():
    keyboard.send('right')
def move_right():
    keyboard.send('left')
def exist_branch(x, y):
    box = (x, y - 1 * 85, x + 1, y)
    im = ImageGrab.grab(box)
    rgb_im = im.convert('RGB')
    x, y = im.size
    result = []
    for i in range(0, 1):
        r, g, b = rgb_im.getpixel((0, y - 1 - i * 85))
        summa = r + g + b
        if summa == 301 or summa == 289 or summa == 244 or summa == 210 or summa == 248 or summa == 217:
            result.append(False)
        else:
            result.append(True)
    return result
def get_mouse():
    while True:
        data = display.Display().screen().root.query_pointer()._data
        x = data["root_x"]
        y = data["root_y"]
        print
        '%s,%s - %s' % (str(x), str(y), exist_branch(x, y))
def main():
    start_x = 1033
    start_y = 715
    while True:
        branches = exist_branch(start_x, start_y)
        branches1 = exist_branch(start_x, 800)
        for elem in branches:
             if elem:
                for elem in branches1:
                 if elem:
                  move_left()
                 else:
                     move_right()
             else:
                 move_right()
try:
    # get_mouse()
    main()
except:
    print
    'Exit..'


text: Q: SearchBar in StackNavigator header I am using TabNavigator inside StackNavigator. The first screen contains the tab, I want inputbox on header with search button on searching it should go to next screen. how should i solve this problem. any help would be appreciated.


text:
Q: Executable isn't made in Qt I tried to make the executable of my qt quick program. But when I do so there isn't any executable file is generated. Even though  I unchecked the shadow building. I searched through many websites and found a video about it where he runs the qmake and then make to generate the executable file. But nothing happened. I even set the build directory to my current project directory. Apart from it I even did this for the QWidget application and the result was the same. There was no executable. Please help me out.

17:36:05: Running steps for project Keba_1...
17:36:05: Starting: "/home/stpl/Qt/5.11.1/gcc_64/bin/qmake" /home/stpl/Keba_1/Keba_1.pro -spec linux-g++ CONFIG+=qtquickcompiler
17:36:05: The process "/home/stpl/Qt/5.11.1/gcc_64/bin/qmake" exited normally.
17:36:05: Starting: "/usr/bin/make" qmake_all
make: Nothing to be done for 'qmake_all'.
17:36:05: The process "/usr/bin/make" exited normally.
17:36:05: Starting: "/usr/bin/make"
make: Nothing to be done for 'first'.
17:36:05: The process "/usr/bin/make" exited normally.
17:36:05: Elapsed time: 00:00.

Please check this out

A: Linux does not have a .exe extension as Windows (maybe you're used to that?)
The circled item is the executable:


text:
Q: Re-generate all ComputedProperty fields I'd like to add a ComputedProperty field to a Model of which there are a many existing entities in the datastore.
To query the existing entities on this new ComputedProperty, I need to generate the computed property first.
What is the most efficient way to trigger a compute and put the computed value back into the datastore?

A: Depends on how many entities you are talking about. Use MapReduce or simply Remote API (launch a console and do it manually)

A: Depends how much data you have really. Here's a task queue solution, but it will eat away at your quota ...
class StampValue(webapp.RequestHandler):
    _task_url = '/tasks/stamp'
    _page_size = 100

    @classmethod
    def fire(cls, **params):
        taskqueue.add(url=cls._task_url, params=params)

    def get(self):
        self.fire()

    def post(self):
        key = self.request.get('key')
        if key:
            entities = MyModel.gql('WHERE __key__ >= :1 ORDER BY __key__ ASC', db.Key(key)).fetch(self._page_size+1)
        else:
            entities = MyModel.gql('ORDER BY __key__ ASC').fetch(self._page_size+1)

        key = None
        if len(entities) == self._page_size+1:
            key = str(entities[-1].key())
            self.fire(key=key)
            entities = entities[:self._page_size]

        for entity in entities:
            # update your field here
        db.put(entities)


text:
Q: OpenWrt + CoovaChilli. TUN device does not come up Am running OpenWrt 19.07.7 on a glinet mini router.
I have used opkg update and opkg install coova-chilli to get coova chilli running
Here is output of /var/run/chilli_cfgXXXXXX.conf
tundev="tun0"
net="192.168.180.0/22"
uamlisten="192.168.182.1"
lease="86400"
leaseplus="600"
ipup="/etc/chilli/up.sh"
ipdown="/etc/chilli/down.sh"
dhcpif="br-guest"
uamserver="https://radius.chillispot.org/hotspotlogin"

The router has three active network interfaces:

*

*br-guest (which should have the hotspot)

*br-lan

*eth0 (inernet link)

According to the documentation on: OpenWrt  Documentation
only the /etc/config/chilli file needs to be edited to get the TUN device running
However after following the guide and issue ifconfig, the TUN device is not available

A: Yes, just /etc/config/chilli file needs to be edited. These are the minimum configuration:
config chilli
    option tundev           'tun0'
    option dhcpif           'br-guest'
    option uamlisten        10.1.0.1
    option net              10.1.0.0/24
    option dns1             8.8.8.8
    option dns1             8.8.4.4
    option ipup             /etc/chilli/up.sh
    option ipdown           /etc/chilli/down.sh
    option radiusnasid      nas01
    option uamserver        your_url_server_handling_authentication
    option radiusserver1    your_radius_server1
    option radiusserver2    your_radius_server2
    option radiussecret     your_radius_secret
    option uamsecret        your_uam_secret

For line 11-15 you have to fill value according your own configuration


text:
Q: NSURLRequest returns NSURLErrorNetworkConnectionLost but reachability says the network connection is on In my app I'm downloading big video files in a row and sometimes my http request fails and reports that NSError code is -1005, which is NSURLErrorNetworkConnectionLost. I check internet connection through Reachability class and it says that its current status is not NotReachable. What can be a reason for that? What can make a request fail? Any ideas, guys?

A: You might not like this but I ran into a somewhat-similar situation a few years back ... the fix, at least for me, was to break the files apart into much smaller "chunks."  Essentially, I switched to a streaming scheme versus having to download them in one fell swoop, and life was good again.
Food for thought ...


text:
Q: Server side request cannot use redirect_uri from iOS client for facebook OAuth I am very new to development so please forgive the occasional misused term, general lack of knowledge, and the poorly worded title.
I am building a new login flow for my company following the guidelines outlined for 'manually building a login flow' at developer.faceboook.com.
After making a request to this URL from the user's device:
GET
https://www.facebook.com/v2.8/dialog/oauth?
response_type=code
&redirect_uri={app-id}://authorize
&client_id={my-app-client-id}
I receive a 'code' which I can in turn use for authentication. The redirect uri above allows me to open the app after the user has granted permission through application(:handleOpen:).
I send the code to our backend and attempt to make this request:
GET
https://graph.facebook.com/v2.8/oauth/access_token?
client_id={app-id}
&redirect_uri={app-id}://authorize
&client_secret={app-secret}
&code={code-parameter} <- received from initial request
The guidelines say that the redirect_uri should match that of the uri from the first request, which mine does, but I still receive this response:
{
"error": {
"message": "Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request",

"type": "OAuthException",

"code": 100,

"fbtrace_id": "XXXXXXXXXXX"

}
}
I'm not sure if what I'm doing is allowed by Facebook. Since the requests are originating from two different sources and the uri provided in the second request doesn't really do anything if the request is made from the backend. I should also mention I am testing the second response using Postman. Is what I'm doing possible or do I have to rethink the flow? Any help would be greatly appreciated and thank you in advance.


text:
Q: How can I print out the first line of a matcher? So I'm having problems with my code. Currently, the matcher in this function I have returns 3 lines instead of 1 line. I want it to return only the first line that it has found. Here's my function:
private void getLibraryMap(String libraryName) {
        File file = new File("/proc/self/maps");
        if (file.exists()) {
            try {
                BufferedReader bufferedReader = new BufferedReader(new FileReader("/proc/self/maps"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    if (line.contains(libraryName)) {
                        String lines = line.replace(String.valueOf(Pattern.compile("\\s+")), " ");
                        Pattern regex = Pattern.compile("\\p{XDigit}+");
                        Matcher matcher = regex.matcher(lines).region(0, 8);
                        while (matcher.find()) {
                            long startAddress = Long.parseLong(matcher.group(0));
                            Log.e("MainActivity", String.valueOf(startAddress));
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

And this is how I invoke it:
getLibraryMap("libwebviewchromium_loader.so");

This is the log I get from it:
E/MainActivity: 96862000
    96864000
E/MainActivity: 96865000

Can anybody help me solve this problem? Many thanks :)

A: change
while (matcher.find()) {
     long startAddress = Long.parseLong(matcher.group(0));
     Log.e("MainActivity", String.valueOf(startAddress));
     }

to
if (matcher.find()) {
 long startAddress = Long.parseLong(matcher.group(0));
 Log.e("MainActivity", String.valueOf(startAddress));
 }

while means it will loop till the condition is true
if here will execute only once as soon as it finds the first match


text:
Q: How to use labelled::look_for with pipes in R I want to choose a variable from df and get the same result of e.g. look_for(df, 'country'). Now I get the result for all variables in df.
The names of the variables are on a list called variabs. Is it possible to purrr::map or  pmap to get the same results for each variable in the list?
library(tidyverse)
library(labelled)

df <- tibble(country = c(1,2,1),
             sex = c(1,1,2))

df$country <- labelled(
  c(1, 2, 1),
  c(PT = 1, UK = 2),
  label = "Country of birth"
)

df$sex <- labelled(
  c(1, 1, 2),
  c(Male = 1, Female = 2),
  label = "Assigned sex at birth"
)

variabs <- list('country', 'sex')

look_for(df, 'country')
#>  pos variable label            col_type values
#>  1   country  Country of birth dbl+lbl  [1] PT
#>                                         [2] UK

showAt <- function(db, v){
  at <- db %>%
    pull(.data[[v]])
  return(look_for(db, at))
}

showAt(df, 'country')
#>  pos variable label                 col_type values
#>  1   country  Country of birth      dbl+lbl  [1] PT
#>                                              [2] UK
#>  2   sex      Assigned sex at birth dbl+lbl  [1] Male
#>                                              [2] Female
showAt(df, variabs[[1]])
#>  pos variable label                 col_type values
#>  1   country  Country of birth      dbl+lbl  [1] PT
#>                                              [2] UK
#>  2   sex      Assigned sex at birth dbl+lbl  [1] Male
#>                                              [2] Female
Created on 2022-08-24 by the reprex package (v2.0.1)

A: You could pass each element of variabs into look_for() like this:
purrr::map(variabs, ~ look_for(df, .x))

# [[1]]
#  pos variable label            col_type values
#  1   country  Country of birth dbl+lbl  [1] PT
#                                         [2] UK
#
# [[2]]
#  pos variable label                 col_type values
#  2   sex      Assigned sex at birth dbl+lbl  [1] Male
#                                              [2] Female

A: It might be of your interest, that you could also just pass a list or vector directly to look_for. It won't show all variables in the data frame, only the ones specified. See below:
library(labelled)

look_for(df_new, c('country', 'sex'))
look_for(df_new, list('country', 'sex'))

Output:
 pos variable label                 col_type values
 1   country  Country of birth      dbl+lbl  [1] PT
                                             [2] UK
 2   sex      Assigned sex at birth dbl+lbl  [1] Male
                                             [2] Female

More data:
df_new <- tibble(country = c(1,2,1),
                 sex = c(1,1,2),
                 third = c(2,1,1))

df_new$country <- labelled(
  c(1, 2, 1),
  c(PT = 1, UK = 2),
  label = "Country of birth"
)

df_new$sex <- labelled(
  c(1, 1, 2),
  c(Male = 1, Female = 2),
  label = "Assigned sex at birth"
)

df_new$third <- labelled(
  c(1, 1, 2),
  c(One = 1, Two = 2),
  label = "XX"
)

A: I found the answer for the first part of my question:
showAt <- function(db, v){
  at <- db %>%
   select(.data[[v]])
  return(look_for(at))
}


text:
Q: how can destroy all task linked to login user in rails I am trying to delete all task that is linked to logged in user but when I click on delete all button it shows the error
 No route matches [POST] "/tasks/destroy_all"

task_controller.rb
 class TaskController < ApplicationController

   def all_destory
       @user = current_user
       @user.tasks.destroy_all
       redirect_to user_tasks_path

   end
 end

route.rb
 get '/tasks/destroy_all', to: 'task#all_destory', as: :destroy_all

HTML
  <% @tasks.each do |task| %>
     <%= task.daily_task  %>
     <%= task.date  %>
  <% end%>
   <%= button_to "delete all", destroy_all_path %>

A: When destroying records you want to use the DELETE HTTP verb.
GET requests are saved in the browsers history and should not create, modify or destroy anything on the server.
Typically in Rails you just have a route to destroy a single record. But if DELETE /things/1 deltes a single resource then DELETE /things should logically destroy the entire collection:
get '/user/tasks', to: 'users/tasks#index', as: :user_tasks
delete '/user/tasks', to: 'users/tasks#destroy_all'

# app/controllers/users/tasks_controller.rb
module Users
  class TasksController < ApplicationRecord
    before_action :authenticate_user!

    # display all the tasks belonging to the currently signed in user
    # GET /user/tasks
    def index
      @tasks = current_user.tasks
    end

    # destroy all the tasks belonging to the currently signed in user
    # DELETE /user/tasks
    def destroy_all
      @tasks = current_user.tasks
      @tasks.destroy_all
      redirect_to action: :index
    end

    private

    # You don't need this if your using Devise
    def authenticate_user!
      unless current_user
        redirect_to '/path/to/your/login',
          notice: 'Please sign in before continuing'
      end
    end
  end
end

<%= button_to "Delete all", user_tasks_path, method: :delete %>

A: Your HTTP verb and your route must match. Currently your button is using POST, but your route accepts GET. You could change them both to POST.
post '/tasks/destroy_all', to: 'task#all_destory', as: :destroy_all

This fixes the problem in the question, but it's not ideal. As @max points out, DELETE would be more communicative of what clicking the button does– delete resources.
DELETE documentation


text:
Q: Why JQuery script does not finish from time to time in ASP.net mcv? I do have a view (asp.net mvc 4) with some JQuery script.
The part with the form data looks like this:
<div class="form-group date">
    @Html.TextBoxFor(m => m.selFilterData.StartDate, new { @class = "form-control", id = "StartDate" })
    @Html.Label("Text", new { @class = "form-control", id = "lbltext" })
</div>

Depending on the model data I show/hide (with JQuery) the Date-Textbox or the label:
$(document).ready(function () {
         // save model Data
         var last24h = function () {
             return @Html.Raw(Json.Encode(Model.selFilterData.last24h)); }();
        var TodayDate = function () {
            return @Html.Raw(Json.Encode(Model.selFilterData.TodayDate)); }();
        var SingleDate = function () {
            return @Html.Raw(Json.Encode(Model.selFilterData.SingleDate)); }();

        // Heute
        if (TodayDate == true) {
            $("#StartDate").hide();
            $("#last24h").prop("checked", false);
            $("#SingleDate").prop("checked", false);
            $("#lbltext").show();
            $("#lbltext").html("Daten von Heute");
            $("#myHead_last_h").css("font-size", "1.2em");
        }

        // Daten der letzten 24h
        if (last24h == true) {
            $("#StartDate").hide();
            $("#TodayDate").prop("checked", false);
            $("#SingleDate").prop("checked", false);
            $("#StartDate").html("Daten der letzten 24h");
            $("#lbltext").show();
            $("#lbltext").html("Daten der letzten 24h");
        }

        // Datumsauswahl
        if (SingleDate == true) {
            $("#StartDate").show();
            $("#TodayDate").prop("checked", false);
            $("#last24h").prop("checked", false);
            $("#lbltext").hide();
            $("#StartDate").css('text-align','center');
            $("#StartDate").css("font-size", "1.2em");
            $("#StartDate").css("font-weight", "bold");
        }
    });

The menu shows like this in the browser:
Menu OK
But sometimes the whole page is fully loaded but both elements are shown:
Menu not OK
After clicking some where on the page the menu will change to the right settings. I debugged the script but I cant see any difference between a good run and a bad run...
I tried the same with Google Chrome (normally we use IE) - there is everything OK.
I also have 3 Partial views(with table) on my main-view - if I load just 2 of them (doesnt matter which one) it will be alwasy OK.
I dont know where the problem could be...


text:
Q: How to hide text once it reaches overflow The goal is to have a responsive design that hides overflowing multi-line text.
I do not want to use jQuery. Would prefer not to use js, but will do if it's a nice way of using it with vue (not using html element selectors preferred).
What I've tried:
text-overflow: ellipsis - Not suitable because it's only for 1 line.
-webkit-line-clamp: x - Not suitable because my characters could be larger or smaller depending on device or user settings. I can't rely on a set amount of lines.
https://dollarshaveclub.github.io/shave/ - Not suitable because same deal as with clamping. And also it uses js and there's no vue3 adaptation.
Is there ANYTHING out there that has text react responsively to the height of its parent or when overflowing?
Will I have to create a vue3 plugin that adds an ellipsis and hides overflowing text?
.recipe-item-content {
  display: flex;
  flex-direction: column;
  flex: 10 1 auto;
  min-height: 0;

  .recipe-item-content__image {
    display: flex;
    flex: 1 1 content;
    min-height: 0;
  }

  .recipe-item-content__text {
    display: flex; //comment this to not have line-clamp problems.
    flex: 1 1 content;
  }

  .recipe-item-content__description {
    display: -webkit-box;
    -webkit-line-clamp: 5;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}

Here's a codepen, showing the problem: https://codepen.io/dazaer/pen/eYyeqzE
All you have to do is resize the window to make it smaller to see the problem with the description.
Currently I'm solving this by commenting out the "flex" property, which works but does not fill the available space with more text as it could.


text:
Q: Ajax control tookit issues on .NET 4.0 Ok, this is one of those really weird errors that seems like the machine's just messing with you.
We have 2 websites, ASP.NET, both were 2.0, and we upgraded them both to 4.0.
They're the same exact codebase, but the web.config files are different, they point at different databases, and they run as separate web apps in IIS.
After the upgrade, one works and one doesn't.
The one that doesn't work will throw a bunch of javascript errors around the Microsoft AJAX Control toolkit like 'Sys is not defined', 'Type is not defined', and '__nonMSDOMBrowser is not defined' (in firebug). When I use the Scripts panel in firebug it lists all the different '...ScriptResource.axd?d=IOBqtxq...' scripts, but when I ask to look at them, many of them will return 'Failed to load source for: /ScriptResource.axd?d=IOBqtxq7p...'.
A couple of them do come back with the CodePlex copyright and some javascript, but many of them don't. And the truly weird thing? If we recycle the app pool for the broken site, we don't get those errors the first time we hit the site. The postback works, we log in, etc. Then we go back and hit it again, javascript errors are back and no postbacks.
Any ideas?

A: Ok, I hate answering my own questions, but since no one else is weighing in, this is the best we've come up with.
There's a setting in IIS for the website that specifies Web Garden Threads, which I assume is how many threads to use if the site is in a load balanaced web garden. We had this new site set to 7, which is how it was in .NET 2.0. Apparently 2.0 is more forgiving (or ignores it), but 4.0 freaks out. The single request to the site is a request for lots of different resources, which end up being handled by different threads, which as you can imagine makes for chaos. And it's different every time depending on which threads do what.
So, unless anyone else has an explanation for this, I'll close this.

A: Running many applications out of the same app pool can cause really strange ajax behaviors. Often times you'll see this with apps sharing the DefaultAppPool.
Try creating a separate app pool for the application.


text:
Q: My array of objects is not working correctly with my ng-select? I have this array of objects:
var abc = [
   {"id":28,"name":"Actions, State & Occurences"},
   {"id":29,"name":"Descriptive Words & Modifiers"}
   {"id":30,"name":"Counting & Measurement"},
   {"id":31,"name":"Time & Dates"}]

Here's the select I am using:
   {{ row.categoryId }}
   <select class="select"
           convert-to-number
           ng-options="option.name for option in abc track by option.id"
           ng-model="row.categoryId"></select>

The problem I have is that the row.categoryId is a number and the correct value is not being selected. When I do select a value here's what my row.categoryId gets set to:
  {"id":28,"name":"Actions, State & Occurences"}

Can someone tell me is there a way I can make this work correctly so that it sets and uses the id value instead of the object?

A: @Alan, you can use the as clause in the ng-options directive in order to tell AngularJS what you want to be set into the variable used in the ng-model directive.
Check the below example(the selected option doesn't appear maybe problem with the version it works here), here from the option object in the ctrl.abc array the id property is set (selected) into the ctrl.row.categoryId and the name property is displayed to the user.
You can find more information about ng-options here

angular
   .module('demo', [])
   .controller('DefaultController', DefaultController);

  function DefaultController() {
    var vm = this;
    vm.abc = [
    { "id":28,"name":"Actions, State & Occurences" },
    { "id":29,"name":"Descriptive Words & Modifiers" },
    { "id":30,"name":"Counting & Measurement" },
    { "id":31,"name":"Time & Dates" }];
  }

    {{ ctrl.row.categoryId }}
    <select class="select"
           convert-to-number
           ng-options="option.id as option.name for option in ctrl.abc track by option.id"
           ng-model="ctrl.row.categoryId">
    </select>

You don't need to use track by if you will be setting the selected option in the select element using the exact same property value which you get from the ng-options directive when a user selects an option.
Check the below sample which sets a selected option using an id of the item. If you would want to set the selected option using a different property than the id property then you can use the track by clause in the ng-options directive.

 angular
   .module('demo', [])
   .controller('DefaultController', DefaultController);

function DefaultController() {
  var vm = this;
  vm.abc = [
    {"id":28,"name":"Actions, State & Occurences"},
    {"id":29,"name":"Descriptive Words & Modifiers"},
    {"id":30,"name":"Counting & Measurement"},
    {"id":31,"name":"Time & Dates"}];

  setItem();

  function setItem() {
    vm.row = {
      categoryId: 30
    }
  }
}

    {{ctrl.row.categoryId}}
    <select class="select"
           convert-to-number
           ng-options="option.id as option.name for option in ctrl.abc"
           ng-model="ctrl.row.categoryId">
    </select>

A: ng-options="option.id as option.name for option  in abc track by option.id"

Working Plunker

A: Use $scope.abc instead of var abc. and replace your select tag with this
 <select class="select"  ng-options="option  as option.name for option in abc track by option.id"
       ng-model="row.categoryId"></select>

And if you need the first value to be pre-selected inside the select tag kindly assign the ng-model to first value of the array like this
$scope.row.categoryId = $scope.abc[0];
That should fix your problem


text:
Q: I cannot get my PHP/XHTML page to fully load. I think it is a syntax error but I cannot find it My Change Password Page does not fully load. I have been searching for errors for hours. Only the  and  tags load. I removed the PHP inside the <form> and the page loads fine. I have been up and down all lines for hours. I also ran through a code checker, plus I use Notepad++ so it also checks for errors. I did have this loading ealier just fine, but as I was making changes the problem occurred. Thanks for any help.
My file change_pass.php contains XHTML.
<?php include("pass.php") ; ?>//Session username and password.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Change Password</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8"  />
<link rel="stylesheet" type="text/css" href="http://website.com/connect.css"  />

Log Out

<form id="chpw_frm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ; ?>" method="post">

<?php
if ( isset($_SESSION["point"]) )//Username and password check
{
$user_sess = $_SESSION["username"] ;
$pass_sess = $_SESSION["pass"] ;
$usr = $_POST["usr"] ;
$old = $_POST["oldpass"] ;
$new = $_POST["newpass"] ;
$conf = $_POST["confpass"] ;

$usr_in = '<input id="usr_in" class="frm" type="text" name="usr" size="25" maxlength="30"  />' ;
$old_in = '<input id="old_in" class="frm" type="text" name="oldpass" size="25" maxlength="30"  />' ;
$new_in = '<input id="new_in" class="frm" type="text" name="newpass" size="25" maxlength="30"  />' ;
$conf_in = '<input id="conf_in" class="frm" type="text" name="confpass" size="25" maxlength="30"  />' ;

echo( '

 ' ) ;
         echo( '
User Name
 ' ) ;
         echo( $usr_in ) ;
      echo( ' 	 ' ) ;

      echo( '  ' ) ;
         echo( '
Old Password
 ' ) ;
         echo( $old_in ) ;
      echo( '
 ' ) ;

   echo( '
 ' ) ;
         echo( '
New Password
 ' ) ;
         echo( $new_in ) ;
      echo( ' 	 ' ) ;

      echo( '  ' ) ;
         echo( '
Confirm Password
 ' ) ;
         echo( $conf_in ) ;
      echo( '
 ' ) ;

   echo( '
 ' ) ;

   if ( $old === $pass_sess && $usr === $user_sess )
      {
      if ( $new === $conf )
         {
         echo ( '

Your Password has been changed!

            ' ) ;
         }
      else
         {
         if ( $usr !== $user_sess )
            {
            echo ( '

Incorrect User Name!

               ' ) ;
            }
         if ( $new !== $conf )
            {
            echo ( '

Your Confirmation Password does not match!

               ' ) ;
            }
         }
      }
   else
      {
      echo ( '

Incorrect!

         ' ) ;
      }
   }
         echo ( ' <input class="log_sub" name="Sub" type="submit" value="Change Password"  /> ' ) ;
         echo ( ' <input class="log_sub" name="res" type="reset" value="Clear" style="margin-right:0px;"  /> ' ) ;
      echo ( '

 ' ) ;
}
?>

</form>

2014-<?php echo date("Y") ; ?> website. All rights reserved.

My pass.php file
<?php
session_start() ;
$_SESSION["username"] = "user" ;
$_SESSION["pass"] = "pass" ;
$_SESSION["point"] ;
?>

...also since the PHP requires to be logged in. A link from another page links to the Change Password Page.
isset($_SESSION["point"])

A: You have 1 extre close bracket after the 3 echoes, remove it

    $usr_in = '<input id="usr_in" class="frm" type="text" name="usr" size="25" maxlength="30"  />' ;
    $old_in = '<input id="old_in" class="frm" type="text" name="oldpass" size="25" maxlength="30"  />' ;
    $new_in = '<input id="new_in" class="frm" type="text" name="newpass" size="25" maxlength="30"  />' ;
    $conf_in = '<input id="conf_in" class="frm" type="text" name="confpass" size="25" maxlength="30"  />' ;

    echo( '

 ' ) ;
    echo( '
User Name
 ' ) ;
    echo( $usr_in ) ;
    echo( ' 	 ' ) ;

    echo( '  ' ) ;
    echo( '
Old Password
 ' ) ;
    echo( $old_in ) ;
    echo( '
 ' ) ;

    echo( '
 ' ) ;
    echo( '
New Password
 ' ) ;
    echo( $new_in ) ;
    echo( ' 	 ' ) ;

    echo( '  ' ) ;
    echo( '
Confirm Password
 ' ) ;
    echo( $conf_in ) ;
    echo( '
 ' ) ;

    echo( '
 ' ) ;

    if ( $old === $pass_sess && $usr === $user_sess )
    {
        if ( $new === $conf )
        {
            echo ( '

Your Password has been changed!

                ' ) ;
        }
        else
        {
            if ( $usr !== $user_sess )
            {
                echo ( '

Incorrect User Name!

                    ' ) ;
            }
            if ( $new !== $conf )
            {
                echo ( '

Your Confirmation Password does not match!

                    ' ) ;
            }
        }
    }
    else
    {
        echo ( '

Incorrect!

            ' ) ;
    }
//}
    echo ( ' <input class="log_sub" name="Sub" type="submit" value="Change Password"  /> ' ) ;
    echo ( ' <input class="log_sub" name="res" type="reset" value="Clear" style="margin-right:0px;"  /> ' ) ;
    echo ( '

 ' ) ;
}
?>

A: Just guessing, but... your error may be simply that you wrote
$user_sess = $_SESSION["userbame"] ;

instead of
$user_sess = $_SESSION["username"] ;

("userbame" instead of "username").


text:
Q: Two objects moving relativistically towards each other Let's say I have two objects moving relativistically toward each other, so the object on the left is moving to the right, say, at .3c and the object on the right is moving to the left at .7c, and they are some distance apart. How would I set up a problem like this to find at what position they meet and at what respective times (do I need to consider each frame?). Thanks!

A: $\def\ns#1#2{#1_{\rm#2}} \def\vA{\ns vA} \def\vB{\ns vB} \def\tA{\ns
tA} \def\xA{\ns xA} \def\xB{\ns xB} \def\tauA{\ns\tau A} \def\cA{{\cal A}} \def\cB{{\cal B}} \let\D=\Delta \def\KA{\ns{\rm K}A} \def\KB{\ns{\rm K}B}$
I want to show how to solve your problem with no use of coordinates and Lorentz transformations - only Minkowski geometry and and spacetime
invariant.
You are given two objects, let us call them A and B (to the right of A). You didn't say, but are initially working in a frame K, and give us both velocities in this frame: $\vA=0.3\,c$ and $\vB=-0.7\,c$. As already remarked by Rodney, you must also know the initial distance (say at $t=0$, $t$ being
time of K frame). Call it $d$.
It is also worth considering two events: $E$ is along A's worldline,
$F$ along B's worldline. According to measurements in frame K, $E$ and
$F$ are simultaneous ($t=0$). A third event $G$ is the encounter
between A and B. Event $G$ is at the intersection of A's and B's
worldlines.

All this is represented in the figure, where you can see two straight
lines, marked $\cA$ and $\cB$, representing the worldlines. Events $E$
and $F$ are connected by a horizontal line, to show their simultaneity
in K. Event $G$, as already said, is at intersection between $\cA$ and
$\cB$.
Let $\D t$ be the time interval between $E$ and $G$ as measured in K (it
is also the time interval between $F$ and $G$). I wish to note at this
point that in frame K, as in every inertial frame you happen to
consider, you must not think of one clock, but of an array of
clocks, ideally infinite, all synchronized one with another. When we
talk about time intervals measured in K between events happening in
different places, you must always keep in mind that two clocks are
involved, one for each event.
In time $\D t$ object A has moved, wrt K, by $\vA\D t$, object B by
$\vB\D t$. Their distance, which was $d$ initially, has become
$d+(\vB-\vA)\,\D t$.  But at their encounter (event $G$) distance is 0, then
$$\D t = {d \over \vA - \vB}.$$
As to A's and B's displacements, they are
$$\D\xA = \vA\D t \qquad \D\xB = \vB\D t$$
(don't forget that $\vB$ is negative).

You ask "the respective times" at which A and B meet. In principle, this means to switch to one of two novel frames: $\KA$ or $\KB$. The former is the frame in which A is resting, the latter the same for B. We can use the invariance of interval:
$$c^2 \D t^2 - \D x^2 = c^2 \D t'^2 - \D x'^2 \tag 1$$
where, for two frames K, K$'$ and for any couple of events, $\D t$, $\D x$
are their time and space separations as measured in K, $\D t'$ and $\D x'$ the same for K$'$.
Applying (1) to frames $\rm K$, $\KA$ and to events E, G we have
$$c^2 \D t^2 - \D\xA^2 = c^2 \D\tauA^2.\tag 2$$
This is because time and space separations in K are $\D t$, $\D\xA$,
whereas in $\KA$ the requested time separation I called $\D\tauA$ and
the space separation is null. From eq. (2) $\D\tauA$ can be computed,
since we already found $\D t$ and $\D\xA$. Same calculation applies
for B.

A: You are dealing with three reference frames in the set-up. First, there is the 'lab' frame in which the given velocities are measured. Second, there is the rest frame of object 1. In this frame, the speed of object 2 will be greater than 0.7$c$ but less than $c$. Finally, there is the rest frame of object 2. In this frame, the speed of object 1 will be greater than 0.3$c$, but again less than $c$. We can assume that all three frames are in the standard orientation, so that all the axes are parallel. We can also assume there is a clock attached to each object, and a third clock at rest in the lab frame, and that all three clocks are synchronized at the instant the two objects are separated by a distance $d$ as measured in the lab frame.
Finding the $(t, x)$ coordinates of the collision in the 'lab' frame will not require anything beyond ordinary kinematics, but you will need to specify the starting distance between the objects. Call that distance $d$. Then the position of object 1 at $t = 0$ can be set to $x = 0$, and the position of object 2 at $t = 0$ can be set to $x = d$. Object 1's position changes according to
$$x_1 = (0.3c)t,$$
and object 2's position changes according to
$$x_2 = d - (0.7c)t.$$
For a given $d$, you can determine the time and position of the collision as measured in the lab frame.
In the rest frames of the objects, you will need to find the speed and position of the moving (other) object using the Lorentz transformation (transforming from the lab frame to each object's rest frame). In each frame, the collision occurs at the origin ($x = 0$) of that frame. But the elapsed times--the proper times measured by the clocks attached to the objects--will be different because the clocks attached to objects 1 and 2 are not ticking at the same rate compared to each other or to the lab clock.


text:
Q: Executemany is failing with "Failed executing the operation; Could not process parameters" I am trying to tweak out INSERT INTO performance of my python code using cursor.executemany(), but I am receiving some errors.
The code:
import mysql.connector

mydb = mysql.connector.connect(
    host="database1",
    user="username1",
    passwd="password1",
    database="dbname"
)

data = [
  'A',
  'B',
  'C',
]

mycursor = mydb.cursor()
query = "INSERT INTO table_name (name) VALUES (%s)"
mycursor.executemany(query, data)
mydb.commit()

According to the example, this should work, however, I am getting errors:
Traceback (most recent call last):
  File "/Users/filipniko/PycharmProjects/scrape/darwin-scrape/venv/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 308, in _batch_insert
    prepared = self._cnx.prepare_for_mysql(params)
  File "/Users/filipniko/PycharmProjects/scrape/darwin-scrape/venv/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 632, in prepare_for_mysql
    raise ValueError("Could not process parameters")
ValueError: Could not process parameters

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "dbtest.py", line 18, in <module>
    mycursor.executemany(query, data)
  File "/Users/filipniko/PycharmProjects/scrape/darwin-scrape/venv/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 350, in executemany
    stmt = self._batch_insert(operation, seq_params)
  File "/Users/filipniko/PycharmProjects/scrape/darwin-scrape/venv/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 329, in _batch_insert
    "Failed executing the operation; %s" % err)

mysql.connector.errors.InterfaceError: Failed executing the operation; Could not process parameters

Notes:

*

*Table is empty

*I am able to add rows using mycursor.execute for every item in a list

Table schema looks like this:
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(100) | NO   | UNI | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

What am I doing wrong?

A: I figured out I am using wrong dependency, I should use mySQLdb instead of mysql.connector:
import MySQLdb as my

mydb = my.connect(
    host="database1",
    user="username1",
    passwd="password1",
    database="dbname"
)

data = [
  'A',
  'B',
  'C',
]

mycursor = mydb.cursor()
query = "INSERT INTO table_name (name) VALUES (%s)"
mycursor.executemany(query, data)
mydb.commit()

https://thepythonguru.com/inserting-rows/


text:
Q: Java array in if statement not working as expected So I have been writing a game and was looking to make the code base more useable. I originally wrote the following code once and worked fine. But for reuse and fewer lines, I was adjusting it. Now it's not working
Main java file:
builder.setStats("p, divine,0,1,2,2,1,2,4");

Builder file:
String [] holder = new String[8];

public void setStats(String sentstats){
     holder = sentstats.split(",",8)

     if(holder[0]== "p"){
         charsheet.style = holder[1];
     }
}

So the issue is the if never does the proper response. I know I have full access to all associated files as I have tested for that. And I know I could get it to work other ways. But to reduce redundancy. And make parts of the code recursive I have done it like this.

A: Use equals() instead of == as you are using String not a character
From:
 if(holder[0]== "p"){
     charsheet.style = holder[1];
 }

, To:
 if("p".equals(holder[0])){
     charsheet.style = holder[1];
 }

A: Stings are not primitive types in Java. They are treated like objects. When you use == for objects, Java checks if both objects have the same reference in memory rather than checking for the values (or similarities in global values) between both objects. This means that Java doesn't care what the values of the strings are; as long as they are not the exact same object referenced in memory, Java will return false. Therefore, you should use equals() or compareTo(), both of these methods actually check the value of the string rather than checking if both objects have the same reference.
METHOD 1
if("p".equals(holder[0])){
    charsheet.style = holder[1];
}

METHOD 2
METHOD 1

if("p".compareTo(holder[0]) == 0){ //compareTo returns 0 if both strings equal
    charsheet.style = holder[1];
}


text:
Q: I get 405 (Method Not Allowed) error on a DELETE Ajax Request in Laravel5.4 I'm new to Laravel.
I'd like to delete a record from a database table by ajax call, but I get this error below.

DELETE http://192.168.33.10/staff/4/edit 405 (Method Not Allowed)
  onDeleteButtonClick @ d2d.js:75

I'm sending a ajax request to "http://192.168.33.10/staff/4" in my JavaScript code, but it seems that the request is sent to "http://192.168.33.10/staff/4/edit".
How can I make my ajax request to "http://192.168.33.10/staff/4"?
HTML Form on http://192.168.33.10/staff/4/edit
<form method="post" action="http://192.168.33.10/staff/{{  $staff->id  }}">

            last name
            <input type="text" class="form-control" id="" name="last_name" placeholder="" value="{{  $staff->last_name }}">

            first name
            <input type="text" class="form-control" id="" name="first_name" placeholder="" value="{{  $staff->first_name }}">

    <button type="submit" class="btn btn-primary">update</button>
    {{ method_field('PUT') }}

    <button id="delete-button" type="button" class="btn btn-danger">delete</button>

    <input id="hidden-value" type="hidden" name="id" value="{{  $staff->id  }}"/>
    {{ csrf_field() }}

</form>

JavaScript
var $deleteButton = document.getElementById("delete-button");

$deleteButton.addEventListener("click", onDeleteButtonClick);

function onDeleteButtonClick(event) {

    var request = new XMLHttpRequest();

    request.ontimeout = function(event){
        console.log("timeout error");
    };

    request.onreadystatechange = function() {

        if(request.readyState === 4) {

            console.log("done");

            if(request.state === 0) {

                console.log("fail");

            } else {

                if(request.status === 200) {

                    console.log("request success");
                    location.href = "http://192.168.33.10/staff";

                } else {

                    console.log("request fail");

                }

            }

        }

    };

    request.onload = function(event) {
        console.log("onload");
        console.log(request.response);

    };

    request.onerror = function(event) {
        console.log("onerror");
        console.log(request.response);

        console.log(request.responseText);

    };

    var id = document.getElementsByName("id")[0].value;
    var token = document.getElementsByName("_token")[0].value;

    var url = "http://192.168.33.10/staff/" + id;

    request.open("DELETE", url, true);

    request.responseType = "json";
    request.timeout = 2000;

    request.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');

    request.send('id=' + encodeURIComponent(id) + '&' + '_token=' + encodeURIComponent(token));

}

Headers Information
GENERAL:

Request URL:http://192.168.33.10/staff/4/edit
Request Method:DELETE
Status Code:405 Method Not Allowed
Remote Address:192.168.33.10:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source

RESPONSE HEADERS:

allow:GET, HEAD
Cache-Control:no-cache, private
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Sun, 07 May 2017 11:17:09 GMT
Server:Apache/2.4.6 (CentOS) PHP/7.0.18
X-Powered-By:PHP/7.0.18
Request Headers
view source

REQUEST HEADERS:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:ja,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:52
content-type:application/x-www-form-urlencoded;charset=UTF-8
Cookie:XSRF-TOKEN=eyJpdiI6ImViWGdkU3RCdkxORk9aV3RpMnNmTkE9PSIsInZhbHVlIjoidGRaT1wvdEpadlVFV1djcE05anhraktKY041ZmZ5VWpISGpjTzBmVk1HXC80ODNjOGNtY05Hc3RDSWw4dHM1M2h4eVRkMEJqVnUzR3FjMzhTMzE2YTlGZz09IiwibWFjIjoiYTNlYjc4MGNhYzkyOWQxMzhkMWNjYWNlNjIyNzNiOGU5M2M4OTE3ZjA0YzE1MmY3NjY4MjdkZTU0YWY5OTE3NSJ9; laravel_session=eyJpdiI6IkpyaWRwVit2NE03NURRSG03NlhCU0E9PSIsInZhbHVlIjoiODBIMGVyYkV6bHhEQzlWZXZIVTRoVFwvT0RnNTJweXBqNG14dnBzYWN4bXFJT3lKcTdTb1FsMUJqejFucE5wdThKNkhQWkY2aDdZWFMwbUhLM2RxaE5nPT0iLCJtYWMiOiI0YTQyN2I1ZjA3NjFhNzY0NWM1ZDRlMzVlOTZiNTI2OTc5M2M2NmMzNmNkNDA2ZWY4Nzc0NjlmYzBmZTgzNGE1In0%3D
Host:192.168.33.10
Origin:http://192.168.33.10
Referer:http://192.168.33.10/staff/4/edit
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36
Form Data
view source
view URL encoded
id:4
_token:zQEHxnSdNlIB63wQ4lzxbHYO6wq5YMEhqddky46L

Route Definitions
[vagrant@localhost door]$ php artisan route:list
+--------+-----------+------------------------------+----------------------+---------------------------------------------------------------+--------------+
| Domain | Method    | URI                          | Name                 | Action                                                        | Middleware   |
+--------+-----------+------------------------------+----------------------+---------------------------------------------------------------+--------------+
|        | GET|HEAD  | /                            |                      | Closure                                                       | web          |
|        | GET|HEAD  | _debugbar/assets/javascript  | debugbar.assets.js   | Barryvdh\Debugbar\Controllers\AssetController@js              |              |
|        | GET|HEAD  | _debugbar/assets/stylesheets | debugbar.assets.css  | Barryvdh\Debugbar\Controllers\AssetController@css             |              |
|        | GET|HEAD  | _debugbar/clockwork/{id}     | debugbar.clockwork   | Barryvdh\Debugbar\Controllers\OpenHandlerController@clockwork |              |
|        | GET|HEAD  | _debugbar/open               | debugbar.openhandler | Barryvdh\Debugbar\Controllers\OpenHandlerController@handle    |              |
|        | GET|HEAD  | api/user                     |                      | Closure                                                       | api,auth:api |
|        | GET|HEAD  | staff                        | staff.index          | App\Http\Controllers\StaffController@index                    | web          |
|        | POST      | staff                        | staff.store          | App\Http\Controllers\StaffController@store                    | web          |
|        | GET|HEAD  | staff/create                 | staff.create         | App\Http\Controllers\StaffController@create                   | web          |
|        | GET|HEAD  | staff/{staff}                | staff.show           | App\Http\Controllers\StaffController@show                     | web          |
|        | PUT|PATCH | staff/{staff}                | staff.update         | App\Http\Controllers\StaffController@update                   | web          |
|  >>>   | DELETE    | staff/{staff}                | staff.destroy        | App\Http\Controllers\StaffController@destroy                  | web          |
|        | GET|HEAD  | staff/{staff}/edit           | staff.edit           | App\Http\Controllers\StaffController@edit                     | web          |
+--------+-----------+------------------------------+----------------------+---------------------------------------------------------------+--------------+

StaffController
class StaffController extends Controller
{

    //other methods here...

    //delete
    public function destroy($id, StaffRequest $request) {

        $staff = Staff::findOrFail($id);
        $staff->delete();

        return response()->json(['apple' => 'red', 'peach' => 'pink']);

    }

}

UPDATE
request.setRequestHeader('XSRF-TOKEN', token);
//request.setRequestHeader('X-CSRF-TOKEN', token);
request.send('id=' + encodeURIComponent(id));
// request.send('id=' + encodeURIComponent(id) + '&' + '_token=' + encodeURIComponent(token));

I changed two lines in my JavaScript code like the above, so that now I'm throwing a DELETE request to "http://192.168.33.10/staff/4".
However I get 500 error instead of 405 error.

A: remove the edit param in your link DELETE http://192.168.33.10/staff/4/edit to be DELETE http://192.168.33.10/staff/4


text:
Q: PHP loop X amount of times I have a string called $columns which dynamically gets a value from 1 to 7. I want to create a loop of 	 for however many times the value of $columns is. Any idea how I can do this?

A: for ($k = 0 ; $k < $columns; $k++){ echo '	'; }

A: Here's a more readable way to achieve this:
foreach(range(1,$columns) as $index) {
   //do your magic here
}

A: I like this way:
while( $i++ < $columns ) echo $i;

Just bear in mind if $columns is 5, this will run 5 times (not 4).
Edit: There seems to be some confusion around the initial state of $i here. You are welcome to initialise $i=0 beforehand if you wish. This is not required however as PHP is a very helpful engine and will do it for you automatically (tho, it will throw a notice if you happen to have those enabled).

A: just repeat $n times? ... if dont mind that $n goes backwards...
the advantage is that you can see/config "times" at the beginning
$n = 5;
while (--$n >= 0)
{
  // do something, remember that $n goes backwards;
}

A: There is a str_repeat() function in PHP, which repeats a string a number of times. The solution for your problem would be:
str_repeat( '	', $columns );

A: If $columns is a string you can cast to int and use a simple for loop
for ($i=1; $i<(int)$columns; $i++) {
   echo '	';
}

A: If you just need to use number of repeat count:
for ($i = 0; $i < 5; $i++){
    // code to repeat here
}

A: A for loop will work:
for ($i = 0; $i < $columns; $i++) {
    ...
}

A: You can run it through a for loop easily to achieve this
$myData = array('val1', 'val2', ...);

for( $i = 0; $i < intval($columns); $i++)
{
    echo "" . $myData[$i] . "	";
}

A: Why use logic at all, don't waste those CPU cycles!
<td colspan="<?php echo $columns; ?>">


text:
Q: How to remove script name from address bar with Apache mod_rewrite I have three domains, lets say frontend.com, platform.com, userpanel.com. Each one of them pointing to my server machine where index.php script makes redirection to frontend.php, platform.php, userpanel.php. Association between domain and scrip can be changed, it is stored in database and index.php checks it each time.
It works fine.
I would like to remove script name from browser address bar, to get frontend.com instead of frontend.com/frontend.php, platform.com instead of platform.com/platform.php and userpanel.com instead of userpanel.com/userpanel.php. How can I achieve it with Apache mod_rewrite?

A: You can use this rule in your DocumentRoot/.htaccess:
RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\. [NC]
RewriteRule ^$ /%1.php [L]


text:
Q: 'loosen up' Laravel Scout's search functionality to return more results with database driver I'm using Laravel Scout with the driver set as database to create a searchable knowlegde base.
The issue i've currently got it that I would like each word in the search term to be searched for an return all results that have any of the words rather than an exact match.
So for example:
search term: pay a bill

database records contain: pay my bill, how to pay a bill, paying my bill

With my current setup, it wont return any of these results as none of them match the exact term searched.
Is there anything I can do in Scout to make it loosely search each word?
I can achieve this by using whereFullText() but I wanted to keep this within Scout and using ::search() if possible.


text:
Q: What are the advantages of specifying the parameter type and return type of a method? I have just recenlty learned that you can specify the parameter and return type of a function in Python, something like this:
def myDef(a: int, b: int) -> int:
    return a+b

Does this have any advantages considering speed or are there any other reasons why this could be useful?

A: Basically the pros Type Hints of are:

*

*Type hints help catch certain errors.

*Type hints help document your code. (you can also use
docstrings if you want to document the expected types of a
function's arguments, but can't be easily used for
automatic checks)

*Type hints improve IDEs and linters. They make it much easier to
statically reason about your code.
Type hints help you build and maintain a cleaner architecture. The
act of writing type hints forces you to think about the types in
your program. While the dynamic nature of Python is one of its great
assets, being conscious about relying on duck typing, overloaded
methods, or multiple return types is a good thing.
It is definitely an avoidable practice as: it takes time and effort, work best in modern Pythons and it gives you a slight penalty in start-up time.


text:
Q: curl/file_get_contents/get_headers "failed to open stream" After isolating my problem, I am testing my API with the following code:
    $url = 'http://example.com/api/myendpoint;
    print_r(get_headers($url));die();

Sometimes it does works, but sometimes it returns a 404.
The link I access simply returns a JSON response.
This started to happen after I reboot my Amazon EC2 server.
If I do in local it seems to work better(but even there sometimes it doesn't work).
     Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Server: nginx/1.10.1
    [2] => Content-Type: application/json
    [3] => Connection: close
    [4] => Cache-Control: private, must-revalidate
    [5] => Date: Wed, 02 Nov 2016 14:47:36 GMT
    [6] => pragma: no-cache
    [7] => expires: -1
    [8] => X-Debug-Token: fadeb4
    [9] => Strict-Transport-Security: max-age=31536000; includeSubdomains;
)

I tried to do in some online php testers. Same problem.
I thing it's a server configuration problem but I have no idea of how debug that.
Thank you for the help.
UPDATE
I got this data when I see the htmlentities of my request/response
Array
(
    [url] => http://example.com/api/myendpoint
    [content_type] => text/html
    [http_code] => 404
    [header_size] => 163
    [request_size] => 206
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.00557
    [namelookup_time] => 0.004207
    [connect_time] => 0.004851
    [pretransfer_time] => 0.004874
    [size_upload] => 0
    [size_download] => 579
    [speed_download] => 103949
    [speed_upload] => 0
    [download_content_length] => 579
    [upload_content_length] => 0
    [starttransfer_time] => 0.005555
    [redirect_time] => 0
    [redirect_url] =>
    [primary_ip] => ::ffff:XX:XX:XX:XX
    [certinfo] => Array
        (
        )

    [primary_port] => 80
    [local_ip] => ::ffff:YY.YY.Y.YY
    [local_port] => 42744
)

The thing is that the primary ip XX:XX:XX:XX:XX is not my actual ip. It's my old ip, before changing the instance in amazon web-server.
This might be causing the problem, but how could I fix it?

A: I discovered what it was:
When I changed my amazon web server, in my OVH hosting I changed the ipv4 of my dns.
But I didn't change the ipv6.
So sometimes when I tried to access the site the calls were being redirected to the right ip (the path showed in ipv4) and sometimes the old wrong one (the path indicated by the ipv6)


text:
Q: If Python 3 is the newest python, why is python 2 still around? I used Python a few years ago when 2 was the only version.
Now there is 2 and 3.
Was there a a reason 2 hasn't continued to upgrade and now there is a split into two different pythons? Like no one uses Python 2.5. They all use 2.7 or whatever it is. Why not just use 3? Obviously there's a reason, but I was unable to find it googling.
My second question is, which one should I use? I am assuming 3, but that's ONLY based on the higher number. I wonder why 2 is still around if 3 is out??? If there aren't any major bugs with 3, I am just going to use that as I don't reckon it much matters: either one would probably work for py QT.

A: Python 3 is significantly different than Python 2.x, and breaks numerous libraries and likely a lot of other dependent code. Python 2.x will likely be around for quite a while, as libraries are ported and 3.0 is field-tested.

A:
Why not just use 3?

A lot of existing Python code is not compatible with Python 3 yet. If you need to use Django for example you are forced to use Python 2.x.

My second question is, which one should I use?

*

*Python 3 and PyQt 4 recommendations

A: it costs a lot to upgrade from python 2.x to python 3, that's why my project still uses python 2.7

A: The latest Ubuntu doesn't ship with Python 3.  12.04 will but that's not out yet.
OpenBSD doesn't have a package for Python 3, either.
Some people may just not have Python 3 on their platform and don't care to compile.


text:
Q: RTMP_ReadPacket, failed to read RTMP packet header I am trying to livestream a 24/7 looping stream from my Ubuntu server to youtube.
I have a gif that is looping and my music gets shuffled from a music list.
for i in ./*.mp3 ; do echo "file '$i'" ; done | shuf >mp3list.txt ffmpeg -f
concat -i mp3list.txt -fflags +genpts -ignore_loop 0 -i giffilename.gif -f
flv rtmp://a.rtmp.youtube.com/live2/(mykeyhere)

But I am getting this error when I run my script:

RTMP_ReadPacket, failed to read RTMP packet header : Unknown error
  occutredm/live2/(mykeyhere)

I did some research, but couldn't find anything about this specific error. I opened port 1935 and it did not change anything.
The OS is Ubuntu 16.04 on a VPS.
Thanks for your help,
Dilie


text:
Q: currently using a module that will create 5 flat rate shipping for magento
Does anyone know how i can add 5 more?

  A client of mine needs 6 pickup locations

  ------
   Or how can i add pickup locations on my own without purchasing an module

  thanks

i looked at other questions on here but cant find the way to edit or the xml related to the 5 flat rate shipping options

i am using MSP_FlatShipping5, any help would be appreciated ty

A: i figured out the answer will post the code incase someone needs it in the future
you go to /public_html/app/code/community/MSP/FlatShipping5/
and edit all of the files and just copy and paste..
go like 6,7,8 etc as many as u need.


text:
Q: Can't get single \ in python I'm trying to learn python, and I'm pretty new at it, and I can't figure this one part out.
Basically, what I'm doing now is something that takes the source code of a webpage, and takes out everything that isn't words.
Webpages have a lot of \n and \t, and I want something that will find \ and delete everything between it and the next ' '.
def removebackslash(source):
    while(source.find('\') != -1):
        startback = source.find('\')
        endback = source[startback:].find(' ') + startback + 1
        source = source[0:startback] + source[endback:]
    return source

is what I have. It doesn't work like this, because the \' doesn't close the string, but when I change \ to \\, it interprets the string as \\. I can't figure out anything that is interpreted at '\'

A: Try using replace:
str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
So in your case:
my_text = my_text.replace('\n', '')
my_text = my_text.replace('\t', '')

A: As others have said, you need to use '\\'.  The reason you think this isn't working is because when you get the results, they look like they begin with two backslashes.  But they don't begin with two backslashes, it's just that Python shows two backslashes.  If it didn't, you couldn't tell the difference between a newline (represented as \n) and a backslash followed by the letter n (represented as \\n).
There are two ways to convince yourself of what's really going on.  One is to use print on the result, which causes it to expand the escapes:
>>> x = "here is a backslash \\ and here comes a newline \n this is on the next line"
>>> x
u'here is a backslash \\ and here comes a newline \n this is on the next line'
>>> print x
here is a backslash \ and here comes a newline
 this is on the next line
>>> startback = x.find('\\')
>>> x[startback:]
u'\\ and here comes a newline \n this is on the next line'
>>> print x[startback:]
\ and here comes a newline
 this is on the next line

Another way is to use len to verify the length of the string:
>>> x = "Backslash \\ !"
>>> startback = x.find('\\')
>>> x[startback:]
u'\\ !'
>>> print x[startback:]
\ !
>>> len(x[startback:])
3

Notice that len(x[startback:]) is 3.  The string contains three characters: backslash, space, and exclamation point.  You can see what's going on even more simply by just looking at a string that contains only a backslash:
>>> x = "\\"
>>> x
u'\\'
>>> print x
\
>>> len(x)
1

x only looks like it starts with two backslashes when you evaluate it at the interactive prompt (or otherwise use it's __repr__ method).  When you actually print it, you can see it's only one backslash, and when you look at its length, you can see it's only one character long.
So what this means is you need to escape the backslash in your find, and you need to recognize that the backslashes displayed in the output may also be doubled.

A: The SO auto-format shows your problem.  Since \ is used to escape characters, it's escaping the end quotes.  Try changing that line to (note the use of double quotes):
while(source.find("\\") != -1):

Read more about escape characters in the docs.

A: I don't think anyone's mentioned this yet, but if you don't want to deal with having to escape characters just use a raw string.
source.find(r'\')

Adding the letter r before the string tells Python not to interpret any special characters and keeps the string exactly as you type it.

A: \ is an escape character; it either gives characters a special meaning or takes said special meaning away. Right now, it's escaping the closing single quote and treating it as a literal single quote. You need to escape it with itself to insert a literal backslash:
def removebackslash(source):
    while(source.find('\\') != -1):
        startback = source.find('\\')
        endback = source[startback:].find(' ') + startback + 1
        source = source[0:startback] + source[endback:]
    return source


text:
Q: AWS Auto Scaling DB I was thinking exactly how Amazon AWS handles the data replication on the fly when a new DB instance is launched when auto scaling is turned on?
I'm more interested about Cassandra, MySql, Redis, Riak, but of course would love to know about others too but after I get clarity about the ones mentioned.
It is confusing me a lot.
Thanks a lot.

A: Core architecture comes from MySQL replication.. where every transaction is also saved as part of bin log. Also, AWS keeps taking snapshot frequently..Now, suppose you start data replication .. It will first take the latest snapshot --> recover it --> (that snapshot also has information that this snapshot has information till what pointer in bin log) --> now, it starts playing bin log on top of new db ( generated from snapshot ) till catch-up is done.
After catch up is done --> then this bin log keeps getting played in real time on replica server.
Note that MySQL gives many options of creating bin log; for example statement based (actual sql statement is logged), row based(all the rows are logged ) or mixed.


text:
Q: Javascript: check if the url is changed or not? My url format is like :
http://domain.in/home
http://domain.in/books/notes
http://domain.in/books/notes/copy

I've called a javascript function on window.load to check if the url has changed or not.
If the url has been changed then code is executed else it will return and checks again after 5 sec.
My code is :
window.onload = function(){
   setInterval(function(){
       page_open();
   }, 5000);
};

function page_open(){
    var pages=unescape(location.href);
    pages=pages.substr( pages.lastIndexOf("studysquare.in/") + 15 );

    // gives book if url is http://studysquare.in/book
    //alert("pages"+pages+"\n\n  recent"+recent);

    if (pages==recent) {    return;     }
    recent=pages;

    alert("Reached down now the code will execute.");
}

The problem now is : when the url is like :
http://domain.in/book

Single level deep, then everything works fine. But when the url is like
http://domain.in/book/copy    or    http://domain.in/book/copy/notes

Then nothing works.....
Any help to check 3 level deep url  change in javascript every 5 sec ? :)
Hi sorry I forgot to tell that... I've .htaccess file which doesnt allow to navigate the page when any length url after the domain.in/ is written.... that means only single page remains open and not affected by the url change...

A: When the user changes the URL, the browser unloads the entire page they're currently on (including your javascript, hence it stops running) and then loads the next page. No javascript is able to run across page changes. You can't monitor a change in the URL like you're doing if they're navigating to another page.
The best way to catch a change in the URL is to add an onUnload event to the body object to fire your javascript when the browser unloads the page just before starting to load the new page the user has requested -- but I'm not sure that's going to help achieve your goal of tracking their recent page views (if that's what you're looking to do).

A: Sounds like a history plugin such as jQuery address would help you a lot.
It lets you handle the event when the URL is changed, so you can load in new content as required.


text:
Q: Upserting subdocumets as a list with mutate_in Would really appreciate your help here.
I am trying to mutate the sub documents by using mutate_in and then defining the SD with a path for each element that I want to put in.
The code looks like this:
cb.mutate_in('1_2',
SD.upsert(
'strat.a', 76543, create_parents=True),
SD.upsert(
'strat.b', "true", create_parents=True),
SD.upsert(
'strat.c', 30, create_parents=True),
SD.upsert(
'strat.d', -25, create_parents=True),
SD.upsert(
'strat.e', "C", create_parents=True),
SD.upsert(
'strat.f', 7, create_parents=True),
)

This is the kind of result it brings in:
{
"strat": {
"a": 76543,
"b": "true",
"c": 30,
"d": -25,
"e": "C",
"f": 7
}
}

What I am looking for is this (Notice that I am putting that in a list here):
{
"Strat": [
{
"a": "12345",
"b": 7,
"c": "C",
"d": "true",
"e": -25,
"f": 25
}
]
}

Once I am able to achieve the above as a list, I should be able to generate multiple sub documents like this:
Notice that now I have 2 elements in this list both having different values:
{
"Strat": [
{
"a": "12345",
"b": 7,
"c": "C",
"d": "true",
"e": -25,
"f": 25
},
{
"a": "34567",
"b": 8,
"c": "F",
"d": "false",
"e": -30,
"f": 40
}
]
}

QUESTION:
can I achieve this with mutate_in and SD.upsert ?
if so, how can I change that code I have provided at the beginning of this thread to put things in a list
Once I can put it as a list, how can I avoid upsert not overwriting the record but to attach another record in that list?

Your help is highly appreciated. Thank you !
Looking forward to some direction from all the couchbase gurus out there

A: You can create a Python Dictionary representing the new JSON Object, and append it to the array (create_parents=True says "create the array if it doesn't already exist").
I am not fluent in Python, and have no idea if this compiles... so let's call it pseudocode :-)
cb.mutate_in('1_2',
    SD.array_append('strat',
        {
            "a": "12345",
            "b": 7,
            "c": "C",
            "d": "true",
            "e": -25,
            "f": 25
        },
        create_parents=True),

    SD.array_append('strat',
        {
            // some other values...
        },
        create_parents=True));

You can append up to 16 items at a time this way (subdoc batches are limited to 16 operations).


text:
Q: Autocomplete django in visual studio code hello everyone I am having a problem the visual studio code autocomplete for django does not work for me, because for python it does it without problems but when working with django the framework options do not work, that is when I work with views based on classes does not generate the autocomplete, such as template_name, form_class, etc ..., likewise with the models it does not generate the help of max_length, and those other things of the framework, I have selected the interpreter but it does not work for me and also python: build workspace symbols and nothing. in advance I appreciate the help.

A: You can install and activate python & Microsoft AI extension in visual studio code.

A: install some of the plugins for local and global
Global in vscode extensions:

*

*Python (Microsoft)

*Djaneiro

*code spell checker

local:
pip install —dev autopep8 pep8 pylint pylint_django

Press CTRL+SHIFT+P(CMD+SHIFT+P for MacOS) -> ">select interpreter" -> select your virtual envirnoment
https://i.ibb.co/TTfkHRF/select-vir.gif
open vscode/setting.json file and past the beneath config code:
{
  ....
  "editor.formatOnSave": true,
  "python.formatting.provider": "autopep8",
  "python.linting.enabled": true,
  "python.linting.lintOnSave": true,
  "python.linting.pylintEnabled": true,
  "python.linting.pylintArgs": [
    "--load-plugin=pylint_django"
  ]
}


text:
Q: Why does CompletableFuture.runAsync() not always submit to ForkJoinPool.commonPool()? CompletableFuture.runAsync documentation states:

Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() after it runs the given action.

However, as far as I can tell, runAsync only submits a task to ForkJoinPool.commonPool() when ForkJoinPool.getCommonPoolParallelism() > 1. If not, it manually creates a new Thread for each submitted task.
Why exactly is this the case?

A: Yes, if ForkJoinPool parallelism level is less than 2, then new thread is created for every task here

All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() (unless it does not support a parallelism level of at least two, in which case, a new Thread is created to run each task).


text:
Q: How to organize your system for multiple projects? I'm looking for a way to manage multiple system setups. As an example, if I start working on a project I might need to install some software and its dependencies. I would like when I finish working in this project to be able to revert the system to its previous state.
My ideal situation would be like having git but for the whole system, thus being able to create branches, experiment, and revert to any point in time.
Is there are a way to achieve this? I've thought about using LVM snapshots, is this a good idea?

A: TL;DR
Use virtualbox snapshots.
Virtual machine snapshots are most commonly used for that sort of requirement. The main reasons are simplicity, and the worst case scenario is zeroing all data root can write. If you have modern development box with 12+GB RAM and 8TB Disk space you might run 5-10 test environments at the same time and store 800 snapshots which is plenty.
On the other hand if testing is relatively tame, the common option is just to keep a log of actions (apt install x y z && mkdir project0) and undo them (apt purge x y z && rm -r project0) or just leave them if they are not interfering with other projects.
brtfs is an interesting option because it can provide a snapshot diff to a backup server efficiently, the disadvantage is that it's slightly more complicated, and much less stable.
There are many other options ( git/lvm/rsync/rdiffbackup/zfs/containers/etc ) but there are disadvantages (like extra time/space or less robust). At the end of the day quality developer time is the most sought commodity so the less time you spend on planning and environment setup the more time you have to be productive. So start with one of the 2 simple options and only if you find time is wasted explore a more complex solution.


text:
Q: Use HTML pages into GWT application I want to use html pages into phone-gap application with the help of GWT application.
I have one HTML page with css and javascript file. So How can I integrate with GWT web application.?
So By the end of compiling, I can use into phone-gap project for same as I designed the page.
can anyone tell me steps for this procedure.?
Thanks in Advance.

A: Haven't tried it but this may help.
http://code.google.com/p/gwt-phonegap/
Heard it is pretty good

A: Try using iframe. It is a standard HTML tag (see http://www.w3schools.com/tags/tag_iframe.asp), where you can put a link to another page and the page will be embedded in your document.

Your browser does not support iframes.

You can add it programmatically as well.
public class FrameExample implements EntryPoint {

    public void onModuleLoad() {
        // Make a new frame, and point it at Google.
        Frame frame = new Frame("http://www.google.com/");

        // Add it to the root panel.
        RootPanel.get().add(frame);
    }

}

The example is from http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/Frame.html.


text:
Q: PDF - Auto adjust for mobile? Does anyone know if there is a function in PDF's to allow them to auto-adjust the view depending on whether it is on a desktop or mobile? Or even by screen size?
I am looking to prepare PDF material for distribution, however, on the user group includes a mix of desktop and mobile, so instead of creating two PDFs I would like to have a single PDF which adapts to the users screen?

A: This is not possible with PDF files up to PDF version 1.7, the most commonly used on out there.
PDF 2.0 which was released three years ago has such a feature but it depends on the viewer implementing it and the PDF writer correctly annotating the PDF. I guess there are PDF viewers out there that can already do this but I'm not specifically aware of any.
If I were you, I would write the document in a format like LaTeX that can easily be converted to both kinds of PDFs, one for desktop and one for mobile.


text:
Q: How to ignore values that are not repeated in Python Counter I need to make sure that the answer in the first case does not output the value of the count_value.
from collections import Counter

def duplicate_count(text):
    count, value, count_value = len(set([i for i in (list(text.lower())) if (list(text.lower())).count(i) >= 2])),set([i for i in (list(text.lower())) if (list(text.lower())).count(i) >= 2]), Counter(text.lower()).most_common(2)
    return f'->{count} # {" and ".join(x for x in list(value))} повторилось {count_value[0][1]} раз'

print(duplicate_count('abcde'))
print(duplicate_count('aabbcde'))
print(duplicate_count('indivisibility')) ```

>>> ->0 #  повторилось 1 раз
>>> ->2 # a and b повторилось 2 раз
>>> ->1 # i повторилось 6 раз

A: is this what you are looking for?
def duplicate_count(text):
    tlower = text.lower()
    count = set([(i, tlower.count(i)) for i in tlower if tlower.count(i) >= 2])
    chars = ' and '.join([i[0] for i in count])
    if count:
        return f'->{len(count)} # {chars} повторилось {max(i[1] for i in count)} раз'
    else:
        return f'->{len(count)}'

print(duplicate_count('abcde'))
print(duplicate_count('aabbcde'))
print(duplicate_count('indivisibility'))

->0
->2 # a and b повторилось 2 раз
->1 # i повторилось 6 раз


text:
Q: Problem when add sqlsrv and pdo_sqlsrv in MAMP Here I want to add sqlsrv and pdo_sqlsrv in MAMP. I want to download and install the package with pecl, running this command:
sudo pecl install sqlsrv pdo_sqlsrv

But i got error:

Could not download from
  "http://pecl.php.net/get/pdo_sqlsrv-5.3.0.tgz", cannot download
  "pecl/pdo_sqlsrv" (File
  http://pecl.php.net:80/get/pdo_sqlsrv-5.3.0.tgz not valid (received:
  HTTP/1.1 503 Service Unavailable )) Error: cannot download
  "pecl/pdo_sqlsrv" Could not download from
  "http://pecl.php.net/get/sqlsrv-5.3.0.tgz", cannot download
  "pecl/sqlsrv" (File http://pecl.php.net:80/get/sqlsrv-5.3.0.tgz not
  valid (received: HTTP/1.1 503 Service Unavailable )) Error: cannot
  download "pecl/sqlsrv" Download failed install failed

I tried to download the package directly from http://pecl.php.net/get/pdo_sqlsrv-5.3.0.tz but just don't know where or how to generate .so files. I'm really new to Mac. Please help. Thanks.

A: Not sure if you still have this problem:
Replace
sudo pecl install sqlsrv pdo_sqlsrv

With
sudo /pathtoyourmamp/php/bin/pecl install sqlsrv pdo_sqlsrv

Edit php.ini:
extension=sqlsrv
extension=pdo_sqlsrv


text:
Q: public override string[] GetRolesForUser(string username) Hello guys here is my problem , i create authentication on my database under role so when i put [Authorize(Roles="admin")]it will read by my program i already set it up in my web.config and also in create class but still it directing me in my log in page as default when not authorize, please help
here is my code
MyRoleProvider.cs
public override string[] GetRolesForUser(string username)
        {
        UserDbEntities OE = new UserDbEntities();
        string s = OE.UserAccounts.Where(x => x.Username == username).FirstOrDefault().Role;
        string[] resultS = {s};
        return resultS;
    }

Controller
 public class CustomerController : Controller
    {
    private UserDbEntities db = new UserDbEntities();

    // GET: Customer
    [Authorize(Roles="admin")]
    public ActionResult Index()
    {
        return View(db.Customers.ToList());
    }

Web.config
 <authentication mode="Forms">
          <forms loginUrl="Account/Login"></forms>
        </authentication>
        <roleManager enabled="true" defaultProvider="MyProvider">
          <providers>
          <clear/>
        <add name ="MyProvider" type="Sample.MyRoleProvider"/>
      </providers>
    </roleManager>


text:
Q: tkinter custom button class **kwargs I'm trying to create a tkinter button class to add a resized image with text.
The button renders ok on the mainwindow as expected, but I cannot pass a command to the button.
The additional **kwargs to the BTN_IMG_TXT create errors with the original tk.button.
Hence I used following in class definition, which I believe the problematic part of the code.
def __init__(self, master, command, *args, **kwargs):
    tk.Button.__init__(self,master=master, command=command)

Following is the full code for testing:
import tkinter as tk
from PIL import  Image, ImageTk

window = tk.Tk()
window.geometry("300x200")

def remove_item(event = None):
    print('Delete button pressed')  #debug

# custom button widget
class BTN_IMG_TXT(tk.Button):
    def __init__(self, master, command, *args, **kwargs):
        tk.Button.__init__(self,master=master, command=command)
        self.fname = kwargs.get('fname')
        self.btn_txt = kwargs.get('btn_txt')
        img = Image.open(self.fname)
        image = img.resize((40,40), Image.ANTIALIAS)  # make static size
        self.photo1=  ImageTk.PhotoImage(image)
        b = tk.Button(self, text=self.btn_txt, image=self.photo1,
                            compound="top", width=70, height=70,)
        b.pack(side="top")

frm_Main = tk.Frame(master=window, bg='#faeaea', borderwidth=2)
frm_Main.pack()
stp_btn = BTN_IMG_TXT(master=frm_Main,fname="stop_b.png",btn_txt='STOP',command=remove_item)
del_btn= BTN_IMG_TXT(master=frm_Main,fname="delete_b.png",btn_txt='DELETE', command=remove_item)
del_btn.pack(side="left", fill="both", expand=False)
stp_btn.pack(side="left", fill="both", expand=False)

window.mainloop()

A: Tkinter Button can display text as well as image together and by using compound parameter we can tell the button widget where to align the text with the image read more about the compound parameter in the config(**options) of Tkinter Button.
You are using a button inside a button that's why the command is not working because it is linking with the BTN_IMG_TXT class, not with the b which is inside of the class.
Here is what I did,
# custom button widget
class BTN_IMG_TXT(tk.Button):
    def __init__(self, master=None, cnf={}, **kw):
        # Merged both cnf and kw dictionaries.
        kw = tk._cnfmerge((kw, cnf))
        # make static size
        if kw.get('image'):
            img = Image.open(kw['image'])
            image = img.resize((40,40), Image.ANTIALIAS)
            self.photo1 = ImageTk.PhotoImage(image)
            kw['image'] = self.photo1
        # Aligns the image on top and text under it
        kw['compound'] = kw.get('compound', 'top')
        super().__init__(master=master, **kw)

frm_Main = tk.Frame(master=window, bg='#faeaea', borderwidth=2)
frm_Main.pack()
stp_btn = BTN_IMG_TXT(master=frm_Main, image="stop_b.png", text='STOP', command=remove_item)
del_btn= BTN_IMG_TXT(master=frm_Main, image="delete_b.png", text='DELETE', command=remove_item)
del_btn.pack(side="left", fill="both", expand=False)
stp_btn.pack(side="left", fill="both", expand=False)

I Hope, this solves your issue.


text:
Q: Conditional Validation for Serialized Array How can I create a validation where committed presence needs to be true only if the challenge's category is habit?
class Challenge < ActiveRecord::Base
  CATEGORY = ['goal', 'habit']
  serialize :committed, Array
  validates :committed, presence: true, if: :habit # I also tried with 'habit' & 'Habit'
end

A: validates :committed, presence: true, :if => lambda { |c| c.category == 'Habit' }

A: Since your category is called 'habit' (note, it is not 'Habit'), the validation would look as follows:
validates :committed, presence: true, if: ->(c) { c.category == 'habit' }

As a sidenote: I do not think your scopes will work, unless you have a column called categories in your challenges table.
Thus, if your intention was to select challenges, which have category 'habit', the scope would look as follows:
scope :habit, -> { where(category: 'habit') }

EDIT
As per discussion in comments, if you want committed to be nil instead of [""] when nothing is there, add custom validation:
validate :committed_content

private

def committed_content
  self.committed = nil if committed.empty? || committed.all?(&:blank?)
  true
end

A: You can have a method and use it like this:
validates :committed, presence: true, if: :habit?

def habit?
  self.category == 'habit'
end


text:
Q: How to run non-dependent sibling tasks sequentially? Let's suppose I have a dag with 4 tasks, and the structure would be more or less like this if we only care about the order in which they are run:
t1.set_downstream(t2)
t2.set_downstream(t3)
t3.set_downstream(t4)

This let's me run the tasks sequentially t1 -> t2 -> t3 -> t4
My issue is, I want them to run in the above sequence, but I want t4 to ignore if and only if t3 fails.
I.e: the graph would look like this if we only care about dependencies
t1.set_downstream(t2)
t2.set_downstream(t3)
t2.set_downstream(t4)

What can I do to have both scenarios?
My current option is to set the trigger rule of t4 to all_done, however, I don't want it to run if t1 or t2 fails.
Any ideas? Is this even possible?

A: You can use a BranchOperator to add the logic you are looking for. Or even create your own SkipOperator based on SkipMixin.


text:
Q: storing line from txt file to string java My program reads a txt file and shows each line in a Jlabel when the Jbutton is clicked.
When the program runs and the Jbutton is clicked nothing appears in the JLabel.
I believe this is because I am not calling the String line correctly in the readFile method.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

import javax.swing.*;

public class Driver {

        List<String> lines;

        static String line = "";

        static Scanner scanner = new Scanner(System.in);

        String s = "Welcome Students!";
        String b = "Start!";
        private JFrame f;
        private JPanel p;

        JFrame frame = new JFrame();

        JButton b1 = new JButton(b);

        JLabel jl = new JLabel(s);

        int i;

        private int clicked;

        public Driver() {
                gui();
        }

        public void gui() {
                lines = readLinesFromFile();
                i = 0;
                f = new JFrame("Flash Card Program");
                p = new JPanel();
                f.setLayout(new GridLayout(2, 1));
                f.add(jl);
                f.add(p);
                p.setLayout(new GridLayout(2, 1));
                p.add(b1);

                jl.setHorizontalAlignment(JLabel.CENTER);

                // pack the frame for better cross platform support
                f.pack();
                // Make it visible
                f.setVisible(true);
                f.setSize(500, 400); // default size is 0,0
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                b1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        jl.setText(lines.get(i));
                        i++;
                        if ( i > lines.size() ) {
                            i = 0;
                        }
                        if (b1.getText().equals("Click For Answer")) {
                            b1.setText("Next Question");
                        } else {
                            b1.setText("Click For Answer");
                        }
                    }
                });

            b1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {

                            if (clicked++ == 10) {

                                    Object[] options = { "No, thanks", "Yes, please" };

                                    int response = JOptionPane.showOptionDialog(frame,
                                                    "Would you like more math questions? ",
                                                    "Math Questions", JOptionPane.YES_NO_CANCEL_OPTION,
                                                    JOptionPane.QUESTION_MESSAGE, null, options,
                                                    options[1]);

                                    if (response == 1)
                                            clicked = 1; // reset
                                    else
                                            System.exit(0);
                            }
                    }
            });
    }

        public static List<String> readLinesFromFile() {
             List<String> lines = new ArrayList<String>();
            try {
                scanner = new Scanner(new File("upload.txt"));
                if (scanner.hasNext()){
                    lines.add(scanner.nextLine());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return lines;
        }

        private static void readFile(File file) throws FileNotFoundException{
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            }
            scanner.close();
        }

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        new Driver();
                        readFile(new File("upload.txt"));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
}

A: If you want to set the label for the jl field with one of the lines from the text file, then you need to do the following:

*

*add a List field inside your Driver class:
public class Driver {
   List<String> lines;
   //other fields that you need
}

*in the gui() method, on the first line, initialize the lines field with the actual lines from the file, and initialize i counter with 0:
public void gui() {
    lines = readLinesFromFile();
    i = 0;
    //other code

*add the following method:
public static List<String> readLinesFromFile() {
    List<String> lines = new ArrayList<String>();
    try {
        Scanner scanner = new Scanner(new File("upload.txt"));
        if (scanner.hasNext()){
            lines.add(scanner.nextLine());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return lines;
}

*change the first ActionListener for b1 with the following:
  b1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jl.setText(lines.get(i));
            i++;
            if ( i > lines.size() ) {
                i = 0;
            }
            if (b1.getText().equals("Click For Answer")) {
                b1.setText("Next Question");
            } else {
                b1.setText("Click For Answer");
            }
        }
    });

Also, using this implementation, you don't need the line variable anymore, because you set the text for the label to one of the values from the lines field.
NOTE: if i gets higher that the actual number of lines in the file, it is reset to 0. If you don't want this, just change the if block in the ActionListener that checks the size