text:
Q: How to pull out images with muuri library and ajax? In my project I am trying to show a grid container with images, this using muuri library, and I am trying to pull out the images from a database using simple vanila javascript, php and ajax on it. The problem with this is that only shows the last image stored in the table in the database. This is my code.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="vistas/css/styles.css">
    <title>Grid</title>

As you can see I am trying to get the images from the images.php file and this file contains the main query to fetch the records from the database and encodes the result in json format...
<?php
$conexion = mysqli_connect('localhost','root','','dbImages');

$query = "SELECT * FROM images";

$result = mysqli_query($conexion,$query);

$images = mysqli_fetch_all($result,MYSQLI_ASSOC);

echo json_encode($images);

Here it's my css code too.
.grid{
    position:relative;
    width:100%;
    opacity:0;
    transition: opacity 0.5s linear 1s;
}

.grid .item{
    position: absolute;
    display:block;
    padding:0;
    margin:10px;
    width: calc(33.333333% - 20px);
}

.grid .item-content{
    position:relative;
}

.grid .item img{
    width:100%;
    cursor:pointer;
    vertical-align:top;
}

I've been working with this so long , and I haven't solve it, it only shows the last image on the table on the database and I would like to do it with a library like this because I want they would be draggagle.
If there is a better idea of how to do this i would be thankful...


text:
Q: Find $b_{n},\ldots ,b_0$ if $a_n \prod^{n-1}_{i=0}(r-i)+a_{n-1}\prod^{n-2}_{i=0}(r-i)+\cdots +a_nr+a_0=\sum\limits_{i=0}^nb_{i}r^i$ I have a polynomial $$\begin{align*}
P(r)=& a_nr(r-1)\cdots (r-(n-1))+a_{n-1}r(r-1)\cdots (r-(n-2))+\cdots +a_1r+a_0\\ =&a_n \prod^{n-1}_{i=0}(r-i)+a_{n-1}\prod^{n-2}_{i=0}(r-i)+\cdots +a_nr+a_0  &&(1)
\end{align*}$$ Let this polynomial be $$\begin{align*}
P&= b_nr^n+b_{n-1}r^{n-1}+\cdots +b_1r+b_0 &&(2)
\end{align*}$$How should I find the coeficient of $(2)$? That is, how should I express thoese $b_{n},b_{n-1},\ldots ,b_1,b_0$ in$(2)$ ?
I tried to directly expand several terms of $(1)$ and hoped to find some patterns, so I can use induction. However, it's quite hard to find a pattern here.
I also tried to find the pattern of expanding $r(r-1)(r-2)\cdots (r-(n-1))$, but this seems not that helpful in dealing with this...
Any help on this? Thanks.

Edit:
By a hint in the comment, I regard $a_0,\cdots,a_n$ as the basis of a vector space, and $b_1,\cdots,b_n$ as the basis of another one. By evaluating $r=n-1,n-2,\ldots$ I get :$$\begin{align*}
\begin{pmatrix} 1 &0 & 0 & 0&  \cdots &0 \\ 1 &1 &0 &0 & \cdots &0 \\ 1 & 2 &2! &0 &\cdots  & 0 \\ 1 & 3 & 3 \cdot2  & 3! & \cdots  & 0 \\ \vdots  &&&&& \vdots  \\ 1 & n & n(n-1) & \cdots  &\cdots & n!   \end{pmatrix} \cdot \begin{pmatrix} a_0  \\ a_1 \\ \vdots \\  \\ \\ a_n  \end{pmatrix} &= \begin{pmatrix} 1 &0 & 0 & 0&  \cdots &0 \\ 1 &1 &1 &1 & \cdots &1 \\ 1 & 2 &2^2 &2 &\cdots  & 2^n \\ 1 & 3 & 3^2   & 3^3 & \cdots  & 3^n \\ \vdots  &&&&& \vdots  \\ 1 & n & n^2 & \cdots  &\cdots & n^n   \end{pmatrix} \cdot \begin{pmatrix} b_0  \\ b_1 \\ \vdots \\  \\ \\ b_n  \end{pmatrix}
\end{align*}$$
Then I denote the LHS $n \times n$ matrix $A$ and if RHS $n \times n$ matrix $B$, If $B$ is invertible and if I can find the inverse of it, I can use $(B^{-1}A) \vec{a}=\vec{b}$, so for $b_0,b_1,\ldots,b_n$ I can know how to express them in $a$. This seems promising, but how should I know that $B$ is invertible? Also. if indeed $B$ is invertible, how should I compute $B^{-1}A$? The computation seemingly involves the pretty amount of work...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two shop pages on woocomerce - filter query param not works I have a shop page which I'm accessing over link.
https://www.notAvailableShopLink.com/shop/
Now I've added one more page - with short code to show only Suspension items (with shortcode)
https://www.notAvailableShopLink.com/suspensions
How can i enable that if i go /suspensions/?filter_fitment=2023 , i will get same results.
This works
https://www.notAvailableShopLink.com/shop/?filter_fitment=2023

This don't
https://www.notAvailableShopLink.com/suspensions/?filter_fitment=2023

Basically filter not works.


text:
Q: DBUnit: Depends the time to import a XML file on the delta? I analyze a test automation framework and the goal is to speed it up.
In this framework DBUnit will be used to bring database in a specific state. During the analysis I recognized the following:

*

*The time to import a DBUnit XML file has nothing to do with the file size

*The bigger the delta between the current database status and the status the XML file will create, the longer takes the import

Can anyone confirm or veto that, please?
If this is true, would it be faster to empty the database and apply the import file then? (No updates or deletes needed, only inserts.)
If this is false, what is the real reason for the import time?
And is there any other way to speed up the import? (Performance tips from DBUnit website are already in place.)
Thank you for your help!

A: My preferred and typical testing approach for fastest performance is with:

*

*An in-memory/embedded database for its speed, such as Apache Derby, automatically started just before launching tests

*No existing rows in any tables; happens automatically with an embedded database and a clean build when storing any of its files in a subdirectory of the build output dir

*dbUnit configured with DatabaseOperation.CLEAN_INSERT [0].

*Minimal dbUnit data for each test.

These three things should provide a good, fast setup for the tests.

The time to import a DBUnit XML file has nothing to do with the file size

The slower the database, the slower the performance with larger data file sizes.
In my experience, the data file sizes are always small, as it is only the data needed for the test with a few extra rows to ensure query accuracy, so this becomes non-relevant.

The bigger the delta between the current database status and the status the XML file will create, the longer takes the import

The more differences, the more statements dbUnit must generate to prep data, which take time to execute.
[0] http://dbunit.sourceforge.net/components.html#DatabaseOperation


text:
Q: Clear old marker(s) then update Below is the code of my website. It refreshes every second. Upon refreshing the new lat/lng it will load the new markers but it keeps the old markers. I have tried many forums etc with no luck. Any help is appreciated thanks.
function initialize() {

var mapOptions = {
    center: new google.maps.LatLng(-36.363, 175.044),
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

var infoWindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
window.setInterval(function() {
        readData();
    }, 1000);
}
   function readData() {

    $.getJSON('https://crossorigin.me/http://radar1.ddns.net:3080/data/aircraft.json', function (data) {
        $.each(data.aircraft, function (i, value) {

            var myLatlng = new google.maps.LatLng(value.lat, value.lon, value.flight, value.altitude);
        var marker = new google.maps.Marker({
                position: myLatlng,
                icon: 'airplane.jpg',
                map: map,
                title: "Callsign   Altitude  " + value.flight + value.altitude

            });

}

            var infowindow = new google.maps.InfoWindow({
                 content: 'Speed: ' + value.speed+  '   HEX:' + value.hex+ '   Altidtude:   ' +value.altitude + '    Vertical Rate:  ' +value.vert_rate

});

 google.maps.event.addListener(marker, 'click', function() {
 infowindow.open(map, marker);
});

        });
    });

}


text:
Q: Inheritance of nested class and visibility scope Consider following code:
namespace base {
class Base {
    protected:
        class Nested {
            protected:
                Base* base;

            public:
                Nested(Base* _base) : base( _base ){}

                virtual void test() {
                    base->foo();
                    /*
                     * hmm.. we can use protected methods
                     */
                    base->bar();
                }
        };

    protected:
        Nested* nested;

        void bar(){}

    public:
        void foo(){}

        virtual void test() {
            nested = new Nested(this);
            nested->test();
        }
};
};

namespace inherited {
class Base : public base::Base {
    public:
        Base()
            : base::Base() {}

    protected:
        class Nested : public base::Base::Nested {
            public:
                Nested( inherited::Base* base )
                    : base::Base::Nested( base ) {}

            public:
                virtual void test() {
                    base->foo();
                    /*
                     * hmm.. and now they are not accessible
                     */
                    // base->bar();
                }
        };

    public:
        virtual void test() {
            foo();
            bar();

            nested = new Nested(this);
            nested->test();
        }
};
};

My qestions is why we have access to protected methods/properties of base::Base from base::Base::Nested but no access to the same methods/properties of inherited::Base from inherited::Base::Nested?
The only thing I could suppose is that base::Base is a kind of global scope for base::Base::Nested thus they are accessible. inherited::Base is a kind of global scope for inherited::Base::Nested and protected members of base::Base are not accessible. However, public inheritance should not change scope of visibility and the reason of access inability is unclear for me.

A: The issue seems to be the type of the stored pointer and not access rights. Consider this:
class B {
protected:
  void bar();
};

class D : public B {
public:
  void call() {
    this->bar(); // works
    static_cast<B*>(this)->bar(); // does not work
  }
};

The situation is similar when you try to call bar through the
pointer that is stored in the base.
You can work around this issue by down-casting base, but I would strongly object to that.

A: §11.4/1 has this to say on access to protected members (highlighting of relevant parts by me):
An additional access check beyond those described earlier in Clause 11 is applied when a non-static data member or non-static member function is a protected member of its naming class (11.2) As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C. If the access is to form a pointer to member (5.3.1), the nested-name-specifier shall denote C or a class derived from C. All other accesses involve a (possibly implicit) object expression (5.2.5). In this case, the class of the object expression shall be C or a class derived from C.
This is not easy to interpret. Thankfully, the Standard gives a number of examples to illustrate the meaning, and one of them seems to be exactly your case (unless I misunderstood something in your code, which is quite possible):
(Note I have removed irrelevant parts of the examples, and renamed some elements for the sake of simplicity.)
class B {
  protected:
  int i;
  static int j;
};

class D : public B {
  void mem(B*);
};

void D::mem(B* pb) {
  pb->i = 1;                // ill-formed
  i = 3;                    // OK (access through this)

  /* The following cases are not directly relevant: */
  B::i = 4;                 // OK (access through this, qualification ignored)
  int B::* pmi_B = &B::i;   // ill-formed
  int B::* pmi_B2 = &D::i;  // OK
  j = 5;                    // OK (because j refers to a static member)
  B::j = 6;                 // OK (because B::j refers to a static member)
}

In other words, in
pb->i = 1;

the member i is found through pb, a pointer to the base class, hence the naming class is B. But the access occurs from mem(), which is a member of D. B is not identical to D, nor is it derived from it (although D is derived from B), so the access is not allowed.
But in
i = 3

the member is found through this, hence the naming class is D and access is allowed.


text:
Q: Pandas: Group Timeseries into parts of a day I have a timeseries that I want to group into time periods of the day.  Grouping by hour of the day is easy:
times = pd.DatetimeIndex(df[datetime_field])
grouped = df.groupby([times.hour])

Now I want to group by an arbitrary number of minutes:
times = pd.DatetimeIndex(df[datetime_field])
grouped = df.groupby(['15M'])

I was excited to see the TimeGrouper class which would accept 15M, but I don't want the timeseries resampled to be in 15 minute chunks, I want it grouped in the 'times of the day' which have a bin size of 15 minutes.
I could add a minute_of_day field and then use pd.cut to group, but that is slow and duplicates data.
Any tips are very appreciated.

A: one way (among many) to achieve that:
df.groupby([df.ts.dt.date, df.ts.dt.hour, df.ts.dt.minute//15])

Explanation:
In [52]: df = pd.DataFrame({'ts':pd.date_range('2016-01-01', freq='1min', periods=10000), 'col': np.random.randint(0,100, len(times))})

In [53]: df.head(10)
Out[53]:
   col                  ts
0   87 2016-01-01 00:00:00
1   89 2016-01-01 00:01:00
2   82 2016-01-01 00:02:00
3   37 2016-01-01 00:03:00
4   80 2016-01-01 00:04:00
5   24 2016-01-01 00:05:00
6   14 2016-01-01 00:06:00
7   32 2016-01-01 00:07:00
8   63 2016-01-01 00:08:00
9   81 2016-01-01 00:09:00

In [56]: df.groupby([df.ts.dt.date, df.ts.dt.hour, df.ts.dt.minute//15]).sum().head(20)
Out[56]:
                  col
ts         ts ts
2016-01-01 0  0   848
              1   716
              2   970
              3   767
           1  0   806
              1   760
              2   745
              3   678
           2  0   783
              1   722
              2   798
              3   713
           3  0   589
              1   773
              2   667
              3   796
           4  0   760
              1   735
              2   846
              3   660


text:
Q: DataGrid save button and CanExecute I have a datagrid and save button in XAML. I have a ObservableCollection bound to a datagrid.
If I add/remove a row in datagrid, I should be able to enable the 'Save' Button to allow the user to save records. However the ObservableCollection's NotifyCollectionChangedAction can't catch the 'edit' (i.e. value changes).  So I want to manually enable the save button when the datagrid's currentcellchanged event is invoked (i.e. set e.CanExecute = true).
Since it's not like you can set enable=true as in WinForms, WPF has this CanExecute and Executed command binding.
In my XAML:
</UserControl.Resources>

    <UserControl.CommandBindings>

            <CommandBinding Command="Save" Executed="Save_Executed" CanExecute="Save_CanExecute">
            </CommandBinding>

    </UserControl.CommandBindings>

 <Button Grid.Row="4" Content="Save" Command="Save" HorizontalAlignment="Right" Margin="5" Name="saveButton" VerticalAlignment="Center" Width="75" >

Code:
private void Save_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }
 private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = businessContractorViewModel != null && businessContractorViewModel.Entry != null;
        }

 private void businessDataGrid_CurrentCellChanged(object sender, EventArgs e)
        {
//?? how to set savebutton e.canexecute = true?

        }

A: i added a trigger, when i finish editing cell, set the bool Edited= true and postback, the save button will catch the change and set itself enable.
i don't know if it's the best, but it works for me.
private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = Edited;
        }

 private void businessDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            Edited = true;
        }


text:
Q: Visualize data in Power Bi as Matrix I have the following data:

With the matrix diagram I was able to visualize it like that:

But I want to visualize this data:

How can I get the two columns Diff and Diff%?

A: I'd create four measures to get the visualization you need. A measure called 2010 Value will calculate the 2010 sum of values; 2011 Value measure will calculate the 2011 sum of values. Diff(2011-2010) calculates the difference between 2011 and 2011 values, and Diff % calculates the porcentual difference between 2011 and 2010.
Use these DAX expressions to create the measures.
2010 Value = CALCULATE ( SUM ( [Value] ), YEAR ( 'Table'[Date] ) = 2010 )

2011 Value = CALCULATE ( SUM ( [Value] ), YEAR ( 'Table'[Date] ) = 2011 )
Diff(2011-2010) = ABS ( [2011 Value] - [2010 Value] )
Diff % = [Diff(2011-2010)]/[2010 Value]
Now you can add every measure to the Values pane in Power BI and it should provide the visualization you expect.

Note this is a static solution so if you have years different to 2010 and 2011 you have to create it manually. If you require dinamically calculate differences and other measures from the last two years in your data you have to play around with some time functions.
Let me know if this helps.


text:
Q: 3D Touch peek and touches I'm trying to implement the peek and pop actions from UIKit.
I noticed that whenever I am in the peek view, there is no way for my view controller to receive touches. This is problematic because I plan to enable user interaction in this view controller.
Any way to accomplish this?

A: Peek view purpose is to preview content of view controller. So it's clear, that preview is for previewing content, not interacting with it.

A: As mentioned in the previous answer when you peek, you cannot get touch events for that view controller but you can perform certain actions by adding previewActionItems.


text:
Q: Drupal Settings file does not exist I'm trying to set up a fresh install of drupal on on linux box and I'm getting the error:
Settings file   The settings file does not exist.
The Drupal installer requires that you create a settings file as part of the installation process. Copy the ./sites/default/default.settings.php file to ./sites/default/settings.php. More details about installing Drupal are available in INSTALL.txt.
I have set the permissions for the settings.php file but it is still doing it. sites,default and files all have 777 permissions but it still won't work. I have both the default.settings.php and settings.php in the default folder.
Thanks

A: You have to keep in mind some things:

*

*Your web server has to have the permission to run your code. If you are using Ubuntu, it would be better if you give www-data.www-data (user and group) permission to sites/default folder

*To give 777 to files is dangerous because someone else can read this sensible file

*Remember that all folders, including your Drupal root folder has to be readable, which means it has to have some thing like 755 permission.

Most time, this problem is related to the user running the web server and files.

A: Change back the settings.php permission.change settings.php permission to 755. (read only, to make protected)
Step by step:

*

*Copy file default.settings.php to settings.php (do not rename). Now you have both files.

*Change file permission settings.php to read/write with chmod 644 settings.php

*Continue the installation..

*After all installation finished, change file permission settings.php to read-only with chmod 755 settings.php
I hope it helps you

A: I have fixed that by this:
chown -Rv apache:apache /var/www

A: go to the directory that contain default.settings.php & settings.php files then, right click on each one then click on Get Info then scroll down until you see the permission of that file, make sure it's 'read & write' enter image description here


text:
Q: Is there a simpler method for getting the two digit year? EDIT: Forced to use 2008 R2
I need to get the two digit year to appended to an invoice number (for simplicity sake I am using a test variable). Previously I only needed the month and day appended but the customer is now asking for the two digit year.
My Method: REPLACE + SUBSTRING + STR + YEAR(variable DATETIME)
REPLACE((SUBSTRING(STR (Year(@Date),4),3,2)), ' ', '0')**

My code:
DECLARE @TestVariable AS VARCHAR(100),
@Date as datetime = GetDate()
SET @TestVariable = '1234'
+ REPLACE(STR(MONTH(@Date), 2), ' ', '0')
+ REPLACE(STR(DAY(@Date), 2), ' ', '0')
+  REPLACE((SUBSTRING(STR (Year(@Date),4),3,2)), ' ', '0')

PRINT @TestVariable

A: You can simplify the whole process, not just the year portion. Using FORMAT you can accomplish this easily.
DECLARE @TestVariable AS VARCHAR(100) = '1234'
    , @Date as datetime = GetDate()

Select @TestVariable + FORMAT(@Date, 'MMddyy')

A: Honestly, just don't work with 2 digit years any more; learn the lessons of last century's mistake and use 4 digits.
If you "have" to, then you could use CONVERT with a style code, and then just replace the characters with an empty string:
DECLARE @TestVariable varchar(100) = '1234',
        @Date datetime = GETDATE();

SELECT @TestVariable + REPLACE(CONVERT(varchar(8),@Date, 1),'/','');

A: select replace(convert(varchar(20),@date,1)'/','') --or any other you need

See the docs

A: I'll echo others' sentiment of "do you really have to use a two-digit year"? But if you have to, I like this sort of thing
set @TestVariable = '1234'
    + right('0' + cast(month(@date)      as varchar(2)), 2)
    + right('0' + cast(day(@date)        as varchar(2)), 2)
    + right('0' + cast(year(@date) % 100 as varchar(2)), 2);

To talk through the general approach, I'm using right('0', «something», 2) as a means to zero pad to two places, using cast(«something» as varchar(2)) to get a string instead of a number (so implicit conversion doesn't just add zero and the relevant datepart), and finally year(@date) % 100 to get the last two digits of the date.


text:
Q: Ruby, use of '?' - db or model method? I love using the ? for boolean fields, e.g, for 'animals' table "alive?" is very obvious.
Where do I define this?  Do I name the db field with it when creating the table migration(don't think so).
Or is it automatic for boolean fields or do I have a little method in the active record model class for animals that says something like def alive?  if alive then true else false end ?

A: Rails automatically generates a method ending in a ? for each of the fields in a model.
Some examples:
Animal #=> Animal(id: integer, alive: boolean, name: string)
a = Animal.new

a.alive #=> nil
a.alive? #=> false
a.alive = true
a.alive? #=> true

a.name #=> nil
a.name? #=> false
a.name = "Giraffe"
a.name? #=> true

Also note that you can easily define your own ? methods:
class Animal
  def young?
    created_at > 1.day.ago
  end
end

A: This behaviour is automatic for all boolean fields in ActiveRecord.
As an extra nicety, I like to name boolean fields with an is_ prefix. is_alive, giving you is_alive?.


text:
Q: Is it possible to download a CGI application I'm running an Apache 2.2 server, and I configured cgi applications to work properly in the folder /cgi-bin.
I was wondering what someone could do in order to "download" the application instead of executing it.
Is it possible that some misconfiguration can lead to such a scenario?


text:
Q: Why won't my game save anymore? My save function on single player seems to be completely gone.
I played for a while yesterday, yet when I opened the game today all my progress was lost and I was right back to where I started yesterday.
I have tried restarting. I have also advanced farther and saved the game again, yet when I exit the game and come back I always return to the same starting point, it never marks or saves my progress.
Is this a problem with the game or with the xbox 360?

A: I solved this problem for myself by not signing in until the game had started. Then, I signed in. When I loaded the last save, it went back to the save that I was unable to access before.

A: Something I've found online, is that it might be a problem with the date on your xbox. Check your Xbox's settings, check if the date (and time) is correct. When a game uses autosaving, it might conflict with a false date...
Have you tried saving an other game? Also an other game with autosave?
If the problem persists (especially with an other game), it might be a symptom of a broken hard drive.

A: I think it's due to the CMOS battery in the Xbox being flat, which causes my Xbox to default to 22 November at 00:00 every time I turn it on, meaning that every time it saves, the date is older than a previous save.
This probably wouldn't be a problem if I connected to Live, but I can't do that as my PC won't allow it at the moment (it used to connect via my PC, and does connect via my girlfriend's laptop, but which is onerous)
If that's the problem, you can't do much about it other than delete all your save games every time you restart Portal 2 and load the most recent save (which may not be the save the Xbox says is most recent).

A: I had this problem too! I was getting so mad because I played so many levels at one time and then save and came back the next day to start all over. To fix it go to load game and try to find the farthest saved file. I dont know why but I found my last save was about the fourth one down while the first auto load game was from awhile back.


text:
Q: Adjust iPhone 5 Screen Size Without Using Autolayout Enabling Autolayout in .xib or .storyboard and adding a splash screen of 640px by 1136px enables iPhone 5 resolution support for the taller screen.
However, doing so, my app started to display some funny things where I assume autolayout is not a great idea.
I am wondering if there is a way to enable iPhone 5 device support, i.e. fix app's resolution without using Autolayout? Maybe I can set in the code?
If yes, then I will have no need to create 2 storyboards or nibs to support iOS5- and iOS6.

A: If you weren't using Autolayout before, you won't need to use it for iPhone 5 support.
When you're putting your interface together, you just need to check your bindings, and toggle between the taller phone size, and the regular phone size, as described here:
Xcode Storyboard displaying the new iPhone 5 screen size?
If your screens look fine in both screen sizes then you're done.
If you are doing a lot of coding to show your UI, then you'll have more work to do.

A: I found a great answer a couple weeks ago (link below). You will copy and paste your older iPhone Storyboard, rename it to reflect the iPhone 5, and press the button that expands the screen size, found on the bottom of the layout grid. Some minor coding adjustments might be needed, but this sample code is used in the AppDelegate to detect which device is running, and hence, which Storyboard to use. You'll just have to duplicate your interfaces, but these GUI changes can be made without code and without AutoLayout (also good to note that AutoLayout removes iOS 5--and lower--compatibility)
xcode 4.5 how to pick storyboards at launch


text:
Q: Shading applied only to the first element with foreach I want to apply the same shading to multiple rectangles. Here is a MWE of the code I use (for a sample of 3 rectangles):
\documentclass{article}

\usepackage[letterpaper,textwidth=8.5in,textheight=11in]{geometry}
\usepackage{lscape}

\usepackage{tikz}
\usetikzlibrary{fadings}

\begin{document}
\pagestyle{empty}
\begin{landscape}
\begin{figure}
\centering
\begin{tikzpicture}[scale=1]

\coordinate(A) at (1.5,4);

\foreach \x in {0,1,2}
\shadedraw [thick, left color=white, right color=black] (A) ++(6*\x,0) rectangle +(1,-0.35);

\end{tikzpicture}
\end{figure}
\end{landscape}
\end{document}

Nevertheless, here is what I get with this code:

Only the first rectangle is shaded... How can I solve this problem?

A: This is indeed rather esoteric but the action (A) ++(x,y) is actually counting the (A) as a part of the path and what you see is the whole fading strip punched and viewed through 3 holes. Because each of them actually takes (A) into account for the fading even though you don't draw anything in between.
You can fix it via ([xshift=6*\x cm]A) or with calc library syntax ($(A)+(6*\x,0)$) and so on. As long as you don't modify the path pen you are good to go.

A: Just playing...
\documentclass[tikz,border=5pt]{standalone}

\usetikzlibrary{fadings}

\begin{document}
  \begin{tikzpicture}

    \coordinate(A) at (1.5,4);
    \foreach \x in {0,1,2}
    \shadedraw [thick, left color=white, right color=black] (A) ++(6*\x,0) rectangle +(1,-0.35);

    \coordinate(b0) at (-4.5,2);
    \path [draw, thick, left color=white, right color=black] foreach \x [count=\i] in {0,1,2} {(b\x |- b0) ++(6,0) coordinate (b\i) rectangle ++(1,-0.35)};

    \coordinate(C) at (1.5,0);
    \foreach \x [count=\i] in {0,1,2}
      \shadedraw [thick, left color=white, right color=black] ([xshift=6*\x cm]C) rectangle +(1,-0.35);

    \coordinate(D) at (1.5,-2);
    \foreach \x in {0,1,2}
    \path (D) ++(6*\x,0) node [minimum height=3.5mm, minimum width=10mm, inner sep=0pt, anchor=north west, thick, draw, left color=white, right color=black] {};

  \end{tikzpicture}
\end{document}


text:
Q: Return value from helper file to another file I have a helper file and I am getting the correct values from the function, which is an extension.
extension IAPHelper: SKProductsRequestDelegate
{

    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse)
    {

        self.products = response.products

        for product in response.products
        {

            print(product.price)

        }

    }

}

I have an another ViewController, in which there is a table cell. I want to pass this price to that cell. How can I do it?

A: There is multiple ways to achieve this, but completion handler is the way i prefer most.
create a var completionHandler in your IAPHelper class, and perform its work after getting your values:
Declare completionHandler in your calls as below:
var completionHandler: (([NSNumber])->Void)?

You can use this in your SKProductsRequestDelegate method of IAPHelper to perform:
var prices :[NSNumber] = []
for product in response.products
{
    print(product.price)
    prices.append(product.price)
}
if let handler = completionHandler {
   handler(prices)
}

To get values in your another ViewController or any other class just do:
   let helper = IAPHelper()
    helper.completionHandler = {
        (val:[NSNumber] ) in
            print(val)
    }

A: In ViewController contains tableView
for product in response.products {
self.items.append(product.price)
}
tableView.reloadData()


text:
Q: Bash cannot echo $(hostname) embedded in variable If I echo a string which contains the $(hostname) command, then it works fine. For example, run in terminal:
echo "http://$(hostname)/main.html"
http://artur/main.html

But if I get that string from a file (previously doing cat to a variable) when I try to print with echo, it does not works:
$ cat site
http://$(hostname)/main.html
$ mysite=$(cat site)
$ echo $mysite
http://$(hostname)/main.html

What am I doing wrong? Any idea?

A: The shell performs variable expansion and the shell performs command substitution but it does not do them recursively:

*

*The result of a variable expansion will not be subjected to any further variable expansion or command substitution.

*The result of a command substitution will not be subjected to any further variable expansion or command substitution.
This is a good thing because, if it was done recursively, there would be all manor of unexpected results and security issues.
One solution is to use eval.  This is a generally dangerous approach and should be regarded as a last resort.
The safe solution is to rethink what you want.  In particular, when do you want hostname evaluated?  Should it be evaluated before the site file is created?  Or, should it be evaluated when the code is finally run?  The latter appears to be what you want.
If that is the case, consider this approach.  Put %s in the site file where you want the host name to go:
$ cat site
http://%s/main.html

When you read the site file, use printf to substitute in the host name:
$ mysite=$(printf "$(cat site)" "$(hostname)")
$ echo "$mysite"
http://artur/main.html

With bash, an alternative for the form for the above is:
$ printf -v mysite "$(< site)" "$HOSTNAME"
$ echo "$mysite"
http://artur/main.html

A: If you only need the placeholder 'hostname' to be replaced by actual hostname, you could use either of these methods:
With your existing site file:
$ cat site
http://$(hostname)/main.html
$ mysite=$(sed 's|\$(hostname)|'"$(hostname)"'|g' site) # or
$ mysite=$(awk '{print gensub("\\$\\(hostname\\)",hostname,"g", $0);}' "hostname=$(hostname)" site)
$ # Note: Above `sed` based method has risk of shell injection. `awk` option is safer.
$ echo "$mysite"
http://artur/main.html

Or if you don't mind changing your site file contents, there is a tool, which is typically used for such purposes - to replace placeholders by actual values: m4 - macro processor
$ cat site
http://HOSTNAME/main.html
$ # HOSTNAME is the placeholder here; can be any identifier string.
$ mysite=$(m4 -D "HOSTNAME=$(hostname)" site)
$ echo "$mysite"
http://artur/main.html


text:
Q: iPad breadcrumb control? I am looking for a breadcrumb style navigation controller for iPad.  Specifically I would like to know if the control in this picture actually exists or is made with custom images:
http://iconlibrary.iconshock.com/wp-content/uploads/2010/04/ipad-vector-buttons-GUI.jpg
The control I'm talking about is towards the top of the image with the home icon followed closely by buttons with the text "label".  The closest thing I can think of is a UISegmentedControl, but that doesn't have the borders that point backwards.

A: There is no UIKit framework for that particular behavior, and I'm not aware of any open source software that would do so.
Depends on how exactly you'd like to implement it, but you could use a UINavigationController with a custom toolbar at the top.


text:
Q: Mongoose opens 2 connections to DB on second request I'm writing a small Node to just monitor MongoDB by making a simple query via Mongoose. If something is returned, the service is deemed as available. Here is my script
var res;
var logPrefix = '[MongoDB]';
var counter = 0;

var mongoose = require('mongoose');
// Simple schema and model for getting a companyprofiles document
var companyProfile = new mongoose.Schema({
    _id: String
});
companyProfile.virtual('Id').get(function () {return this._id});

function closeConnection() {
    console.log('8');
    mongoose.connection.close(function () {
        console.log('9');
        console.log('%s Closed connection%d', logPrefix, counter);
    });
}

function connectAndCheckHealth() {
    console.log('2');
    mongoose.connect('mongodb://localhost:27017/testdb');

    console.log('3');
    mongoose.connection.on('error', function(err) {
        console.log('%s Error connecting to DB:\n%s %s', logPrefix, logPrefix, err);
        res.send(503, 'ERR');
    });

    mongoose.connection.on('open', function() {
        mongoose.connection.db.serverConfig.options.auto_reconnect = false;
    });

    console.log('4');
    mongoose.connection.on('connected', checkHealth);

    console.log('5');
    mongoose.connection.on('close', function() {
        console.log('%s Connection to MongoDB closed %d', logPrefix, counter);
    });
}

function checkHealth() {
    console.log('6');
    cpModel = mongoose.model('companyProfile', companyProfile, 'companyprofiles');
    cpModel.findById('spin', handleModelResponse);
}

function handleModelResponse(error, doc) {
    console.log('7');
    closeConnection();
    console.log('10');
    if (error !== null) {
        console.log('11');
        console.log('%s Error handling response from model:\n%s %s', logPrefix, logPrefix, error);
        res.send(503, 'ERR');
    } else {
        console.log('12');
        if (doc.Id.match(/company1/)) {
            console.log('13');
            console.log('%s App status is ok', logPrefix);
            res.send(200, 'OK');
        } else {
            console.log('14');
            console.log('%s Couldn\'t find the spin company profile. Found %s', logPrefix, doc.Id);
            res.send(503, 'ERR');
        }
    }
}

module.exports = {
    health: function(response) {
        counter++;
        var date = new Date();
        console.log('%s Retrieving health from MongoDB at %s', logPrefix, date);
        res = response;
        console.log(mongoose.connection);
        console.log('1');
        connectAndCheckHealth();
        console.log('15');
    }
}

As you can see, I've peppered the script with console.log lines with numbers to try and work out the control flow. Here's the output:
1
2
3
4
5
15
6
6
6
7
8
[MongoDB] Connection to MongoDB closed 3
[MongoDB] Connection to MongoDB closed 3
[MongoDB] Connection to MongoDB closed 3
9
[MongoDB] Closed connection3
10
12
13
[MongoDB] App status is ok
7
8
9
[MongoDB] Closed connection3
10
12
13
[MongoDB] App status is ok

/home/GTP/healthcheck/node_modules/mongoose/lib/utils.js:413
        throw err;
              ^
Error: Can't set headers after they are sent.

Notice that 6 appears three times (the callback after we have connected). I can't tell why we are opening multiple connections. I've turned autoconnect off and am closing the connection after every request.
Any help would be greatly appreciated.

A: Mongoose opens a pool of 5 connections by default; if you only want a single connection you can change your connect call to be:
mongoose.connect('mongodb://localhost:27017/testdb', { server: { poolSize: 1 }});

A: db.once('open') worked for me.
While testing my page, I had noticed that double and rapid form submits were triggering errors about the headers already sent.  This stopped that.


text:
Q: Stripping code of #define I'm looking at a ton of code like this:
#define CONSUMPTION_MODE_MOBILE 0
#define CONSUMPTION_MODE_WIFI 1
#define CONSUMPTION_MODE_COMBINED 2

What would be the best to change this to? Enum? Individual const int's? Or something else?
I have little experience of preprocessor stuff (and not that much with Xcode, so consider this a close-to-noobie question), but I am reasonably sure I don't need this hanging round the codebase I've inherited. Not sure what is best practice, however.

A: "Best" is a very subjective concept, the best that you could hope for :-) would be to understand the pros and cons of each possibility.
There's absolutely nothing wrong with using #define like that to create constants, the only thing I don't like about it is that you often don't get the "symbols" passed all the way through to a debugger. But that's actually nothing to do with the language per se, more to do with the build tools you're using.
And there's certainly nothing wrong with leaving code alone if it works fine. I wouldn't be changing something just because you think there's a cleaner way, since that always runs the risk of introducing new problems.
If you find yourself ever having to make substantial changes to the relevant code for some other reason, that's when I'd consider cleaning up as well, tempered against the possible impact it may have elsewhere.


text:
Q: Ruby specifying regexp How would I write a regexp so that the string MUST equal the exact format in the regexp?
For example:
/\d:\d/ =~ 5:4

BUT
/\d:\d/ is also equal to 5:42alskjf2425

how do I make it so that my regexp checks for only a digit, followed by a colon, followed by a digit, and nothing else?
Thanks.

A: Use \A and \z anchors, to match the beginning and end of a string:
/\A\d:\d\z/ =~ '5:4'  # => 0   (boolean true)
/\A\d:\d\z/ =~ '5:4x' # => nil (boolean false)

A: If you need to specify how many characters must be found, you can do it a couple ways:

*

*\d finds one.

*\d{1} finds one.

*\d{1,2} finds one or two.

*\d{1,} finds one or more.

*\d{,2} finds zero, one or two.

In other words, use:
/\d{1}:\d{1}/

Check it out:
'5:4'[/\d{1}:\d{1}/]             # => "5:4"
'5:42alskjf2425'[/\d{1}:\d{1}/]  # => "5:4"

That's all documented so take the time to read through the Regexp documentation.


text:
Q: remove item from a map of string I have a map of string Map<String, String> data = {}; and I added user input items and store it in the map. but when I try to remove the item the key/id changes and the value becomes null.
this is what I have when I added the items and remove them after.
//called on onChanged
if (data.containsKey('$index') && value != null) {
   data['$index'] = value!;
}

//called on remove
data.remove('$index');
data.removeWhere((key, value) => key == "");

//added result
print(${json.encode(data)});

before remove called=> {"0":"Manager","1":"Service","2":"Sales","3":"Reception"},
after remove called=> {"0":"Manager","1":"Service","3":"Reception","4":""}
what should be => {"0":"Manager","1":"Service","2":"Sales"}
so what is the problem here?

A: Use .remove(key) to remove all key along with its value.
  final data = {
    "0": "Manager",
    "1": "Service",
    "2": "Sales",
    "3": "Reception"
  };
  data.remove("3");
  print(data); //{0: Manager, 1: Service, 2: Sales}
});

More about /Map/remove


text:
Q: Need batchfile to separate & move characters and numbers in textfile first post here since usually I can find my solution by just using google. But this time, nope. First of, OS is Windows 7, and it definitely has to be done within a batchfile - but additional scripts is no problem, as long as it's no software which requires installation.
I get files which are always looking like this, but the values are never the same.
Example\Example\Example\examplefile.ext
1 0
4 16 7 5 3 9
46215
0
20689
20656
20667
6125
33585
46213
10256
20661
40189
21650
49792
31776
2101
(blank line)
(blank line)

the last 2 lines "(blank line)", are as a matter of fact - blank lines.
Now, what I need the output file to look like, is this:
<A:Example\Example\Example\examplefile.ext>
<B:1 0>
<C:4>
<D:16>
<E:7>
<F:5>
<G:3>
<H:9>
<I:46215>
<J:0>
<K:20689>
<L:20656>
<M:20667>
<N:6125>
<O:33585>
<P:46213>
<Q:10256>
<R:20661>
<S:40189>
<T:21650>
<U:49792>
<V:31776>
<X:2101>

So, thats how I need the output. All help would be very much apprieciated.

A: This will do what you want.
Notes

*

*This will only support a file with at most 26 items. (A-Z)

*The second line will never be separated.

Script
@echo off
setlocal EnableExtensions EnableDelayedExpansion
>output.txt <nul set /p "="
set "A=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for /f "tokens=*" %%A in (Example\Example\Example\examplefile.ext) do (
    if "!A:~0,1!" equ "B" (
        echo ^<B:%%A^>>>output.txt
        set "A=!A:~1!"
    ) else (
        for %%B in (%%A) do (
            echo ^<!A:~0,1!:%%B^>>>output.txt
            set "A=!A:~1!"
        )
    )
)
endlocal


text:
Q: Creating points along line based on line lengths I have a road network network (polyline shape layer) with multiple line lsegments. Each line segment has different line length as shown in image 1.

*

*I am trying to generate points along lines based on specific distance. For instance, If the length of lines is less than 80 meters generate one point along line else two points for higher lengths.

*I tried to generate points along lines by using PyQGIS as the script is given below. The problem is, it generate only midpoints of lines by dividing the line.

I searched some of the existing answers: answer 1, answer 2, answer 3. But the problem is these solutions are only generating random points along line without considering length of line.
layer = iface.activeLayer()

temp = QgsVectorLayer("Point?crs=epsg:4283", "result", "memory")
temp.startEditing()

attrs = layer.dataProvider().fields().toList()
temp_prov = temp.dataProvider()
temp_prov.addAttributes(attrs)
temp.updateFields()

for elem in layer.getFeatures():
    feat = QgsFeature()
    geom = elem.geometry().interpolate(elem.geometry().length()/2)
    feat.setGeometry(geom)
    feat.setAttributes(elem.attributes())
    temp.addFeatures([feat])
    temp.updateExtents()

temp.commitChanges()
QgsProject.instance().addMapLayer(temp)

A: We can check the length of line from the 'length' attribute and then add an if statement to capture the lines where the length is <80 and create a point at 1/2 the length.
Otherwise, else,  generate a point at 1/3 and at 2/3 of the length of the line.
layer = iface.activeLayer()

temp = QgsVectorLayer("Point?crs=epsg:4283", "result", "memory")
temp.startEditing()

attrs = layer.dataProvider().fields().toList()
temp_prov = temp.dataProvider()
temp_prov.addAttributes(attrs)
temp.updateFields()

for elem in layer.getFeatures():
    feat = QgsFeature()
    #read length field of feature
    len = elem["length"]
    #print (len)
    #if length is <80
    if len < 80:
        geom = elem.geometry().interpolate(elem.geometry().length()/2)
        feat.setGeometry(geom)
        feat.setAttributes(elem.attributes())
        temp.addFeatures([feat])
        temp.updateExtents()
    else:
        #get one 1/3 of line length
        geom = elem.geometry().interpolate(elem.geometry().length()*(1/3))
        feat.setGeometry(geom)
        feat.setAttributes(elem.attributes())
        temp.addFeatures([feat])
        # get one 2/3 of line length
        geom = elem.geometry().interpolate(elem.geometry().length()*(2/3))
        feat.setGeometry(geom)
        feat.setAttributes(elem.attributes())
        temp.addFeatures([feat])
        temp.updateExtents()

temp.commitChanges()
QgsProject.instance().addMapLayer(temp)


text:
Q: H2 + Hibernate with non nullable String stores empty string I'm currently migrating some existing code from Hibernate 3.2 to Hibernate 3.6.10.Final
(and also from Spring 2.0 to Spring 3.1.2 by the way).
I have an issue with some integration tests running against H2 database, verifying that some fields are not nullable.
- I test that an attempt to insert a null String into a field marked as nullable=false ends with an Exception
- I checked that the schema is correctly created : the column is not nullable.

*

*Using H2 (with MySQL mode), nullable constraint is ignored : an empty String is inserted in database.

*I don't reproduce the case if I run my test against a MySQL database.

*It worked before with Hibernate 3.2

For example, if I have a class Person :
@Entity
class Person {
    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable=false)
    private String name;

    //getters and setters

}

And then I have a test (still using JUnit3, I'll migrate this later) :
@ExpectedException(value=DataIntegrityViolationException.class)
public void testPerson_NameCantBeNull() throws Exception {
    // Given
    Person person = new Person();
    person.setName(null);

    // When
    getHibernateTemplate().persist(person);
    //Flush and clear session
}

I could fix this by replacing nullable=false by @NotNull annotation but I don't want to replace it in my huge code base as I wouldn't expect the same Exception.
I had a quick look into H2Dialect class and JIRA issues in Hibernate but I didn't find anything.
Does anybody know where it comes from ?
EDIT :
Some additional informations, I added the TRACE level in Hibernate logs.

*

*When I insert null and the field is marked with @Column(nullable=false), I have the following log :
2013-01-16 15:57:52 TRACE [BasicExtractor] found [] as column [NAME1_3_]

*When I insert null and the field is not marked with @Column(nullable=false), I have the following log :
2013-01-16 15:57:52 TRACE [BasicExtractor] found [null] as column [NAME1_3_]
EDIT (22/01/13) :
I still didn't found where the problem exactly come from, but I found out that it is tied to MySQL mode with H2 : if I disable MySQL mode, Hibernate doesn't try anymore to replace my null Strings by empty Strings.
But I can't do this since some other pieces of code are tied to MySQL syntax.
Any idea ?

A: I didn't have enough time to digg in Hibernate and MySQL dialect, so I moved to Java Validation Framework, using @NotNull annotation.
It does the job and meets one of our other requirement : a part of our model is used in a Grails application and we want to use constraints to validate part of CRUD operations (not possible with pure javax.persistence annotations).


text:
Q: Understanding jQuery's jqXHR I have a set of $.get() requests that I need to refactor to include a failure callback.  The requests are of the form
$.get(url,
      {},
      function(data) {//success, do work
      //work
      },'json');//or 'html'

According to the jQuery API, I simply add a jqHXR object.  So in my case, I believe I should do
var jqxhr =  $.get(url,
          {},
          function(data) {//success, do work
          //work
          },'json').error(function() { alert("error"); });//or 'html'

I don't understand the reason for the second success callback in the example.  I suppose it could be there for setting up a callback chain.  I want error to execute in error, and success to execute on success.  So, is this correct?

A: This page has a lot of documentation on how jqXHR (jQuery XHR) differs from XHR (XMLHttpRequest).
http://api.jquery.com/jQuery.ajax/#jqXHR

A: The code you are using should be fine. The second success is just another place where you can define a success method. Some people use the jqxhr success instead of the one passed into $.get(), and others use the deferred object's done handler to do the same.

A: I think the second success callback in the example is just there to illustrate that, using this syntax, you can have multiple handlers for success, error, and complete events. In the standard jQuery .ajax() method, you can only assign a single handler to each of these events. I can't think offhand of an example that would require multiple handlers, but it does seem a little clearer and more like the standard jQuery idiom to use
$.get('my_url.php')
    .success(handlerOne)
    .success(handlerTwo);

instead of
$.get('my_url.php', function(data, textStatus, jqXHR) {
    handlerOne(data, textStatus, jqXHR);
    handlerTwo(data, textStatus, jqXHR);
});

In your case, though, it might be easier and cleaner to just convert your $.get() statements to $.ajax(). The $.ajax() syntax is probably more familiar to most jQuery programmers, and since you don't need the special functionality (multiple handlers, post-request handler assignment) available in the other syntax, there's no reason not to just use $.ajax():
$.ajax({
    url: url,
    success: function(data) {
        // success, do work
    },
    error: function(data) {
        // error, handle failure
    },
    dataType:'json'
});


text:
Q: Cannot retrieve the principal from the client x509 certificate I am using Spring security in my web application and am using x509 certificates for authentication.
<x509 subject-principal-regex="CN=[^,]* ([^,]*),.*$" user-service- ref="MyAuthService"  />

Everything works fine and I can retrieve my principal and get it in my Java class.
My trouble starts when there are infrastructure level changes on the environments (server migrations and security changes etc). I am no longer able to retrieve this information.
What I would like to do is to debug what headers / subject I am getting from the x509 certificate in order to see if I need to change the regex to retrieve the principal.
But I don't know how to do that in spring security. How can I say log the complete header / subject from the x509 certificate at the application level. I am using spring security 3.1

A: If you wish to see more details of the certificates as they are processed, it's worth noting that the Spring code to implement these filters does implement debug logging. For instance, the X509AuthenticationFilter logs the result of toString() on the X509Certificate object:
logger.debug("X.509 client authentication certificate:" + certs[0]);

Likewise, the SubjectDnX509PrincipalExtractor logs the subjectDN that it extracts from the certificate and the username that it has determined.
Given that this is the case, if you are using Log4J, you could get these in your log files by putting the following in your log4j.xml config file.
<logger name="org.springframework.security.web.authentication.preauth.x509">
    <level value="debug" />
</logger>

Other logging frameworks will have similar mechanisms for enabling debug logging of particular classes or packages.


text:
Q: Why is CSS file canceled? I'm doing a simple node project to practice but i can't manage to serve html file with its css styles. I asked the same question before on SO but I didn't mention that the status of css file was "canceled" in the developer tools. When I edited it nobody answered about why it is canceled, so i wish someone help me with this. It is making me crazy.
Here is my app.js code:
    app.use("/signup", express.static("public"));
app.get("/", (req, res)=>{
 res.send("Welcome to our website");
});

app.get("/signup", (req, res)=>{
 res.sendFile(`${__dirname}/index.html`)
})

Here is my html code:
<head>
    <title>testapp</title>
    <link href="./public/styles.css" type="text/css" rel="stylesheet"/>
</head>
<body>
    <form method="post" action="/signup">
        <input type="text" placeholder="*First Name" required></input>
        <input type="text" placeholder="*Last Name" required></input>
        <input type="number" placeholder="*Age" required></input>
        <input type="email" placeholder="*Email" required></input>
        <input type="submit" value="Submit" required></input>
    </form>
</body>

When I remove the get method of "/signup", and put my index.html in the public directory while updating the link to css, it works just fine, but i don't want it in the '/' route. And also when opening the index.html file without the localhost, it works fine.
I searched about it and found someone who had kind of the same issue asked about on SO, I think that the answers aren't right in my case, i'm not sure and i didn't understand well.What does status=canceled for a resource mean in Chrome Developer Tools?.
Thank you in advance.

A: Read the documentation about static serving here : https://expressjs.com/en/starter/static-files.html
You don't need to specify /public in your css link; just do as following :
<link href="/styles.css" type="text/css" rel="stylesheet"/>


text:
Q: how can i separate filter by function from header text or v-text-field in Vuetify v-data-table As you can see in this codepen link, I have replaced the header text with v-text-field but the problem is the v-text-field is attached with filterBy icon (the up-down arrow icon) as well. When i click on the text-field the filterBy function is working that i dont want. So far I think the @click event is covering whole area. I wish to separate the text-field and filterBy behavior. Any help will be greatly appreciated.
https://codepen.io/MicroDreamIT/pen/vYRvMza

A: You can disable the filter option on v-table columns by using the property 'sortable'.
Your headers data should look like that :
headers: [
      {
        text: "Dessert (100g serving)",
        align: "left",
        value: "name",
        sortable: false // this will disable filter property and hide the icon
      },
      { text: "Calories", value: "calories", sortBy: true },
      { text: "Fat (g)", value: "fat" },
      { text: "Carbs (g)", value: "carbs" },
      { text: "Protein (g)", value: "protein" },
      { text: "Iron (%)", value: "iron" }
    ],


text:
Q: All namespaces in one line How can I achieve that all namespaces are in one line, so that this

becomes this

These are my clang format settings:
---
AccessModifierOffset: '0'
IndentWidth: '4'
BreakBeforeBraces: Linux
KeepEmptyLinesAtTheStartOfBlocks: 'false'
SpaceBeforeParens: Never
TabWidth: '4'
UseTab: Always
ColumnLimit: 0
...

A: You can't; from the clangformat page the only thing you can change is the indentation.
I suspect it's not a particularly common desire to put everything on one line as it becomes harder to ensure that your {} line up.


text:
Q: R function scope: want to see the return value on next iteration I am trying a code a linear algebra exercise on eigenvalues, where I pass a vector to a matrix, get a another vector back, then pass that vector back again to the same matrix; I am supposed to get a steady-state value for the vector.
this is my reproducible example version of that:
M <- 2
v <- c(2,4,6)
c <- c()
funscope <- function(){
  c <- (M * v)/max(v)
  # want to return c and send it back in as 'v'
  #?
}
replicate(2, funscope())

want to get (in decimal form) these two vectors:
[4/6, 8/6, 12/6], [8/12, 16/12, 24,12]

A: Doing recursive iteratin like this is often easiest in a loop, but the Reduce function can help here too. Here's a simple wrapper to make it easier to work with in this scenario
iterfun <- function(f, start, N=1) {
  Reduce(function(prev, curr) {
    f(prev)
  }, rep(1, N), init=start, acc=T)[-1]
}

This will take a function and repeatedly perform it on itself.
If we define your function as a proper function and start out with
M <- 2
v <- c(2,4,6)
funscope <- function(v){
  (M * v)/max(v)
}

We can run it with
iterfun(funscope, v, N=2)
# [[1]]
# [1] 0.6666667 1.3333333 2.0000000
#
# [[2]]
# [1] 0.6666667 1.3333333 2.0000000

As a traditional loop, we might do
N <- 2
out <- vector("list", N)
x <- v
for(i in 1:N) {
    x <- funscope(x)
    out[[i]] <- x
}

A: Usually one wants to stop based on a test for convergence rather than using a fixed number of iterations.  This will iterate up to N times stopping when the maximum difference of two successive iterations is less than eps.  At the end cc contains the value converged to, maxabseps contains the error and i contains the number of iterations run.
M <- 2
v <- c(2,4,6)
N <- 100 # max no of iterations
eps <- 1e-5  # abs error

c <- v
for(i in 1:N) {
   cc <- (M * c) / max(c)
   maxabsdiff <- max(abs(cc - c))
   cat(i, "maxabsdiff:", maxabsdiff, "vector:", cc, "\n")
   if (maxabsdiff < eps) break
   c <- cc
}

giving this output:
1 maxabsdiff: 4 vector: 0.6666667 1.333333 2
2 maxabsdiff: 0 vector: 0.6666667 1.333333 2

A: The function replicate simply repeats the expression a number of times. No information is exchanged between the different calls to funscope.
If you want to assign a value to a global variable (i.e. a variable outside of the function), use v <<- c.
There is however a trick to you linear algebra:
v %*% M = c_1
c_1 %*% M = c_2
c_2 = v %*% M %*% M = v %*% M^2

A: An alternative version based on your custom function and a for loop used for populating a list. You can use the C list to store results and use them for the next iterations.
# your function
funscope <- function(M, V){
  (M * V)/max(V)
}

# some starting params
M <- 2
V <- c(2,4,6)
C <- list()

# a foor loop to populate the list
for (i in 1:2) {
  if (i == 1) {
    C[[i]] <- funscope(M, V)
  } else {
    C[[i]] <- funscope(M, C[[(i-1)]])
  }
}

Results are stored in C
# print to console
C

[[1]]
[1] 0.6666667 1.3333333 2.0000000

[[2]]
[1] 0.6666667 1.3333333 2.0000000

If you want to get them as a matrix, you can simply rbind (row-wise) or cbind (column-wise) them.
do.call(cbind, C) # rbind or cbind


text:
Q: Compact set of $\mathbb{R}^n$ is bounded and closed. (proof verification) Want to show: If $X$ is a compact set of $\mathbb{R}^n$ then $X$ is closed and bounded.
I was able to show it was bounded but I was unsure whether my proof of showing $X$ was closed was correct.
my attempted proof: I want to show $\mathbb{R}^n \backslash X$ is open.  Let $a \in \mathbb{R}^n \backslash X$.  Then since $X$ is closed it contains all its limit points.  Since $a$ is not in $X$, then $a$ is not a limit point of $X$, so there exists a open $U$ containing $a$ such that $U\backslash\{a\}  \cap X = \emptyset$, which implies $U \cap X = \emptyset$.  It follows that $a \in U \subset \mathbb{R}^n \backslash X$, concluding my argument.
I was wondering if this was a valid arugment, since most of the proofs I have seen in textbooks and online involve explicitly finding a $\epsilon$ such that $a$ is contained in the open ball around $a$ of radius $\epsilon$.
Much appreciated

A: Thanks to @Thorgott.  I used the fact that the set was closed in my argument which was what I was trying to prove.


text:
Q: how to collapse all previous nested view when onclick current view in android my layout code is below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/invitation_single"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="?android:dividerVertical"
    android:dividerPadding="5dp"
    android:showDividers="middle"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_action_event" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:clickable="false"
        android:focusable="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/invitation_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:paddingRight="0dp"
            android:paddingTop="3dp"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/invitation_place"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:paddingRight="0dp"
            android:textColor="@color/black"
            android:textSize="15sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/hidden"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginLeft="-270dp"
        android:layout_marginTop="60dp"
        android:layout_weight="1"
        android:clickable="true"
        android:focusable="true"
        android:orientation="horizontal"
        android:paddingTop="1dp"
        android:visibility="gone"
        android:weightSum="3">

        <Button
            android:id="@+id/yesbutton"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="7dp"
            android:layout_weight="1"
            android:background="@color/blue"
            android:text="Yes"
            android:textColor="@color/black"></Button>

        <Button
            android:id="@+id/nobutton"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="25dp"
            android:layout_weight="1"
            android:background="@color/blue"
            android:text="No"
            android:textColor="@color/black"></Button>

        <Button
            android:id="@+id/buttonmaybe"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="25dp"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:background="@color/blue"
            android:text="Maybe"
            android:textColor="@color/black"></Button>

    </LinearLayout>

In above code "invitation_single" is root layout  and "hidden" is nested layout.
my programming code is below
final LinearLayout first = (LinearLayout) convertView.findViewById(R.id.invitation_single);
 final LinearLayout second = (LinearLayout) convertView.findViewById(R.id.hidden);
 first.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.invitation_single:
 second.setVisibility(second.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
   break;

                    }

                }

            });

My root layout(invitation_single) have two "textviewes" and nested layout(hidden) have three "buttons".When i am on tap my root layout the nested layout visible immediately below the root layout.In my output i have two events when i am on tap first event the nested layout(buttons) visible similarly if i am on click second event i need to hide the nested layout of previous event and show the nested layout of current event(that means i need to visible the nested layout of current event and close all other nested layouts).how can i achieve this help me.

A: Playing with View.GONE and View.VISIBLE is tricky. When the view is gone, it does not simply come back, it can mess up everything. One simple solution to get it back is to re-call setContentView after changing from View.GONE to View.VISIBLE. Make sure you save the contents of your views before calling setContentView and then refresh them with the saved values after calling setContentView.
Some people choose to call onCreate(null) which also does the job. In both case you need to save and restore the contents of your views.
Another alternative is to use LayoutInflater.
Example (not tested)
    first.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.invitation_single:
                    if(second.getVisibility() == View.VISIBLE){
                        second.setVisibility(View.GONE);
                    }else{
                        // save the content of your views
                        setContentView(....); // call as you called in onCreate or whatever
                        // restaure the content of your views.
                    }
                break;

            }

        }

    });


text:
Q: Angular JS RouteProvider does not call I'm working on an e-commerce like webapp to learn Angular. I have a menu on my home page (common and visible on all pages), which provides available products for e.g. Books, Clothes etc.
On my menu I have list items as follows:

Computers

Academics & Professional

searchProduct function in my first controller sets the selected product in scope and sets the location.path.
$scope.searchProduct =function(productTBSearched){
            $scope.TBFProduct=productTBSearched;
            $location.path("/SearchProducts");
        }

I also have route provider in my first controller which refers to another html and 2nd controller.
$routeProvider.when("/SearchProducts", {
    templateUrl: "./views/HomeSearchProducts.html" ,
    controller: "productSearchCtrl"
});

In my second controller, I call a REST WS to search DB and build my Response JSON. The issue is when I click on the first item on menu at home page, I get search results and I can see my URL gets changed to  ".......Index2.html#/SearchProducts"
Now at this page when I try to choose another menu item, Routeprovider does not call the "ProductSearchCtrl" again and no Ajax call is executed for newly selected item. Could anyone help on this?

A: I think you are trying to reload the route. You can update your code to something like below in order to reload the route.
$scope.searchProduct =function(productTBSearched){
    $scope.TBFProduct=productTBSearched;
    if($location.path() === "/SearchProducts") {
        $route.reload();
    } else {
        $location.path("/SearchProducts");
    }
}


text:
Q: How to set automatic deletion of folder with Box REST api V2? I want to set automatic delete date for a folder in Box through REST api. I don't see any option for it now? Is it possible through Box v2 api?

A: What is the particular use case? If it's to prevent a user from having access to a folder, perhaps setting an unshare date may work for you? I don't believe you can do the same for the deletion of a folder.
Is creating a service with a timer job that executes the delete folder request out of the question?


text:
Q: postMessage not working across different domains using React.js On Sender side (localhost:3000):
 const handleExportJSON = () => {
    let win = window.open("http://localhost:3001");
    win.postMessage("Hello there", "http://localhost:3001");
  };

Receiving Side (localhost:3001):
  componentDidMount() {
    window.addEventListener("message", this.receiveMessage, false);
  }

    receiveMessage = event => {
        console.log("Event is", event);
        // if (event.origin !== "http://im-amir/github.io/origin1") return;
    };

    render(){
        return
    ....
}

No data is logged on receiver side. Even the event parameter is not logged.
I have also tried "*" in postMessage as a second parameter.
Any help will be appreciated.


text:
Q: c# linq join on a sublist in a list I have a list:  var_assets_root that has a nested sub list: contents.  I can do a join on the root list and augment it with extra items from the two other lists lst_invtypes_assets and lst_stations_composite_retribution by doing two joins on index items in var_assets_root.  But I also want to do a join on the items that are within the sublist var_assets_root-->contents\b.contents which the code below is not doing so far.
Image>>structure of var_assets_root in watch window
mysql mysql_object = new mysql();
  List<mysql.invtypes_asset> lst_invtypes_assets = mysql_object.dbmysql_invtypes_asset_to_list();
  List<mysql.stations_composite_retribution> lst_stations_composite_retribution = mysql_object.dbmysql_select_stastations_composite_retribution_to_list();
  var lst_assets_list = new AssetList("134399", "343434SxSFX7qO81LqUCberhS1OQtktMvARFGED0ZRSN5c4XP230SA", "434367527");
  lst_assets_list.Query();
  var var_assets_root = lst_assets_list.assets.ToList();

  var var_assets_root_typeid_station
    = from b in var_assets_root
    join c in lst_invtypes_assets on b.typeID equals c.typeID
    join d in lst_stations_composite_retribution on b.locationID equals d.stationID
    select new {b.contents, b.flag, b.itemID, b.locationID, d.solarSystemName, d.security, d.securityClass, d.regionName, b.quantity, b.singleton, b.typeID, c.groupID, c.marketGroupID, c.volume,
      c.typeName, c.description};

I have done a solution of running a linq query for every content sub list and assigning values accordingly.
private void btn_evenet_Click(object sender, EventArgs e)
{
  Stopwatch stopwatch1 = new Stopwatch();
  Stopwatch stopwatch2 = new Stopwatch();
  stopwatch1.Start();
  mysql mysql_object = new mysql();
  List<mysql.invtypes_asset> lst_invtypes_assets = mysql_object.dbmysql_invtypes_asset_to_list();
  List<mysql.stations_composite_retribution> lst_stations_composite_retribution = mysql_object.dbmysql_select_stastations_composite_retribution_to_list();
  AssetList lst_assets_list = new AssetList("2312099", "J&VNM14RFUkSxSFX7qAAAAAA1OQtktMvYTVZZBhkO23235c4Z&HJKODPQLM", "123231527");
  lst_assets_list.Query();
  var var_assets_root = lst_assets_list.assets.ToList();
  var var_assets_root_typeid_station
    = from b in var_assets_root
    join c in lst_invtypes_assets on b.typeID equals c.typeID
    join d in lst_stations_composite_retribution on b.locationID equals d.stationID
      select new { b.contents, b.flag, b.itemID, b.locationID, d.solarSystemName, d.security, d.securityClass, d.regionName, b.quantity, b.singleton, b.typeID, c.groupID, c.marketGroupID, c.volume,
      c.typeName, c.description};
  var lst_assets_root_typeid_station = var_assets_root_typeid_station.ToList(); // Using .ToArray() is about 200ms faster than .ToList()
  stopwatch2.Start();
  for (Int32 a = 0; a < lst_assets_root_typeid_station.Count(); a++)
  {
    if (lst_assets_root_typeid_station[a].contents.Count() >= 0)
    {
      for (Int32 b = 0; b < lst_assets_root_typeid_station[a].contents.Count(); b++)
      {
        var var_row_invtypes_assets = lst_invtypes_assets.Where(x => x.typeID == lst_assets_root_typeid_station[a].contents[b].typeID).ToArray();
        lst_assets_root_typeid_station[a].contents[b].groupID = var_row_invtypes_assets[0].groupID;
        lst_assets_root_typeid_station[a].contents[b].typeName = var_row_invtypes_assets[0].typeName;
        lst_assets_root_typeid_station[a].contents[b].description = var_row_invtypes_assets[0].description;
        lst_assets_root_typeid_station[a].contents[b].volume = var_row_invtypes_assets[0].volume;
        lst_assets_root_typeid_station[a].contents[b].marketGroupID = var_row_invtypes_assets[0].marketGroupID;
        if (lst_assets_root_typeid_station[a].contents[b].contents.Count() != 0)
        {
          for (Int32 c = 0; c < lst_assets_root_typeid_station[a].contents[b].contents.Count(); c++)
          {
            var_row_invtypes_assets = lst_invtypes_assets.Where(x => x.typeID == lst_assets_root_typeid_station[a].contents[b].contents[c].typeID).ToArray();
            lst_assets_root_typeid_station[a].contents[b].contents[c].groupID = var_row_invtypes_assets[0].groupID;
            lst_assets_root_typeid_station[a].contents[b].contents[c].typeName = var_row_invtypes_assets[0].typeName;
            lst_assets_root_typeid_station[a].contents[b].contents[c].description = var_row_invtypes_assets[0].description;
            lst_assets_root_typeid_station[a].contents[b].contents[c].volume = var_row_invtypes_assets[0].volume;
            lst_assets_root_typeid_station[a].contents[b].contents[c].marketGroupID = var_row_invtypes_assets[0].marketGroupID;
          }
        }
      }
    }
  }
  stopwatch2.Stop();
  stopwatch1.Stop();
  lbl_stopwatch1.Text = "Everything: " +  stopwatch1.Elapsed.ToString("mm\\:ss\\.ff"); // 1.53 seconds no debugging
  lbl_stopwatch2.Text = "contents sublists: " +  stopwatch2.Elapsed.ToString("mm\\:ss\\.ff"); // contents sublists take 1.03 seconds no debugging
}
 }

Once I figured that 'yield' pops one content node from a stack of content nodes when  getAllContents is called I adapted my code and your function so that now all content nodes get recursed into and have their empty values filled from a linq query.  Also the new code that is after the linq creation of var_assets_root_typeid_station is now almost twice as fast.  Thank you.
private void btn_evenet_Click(object sender, EventArgs e)
{
  Stopwatch stopwatch1 = new Stopwatch();
  Stopwatch stopwatch2 = new Stopwatch();
  stopwatch1.Start();
  mysql mysql_object = new mysql();
  List<mysql.invtypes_asset> lst_invtypes_assets = mysql_object.dbmysql_invtypes_asset_to_list();
  List<mysql.stations_composite_retribution> lst_stations_composite_retribution = mysql_object.dbmysql_select_stastations_composite_retribution_to_list();
  AssetList lst_assets_list = new AssetList("12345678", "ABCDEFFGHIKL01235kokJDSD213123", "12345678");
  lst_assets_list.Query();
  var var_assets_root = lst_assets_list.assets.ToList();
  var var_assets_root_typeid_station
    = from b in var_assets_root
    join c in lst_invtypes_assets on b.typeID equals c.typeID
    join d in lst_stations_composite_retribution on b.locationID equals d.stationID
      select new
        {b.contents, b.flag, b.itemID, b.locationID, d.solarSystemName, d.security, d.securityClass, d.regionName, b.quantity, b.singleton, b.typeID, c.groupID, c.marketGroupID, c.volume,
      c.typeName, c.description};
  var lst_assets_root_typeid_station = var_assets_root_typeid_station.ToList(); // Using .ToArray() is about 200ms faster than .ToList()
  stopwatch2.Start();
 for (Int32 a = 0; a < lst_assets_root_typeid_station.Count(); a++)
  {
    if (lst_assets_root_typeid_station[a].contents.Count() > 0)
    {
      for (Int32 z = 0; z < lst_assets_root_typeid_station[a].contents.Count(); z++)
      {
        foreach (AssetList.Item contentnode in getAllContents(lst_assets_root_typeid_station[a].contents[z]))
        {
          var var_row_invtypes_assets = lst_invtypes_assets.Where(x => x.typeID == contentnode.typeID).ToArray();
          contentnode.groupID = var_row_invtypes_assets[0].groupID;
          contentnode.typeName = var_row_invtypes_assets[0].typeName;
          contentnode.description = var_row_invtypes_assets[0].description;
          contentnode.volume = var_row_invtypes_assets[0].volume;
          contentnode.marketGroupID = var_row_invtypes_assets[0].marketGroupID;
        }
      }
    }
  }
  stopwatch2.Stop();
  stopwatch1.Stop();
  lbl_stopwatch1.Text = "Everything: " +  stopwatch1.Elapsed.ToString("mm\\:ss\\.ff"); // 1.16 seconds no debugging
  lbl_stopwatch2.Text = "contents sublists: " +  stopwatch2.Elapsed.ToString("mm\\:ss\\.ff"); // contents sublists take 0.63 seconds no debugging
}

IEnumerable<AssetList.Item> getAllContents(AssetList.Item contentNode)
{
  if (contentNode.contents.Count == 0)
  {
    yield return contentNode;
  }
  else
  {
    foreach (AssetList.Item subContentNode in contentNode.contents)
    {
      yield return subContentNode;
      foreach (AssetList.Item subSubContentNode in getAllContents(subContentNode))
        yield return subSubContentNode;
    }
  }
}

A: Aren't you just looking for SelectMany?

var contents = lst_invtypes_assets.contents.SelectMany(x => x.contents);

A: What I think you're getting at is that you want to access the outer .contents property, and if it contains any contents, then access those, too, and so on... recursively.
While you could do this by defining a recursive Func<AssetList.Item, IEnumerable<AssetList.Item>> and a line of LINQ using .Aggregate, it will probably be easier/more readable to define your own recursive method.
IEnumerable<AssetList.Item> getAllContents(AssetList.Item station) {
    foreach (AssetList.Item subStation in station.contents) {
        yield return subStation;
        foreach (AssetList.Item subSubStation in getAllContents(substation))
            yield return subSubStation;
    }
}

You can then do a simple foreach(var station in getAllContents(parentStation)), or modify this to include the original station, make it an extension method, etc.


text:
Q: Retrieving and parsing protein sequences from GenBank using Entrez in BioPython As will soon be obvious, I am new to Python and coding in general. I have a list of Gene IDs stored as a text file and I want to use the Entrez functions to search the GenBank database and retrieve the protein sequences corresponding to the IDs. Ideally I want the end product to be a FASTA file as I am really only interested in the sequence at this point. Using the Biopython tutorial (http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec15), I came up with this:
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "me@mysite.com"
id_list = set(open('test.txt', 'rU'))
handle = Entrez.efetch(db="protein", id=id_list, rettype="fasta", retmode="text")
for seq_record in SeqIO.parse(handle, "fasta"):
    print ">" + seq_record.id, seq_record.description
print seq_record.seq
handle.close()

But when I run it, I get the error:
File "C:/Python27/Scripts/entrez_files.py", line 5, in <module>
  handle = Entrez.efetch(db="protein", id=id_list, rettype="fasta", retmode="text")
File "C:\Python27\lib\site-packages\Bio\Entrez\__init__.py", line 145, in efetch
  if ids.count(",") >= 200:
AttributeError: 'set' object has no attribute 'count'

I get a similar error every time I use rettype = 'fasta'. When I use rettype = 'gb' I don't get this error, but I really want to end up with a fasta file. Does anybody have some suggestions? Thank you!
EDIT:
sorry I neglected to include what the input file is like. In a perfect world the code would accept an input format like this:
gi|285016822|ref|YP_003374533.1|
gi|285018887|ref|YP_003376598.1|
gi|285016823|ref|YP_003374534.1|
gi|285016824|ref|YP_003374535.1|
....

But I have also tried using a simplified version with only the Gene IDs (GIs) like this:
285016822
285018887
285016823
285016824...

A: As you can see in efetch's source code, the id parameter must have a count method. Usually this will be a string with a single ID or a Python list with all the IDs. You are using a set, presumably to eliminate repeated values, so you can convert to a list like this:
id_list = set(open('test.txt', 'rU'))
id_list = list(id_list)


text:
Q: .NET WebRequests fail on network with Blue Coat proxy I have a .NET 3.5 application that makes a standard http WebRequest:
var webRequest = WebRequest.Create(new Uri("http://myserver.com/target.xml));
var webResponse = webRequest.GetResponse();

This application is often deployed within networks that utilize proxies but I never really had issues with this until it was recently deployed at a client that utilizes the "Blue Coat" Proxy/Firewall.
Their proxy is configured as a transparent proxy.
The issue is that 90% of the time, my WebRequests fail with 401 Unauthorized, yet sometimes they work fine (the behavior is the same on 10+ client machines).
Also, on all of them, it works completely fine if Internet Explorer is opened first and they manually browse to one of my URL's (I checked their IE config and no proxy config is entered). Consequently, all WebRequests from my application work seamlessly.
Their network team has no suggestions but does admit to have seen "funky" behavior in the past.
Anyone have any idea what's going on here and what could be done?

A: If you have no specific proxy defined, try this by default:
webRequest.Proxy = WebRequest.DefaultWebProxy;
webRequest.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;


text:
Q: SQL Query Param type affects query speed We had a slow page loading and upon investigating it was the query execution. I noticed the page on the dev server was fine and I noticed when I ran the query via MSSQL Mgt Studio it ran fine, only on the CF page it was slow. I noticed the ids were being checked with a cfsqltype of cf_sql_numeric instead of cf_sql_integer. For kicks I changed it to integer and it now loaded as expected.
So, what gives, why would that make a difference?
As to why it may have suddenly started going slow was our DBA added some indexes recently to speed up the DB in general. But still, why so slow just based on the param type.


text:
Q: Sharepoint Format Text tab in a compact view? So today while editing a page in sharepoint i suddenly noticed all the tabs for the page edit is in some form of a compact view. I do not recall changing it, perhaps i hit some kind if keybind. How would i be able to change the view back so all of the options are not in a drop down menu style.

A: I believe the formatting on the ribbon is based off of your windowed view. There physically is not enough space for all the elements to fit in the ribbon. To expand the ribbon, expand your window.
The first image below is my full-screen view of the page and has all the bells a whistles in their expanded view. The second image is a partial window. Try either zooming out (maybe your browser is at 150% zoom), or changing monitors, or maximizing your window.


text:
Q: Difficulties merging revisions with subversive Good morning,
Supose a developer has commited a unique revision (let's say 4582) in two different projects which are in two different branches. For example:
 Project A (branches/ProjectA/V2.0)
 Project B (branches/ProjectB/V2.1)
What we would like to do is merging this revision 4582 to other two branches in a single step (i.e. without the necessite to perform the merge separetedly), for example:
 Project A (branches/ProjectA/V2.0)  ===>  Project A (branches/ProjectA/V1.4)
 AND
 Project B (branches/ProjectB/V2.1)  ===>  Project B (branches/ProjectB/V1.3)
Anybody knows if is it possible to do this scenario in just one step using subersive?
tks,
Daniel.

A: I don't think subversive is able to do this.
Even using the console client you would have to split the merge in two steps, when working directly on the repository.
If it is that important that it is in one commit, you could checkout the whole repository, do both merge steps and then commit the whole repository. But that will need much disk space, because all tags, branches, etc. are checked out.


text:
Q: mod_rewrite gives 404 when url contains words dvd-player - reserved words? I am rewitting url-s (mapping subdomains to subdirectories) and it works perfect except for urls that contain the following words: "mp3-player" or "dvd-player". In this case I always get 404 error. It doesn't matter if the words are contained in a subdomain or in a path, if they are at the beginning, middle or the end:
http://blahblah-dvd-player-blahblah.example.com/blahblah/somefile.html
http://blahblah.example.com/blahblah-mp3-player-blahblah/somefile.html
All other subdomains and paths work perfectly. Urls that are not rewritten and contain those words also go well.
Could those be some kind of reserved words? Can somebody please help me? I have no idea how to debug this.
Problem is solved! It was caused by xss filter.
Thanks everybody.


text:
Q: Microsoft filter's sizingMethod='scale' - May it only scales the image horizontally? I was trying to apply a shadow background in a row by using CSS3 property background-size and it worked as excepted in modern browsers accept IE8 below.
Then I got a solution for IE mentioned in this post (make background-size work in IE?)
The above solution also works in IE8 below, but it scales the image proportionally (both horizontally and vertically).
But I need to scale it only horizontally, as I achieved with CSS3 property mentioned below:
background-size: 100% 25%;

/*
    100% for horizontally
    25% for vertically
*/

My question: Is it any value of sizingMethod which scale the image only either horizontally or vertically (or any other work-around [^ jQuery/Javascript ^]) to get the required result as I got with CSS3 property background-size for modern browsers?
Here is my code that I've used:
CSS:
 .row-shad {
     background:url(../images/cat-bot-shad.png) center bottom no-repeat;

    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
    src='http://full-path-to-images/images/cat-bot-shad.png',
    sizingMethod='scale'); /*For IE 8 and less*/

    background-size: 100% 25%; /* for good browsers*/
}

--- Here is the live result, in good browsers and in IE8, see the difference. ---
Any help in this regard should really be appreciated.
Thanks!

A: Method 1: fixed background color
If your background has always the same color, you can use an image replacement like this:

When it's scaled, the proportions will be respected.
Demo (tested and working with IE8)

Method 2: transparent background
If you need a transparent background (using the method above) you'll have to add a multiple filter to solve IE's PNG transparency problems:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
    src='http://full-path-to-images/images/cat-bot-shad-ie.png',
    sizingMethod='scale')
    alpha(opacity = 100); /*For IE 8 and less */

And a conditional commented style to overwrite the original background declaration:
<!--[if lt IE 9 ]>
<style>
.row-shad { background:none; }
</style>
<![endif]-->

Demo (tested and working with IE8)
By the way, if you use conditional comments in your <html> tag, you can easily target IE8 and below this way:
HTML tag:
<!--[if lt IE 9]> <html class="ielt9"> <![endif]-->
<!--[if !IE]>--> <html> <!--<![endif]-->

CSS:
.ielt9 .row-shad { background:none; }

The IE7 issue
Your method doesn't work on IE7.
You can approach it in a graceful degratadion way, by adding a CSS hack and a custom background image for IE7 (less than 2% users worldwide):
*background:url(../images/cat-bot-shad-ie7.png) center bottom repeat-x;

*property targets IE7 and below only. Or again, you can easily do it with a conditional comment.
Demo (tested and working with IE7-8)

Putting together method 2 and IE7 hack
Eventually, to use both transparent png for IE8 and a custom image for IE7, you've to use multiple conditional comments:
<!--[if IE 8 ]>
<style>
#row { background:none; }
</style>
<![endif]-->
<!--[if lt IE 8 ]>
<style>
#row { background:url(../images/cat-bot-shad-ie7.png) center bottom no-repeat; }
</style>
<![endif]-->

Demo (tested and working on IE7-8)
Or again, conditional html tag:
<!--[if lt IE 8]> <html class="ielt8"> <![endif]-->
<!--[if IE 8]> <html class="ie8"> <![endif]-->
<!--[if !IE]>--> <html> <!--<![endif]-->

CSS:
.ie8 .row-shad { background:none; }
.ielt8 .row-shad { background:url(../images/cat-bot-shad-ie7.png) center bottom no-repeat; }

A: Unfortunately there is no way to make IE 8 and below scale differently than 100%/100%. Which means you need to do this some other way.
One method would be to make the image fit the element.
Since your element is 25% of the element's height, make the image 4x higher and fill the empty space with transparent or the background colour, then change the scale height to 100% instead of 25% for browsers that use the CSS3 property.
background-size: 100%;

Since you're using a PNG which is run-length encoded, this will add an extremely small amount of data to the image, and will work in all browsers just fine.
The only other way to do this is going to be adding a dummy element with 25% height and have it display behind the element's normal content, which is non-semantic and should be avoided when possible.


text:
Q: POST request with Axios not sending data to my server Here is my React code for the form submission:
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('item:', item);
    Axios.post('http://<MY_SERVER>/item/add', {name:item})
      .then(response => console.log(response))
      .catch(err => console.log(err));
  };

and this is the code in my Node API:
// Add a new Item
app.post('/item/add', (req, res) => {
  const newItem = new Item({
    name: req.body.name
  });

  newItem.save()
    .then(item => {
    res.json({msg: 'success'});
    })
    .catch(err => console.log(err));
});

When I run the handleSubmit nothing happens. I only get the console.logs... Also, here is the error from my server
'ValidationError: item validation failed: name: Path' `name` is required

So it is clear that the data sent over to the api is never received. I've tried changing it up in many ways I have came across online but no luck.

A: I have attached both ways to post data i.e. Form URL Encoded and JSON. For sending Form Url Encoded data we need an additional Library querystring.
You can install it using npm install query-string
Here is the code for both the requests. You don't need query-string if you are using content type application/json.
Here you go
var axios = require('axios');
const qs = require('querystring');

function sendFormUrlEncodedData() {
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  };

  const payload = {
    name: 'morpheus',
    job: 'leader'
  };

  //Send data with form url using querystring node package for it.
  axios
    .post('https://reqres.in/api/users', qs.stringify(payload), {
      headers: headers
    })
    .then(res => {
      console.log(res.data);
    })
    .catch(err => {
      console.log(err);
    });
}

function sendJSONData() {
  const headers = {
    'Content-Type': 'application/json'
  };

  const payload = {
    name: 'morpheus',
    job: 'leader'
  };

  //Send data with JSON, so stringifying it.
  axios
    .post('https://reqres.in/api/users', JSON.stringify(payload), {
      headers: headers
    })
    .then(res => {
      console.log(res.data);
    })
    .catch(err => {
      console.log(err);
    });
}

sendFormUrlEncodedData();
sendJSONData();

A: First  of all check whether your backend code is working or not by using postman. I think you are getting validation error because of the error of your backend code. And also check whether that you are implemented the name attribute correctly with its data type.
After that update, the react code as below.
import axios from 'axios';

constructor() {
  this.item = {
    name: ''
  }
}

 handleSubmit(event) {
    console.log('item:', this.item.name);
    event.preventDefault();

    axios.post('http://<MY_SERVER>/item/add', this.item)
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.log(error);
    });

}