text:
Q: Saving cURL -w variables to a bash variable I have a command like
curl -kso /dev/null -w "dns lookup:%{time_namelookup}, tcp:%{time_connect}, ssl:%{time_appconnect} , total:%{time_starttransfer} )\n" https://www.google.com

I want to capture the variables like time_namelookup,time_connect,time_starttransfer which are provided by cURL (as shown in man page snippet below), in a bash variable so that I can use it further.
I tried using read command but that is not helping. I tried something like this
curl -kso /dev/null -w "dns lookup:%{time_namelookup}, tcp:%{time_connect}, ssl:%{time_appconnect} , total:%{time_starttransfer} $(something=%{time_starttransfer})\n" https://www.google.com

but still, the something variable is empty.
Please suggest how should it proceed.
   -w, --write-out <format>
          Defines what to display on stdout after a completed  and  suc‐
          cessful  operation.  The  format  is a string that may contain
          plain text mixed with any number of variables. The string  can
          be  specified  as "string", to get read from a particular file
          you specify it "@filename" and to tell curl to read the format
          from stdin you write "@-".

          The variables present in the output format will be substituted
          by the value or text that curl thinks fit, as described below.
          All  variables are specified as %{variable_name} and to output
          a normal % you just write them as %%. You can output a newline
          by  using  \n,  a carriage return with \r and a tab space with
          \t.

          NOTE: The %-symbol is a special symbol in  the  win32-environ‐
          ment,  where  all  occurrences of % must be doubled when using
          this option.

          The variables available are:

          content_type   The Content-Type of the requested document,  if
                         there was any.

          filename_effective
                         The  ultimate filename that curl writes out to.
                         This is only meaningful  if  curl  is  told  to
                         write  to  a  file  with  the  --remote-name or
                         --output option. It's most useful  in  combina‐
                         tion   with  the  --remote-header-name  option.
                         (Added in 7.25.1)

          ftp_entry_path The initial path curl ended up in when  logging
                         on to the remote FTP server. (Added in 7.15.4)

          http_code      The  numerical  response code that was found in
                         the last retrieved HTTP(S) or FTP(s)  transfer.
                         In  7.18.2 the alias response_code was added to
                         show the same info.

          http_connect   The numerical code that was found in  the  last
                         response  (from  a  proxy)  to  a  curl CONNECT
                         request. (Added in 7.12.4)

          local_ip       The IP address of the local  end  of  the  most
                         recently  done  connection - can be either IPv4
                         or IPv6 (Added in 7.29.0)

          local_port     The local port number of the most recently done
                         connection (Added in 7.29.0)

          num_connects   Number  of  new  connects  made  in  the recent
                         transfer. (Added in 7.12.3)

          num_redirects  Number of redirects that were followed  in  the
                         request. (Added in 7.12.3)

          redirect_url   When  an  HTTP  request  was made without -L to
                         follow redirects, this variable will  show  the
                         actual URL a redirect would take you to. (Added
                         in 7.18.2)

          remote_ip      The remote IP address of the most recently done
                         connection  - can be either IPv4 or IPv6 (Added
                         in 7.29.0)

          remote_port    The remote port number  of  the  most  recently
                         done connection (Added in 7.29.0)

          size_download  The total amount of bytes that were downloaded.

          size_header    The  total  amount  of  bytes of the downloaded
                         headers.

          size_request   The total amount of bytes that were sent in the
                         HTTP request.

          size_upload    The total amount of bytes that were uploaded.
 [...]

Edit: I can see various methods to capture variables but while capturing the output of the given command should not be changed. In short, I'm trying to capture variables without changing the output of the given command.

A: It's not possible just like that coz every command run in its own subshell, create own vars and so on. Try this code:
export somevar=test; curl -kso /dev/null -w "$(export somevar=%{time_connect}; env | grep somevar)\n" https://www.google.com; env | grep somevar

The output(in my case) will be:
somevar=0,004898
somevar=test

So the way to do it is to output directly to var.
somevar=$(curl -kso /dev/null -w "%{time_connect}" https://www.google.com)

$ echo $somevar
0,005093

Or to an array, if you need multiple items.
somearray=( $(curl -kso /dev/null -w "%{time_connect} %{time_namelookup} %{time_appconnect}" https://www.google.com) )

$ echo ${somearray[@]}
0,005095 0,004317 0,165347

A: Here's a way to do it based on Linux bash: Multiple variable assignment
read -r time_namelookup time_connect time_appconnect time_starttransfer<<<$(curl -kso /dev/null -w "%{time_namelookup} %{time_connect} %{time_appconnect} %{time_starttransfer}" https://www.google.com)

The variables:
echo dns lookup:$time_namelookup, tcp:$time_connect, ssl:$time_appconnect, total:$time_starttransfer

Output:
dns lookup:0.004143, tcp:0.044270, ssl:0.112656, total:0.195420

A: You can use format file and use it in curl.
curl-format.txt:

        time_namelookup:  %{time_namelookup}\n
           time_connect:  %{time_connect}\n
        time_appconnect:  %{time_appconnect}\n
       time_pretransfer:  %{time_pretransfer}\n
          time_redirect:  %{time_redirect}\n
     time_starttransfer:  %{time_starttransfer}\n
                        ----------\n
             time_total:  %{time_total}\n
              http_code: %{http_code}\n

check_stats.sh:

    CURL='/usr/bin/curl'
    CURL_OPTS="-w "@curl-format.txt" -sS"
    URL="https://www.google.com"
    STATS=$(${CURL}  ${CURL_OPTS} ${URL})
    STATS_ARRAY=($( echo $STATS | ${SED} ':a;N;$!ba;s/\r\n/ /g' ))
    time_namelookup=${STATS_ARRAY[1]}
    time_connect=${STATS_ARRAY[3]}
    time_appconnect=${STATS_ARRAY[5]}
    time_pretransfer=${STATS_ARRAY[7]}
    time_redirect=${STATS_ARRAY[9]}
    time_starttransfer=${STATS_ARRAY[11]}
    time_total=${STATS_ARRAY[14]}
    http_code=${STATS_ARRAY[16]}


text:
Q: nodemon issue with debug package in nodejs I am trying to dubug my app using debug package through nodemon package and I am facing this much trouble that my required output is hidden inside the messy irrelevant information as you can see
Error / Issue
[nodemon] restarting due to changes...
  nodemon bus emit: restart +25s
  nodemon bus new listener: start (0) +0ms
  nodemon bus new listener: start (0) +1ms
[nodemon] starting `node ./build/index.js`
  nodemon fork C:\Windows\system32\cmd.exe /d /s /c node ./build/index.js +25s
  nodemon bus emit: start +5ms
  nodemon bus new listener: exit (2) +1ms
  nodemon start watch on: *.* +2ms
[nodemon] restarting due to changes...
  nodemon bus emit: restart +4ms
  nodemon bus.emit(exit) via SIGUSR2 +218ms
  nodemon bus emit: exit +215ms
[nodemon] starting `node ./build/index.js`
  nodemon fork C:\Windows\system32\cmd.exe /d /s /c node ./build/index.js +5ms
  nodemon bus emit: start +5ms
  nodemon bus new listener: exit (1) +1ms
  nodemon start watch on: *.* +2ms
  app:normal it is normal debugger... +0ms
Listening on port: 3000
^CTerminate batch job (Y/N)? y

E:\Web Apps\RESTful API\express-demo>nodemon ./build/index.js
  nodemon bus new listener: reset (0) +0ms
  nodemon bus new listener: reset (0) +3ms
  nodemon bus new listener: quit (0) +26ms
  nodemon bus new listener: quit (0) +0ms
  nodemon bus new listener: restart (0) +1ms
  nodemon bus new listener: restart (0) +0ms
  nodemon bus new listener: reset (2) +6ms
  nodemon bus emit: reset +1ms
  nodemon resetting watchers +0ms
  nodemon reset +0ms
  nodemon config: dirs [ 'E:\\Web Apps\\RESTful API\\express-demo' ] +0ms
[nodemon] 1.17.3
[nodemon] to restart at any time, enter `rs`
  nodemon bus new listener: error (0) +106ms
  nodemon bus new listener: error (0) +0ms
[nodemon] watching: *.*
[nodemon] starting `node ./build/index.js`
  nodemon fork C:\Windows\system32\cmd.exe /d /s /c node ./build/index.js +0ms
  nodemon bus new listener: exit (0) +12ms
  nodemon bus new listener: exit (0) +1ms
  nodemon start watch on: *.* +3ms
  nodemon start watch on: E:\Web Apps\RESTful API\express-demo +119ms
  nodemon ignored [ '**/.git/**',
  '**/.nyc_output/**',
  '**/.sass-cache/**',
  '**/bower_components/**',
  '**/coverage/**',
  '**/node_modules/**',
  re: /.*.*\/\.git\/.*.*|.*.*\/\.nyc_output\/.*.*|.*.*\/\.sass\-cache\/.*.*|.*.*\/bower_components\/.*.*|.*.*\/coverage\/.*.*|.*.*\/node_modules\/.*.*/ ] +1ms
  nodemon watch is complete +147ms
  app:normal it is normal debugger... +0ms
Listening on port: 3000

I am following these commands to debug my app
Inside index.js
const debug = require('debug')('app:start')
debug('debugging the app... Yup!')

Inside Terminal
set DEBUG=app:start // inside terminal
nodemon index.js // inside terminal

A: Issue was very silly that I was running these two commands in different terminals that cause the problem
set DEBUG=app:start // inside terminal
nodemon index.js // inside terminal

be sure to run these commands in the same terminal.
Hope this will save time for someone.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring Batch how to write a composite entity to multiple DB tables with chunking (using batch writers) My requirement is to read Foo entries from a flat file and store them in the database after processing. However, the processing step may optionally require an additional set of 'Bar' entities (for each Foo) to be written to the Bar table. Can this be achieved with CompositeItemWriter and JdbcBatchItemWriters (for Foo and Bar) without me writing a custom writer that writes Foo and its corresponding Bar[] in batch. I am processing the records in chunks and have no foreign key ID reference requirement from Bar to Foo.
I've reviewed a bunch of posts in SO related to this and want to do something like this:
// create a composite type Foo-Bar as output of processor
Foo-Bar {
  Foo foo, // processed foo
  List<Bar> bars // zero or more bars
}

// define step using these
ItemReader<Foo>
ItemProcessor<Foo, Foo-Bar>
ItemWriter<Foo-Bar>

but can't figure out the right approach for ItemWriter esp given each Foo item has a list of Bar items. How do you setup a JdbcBatchItemWriter to write Bar[] items for each Foo when write(List<Foo-Bar> fooBars) is called by batch framework for each chunk of fooBars.
Thank you.


text:
Q: Best way to hook a custom url? Let say I've a custom page with slug created "/products", I want user will be able to POST to a form with url  "/products/create" and allow us to render some JSON output.
The "/products/create" page does not actually exist.
I see from [1], the basic approach are

*

*Add a rewrite if match my target url, add a custom query var, e.g. is_my_action=1

*Register the custom query var (is_my_action) via "query_vars" action hook

*In the parse_request hook check for this query var, and perform my works.

This approach work, but seems a little hackish, are there any potential issue with the above approach?
Are there any better way to add custom virtual url that  ?
[1] http://www.coderrr.com/create-an-api-endpoint-in-wordpress/

A: The approach is pretty much sound, this is how these things work in WordPress.
You might want to use add_rewrite_enpoint() for implementation though, since it compresses multiple steps into on integrated call and fits many use cases well.


text:
Q: is it possible to extract images from iframe video? I have iframe tag which is running live streamings. My question is , is there any way to extract frame from iframe video?
here is the tag:
<iframe id="video" width="100%" height="419" src="http://videoplayer.vodobox.com/vodobox_player.php?vid=http://109.123.70.72:1935/live/ptvsports/samitv.m3u8&img=&play=?" frameborder="0" allowfullscreen></iframe>

Is it possible to get image or screenshot of particular frame?


text:
Q: How to count and group by As you can see in this image below, I need to count how many number '1' is on every column, the number '1' means that the person interviewed feels secure at Home(AP_4_01),Workplace(AP4_4_02) and so on..
Number 2 = Insecure
Number 3 = Doesn't Apply
Number 9 = Didn't Answer
+----------+----------------------+
| Columns  | Numbers of persons   |
+----------+----------------------+
| AP4_4_01 | 312                  |
| AP4_4_02 | 232                  |
| AP4_4_03 | 345                  |
| AP4_4_0X | XXX                  |
+----------+----------------------+

A: You just need to use the SUM function on some case statements
SELECT
    SUM(CASE WHEN AP_4_01 = 1 THEN 1 ELSE 0 END)
   ,SUM(CASE WHEN AP_4_02 = 1 THEN 1 ELSE 0 END)
   ...etc
FROM Table

To get a result set like the one in your question, you will need to use the UNPIVOT function, or you can transpose it in excel.


text:
Q: How to make Numeric Entries in Xamarin Forms wait until user is done entering number I have a NumericEntry in Xamarin Forms, that for example wants to check if a number is equal to 50, but when the user starts to enter 50, they enter the "5" first, but then immediately it's wrong, because 5 != 50 obviously. How do I make it so that the user can enter the full number, but then once they click away from the entry/press enter on the keyboard, then we check if the number is equal to 50?
Specifically what I'm looking for that would make things a lot easier is a keyword that says the entry isn't "highlighted" anymore, meaning the user clicked enter on the keyboard, or tapped away from the entry on the screen somewhere. Is there something like that that exists?
Right now the code that I'm working on has two functions, an UpdateText and a OnTextChanged, and every time the text changes (the 5 gets entered in my example), then UpdateText immediately gets called, but I want to make a condition that checks if the user is done before UpdateText gets called.
Thanks!
edit: I found something called "IsFocused", would this be the right way to use it?
IsFocused="{Binding EntrySelected}"

would be in my XAML file, and in my C# file, `public bool UserFinished;
    public bool EntrySelected
    {
        get
        {
            return UserFinished;
        }
        set
        {
            UserFinished = value;
        }
    }

and using  if(EntrySelected){ inside my functions?

A: use the Completed event.  You can also customize the appearance of the Return key using the ReturnType property
<Entry Completed="Entry_Completed" ReturnType="Send" />

void Entry_Completed (object sender, EventArgs e)
{
    var text = ((Entry)sender).Text; //cast sender to access the properties of the Entry
}


text:
Q: When do you need the Windows SDK for MSBuild? I'm setting up my first build server for .NET 3.5 projects, and found this interesting line in the MSBuild log after a successful build of a simple test application:

Could not locate the expected version
  of the Microsoft Windows SDK. Looked
  for a location specified in the
  "InstallationFolder" value of the
  registry key
  "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft
  SDKs\Windows\v6.0A". If your build
  process does not need the SDK then
  this can be ignored.

When exactly would your build process need the SDK? I don't want to install it on the build server if it's not going to be necessary, but I also don't want to discover that I need it by having a build mysteriously break.
At the moment, I only have .NET Framework 3.5 SP1 installed on the server.

A: The SDK has a couple of additional tools that are **sometimes** used, depending on the contents of your project - such as (IIRC) the reports compiler. But for most things, no: you don't need the SDK. I installed in on my build server just to get clean output ;-p

A: If you need to compile C or C++ code - to the best of my knowledge.


text:
Q: Use LINQ expression to Update Property of object So I have a situation where I need to dynamically update properties of my object based on values contained. In the case below, I need to update the value with replacing the first two characters of the current value with a different string if condition is true.
PersonDetail.EvaluateConditionalRule("ID",
                    "((ID.Length > Convert.ToInt32(@0) ) AND ID.Substring(Convert.ToInt32(@1), Convert.ToInt32(@2)) == @3 )",
                     new[] { "1", "0", "2", "SS" }, " ID = (@0  + ID.Substring(Convert.ToInt32(@1))) " , new[] { "98", "2" });

   public static void EvaluateConditionalRule(this PersonDetail  Detail, String PropertyToEvaluate,
            String ConditionalExpression, String[] parameters, String IfTrueExpression,String[] IfTrueExpreassionparameters  )
          {
               var property =  Detail.GetType().GetProperties().Where(x => x.Name == PropertyToEvaluate).FirstOrDefault();
               if (property == null)
                    throw new InvalidDataException(String.Format("Please specify a valid {0} property name for the evaluation.",  Detail.GetType()));
               //put together the condition like so

               if (new[] {  Detail }.AsQueryable().Where(ConditionalExpression, parameters).Count() > 0 && IfTrueExpression != null)
               {
                    var result = new[] {  Detail }.AsQueryable().Select(IfTrueExpression, IfTrueExpreassionparameters);

                  //Stuck Here as result does not contain expected value

                    property.SetValue( Detail,result , null);
               }
          }

Essentially what I want is, to be able to execute expressions fed this, and I don't think I have the format right for the substring replace expression to correctly evaluate.  What I want from the above is something like
ID = "98"+  ID.Substring(2);

Any help will be appreciated. Thanks

A: Not sure what exactly you mean saying "dynamically" but i suppose the approach with lambdas does not fit you:
static void Main(string[] args) {
        User user = new User { ID = 5, Name = "Test" };
        SetNewValue(user, u => u.Name, s => s.StartsWith("T"), s => s + "123");
    }

    static void SetNewValue<TObject, TProperty>(TObject obj, Func<TObject, TProperty> propertyGetter, Func<TProperty, bool> condition, Func<TProperty, TProperty> modifier) {
        TProperty property = propertyGetter(obj);
        if (condition(property)) {
            TProperty newValue = modifier(property);
            //set via reflection
        }
    }

So I would recommend you using Expression trees which allow you to build any runtime construction you like, for part of your example
var exp = Expression.Call(Expression.Constant("test"), typeof(string).GetMethod("Substring", new[] { typeof(int) }), Expression.Constant(2));
Console.WriteLine(Expression.Lambda(exp).Compile().DynamicInvoke()); //prints "st"

However if you want to use strings with raw c# code as expressions check the CSharpCodeProvider class

A: Please give us some information on why you need the updates to be this dynamic. Do you want the user to enter the condition strings by hand?
About your code:
Your selector string is wrong. In the LINQ Dynamic Query Library there is a special syntax for it. Please look that up in the Documentation (see paragraph Expression Language and Data Object Initializers) provided with the sample: http://msdn.microsoft.com/en-US/vstudio/bb894665.aspx
I wrote a small sample:
var id = new string[] { "SS41231" }.AsQueryable();

// *it* represents the current element
var res = id.Where("it.Length > @0 AND it.Substring(@1, @2) = @3", 1, 0, 2, "SS"); // Save the result, don't throw it away.

if (res.Any())
{
    // Line below in normal LINQ: string newID = res.Select(x => "98" + x.Substring(2)).First();
    string newId = res.Select("@0 + it.Substring(@1)", "98", 2).Cast<string>().First();

    Console.WriteLine(newId);
}

Please write some feedback.
Greetings.


text:
Q: Knockout 3.4 and above fail with iOS 11 to embed  tag I use Knockout templates to dynamically build up a page containing a number of inline video clips.
I noticed recently that iOS11 was acting very quirkily and not playing videos well.
The video would appear as it if was starting to play - the progress bar would even move - but the video didn't play. Interestingly clicking the 'full screen icon' would trigger it to start playing in full screen and it would continue playing fine inline when the full screen mode is closed.
After stripping the site completely down it seems that my use of Knockout templates with the video tag was causing the issue. Reverting to Knockout version 3.3.0 restored flawless operation. This is the version of Knockout that introduced microtasks and I'm guessing the issue maybe has something to do with a weird timing problem.
This is the simplest version that fails:
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

The following video is dynamically inserted from a Knockout template

This version is Knockout 3.4.0

    <template id="videoTemplate">

        <video muted playsinline preload="auto" controls
               width="500" height="300">

            <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
        </video>

    </template>

Knockout 3.4.0 version (doesn't work on iOS11)
https://embed.plnkr.co/L05w8x1iVBbauibG7yev?show=preview
Knockout 3.3.0 version (OK)
https://embed.plnkr.co/EpPkzCdq2zgNIRYO8eYU?show=preview
How I can fix or work around this?
I don't know if I need to disable microtasks, generate the video tag from scratch, or reassign the source dynamically after the template is created. Trying to Google for iOS video bugs brings up mostly ancient stuff.
I believe Safari on Mac also has this problem but I only have access to iOS.

A: It appears that reverting back to


text:
Q: I can't verticaly align an element to bottom I'm trying to get my fullcalendar.io event to show up at the bottom of the day instead of in the middle. I've been trying to modify different elements to vertical-align: "bottom" but nothing seems to work. Here is a link to my fiddle that has different css overloaded calls to set the vertical-alignment to bottom for a calendar event. Currently the event is placed in the middle of the day, I want it at the bottom of the cell.

$(document).ready(function() {

    // page is now ready, initialize the calendar...
    var eventsArray = [
            {
                title: 'Test1',
                start: new Date()
            },
            {
                title: 'Test2',
                start: new Date(2015, 4, 21)
            }
        ];

    $('#calendar').fullCalendar({
        // put your options and callbacks here
        header: {
            left: 'prev,next', //today',
            center: 'title',
            right: ''
        },
        defaultView: 'month',
        editable: true,
        allDaySlot: false,
        selectable: true,
        events: eventsArray
    })

});
//all the different things I've tried!!!!!!!
tbody {
    vertical-align: bottom;
}

tr td.fc-event-container {
    vertical-align: bottom;
}
td.fc-event-container {
    vertical-align: bottom;
}

td {
    vertical-align: bottom;
}

.fc-event-container {
    vertical-align: bottom;
}

tr {
    vertical-align: bottom;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.3.1/fullcalendar.css" rel="stylesheet"/>

I inspected the elements in the explorer window in Chrome and I'm not sure which element needs the vertical alignment set.
Here is a pic of the elements in Chrome.

A: The element which contains the table is held open by its content. Your vertical alignment is working but the element is only as tall as its content. Simply make sure the container is 100% high:
.fc-content-skeleton,
.fc-content-skeleton table {height:100%;}

https://jsfiddle.net/4v65ggos/9/

A: Two issues:
1) the containing element isn't 100% of the "cell" height (which is set by a second "skeleton" table)
2) the vertical-align is overriden, so we'll need to increase specificity
Here's the CSS that will set the height to 100%:
.fc-row .fc-content-skeleton {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

.fc-content-skeleton table {
    height: 100%
}

And finally, to increase specificity:
.fc-content-skeleton .fc-event-container {
    vertical-align: bottom;
}

(Or, we could add !important)
An updated fiddle: https://jsfiddle.net/4v65ggos/13/

A: You can set a fixed height to the table element.
   .fc-row  table{
      height:72px;
    }

This though won't work well if the site you are working on it's responsive.
Make sure you apply height:100% to both elements, the table and its container.
.fc-content-skeleton,.fc-content-skeleton table{
   height:100%;
}

A: You need to set the same height for the fc-content-skeleton as the fc-bg (you can set it to 64px as the background one just to try). The same for the table inside the fc-content-skeleton (or height: 100%).
Then the fc-event-container can use vertical-align: bottom you wanted to use.
In order to use this property, the parent must have a non-automatic height.


text:
Q: Spacing between elements not works right in TailwindCSS I am using spacing for controlling the space between child elements in TailwindCSS but it not works right. See at first image, the first element has excess and uneven spacing, the image 2 is what i am expected. How can i solve this?
Image 1
Image 2 (my expected results)
My code not working right as my expect below:

Box

Box

Box

Box

Box

Box

Box

Box

Box

Box


text:
Q: Retrieve facebook id from profile image address If I only have the facebook profile address (something like https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/c0.0.180.180/1425794_10202604468931708_129792007_a.jpg ) , can I retrieve it's user ID? The aforementioned address is the only information known.
Thanks

A: Yes.
From the second set of numbers in the file name go to this URL http://facebook.com/10202604468931708
You will see that takes you to a page for that picture. On that page you can see the owner of the picture.  Navigate to the profile.
From the profile, change www to graph In the URL.
The resulting page will show the Facebook id of the user.

A: The second set of numbers is indicative of the profile it originated from.
www.facebookcreep.com is a tool that takes this number and searches for the profile it came from.
Hope this helps people!


text:
Q: Show the following expression holds for the volume of a parallelepiped spanned by three vectors. Let $V$ be the volume of the parallelepiped spanned by vectors $\pmb{u},\pmb{v}$ and $\pmb{w}; \in \mathbb{R^3}$. Show that
$$V^2=
\begin{vmatrix}
\langle \pmb{u},\pmb{u}\rangle & \langle \pmb{u},\pmb{v}\rangle & \langle \pmb{u},\pmb{w}\rangle \\
\langle \pmb{v},\pmb{u}\rangle & \langle \pmb{v},\pmb{v}\rangle & \langle \pmb{v},\pmb{w}\rangle \\
\langle \pmb{w},\pmb{u}\rangle & \langle \pmb{w},\pmb{v}\rangle & \langle \pmb{w},\pmb{w}\rangle
\end{vmatrix}
$$
using an orthonormal basis and $\det{AB}=\det{A}\det{B}$.
My idea was to establish orthonormal basis $\pmb{e_1},\pmb{e_2},\pmb{e_3}$ and write $\pmb{u}=u_1 \pmb{e_1}+u_2 \pmb{e_2}+u_3 \pmb{e_3},\pmb{v}=v_1 \pmb{e_1}+v_2 \pmb{e_2}+v_3 \pmb{e_3} $ and $\pmb{w}=w_1 \pmb{e_1}+w_2 \pmb{e_2}+w_3 \pmb{e_3}$. Then the matrix represneting the determinant, let's call it A,  would look like the following:
$$A=
\begin{bmatrix}
\langle \pmb{u},\pmb{e_1}\rangle & \langle \pmb{v},\pmb{e_1}\rangle & \langle \pmb{w},\pmb{e_1}\rangle \\
\langle \pmb{u},\pmb{e_2}\rangle & \langle \pmb{v},\pmb{e_2}\rangle & \langle \pmb{w},\pmb{e_2}\rangle \\
\langle \pmb{u},\pmb{e_3}\rangle & \langle \pmb{v},\pmb{e_3}\rangle & \langle \pmb{w},\pmb{e_3}\rangle
\end{bmatrix}
$$
When trying to compute $A^2$ (which we then simply take the determinant of), we run into multiplying inner products, which we can do according to $\langle x,y\rangle \langle w,z\rangle=\langle \langle x,y\rangle w,z\rangle$, but performing multiplication does not give (as far as I'm aware) the first entry to be the desired $u_1^2+u_2+u_3 ^2$, so I'm stuck. Also, where does the product theorem of the determinant come in?
Any help would be much appriciated.


text:
Q: Render custom json polymorphic list I have a /tags.json where i want to render a list of players and teams, using the following which i have put in both players and teams model.
def token
  "#{id}_#{self.class.name}"
end

Tags controller
def index
  @players = Player.all
  @teams = Team.all
  @tags = @teams + @players

  respond_to do |format|
     format.json { render json: @tags}
  end
end

But how can i create a list in my tags controller, so i can get something like this
[
    {"name":"Bob","token":"1_Player"},
    {"name":"Yankees","token":"1_Team"}
]

How can i do this?
Edit
format.json { render json: @tags.as_json(only: [:name])}

renders
[
    {"name":"Bob"},
    {"name":"Yankees"}
]

But how could i get token?

A: Try something like this:
@tags = []
Team.all.each do |team|
  @tags.push({name: team.name, tag: team.token})
end
Player.all.each do |player|
  @tags.push({name: player.name, tag: player.token})
end

respond_to do |format|
  format.json { render json: @tags}
end


text:
Q: Reference website live updating status from App I have a website: http://www.grandforks.af.mil/library/weathercenter/index.asp
There is a logo on the middle of the page for the current road conditions on base.
The file names for each condition is different by 1 number.

*

*Green is 19

*Yellow is 20

*Red is 21

I do not have control over this website.
My question is how can I have the current road conditions in an app that I am building display as a reflection of the website?  I don't want to have any user input I want the app to be able to pull off of the site.  I have tried using UIWebView but I cannot get it to focus on that area of the page. If I could do that it would probably be the better solution.

A: Ugly solution:
you can download the html of the website, parse it searching the string "http://www.grandforks.af.mil/shared/media/document/AFD-121002-" and get the actual URL (which is something like http://www.grandforks.af.mil/shared/media/document/AFD-121002-019.jpg).
After that, you can load that URL in your UIImageView or (better) discriminate and show your image that is included in the app.
The ugliness depends by the fact that if they change the image's URL, your app stops working.
I would suggest that when the user opens the app, it goes to check your page and eventually download the string your are looking for. Doing so, if the website changes the url, you can manually modify the source without update the app.
I don't know if using others information is legal.

EDIT:
here is an example that I built that demonstrate how you can substring a string:
NSString *myString = @"11111www.the-site.com/img42.jpg222222222222222";
NSString *searchString = @"www.the-site.com/img";
NSRange range = [myString rangeOfString:searchString];
NSLog(@"searched string strart at character %lu, and it's long %lu charactrers", (unsigned long)range.location, (unsigned long)range.length);
NSInteger index = range.location + range.length;
NSString *mySubString = [myString substringFromIndex:index];
NSLog(@"string from the index: %@", mySubString);
//I know that the substring I'm looking for is long exactly 2 characters
NSString *the_answer = [mySubString substringToIndex:2];
NSLog(@"this should print 42: %@", the_answer);

I added some prints, so you can see step by step what I'm doing.
Obviously you have to change "searchString" with "http://www.grandforks.af.mil/shared/media/document/AFD-121002-" and myString is the html of the page.
I hope it helps.


text:
Q: Fix closing tags with Java I have the following excerpt (in a String):
<Name/>Jhon<Name/><Number/>123B<Number/> <Cod Id="70" />ABCD9<Cod/>

I would like to correct the closing of the tags, to:
<Name>Jhon</Name><Number>123B</Number> <Cod Id="70" >ABCD9</Cod>

Any suggestions using java?
I tried like this:
Set<String> tagsOk = new HashSet<String>();
String tag = null;
String temp = null;
Pattern p = Pattern.compile("<([^\\s>/]+)");
Matcher m = p.matcher(xml);
while(m.find()) {
    tag = m.group(1);
    if(!tagsOk.contains(tag)) {
        temp = StringUtils.substringBetween(xml, "<"+tag+"/>", "<"+tag+"/>");
        xml = xml.replaceAll("<"+tag+"/>"+temp+"<"+tag+"/>", "<"+tag+">"+temp+"</"+tag+">");
    }
    tagsOk.add(tag);
}

UPDATE 1:
I forgot to mention, but they can be tags within tags
</tag Id="456" ><Name/>Jhon<Name/><Number/>123B<Number/> <Cod Id="70" />ABCD9<Cod/></tag >

A:
Any suggestions using java?

How about the following.
/*
 * import java.util.regex.Matcher;
 * import java.util.regex.Pattern;
 */
String str = "<Name/>Jhon<Name/><Number/>123B<Number/> <Cod Id=\"70\" />ABCD9<Cod/>";
StringBuilder result = new StringBuilder(str.length());
Pattern pattern = Pattern.compile("(<.+?/>)([^<]+)?");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    String one = matcher.group(1);
    String two = matcher.group(2);
    if (two == null  ||  two.strip().length() == 0) {
        one = one.replace("<", "</");
        one = one.replace("/>", ">");
        two = "";
    }
    else {
        one = one.replace("/>", ">");
    }
    result.append(one);
    result.append(two);
}
System.out.println(result);

one is the [XML] tag since, in your example string, each "start" tag has an identical "end" tag.
two is the [XML] tag "contents".
Running the above code prints the following:
<Name>Jhon</Name><Number>123B</Number><Cod Id="70" >ABCD9</Cod>

A: You may be able to get away with a regular expression accompanied by a find-and-replace in a loop, such as this:
public static String correctTags(String str) {
    Pattern patt = Pattern.compile("<([A-Z]+)([^/]*)/>(.*?)<\\1/>", Pattern.CASE_INSENSITIVE);

    boolean changed;
    do {
        changed = false;
        Matcher m = patt.matcher(str);
        String strNew = m.replaceAll("<$1$2>$3</$1>");
        if (!strNew.equals(str)) {
            changed = true;
            str = strNew;
        }
    } while (changed);

    return str;
}

The key here is the use of capturing groups (bits of the regex inside parentheses), plus the use of \1 that means 'an occurrence of whatever characters were captured as part of group 1'. Similarly, in the replacement, $1 means "whatever characters were captured as part of group 1". Then similarly, group 2 is any attribute content after the tag name, and group 3 is the tag contents. Of course, to deal robustly with all the possibilities of XML, the expression would need to be expanded considerably, and would probably reach a point where it wasn't practical to use regular expressions. But this quick-and-dirty solution may work for your specific case.

A: Thanks for all the suggestions, I managed to solve it as follows:
Map<String, String> mapTag = new HashMap<String, String>();
String tagTemp = null;
String startTag = null;
String endTag = null;
String contentTag = null;
String key = null;
int end = 0;
Pattern p = Pattern.compile("(<.+?/>)");
Matcher m = p.matcher(xml);
while(m.find()) {
    tagTemp = m.group(1);
    end = tagTemp.indexOf(" ");
    if(end == -1) {
        end = tagTemp.indexOf("/");
    }
    key = tagTemp.substring(0, end).replace("<", "");
    if(mapTag.containsKey(key)) {
        startTag = mapTag.get(key);
        endTag = tagTemp;
        contentTag = StringUtils.substringBetween(xml, startTag, endTag);
        xml = xml.replace(startTag+contentTag+endTag, startTag.replace("/>", ">")+contentTag+endTag.replace("/>", ">").replace("<", "</"));
    }else {
        mapTag.put(key, tagTemp);
    }
}
xml = xml.replaceAll(" >", ">");


text:
Q: Code::Blocks return error when using OpenCV "undefined reference to `cvFree_'|" in C /home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvDecRefData':|
main.c|| undefined reference to `cvFree_'|
main.c|| undefined reference to `cvFree_'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvGetRow':|
main.c|| undefined reference to `cvGetRows'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvGetCol':|
main.c|| undefined reference to `cvGetCols'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvReleaseMatND':|
main.c|| undefined reference to `cvReleaseMat'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvSubS':|
main.c|| undefined reference to `cvAddS'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvCloneSeq':|
main.c|| undefined reference to `cvSeqSlice'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvSetNew':|
main.c|| undefined reference to `cvSetAdd'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvGetSetElem':|
main.c|| undefined reference to `cvGetSeqElem'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvEllipseBox':|
main.c|| undefined reference to `cvEllipse'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvFont':|
main.c|| undefined reference to `cvInitFont'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvReadIntByName':|
main.c|| undefined reference to `cvGetFileNodeByName'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvReadRealByName':|
main.c|| undefined reference to `cvGetFileNodeByName'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvReadStringByName':|
main.c|| undefined reference to `cvGetFileNodeByName'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvReadByName':|
main.c|| undefined reference to `cvGetFileNodeByName'|
main.c|| undefined reference to `cvRead'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvContourPerimeter':|
main.c|| undefined reference to `cvArcLength'|
/home/piotr/Dokumenty/Projekt antybulglar/main.o||In function `cvCalcHist':|
main.c|| undefined reference to `cvCalcArrHist'|
||=== Build failed: 18 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

I,ve tried to install it in many ways for example:
https://www.youtube.com/watch?v=MqQB5KKJCh0
And still nothing.

A: Already fixed it, I needed to add OpenCV to Code::Blocks in Settings/Compiler there i first add "usr/include/opencv" and "usr/include/opencv2" to Search Directories/Compiler. And add all .so from usr/local/lib for OpenCV in Linker Settings tab.


text:
Q: android recyclerview load more button Is there a tutorial/example to include a load more button with recyclerview?
 I need to add a button after displaying 8  elements in the recyclerview.  The user can click this button to load the next 8 contents.

A: Add a footer view to your recyclerview which includes Load More button. When clicking the button, make a request for next 8 items. After loading items, notify the adapter.
RecyclerView header and footer

A: what you need is endless recycler view ,which will load the data while scrolling . Here I have attached link for that implementation.
Follow this link


text:
Q: How to bind selected kendo grid rows to another kendo grid in mvc I have one kendo grid with check box options in popup window and one more empty kendo grid in the main view.What i need is to bind the selected checkbox rows in grid 1 to empty kendo grid in mvc

A: Check the following post, which discusses a similar scenario:
https://stackoverflow.com/a/38707214/3086237
Even if you are not using the built-in selection feature, the core step is to retrieve a collection of the checked/selected rows in the first Grid via the dataItem method and push them to an array. Then, assign the array to the second Grid's dataSource instance.
An important note - the first Grid should use Ajax binding, otherwise there are no client-side data item instances.


text:
Q: ö in Latex - strange symbols In the acknowledgements of my paper I have to thank a German professor and his last name contains an ö. Every time I compile the file I end up getting an A with a tilde and an ü instead of an ö (see picture).
Does anyone know how to circumvent this?
Thanks for the support.

A: The characters ä,ö,ü are called "Umlaute" in german.
Maybe that does help you in some way.
I found this TeX answer.
According to it, the encoding of ö should be {\"o} in LaTeX.

A: You can use \ddot{o}
If you need an ä \ddot{o}


text:
Q: Trouble with intersection between line segments I have a path stored as points in an arraylist and I want to check if the line segments are intersecting. For some unknown reason it's not working! I don't get any message in the LogCat despite that I'm drawing a shape that intersects. Preciate if someone could see what I have done wrong or have suggestions how to improve code.
    // Intersection control
    if(touchActionUp) {

        // Loop throw all points except the last 3
        for (int i = 0; i < points.size()-3; i++) {
            Line line1 = new Line(points.get(i), points.get(i+1));

            // Begin after the line above and check all points after that
            for (int j = i + 2; j < points.size()-1; j++) {
                Line line2 = new Line(points.get(j), points.get(j+1));

                // Call method to check intersection
                if(checkIntersection(line1, line2)) {
                    Log.i("Intersection", "Yes!");
                }
            }
        }
    }

And the method:
    // Method to check for intersection between lines
private boolean interceptionControl(Line line1, Line line2) {
    int x1 = line1.pointX1;
    int x2 = line1.pointX2;
    int x3 = line2.pointX1;
    int x4 = line2.pointX2;

    int y1 = line1.pointY1;
    int y2 = line1.pointY2;
    int y3 = line2.pointY1;
    int y4 = line2.pointY2;

    // Check if lines are parallel

    int denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);

    if(denom == 0) { // Lines are parallel
        // ??
    }

    double a = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
    double b = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom;

    // Check for intersection
    if( a >= 0.0f && a <= 1.0f && b >= 0.0f && b <= 1.0f) {
        return true;
    }
    return false;
}

A: You are using int for coordinates and so it does integer division (i.e., 3/2 = 1). This might be the reason when you are dividing by denom. You can fix it by dividing by ((double)denom) instead of simply denom.


text:
Q: Element of group ring not invertible, but invertible in bigger group ring. I have thought about such problems:

*

*Is there a field $F$ and a group $G$ such that there exists element $x$ of group ring $FG$ which is not invertible in $FG$, but is invertible in $KG$, where $K$ is some field extension of $F$?

*A more particular version of my question is this: is it known for some $F$ being not algebraically closed and $K$ being algebraic closure of $F$?


text:
Q: Failed to load dynlib/dll I am trying to package the following Python code into an executable file using PyInstaller:
import pandas as pd
import teradatasql

with teradatasql.connect(host='abcdxxx', user='abcdxxx', password='abcdxxx') as connect:
        query = "SHOW TABLE AdventureWorksDW.DimAccount"
        df = pd.read_sql(query, connect)
        print(df)

When I run the .exe file, it gives me the error:
PyInstallerImportError: Failed to load dynlib/dll
'C:\\Users\\GAX~1.P\\AppData\\Local\\Temp\\_MEI153202\\teradatasql\\teradatasql.dll'.
Most likely this dynlib/dll was not found when the application was frozen.
[9924] Failed to execute script 'hello' due to unhandled exception!

I tried to make the following changes to the .spec file:
b = [
    ('C:\Users\Path_to_Python\Python\Python310\Lib\site-
      packages\teradatasql\teradatasql.dll', '.\\teradatasql')
     ]

a = Analysis(['hello.py'],
             pathex=[],
             binaries=b,
             datas=[] # , .....
             )

But it doesn't resolve the problem. How to fix this?

A: We provide an article explaining how to include the Teradata SQL Driver for Python into an application packaged by PyInstaller:
https://support.teradata.com/community?id=community_blog&sys_id=c327eac51b1e9c103b00bbb1cd4bcb37


text:
Q: Average idle temperature for i7 965 Nehalem 1366? Just wondering what should be the average idle temperature should be for an i7 965 Extreme Edition Nehalem 1366 processor.
The thing is, ever since the first day I bought and assembled this computer, my average idle temps have been between 45-50 C, and this is with a Zalman 9900LED, which is supposed to be a pretty decent heatsink.  On 100% load with Prime95's Blend test running, it goes up to 75-80C and stays there.
Today, as part of some maintenance, I cleaned out the dust that was caked onto the Zalman, cleaned out and reapplied thermal paste to the CPU.  I thought that perhaps if I did this it would help with the temps, but the temps have remained roughly the same.
I have no air conditioning - we live in a fairly humid place where average temps are around 27-29C with 60-70% humidity.  I'm not sure if the ambient temperature is a significant part of the problem, but I'm reading forum posts here that say that my average idle temps should be 35-40C, about 10 degrees cooler than what my idle temps are.
I'm using an Antec 1200 for my case, which is supposed to have great airflow.  I'm getting these temps without any overclocking, so I'm wondering if I'm just applying the thermal paste wrong, or if I'm missing something blatantly obvious.

A: From what I can find out, your CPU will be happy and long-lived at anything less than 105 C.
Average idle temperatures do depend on ambient temperature, as well as specific case and cooling system design as well as settings that affect how the cooling system responds to changes in (e.g fan speed settings).
No CPU is ever completely idle (unless in a halted state), it's "idle" workload depends on a lot of background tasks that vary a lot depending (amongst other things) on the version of the operating system and the peripheral drivers installed.


text:
Q: IQKeyboardManagerSwift: Next/Previous buttons invisible I've posted this issue here, but am posting here too in case I have more luck.
In the attached screenshots, the fields are laid out as so:
Superview (class IQPreviousNextView)
  Scroll View
    UIStackView ("Content Stack")
      UIStackView ("Input Stack")
        UIStackView ("Diameter Stack")
          UILabel
          UITextField
        UIStackView ("Perimeter Stack")
          UILabel
          UITextField
        UIStackView ("Area Stack")
          UILabel
          UITextField

And as you can see, when installing the application to my phone via Xcode, everything works as expected. But archiving + uploading and then using TestFlight seemingly makes these buttons invisible.
On another app I am developing, where this does actually work, I don't use any UIScrollViews - only multiple nested UIStackViews. Therefore is it possible that it's the UIScrollView causing issues?
In AppDelegate, I have this set up with IQKeyboardManager.shared.enable = true and no further configuration.

A: You have to just make UIViewcontoller's base view class of IQPreviousNextView, and all will be fine

A: There is another property to hide previousNext button, you should use shouldHidePreviousNext for this.
https://github.com/hackiftekhar/IQKeyboardManager/issues/546

A: Fixed by running pod deintegrate and then pod install. Not sure what the issue was - I'm guessing a corrupt installation...


text:
Q: How to insert/pass NULL value into Date field I am trying to insert a null value into a field of type Date (in SalesForce) using a PHP Script.
Here is my logic.
$Date = '',
$createField['Date__c'] = $Date;

I tried the following, but none of them work.
$Date = '';
$Date = null;
$Date = NULL;
$Date = 'NULL';
$Date = 'null';

A: You need to use the fieldsToNull attribute, as noted in the update documentation.
$createField["fieldsToNull"] = array("Date__c");


text:
Q: Cassandra cluster и точка входа для клиента Решил почитать про noSQL Cassandra, вроде все понятно, все интересно, НО, возник вопрос про доступ к кластеру.
Например, есть у меня кластер из нескольких нод. Все хорошо, реплицируется, но какую точку входа использовать? например я буду использвоать для подключения ноду 0 с адресом 192.168.0.1. Если вдруг по какойто причине она будет недоступна, то я могу использовать вторую ноду (нода 1) с адресом 192.168.0.2.
Вопрос состоит в том что как это сделать прозрачно для работы, в плане того, что я (читай разработчик) не должен "пинговать" ноды на предмет их доступности. Я вижу только чтото типа DNS RoundRobin, однако это добавляет туже проблему, что если одна нода недоступна, то мне нужно все равно еще раз подключаться к  ноде по доменому имени? ЗалУпить попытки подключения пока оно не будет установлено? Вообще как это реализуется в продакшене?

Хотя наверное это не только к cassandra относится :)

после просмотра исходников все встало на свои места, при подключении указываются все ноды кластера и библиотека сама все пингует и подключается. Так что вопрос неактуален стал. :) Посыпаю голову пеплом...
A: А как вы еще собираетесь определять отпавшие ноды или ноды с большой латентностью? Ребята из Netflix ,например, написали свой Java-клиент для Cassandra - Astyanax с failover, пулом соединений, мониторингом и прочими плюшками. Используйте или изучайте, как именно они организовали доступ к Cassandra-кластеру.


text:
Q: How to use ruby code in coffeescript jquery when we want to select an object with dynamic id? Well, I know that's a common question and found a lot of advice how to do it but it doesn't work for me and I can't understand what's the matter.
index.html.slim
- books.each do |book|
  .row class = "review_form" id = book.id
    .panel
      == render 'reviews/form', review: review, book: book

book.js.coffee
$('.row.review_form').hide()
  $('#new_review_button').on "click", ->
    $('.row.review_form#<%= book.id %>').show()
    $('#new_review_button').hide()
  $('#cancel_review').on "click", ->
    $(".row.review_form#<%= book.id %>").hide()
    $('#new_review_button').show()

According to instructions if you want to use ruby code in javascript you should use <%= ruby code %> as i'm doing here         $('.row.review_form#<%= book.id %>').show() but nothing happens. It seems like when i write <%= in brackets it changes into one string and js doesn't understand it's a selector with ruby code. What am I doing wrong? Please, help, I'm totally confused! ><

A: In your case you dont have a rails object in your coffee script file. You can rename your file to book.js.coffee.erb to execute <%= %># erb tags. Otherwise it will be considered as a string only. Refer to this  answer for more details. Hope it works :-)


text:
Q: Div visibility in javascript i was working on some requirements of my project and one of the requirement was to hide/unhide a Div on client side(Project is in .net technology and div's visibility will be set on client side using JS)
Code Snippet:
var block = document.getElementById('Your_Div_Id');
block.style.display = "none";   //some where it works to hide
block.style.visibility = "hidden";   //some where it works to hide

my question is why?
This is just hit and trial. first one was not working in one place so I used second one.I could not got to know why...

A: In case you dont want to use jQuery, Make sure your Id of element is unique and is set properly in javascript code
you may also try writing the code in one line as below :
document.getElementById("element-id").style.display="none";

A: Remember that display: none and visibility: hidden are different.
The first one "delete" the node from the DOM, and the other nodes can take it place.
The second one just hide hide, but the node preserves it position and sizes.
Tip: Try to use jQuery
$("#foo").hide();


text:
Q: so deep as that into his feelings? He paused; then went on: I don't know that the commanding officer delved so deep as that into his feelings. But he did suffer from them—a sort of disenchanted sadness. It is possible, even, that he suspected himself of folly. Man is various. But he had no time for much introspection, because from the southwest a wall of fog had advanced upon his ship. Great convolutions of vapours flew over, swirling about masts and funnel, which looked as if they were beginning to melt. Then they vanished.
This is a paragraph excerpted from a short story by Joseph Conrad: Tha Tale.
At first glimpse, I thought it is a plain "so adjective as" comparison sentence. I, however, got lost where "that" popped up.
1) I cannot understand why there is "that" right after "as", and what its grammatical function is.
2) I wonder what this sentence means. Does this mean that the narrator(I) doesn't know that the commanding officer delved so deep into something as the commanding officer delved deep into his feelings?

A: "That" refers back to something previously mentioned before your quotation begins.
The quote comes from The Tale by Joseph Conrad. Prior to your quotation, it speaks of "the murderous stealthiness of methods and the atrocious
callousness of complicities that seemed to taint the very source of
men's deep emotions and noblest activities; to corrupt their
imagination which builds up the final conceptions of life and death."
So, by saying "I don't know that the commanding officer delved so deep as that into his feelings", he is saying that he does not think the officer delved as deep so as to consider the "deep emotions and noblest activities" that they had just spoken of.


text:
Q: Trouble with Inclusion-Exclusion (Multiplication Theorem) $A_i$ is one event out of $n$.
$$P\left(\bigcap_{i=1}^n A_i\right) = P(A_1)P(A_2|A_1) \dotsb P(A_n|A_1A_2...A_{n-1})$$
I have trouble with this theorem (I am not sure what its name is, so the title might be wrong). It makes sense intuitively if the events are dependent to multiply them this way. But once I try to apply it to a problem I fail miserably.
I can't always calculate the intermediate steps $P(A_1|A_2)$.
An example where I couldn't:
A family has 8 dogs (named from 1 to 8). Each dog has his own sleeping spot named after him (1 to 8). What is the probabilty that no dog sleeps in his own spot this night? Assuming they pick the sleeping spots randomly.
In this case event $A_1$ would be that dog 1 doesn't sleep in his spot.
$P(A_1)$ is clear to me, it must be $\frac 7 8$. Or the permutations where dog 1 is not sleeping in his place $7*7!$ divided by all $8!$. After that I am lost.

A: I call that thing the product rule. But I think it is more commonly known as the chain rule.

As for the example, that's not quite the approach you want to take. It is easier compute the complementary probability. Let $\bar A$ be the event that no dog sleeps in his spot. Notice that the complement is $A =\{\text{at least one dog sleeps in his spot}\}$. Let $A_i$ be the event that the dog $i$ sleeps in his spot $i$. Then
$$P(\bar A) = 1-P(A) = 1-P(A_1\cup A_2\cup\dotsb\cup A_7\cup A_8)$$
At this step is where you want to use inclusion-exclusion.


text:
Q: hr-xml - the namespace attribute of an import should be the same value as the tragetnamespace of the imported schema I'm receiving the error at below line as
"the namespace attribut 'http://www.applications.org/sdf/9' of an import should be the same value as the tragetnamespace 'http://www.hr-xml.org/3' of the imported schema"
<xsd:import namespace="http://www.applications.org/sdf/9" schemaLocation="Components.xsd"/>

Components.xsd -
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:oa="http://www.applications.org/sdf/9" xmlns:ccts="udn:dn:udede:dndedact:ddcdmdndation:1.1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.hr-xml.org/3" targetNamespace="http://www.hr-xml.org/3" elementFormDefault="qualified" attributeFormDefault="unqualified">
  <xsd:annotation>
    <xsd:documentation>Name: Components.xsd Status:  3.2 Release Date this version: 2011-Sep-28</xsd:documentation>
  </xsd:annotation>
  <xsd:import namespace="http://www.applications.org/sdf/9" schemaLocation="Components.xsd"/>
  <xsd:include schemaLocation="Fields.xsd"/>
  <xsd:element name="AlternateScriptPersonName" type="AlternateScriptPersonNameType"/>
</xsd:schema>

Please any help?

A: Can you look into the Components.xsd file?
What is the default namespace there?
That is the namespace that should be put here:
<xsd:import namespace="http://www.applications.org/sdf/9" schemaLocation="Components.xsd"/>

instead of http://www.applications.org/sdf/9
That should do the trick.


text:
Q: Gigabit lan has slow speeds So I am trying to setup gigabit lan and be able to transfer files across computers at over 100 MB/s. But I can only achieve 20-25 MB/s. My setup is the following: - Two machines: a brand new laptop with an NVME drive (read speeds over 3000 MB/s) and a desktop (a bit old but has SATA 3 SSD (Kingston A400, read speeds around 420 MB/s), gigabit ethernet ports, and no CPU bottleneck).
I have both computers connected with CAT5e cables to the router (my ISP has a all in one router, ONT, router and wifi). I managed to samba share a folder on the desktop PC, with a single 6GB ISO file, and downloaded it from the laptop. However, the transfer speed is 20-25MB/s.
Note that both computers have gigabit connection (i checked it) and even the config page of the router says that the ports of the laptop and desktop are enabled with gigabit connection. Still the transfer speed is slow.
Any thoughts? The only thing that could be troublesome is the ethernet dongle on the laptop, but it has gigabit speeds and it appear correctly
Thank you!

A: Be careful about mixing up bandwidth (the rate of network data you can transmit on a network interface, in this case 1 gigabit) with throughput (the amount of data you can actually push through a particular system).
The test you are doing does not measure the LAN speed, it's measuring the overall throughput of a Samba server, a Samba client, and the disk I/O required to read the file on the server side and to write the file on the client side, and also the performance of the SMB protocol used to transfer the files. All of these factors add up, especially the performance of the SMB protocol and the time spent writing the destination file.
To test JUST the network speed, you need a specialized utility that's designed to generate and receive network traffic without doing any disk I/O or anything else that might slow the process down. The ttcp utility is one such tool, try using that on both machines to test your bandwidth (or iperf as suggested in the comments). Note that you're still not going to see 1000 Mbps transfer rates - there is always some overhead for the framing of the Ethernet packets and for the IP protocol - 800 or 900 Mbps is more likely. See this page for a more complete discussion of overhead and how much throughput you can expect to see on a gigabit Ethernet connection.
Another tip - my rule of thumb when translating between bits per second (network bandwidth) and bytes per second (payload bandwidth such as file transfers) is to divide or multiply by ten, because to transmit an 8-bit byte over the network usually requires around 10 bits of actual data on the wire due to packet framing. So your current speeds of 20-25 MBps (bytes per second) are roughly equivalent to 200-250 Mbps (bits per second).


text:
Q: Java - Making inherited variables PRIVATE I need to make my inherited instance variables private; is this possible?
IE, Superclass "Entity" has an int instance variable "health".
How can subclass "Zombie" (Extends "Entity") inherit the health variable from Entity, and have it private? I don't want other classes to be able to directly access the health variable, I want set and get methods for it.
Tell me if I wasn't specific enough; any help appreciated.

A: Simply : you can't.
This would break the contract of the superclass. Your class, being an Entity, exposes, like its superclass, a field named health. If you had the ability to make it private, all code using this field in instances of Entity (including instances of subclasses of Entity) would break with your class...
If you can, change the superclass (ie Entity) to make the field private. That's the common practice.

A: You cannot decrease the visibility of any instance variable or method of the super class in your subclass..
Suppost you have super class with a public method.. And, suppose you were allowed to decrease the visibility to private in sub class..
Then see what's happens when you create object like this, and access that method of super class: -
SuperClass obj = new SubClass();
obj.pubMethod();

Now, at compile time, compiler sees that method pubMethod() is public in SuperClass, it will allow the access.. Note it does not check for the instance type on the RHS..
Now, at runtime, when JVM checks that the instance is of SubClass, then the actual method it would try to invoke will be searched in the SubClass..
But wait.. Did you see what happened when JVM went to search for pubMethod in SubClass that you made private..  BOoooooMMM --  A Crash..
That's why it is not allowed..
So, you cannot make it private..
From JLS Section - 8.4.8.3:  -

The access modifier (§6.6) of an overriding or hiding method must
  provide at least as much access as the overridden or hidden method, or
  a compile-time error occurs. In more detail:

*

*If the overridden or hidden method is public, then the overriding or    hiding method must be public; otherwise, a compile-time error
  occurs.

*If the overridden or hidden method is protected, then the overriding    or hiding method must be protected or public; otherwise,
  a    compile-time error occurs.

*If the overridden or hidden method has default (package) access, then    the overriding or hiding method must not be private;
  otherwise, a    compile-time error occurs.

A: Make the variable private in the superclass and let all subclasses use accessor methods.
A second choice would be to make it package-private and arrange for those classes to which you want to deny access to be in another package. This would make sense if your Zombie is especially close to Entity (shares many internals) whereas other classes are more loosely coupled to their superclass.

A: You cannot add restrictions to an instance variable in a subclass, i.e. of health is protected in Enitity it cannot be private in Zombie (you can make it public).
However, you can make health private in Entity and define a protected getter and setter there. Subclasses can use these methods.


text:
Q: Архитектура Vue приложения Нуждаюсь в правильном совете по организации приложения. Пишу на vue+vuetify, взял за основу проект с github. В моем приложении есть три типа страниц. Первая страница простая, содержит навигационную панель и при клике на пункты меню меняется содержимое страницы. Тут все просто, используя vue-router можно менять содержимое страницы.

Но есть второй вариант, более сложный. При клике на этот тип страницы, открывается вариант страницы с сайдабаром, то есть кликаем на элементы сайдбара, меняется содержимое окошка справа. И тут я уже не знаю что делать, получается что vue-router в vue-router, но как приложению понять какой из роутеров надо открыть?

И есть вариант страницы 3. В сайдбар добавляются ещё и вкладки, и содержимое сайдбара меняется от выбранной вкладки. В тоже время в меню справа грузится либо что-то от выбранного во вкладке, либо что-то что назначено в Menu 1. То есть получается и для сайдбара vue-router и для содержимого вкладок и для окна справа, как в них не запутаться то...

Приложение для организации путешествий, отелей, и т.д.. Как правило в окне справа будет гугл карта, но не всегда. В некоторых случаях будет другой контент.
Надеюсь все объяснил правильно. Помогите пожалуйста советом и если можно кусками кода, как сделать такой функционал приложения? Спасибо.


text:
Q: google-maps-react adding a Marker I'm using the google-maps-react library to add a google map with markers that update on state change.
I want to dynamically add markers after fetching locations from Google's place api and storing them in state.
I fetch the data, add it to state then call displayMarkers:
displayMarkers = () => {
    this.state.newStations.map((station, index) => {
      let lat = station.geometry.location.lat();
      let lng = station.geometry.location.lng();
      return (
        <Marker
          key={index}
          id={index}
          position={{
            lat: lat,
            lng: lng,
          }}
          onClick={() => console.log("You clicked me!")}
        />
      );
    });
  };

State is being updated but the markers do not appear on the map.
Reading the doc for google-maps-react, it seems to me that marker must be a child of map in order to be overlaid onto the map.

Marker To place a marker on the Map, include it as a child of the
  component.

Is there any way to return the Marker as a child of Map?
In the google maps API it seems as though you can do this like so:
var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
  });

You pass in the value map, which is the map you wish your marker to be attached or overlaid onto. The prop "map" exists in google-maps-react but there doesn't seem to be a property in Marker which accepts map.

A: You can do it like this in google-maps-react. You need to have an array in the state to hold the results array. Then when fetching Places results, create an array variable then push the result on that arrau variable. You then set the marker array state value as the array variable.
Then inside your Map object, put the Marker object however you need to add condition that will check if the marker array state value is not null and you map each of the marker array state value in the marker object..
import React, { Component } from "react";
import { Map, GoogleApiWrapper, Marker } from "google-maps-react";

export class MapContainer extends Component {
  state = {
    center: {
      lat: 40.854885,
      lng: -88.081807
    },
    markers: null,
  };

  fetchPlaces = (mapProps, map) => {
    let coordinates = [];
    const { google } = mapProps;
    const service = new google.maps.places.PlacesService(map);
    var request = {
      location: this.state.center,
      radius: "500",
      query: "restaurant"
    };
    service.textSearch(request, (results, status) => {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          //console.log(results[i]);
          coordinates.push(results[i]);
        }
        this.setState({ markers: coordinates });
      }
    });
  };

  clickMarker = (props, marker) => {
    console.log(props.placeId);
  };

  render() {
    if (!this.props.loaded) return
Loading...
;

    return (

        <Map
          className="map"
          google={this.props.google}
          center={{
            lat: this.state.center.lat,
            lng: this.state.center.lng
          }}
          onReady={this.fetchPlaces}
          style={{ height: "100%", position: "relative", width: "100%" }}
          zoom={8}
        >
          {this.state.markers != null &&
            this.state.markers.map(coords => (
              <Marker
                key={coords.place_id}
                position={coords.geometry.location}
                onClick={this.clickMarker}
                placeId={coords.place_id}
              />
            ))}
        </Map>

    );
  }
}
export default GoogleApiWrapper({
  apiKey: "YOUR_API_KEY"
})(MapContainer);```


text:
Q: Why are some items in my HTML & CSS not linking? Below is my HTML:

<meta charset="utf-8">

<title>Animal Trading Cards</title>

<link rel="stylesheet" href="styles.css">

Tiger

The tiger is the largest cat species.

Scientific Name: Panthera tigris

Average Weight: 485 pounds

Average Lifespan: 10-15 years

Habitat: Forests, grasslands, swamps, and woodlands

 A Tiger is a powerful carnivore, a hunter with sharp teeth, strong jaws, and a very agile body. They are the largest naturally occurring species of cat, of which the Siberian tiger is the largest, weighing up to 800 pounds and measuring up to 11 feet head to tail.

My CSS is below. My image in my code, for example, is not changing size. Items that should be italicized are not...
html {
  font-family: Arial, Helvetica, sans-serif;
}

#card {
width: 300px;
padding: 10px;
border: 1px solid #cccccc;
box-shadow: 5px 5px
}

.title {
font-weight: bold;
}

.picture {
  width: 300px;
  height: 200px;
}

#card-info {
margin: 0px;
padding: 10px;
border: 1px solid #cccccc;
}

.fact {
font-style: italic;
}

.list {
  list-style: none;
  padding: 0px;
}

.label {
 font-weight: bold;
}

Sorry, completely new to this. Its my first post! I believe I actually go the two to link properly after putting them in a separate folder on my desktop.

A: To change image size,
img {
    width: 200px;
    height: 200px;
}

To change font size for your class label,
.label {
    font-size: 30px;
}

To change your text italic, for your class label,
.label {
    font-style: italic;
}

If you used these and still doesn't show in your webpage, it may be because, you are using css in separate file, styles.css . So, may be your browser doesn't sync latest css data and still using old caches. (recommened to use firefox browser or press ctrl+F5 to refresh the page in chrome)


text:
Q: Choose value in column depending on a second column I have some DataFrame:
df = pd.DataFrame({'Food': ['pizza', 'pasta', 'pizza'], 'Day': [3, 4, 5], 'Time': [8,9,10]})

I would like to add a new column, NEW that selects the Day if the Food is pizza or the Time if the Food is pasta, e.g.:

A: We use np.where
df['New']=np.where(df.Food=='pizza',df.Day,df.Time)

A: Or loc:
df['NEW'] = df['Day']
df.loc[df['Food'].eq('pasta'), 'NEW'] = df['Time']
print(df)

Output:
   Day   Food  Time  NEW
0    3  pizza     8    3
1    4  pasta     9    9
2    5  pizza    10    5


text:
Q: Measurability of a generalized point spectrum Assume that  $ T:H\oplus H\rightarrow H\oplus H$ is a unitary linear operator on the double sum of a separable Hilbert space $H$ with itself.
Let us call a pair $(\lambda, \mu)\in\mathbb{C}\oplus\mathbb{C}$ to be a point of the generalized point spectrum $\sigma(T)$ if and only if there exists a vector $(x,y)\neq (0,0)\in H\oplus H$, such that $T(x,y)=(\lambda x, \mu y)$.
Question: Is it true that $\sigma(T)$ is a Lebesgue measurable subset of $\mathbb{C}\oplus\mathbb{C}$ ?


text:
Q: How do I call a function that includes Graphics g I was wondering how I could call a function that includes Graphics G if a certain thing happens in my program.
public void dead (Graphics g) {
    right = false;
    left = false;
    up = false;
    down = false;
    dead = true;
    score = 0;
    moves = 0;
    g.setColor(Color.WHITE);
    g.setFont(new Font("arial", Font.BOLD, 50));
    g.drawString("Game Over", 300, 300);

    g.setFont(new Font("arial", Font.BOLD, 20));
    g.drawString("Press \"Space\" To Restart", 312, 340);
}

How do I call this from somewhere else? I tried doing dead(); but it says that this method is not vailable for this argument. Thanks in advance!
EDIT: Here is my JFrame:
    JFrame obj = new JFrame("Snake");
    gameplay gameplay = new gameplay();
    obj.setBounds(10, 10, 905, 700);
    obj.setBackground(Color.DARK_GRAY);
    obj.setResizable(false);
    obj.setVisible(true);
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.add(gameplay);

A: This dead(g) method us supposed to be called in paintComponent(Graphics g) to update the screen when the snake is dead:
In the panel displaying your paintings, you will have something like this:
@Override
public void paintComponent(Graphics g){
    super.paintComponent(g):
    if(gameOver)
        dead(g);
}

By the way, you may not want to include codes non-related to painting into your dead(g) method such as:
right = flase:
left = flase;
...
score = 0;
moves = 0;

Whenever possible, keep your painting methods clutter free from other non-painting related codes. In extreme cases, cluttering it may cause your display to lag.


text:
Q: A terminal that has a separate input and output window? I am looking for a terminal on Ubuntu Desktop (or Windows) that can split input and output in different windows. Like a split window, on the left side I type all the commands, the results will be displayed in the window on the right side.
I've been seaching for this for a long time and so far I have not found anything can do such.
Any good suggestions?

A: I managed to produce this output without any special software.   I did the following -

*

*Opened up 2 windows.  (The left I will use for input, the right for output)

*In the right hand window I created a named pipe with the below command  (I used /dev/shm because that is shared memory but I could have just as easily put it somewhere else, and the output filename is arbitrary).
mkfifo /dev/shm/test.fifo

*In the second window I then issued a command to read the pipe -
tail -f /dev/shm/test.fifo

*On the left side I typed the below to create a bash shell whose contents was sent to the FIFO file which was read by the fifo.   This will push stdout to the fifo.   This seems to leave the command prompt on left window
bash > /dev/shm/test.fifo
Alternatively, to output both stdout and stderr  (this removes the command prompt on the left window)
bash > /dev/shm/test.fifo 2>&1
You can type exit to close the bash shell,  to stop catting the output and rm /dev/shm/test.fifo to remove the named pipe.

A: I don't know of a dual-pane terminal window but I can tell you how to send the output to another open terminal window. Open two terminal windows and in the second, use the tty command. The result will be something like /dev/pts/1.
Back in the first window, type your command and send the output to the second window.
For example, $ls > /dev/pts/1.The result will show up in the second window.

A: I would love to see a mockup (maybe a pencil drawing on a piece of paper) how you imagine this to look like.
How would the inputs and the outputs be paired up? What would be displayed on the left side if the output is quite long? How would it not result in an enormous waste of precious screen space? (Or would it?)
How would it look like when you have an interactive application (e.g. text editor) running?
What do you exactly consider "input" vs. "output"? For example, is the shell prompt "input" or "output" according to your idea? If you press Ctrl+R and the shell displays (reverse-i-search), where does it belong? These are strings output by your shell, so strictly speaking you said you'd want them in the right column. But if they're displayed there then editing the command line would work quite silly, so I'd rather expect you'd like to see it in the input pane...

The reason that there's no such terminal is probably partially some of the above (e.g. figuring out how to use the space efficiently), but mainly that the notion of input and output are quite different from how you imagine them to be.
In fact, everything that a terminal displays is the output of some other component (sometimes an application, sometimes the kernel). The keyboard input (which I presume you refer to by "input") is never(*) directly displayed by the terminal.
((((*) Strictly in parentheses, just for technical correctness: a few terminals implement a mode when the input is displayed immediately by the terminal, but it's hardly, if ever, in use in practice. It's a legacy we've left behind decades ago. Forget that I said anything here.)))
Depending on what application is running in the terminal emulator and what context that application is in (e.g. you're typing a command line), if you press a certain letter, let's say you press the letter x, the response may or may not be a letter x appearing. But it's never because the terminal decides to paint the pressed letter. It's because the terminal forwards that letter to the kernel, which may respond itself or may forward it to an application, which may respond, and that response may be (but is not necessarily) to print the letter x, which then causes the terminal to paint the letter x.
The differentiation that you imagine between the input and the output of the terminal is not what it has. The input is a keypress that it forwards but doesn't display. Everything that the terminal displays is the output of the kernel or an application (nitpicking: which is an input to the terminal, not from the user but from the application, but this is what we usually refer to as "output", i.e. looking at the story from the kernel's or application's point of view).
What I presume you'd like to have split into two panes are the command line (prompt and the command you're editing) versus the command's output. The terminal emulator could not automatically make such distinction, it has no idea whether the received data was sent by the shell (command line handler) or by an application; in fact, a terminal emulator has no idea what a shell is. All it sees is a single stream of instructions. The prompt, and then if you're typing "ls" then the letters "l" and "s", and then if you press Enter then the file listing all arrive in the same single stream, and the terminal treats them all equally because that's what it has to do, and because even if it wanted to it had no clue how to separate them into multiple kinds of data.
What you would like to have would require some kind of splitting. Either escape sequences in this stream that tell the terminal which side to print the data to, or two separate tty lines and then support from the shell to print the prompt and the command line into one tty line and connect the application's output to another – coupled up with a terminal application that displays two terminals next to each other and launches that special shell in a way that it's connected to both of these terminals.

I'm fairly confident that what you wish to have doesn't exist. Reasons include that it's not a commonly sought feature, that it would need cooperation between multiple crucial components (therefore it's unlikely that one person would quickly implement it and gain some popularity), that it would likely result in large unused screen area, and that the whole concept of terminal input and output (that I believe you fundamentally misunderstand) aren't built up in a way that could easily accomodate support for this feature.
My best recommendation is to get used to how existing terminals and shells work. Feel free to play around to find your preferred shell and customization thereof, make the prompt and the command line stand out or blend in the context as much as you wish to (e.g. using colors, bold or italic typeface, special Unicode characters, possibly multiline prompt etc.).


text:
Q: jQuery: getting the nth position of an object I have a div that contains checkboxes. I also have a function that accepts a jquery object parameter. It looks like this:
function analyze_checkbox(cb) { ... }

Given this, is there a straightforward way to know the child position of the cb parameter? I was thinking of something like this:
cb.parent().index(cb)

What is the proper way to do it?
Thanks,
Erwin

A: Quoting from .index()

If no argument is passed to the
.index() method, the return value is
an integer indicating the position of
the first element within the jQuery
object relative to its sibling
elements.

So in  your case cb.index(); should do it
Example at http://www.jsfiddle.net/qQzte/
and do not forget that the results is 0-based

A: If your checkboxes really are siblings of each other, then Gaby's answer saying cb.index() should do it is quite correct. Be careful, though, that you understand what index is actually telling you. For example, with this markup:

    <input type='checkbox' value='1' name='one'>One
    <input type='checkbox' value='2' name='two'>Two
    <input type='checkbox' value='3' name='three'>Three
    <input type='checkbox' value='4' name='four'>Four

...if your cb is from (say) $('#thediv input[type=checkbox][name=three]'), the result of cb.index() will be 0 (link to example). Clearly not what you want.
You can handle that in a couple of ways. With the specific example above, you could just look to see where the parent label was relative to its siblings: cb.parent().index() (link to example). But depending on your markup, that could be complicated.
There's a way that's less subceptible to subtle markup changes: Select exactly the list of elements you want to consider, and then ask jQuery where cb is within that list. So with the markup above, you might do this:
// The selector choose *exactly* the set of things we want to
// look at, and then `index` looks for `cb` within that list
var index = $('#thediv input[type=checkbox]').index(cb);

link to example


text:
Q: Página pisca ao dar F5 Não sei se minha dúvida é algo comum ou não.
Estou criando um site, ele está totalmente otimizado (Imagens super leves, Códigos, Scripts e etc.), no entanto, sempre que atualizo a página, ele meio que pisca uma tela branca rapidamente e abre a página. Como posso corrigir isso?

A: Evitar completamente, acredito que não tenha uma solução definitiva, mas existem algumas práticas que vão ajudar você a mitigar esse problema, algumas feitas no lado do cliente e outras no servidor mesmo.
Html

*

*Folhas de estilho deve ser declaradas no início do arquivo.

*Scripts devem ser declarados no final do arquivo.

*Adicione uma cor de fundo através do atributo e estilo na tag <html> e <body>
<body bgcolor="#ccc" style="background-color:#ccc;">

*Evite realizar requisições POST quando um GET pode ser usado
Servidor

*

*Configurar e habilitar o Cache.

*Compressão para transferência de arquivos
estáticos (GZIP)

*Distribuir os conteúdos que podem ser baixados paralelamente em diferentes hosts (CDN)


text:
Q: Where can I find the gradient calculation implementations for each operation in tensorflow ? I went through the source code and the gradient function implemented in this python file
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/gradients_impl.py
But still I couldn't find any python api for calculating gradients ?
What is this process ?

A: Here's an example from my code where I'm taking the gradient of my loss function with respect to the activations of the last layer of my network and then passing that to tensorboard in the form of a single scalar value and as a histogram.
gradient_a = tf.gradients(loss, [0], [3]), [out_layer_a], name='gradient_position_a')
tf.summary.scalar('mean_gradient_magnitude_a', tf.reduce_mean(tf.abs(self.gradient_a)))
tf.summary.histogram('gradient_magnitude_a', gradient_a)

If you want to output the gradient just fetch gradient_a in your call to session.run([loss, gradient_a], feed_dict={...})


text:
Q: Splitting in Python says to me, "IndexError: list index out of range" I have this function.
blocklist_data = unpack_blocklist_data()
hostnames = []
for entry in blocklist_data:
    if not entry.startswith('#'):
        hostname = entry.split()
        if len(hostname) == 1:
            hostnames.append(hostname[0])
        else: hostnames.append(hostname[1])
return hostnames

blacklist_data is just different txt files. Some have entries that look like;
0.0.0.0 site.domain.org

Other files have entries that look like;
site.domain.org

Those are the only two options.
I am getting error in regard to the else: line;

 else: hostnames.append(hostname[1])
                        ~~~~~~~~^^^
IndexError: list index out of range

I am just wanting to split when the entry looks like 0.0.0.0 site.domain.org - otherwise, don't split because there is no need.

A: Based on the comments you can also try to solve it in a single line via list comprehensions with:
hostnames = [x.split()[0] if len(x.split()) == 1 else x.split()[1] for x in blocklist_data if (len(x) > 0 and not x.startswith("#"))]

Based on the following example:
blocklist_data = ['','0.0.0.0 site.domain.org','site.domain.org','# 0.0.0.0 site.domain.org']
hostnames = [x.split()[0] if len(x.split()) == 1 else x.split()[1] for x in blocklist_data if (len(x) > 0 and not x.startswith("#"))]

We get:
['site.domain.org', 'site.domain.org']


text:
Q: I thought magnets could affect the operation of chips, but I see Apple use them increasingly in more their products, am I wrong in my thinking? I'm a bit confused because I used to use magnets to fix the TV monitor when it had faults in the image, but it wasn't good to use it that much.
Apple is using magnets in their products such as AirPods and iPad, could someone provide some clarity on this please?

A: Most chips are not particularly sensitive to static magnetic fields, so including one in a product is usually not a serious problem.  CRT monitors and TVs are sensitive to magnetic fields because they're big vacuum tubes, but they don't put vacuum tubes in electronics much anymore.

A:
Figure 1. Cathode ray tubes work be sending a beam of electrons from the cathode to the phosphor coated screen. Beam position is controlled by deflection using electric or magnetic field. Image: Cathode-ray tube on Wikipedia.
The important point here is that there is a beam of electrons moving through open space and these can be deflected. When semiconductors such as transistors came along the term "solid-state" came into use to describe the electronics as made of solid components without vacuum tubes.

Figure 2. The Hall-effect.

If an electric current flows through a conductor in a magnetic field, the magnetic field exerts a transverse force on the moving charge carriers which tends to push them to one side of the conductor. This is most evident in a thin flat conductor as illustrated. A buildup of charge at the sides of the conductors will balance this magnetic influence, producing a measurable voltage between the two sides of the conductor. The presence of this measurable transverse voltage is called the Hall effect after E. H. Hall who discovered it in 1879. Source: Hyperphysics.

So, magnetic fields can affect charged-carrier movement in solid-state devices and this is used to advantage in Hall-effect sensors in current measurement and magnetic position sensors (on industrial pneumatic actuators, for example). In most electronic applications magnetic field effects are far too small to cause problems.


text:
Q: pick latest record in join query Below is my query to update manager field in one table. The problem I am facing is I want to pick the user (NRH.AffectedUserNumber) with lastest start date in RH Table.
WITH [NewReqHeader]
AS
(SELECT ROW_NUMBER()
           OVER(ORDER BY RH.StartDate DESC) AS rowid
          , RH.RequestId
          , RH.RequestType
          , RH.RequestStatusID
          , RH.AffectedUserNumber
          , RPD.TaskId
          , RPD.HotelID
          , RH.StartDate
      FROM DBO.RequestPermissionDetail RPD
           JOIN DBO.RequestHeader RH ON  RH.RequestId = RPD.RequestId
                    AND RH.RequestType = 2
                    AND RH.RequestStatusID = 20
                    AND RPD.TaskId = 923
)
UPDATE #Facility_Manager
SET    Manager = NRH.AffectedUserNumber
FROM   #Facility_Manager FM
       LEFT OUTER JOIN [NewReqHeader] NRH ON  FM.FacilityId = NRH.HotelID
                AND ISNULL(FM.FacilityId ,'') != ''
WHERE  FM.SecPermissionCount > 1

A: You will need to add a PARTITION BY clause to the ROW_NUMBER function to get a count by each HotelID.
Then just limit the WHERE clause to
WHERE  FM.SecPermissionCount > 1 AND NRH.rowid = 1

A: update fm
set
  Manager = (
    select top 1 AffectedUserNumber
    from
    NewReqHeader nrh
    where fm.FacilityID = nrh.HotelID
    order by StartDate desc
  )
from
#Facility_Manager fm
where
SecPermissionsCount > 1


text:
Q: $a_1 a_1', a_2 a_2', ..., a_n a_n'$ is not a reduced modulo system $\mod p$. If $a_1, a_2, ..., a_n$ is a reduced residue system $\mod p$ and $a_1', a_2', ..., a_n'$ is another reduced residue system $\mod p$ then $a_1 a_1', a_2 a_2', ..., a_n a_n'$  is not a reduced modulo system $\mod p$.
Not able to show a counter to it. Help Needed.

A: Since $\{a_1,a_2,\ldots,a_n\}$ is a reduced residue system modulo $p$, we know that modulo $p$, $\{a_1,a_2,\ldots,a_n\}$ is a permutation of $\{1,2,\ldots,p-1\}$.
Knowing this, we have by Wilson's Theorem $\prod_{k=1}^na_k\equiv1\times2\times\ldots\times (p-1)\equiv -1(\mathrm{mod}~p)$.
Now $\prod_{k=1}^na_ka'_k\equiv\left(\prod_{k=1}^na_k\right)\left(\prod_{k=1}^na'_k\right)\equiv(-1)^2\equiv1(\mathrm{mod}~p)$
Since the first result holds for any reduced residue system, we can conclude that $\{a_1a'_1,a_2a'_2,\ldots,a_na'_n\}$ is not a reduced residue system modulo $p$.


text:
Q: Function to REPLACE* last previous known value for NULL I want to fill the NULL values with the last given value for that column. A small sample of the data:
2021-08-15  Bulgaria    1081636
2021-08-16  Bulgaria    1084693
2021-08-17  Bulgaria    1089066
2021-08-18  Bulgaria    NULL
2021-08-19  Bulgaria    NULL

In this example, the NULL values should be 1089066 until I reach the next non-NULL value.
I tried the answer given in this response, but to no avail. Any help would be appreciated, thank you!
EDIT: Sorry, I got sidetracked with trying to return the last value that I forgot my ultimate goal, which is to replace the NULL values with the previous known value.
Therefore the query should be
UPDATE covid_data

SET people_vaccinated = ISNULL(?)

A: Assuming the number you have is always increasing, you can use MAX aggregate over a window:
SELECT dt
     , country
     , cnt
     , MAX(cnt) OVER (PARTITION BY country ORDER BY dt)
  FROM #data

If the number may decrease, the query becomes a little bit more complex as we need to mark the rows that have nulls as belonging to the same group as the last one without a null first:
SELECT dt
     , country
     , cnt
     , SUM(cnt) OVER (PARTITION BY country, partition)
FROM (
    SELECT country
         , dt
         , cnt
         , SUM(CASE WHEN cnt IS NULL THEN 0 ELSE 1 END) OVER (PARTITION BY country ORDER BY dt) AS partition
    FROM #data
) AS d
ORDER BY dt

Here's a working demo on dbfiddle, it returns the same data with ever increasing amount, but if you change the number for 08-17 to be lower than that of 08-16, you'll see MAX(...) method producing wrong results.

A: In many datasets it is incorrect to make assumptions about the behaviour of the data in the underlying dataset, if your goal is simply to fill the blanks that might appear mid-way in a dataset then the answer to the post you referenced A:sql server nulls duplicate last known value in table is still one of the best solutions, here is an adaptation:
SELECT dt
     , country
     , cnt
     , ISNULL(source.cnt, excludeNulls.LastCnt)
  FROM #data source
  OUTER APPLY ( SELECT TOP 1 cnt as LastCnt
                FROM  #data
                WHERE dt < source.dt
                AND cnt IS NOT NULL
                ORDER BY dt desc) ExcludeNulls
 ORDER BY dt

MAX and LAST_VALUE will give you the a value with respect to the entire record set, which would not work with the existing solutions if you had a value for 2021-08-19. In that case the last value would be used to fill the gaps, not the previous non-null value.
When we need to fill in gaps that occur part-way through the results we need to apply a filter to the window query, TOP 1 ... ORDER BY gives us the ability to filter and sort on entirely different fields to the one that we want to capture, but also means that we can display the last value for fields that are not numeric, see this fiddle a few other examples: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=372285d29f97dbb9663e8552af6fb7a2


text:
Q: Python subplots with seaborn or pyplot I'm a R programmer learning python and finding the plotting in python much more  difficult than R.
I'm trying to write the following function but haven't been successful. Could anyone help?
import pandas as pd

#example data
df1 = pd.DataFrame({
        'PC1':[-2.2,-2.0,2.04,0.97],
        'PC2':[0.5,-0.6,0.9,-0.5],
        'PC3':[-0.1,-0.2,0.2,0.8],
        'f1':['a','a','b','b'],
        'f2':['x','y','x','y'],
        'f3':['k','g','g','k']
        })

def drawPCA(df,**kwargs):
    """Produce a 1x3 subplots of scatterplot; each subplot includes two PCs with
    no legend, e.g. subplot 1 is PC1 vs PC2. The legend is on the upper middle of
    the figure.
    Parameters
    ----------
    df: Pandas DataFrame
        The first 3 columns are the PCs, followed by sample characters.
    kwargs
        To specify hue,style,size, etc. if the plotting uses seaborn.scatterplot;
        or c,s,etc. if using pyplot scatter
    Example
    ----------
    drawPCA(df1, hue="f1")
    drawPCA(df1, c="f1", s="f2") #if plotting uses plt.scatter
    drawPCA(df1, hue="f1", size="f2",style="f3")
    or more varialbes passable to the actual plotting function
    """

A: This is what I come up with! Just two question:

*

*is there a parameter to set the legend horizontal, instead of using the ncol?

*how to prevent the figure from being displayed when running the function like this?

fig,ax=drawPCA(df1,hue="f1",style="f2",size="f3")
#may do more changing on the figure.

Here is the function:
def drawPCA2(df,**kwargs):
    import matplotlib.pyplot as plt
    import seaborn as sns
    from matplotlib.figure import figaspect

    nUniVals=sum([df[i].unique().size for i in kwargs.values()])
    nKeys=len(kwargs.keys())

    w, h = figaspect(1/3)
    fig1, axs = plt.subplots(ncols=3,figsize=(w,h))
    fig1.suptitle("All the PCs")
    sns.scatterplot(x="PC1",y="PC2",data=df,legend=False,ax=axs[0],**kwargs)
    sns.scatterplot(x="PC1",y="PC3",data=df,legend=False,ax=axs[1],**kwargs)
    sns.scatterplot(x="PC2",y="PC3",data=df,ax=axs[2],label="",**kwargs)
    handles, labels = axs[2].get_legend_handles_labels()
    fig1.legend(handles, labels, loc='lower center',bbox_to_anchor=(0.5, 0.85), ncol=nUniVals+nKeys)
    axs[2].get_legend().remove()
    fig1.tight_layout(rect=[0, 0.03, 1, 0.9])

    return fig1,axs


text:
Q: How to randomly select a video and play? Im learning JQuery and php.
Is it possible to store multiple video links within  variables and get php to echo one at random??
My goal is to control my own video ads on my site and I thought this would be a good idea but I dont have a clue where I should look online.
Here is what I was thinking
<?php

 $advert1 = 'MyVIDEO1.mp4';
 $advert2 = 'MyVideo2.mp4';
 $advert3 = 'MyVideo3.mp4';

 I want a code that would go here and say: randomly select one of these vars.

 echo "At random one of the vars";

?>

I hope Im making sense. help?

A: You could make an array, like this:
$advert[] = array();
$advert[1] = 'MyVIDEO1.mp4';
$advert[2] = 'MyVIDEO2.mp4';
$advert[3] = 'MyVIDEO3.mp4';

$chosen_one = rand(1,count($advert));

echo $advert[$chosen_one];

A: You can also use array_rand() instead of shuffle():
<?php
$videos = array("MyVIDEO1.mp4", "MyVideo2.mp4", "MyVideo3.mp4");
echo $videos[array_rand($videos)];
?>

For embedding the video in the right way, have a look at http://www.w3schools.com/html/html_videos.asp

A: For a start, PHP itself won't exactly play a video.  You could use it to echo out one of the URL's to a video.  So, bear in mind there is a lot more to do than just select a video.
To answer your question in the code I'd recommend the following:
Try looking up PHP arrays.  You want to keep all the videos in an array.
Next up, you'll want to shuffle that array. Then select the first element.
$videos = array("MyVIDEO1.mp4", "MyVideo2.mp4", "MyVideo3.mp4");
shuffle($videos);
echo $videos[0];

A: This is a simple solution
Place your adverts in an array
<?php
$adverts = array("advert1" => "MyVIDEO1.mp4",
                 "advert2" => "MyVIDEO2.mp4",
                 "advert3" => "MyVIDEO3.mp4");

$count = count($adverts);
$rand_advert = rand(1, $count);
echo $adverts['advert'.$rand_advert];
?>

Or alternatively if you don't want to have keys and just put the values in the array straight away
<?php
$adverts = array("MyVIDEO1.mp4",
                 "MyVIDEO2.mp4",
                 "MyVIDEO3.mp4");

shuffle($adverts);
echo $adverts[0];
?>

A: You have need all value in a array then find index randomly and show it.
<?php

$advert  = array(
        'MyVIDEO1.mp4',
        'MyVideo2.mp4',
        'MyVideo3.mp4'
    );

$total_video = count($advert);

$total_video--; //array index starting from 0 so decrease 1

$random_index = rand(0, $total_video); //array index 0 to 2

$video_to_play = $advert[$random_index];

echo $video_to_play;

?>