text:
Q: android webview not able to add Custom font? I'am not able to change webview Font at all , I've tried every example here the custom font wont work
my custom font path is
assets/fonts/neu.ttf

I've changed the ttf font many times to check if its work or not all fonts working fine with TextView by when i attempt to use them on webview they wont work
this is my webview Header
String global_css =  "@font-face {font-family: 'feast';src: url('file:///android_asset/fonts/neu.ttf');format('truetype');}"+
                         "body,html{font-family: 'feast';color : #000000;font-size: 10pt; word-wrap: break-word;"
                         + "-webkit-touch-callout:none;"
                         + "-webkit-user-select:none;"
                         + "-khtml-user-select:none;"
                         + "-moz-user-select:none;"
                         + "-ms-user-select:none;"
                         + "user-select:none;"
                         + "-webkit-tap-highlight-color:rgba(0,0,0,0);} "+
                        "img{margin : 2px;} "+
                        "img.youtbe_img{padding: 2px;border : 1px solid #dfdfdf;background-color : #ebebeb;margin : 3px;}"+
                        "a {text-decoration: none;color: #0066CC}"+
                        "fieldset{word-wrap:break-word;font-size: 9pt;border : 1px solid #e6e6e6;margin : 10px 0;color: #636363;background-color: #f6f6f6;padding:5px;}"+
                        "legend{font-size: 9pt;border : 1px solid #e6e6e6;padding: 4px 5px;background-color : #ffffff;color : #6a6a6a;}"+
                        "img,legend,fieldset{-webkit-border-radius: 5px 5px 5px 5px;border-radius: 5px 5px 5px 5px;}"+
                        "img.effect_me{-webkit-box-shadow: 0 0 1px 1px #b2b2b2;box-shadow: 0 0 1px 1px #b2b2b2;}";

    return "<style type=\"text/css\">"+global_css+"</style>";

and the Webview
holder.message.loadDataWithBaseURL(null,aHtml.output(post.pagehtml),"text/html","UTF-8",null);

I've tried removeing file:///android_asset and format('truetype')
still not working
any advice will be very much appreciated

A: Try this.
holder.message.loadDataWithBaseURL("file:///android_asset/",aHtml.output(post.pagehtml),"text/html","UTF-8",null);


text:
Q: Isolate jQuery's (.off) to one specific element on scroll I've been working with this scrolling count-up script that animated some numbers when you scroll down to a specific spot on the page. So far, everything is working as expected, but I've noticed that within the script that kills any other jQuery scroll events for everything else on the page. Here's what I have:
//count up script
  $(function () {
    var fx = function fx() {
      $(".stat-number").each(function (i, el) {
        var data = parseInt(this.dataset.n, 10);
        var props = {
          "from": {
            "count": 0
          },
          "to": {
            "count": data
          }
        };
        $(props.from).animate(props.to, {
          duration: 500 * 1,
          step: function (now, fx) {
            $(el).text(Math.ceil(now));
          },
          complete:function() {
            if (el.dataset.sym !== undefined) {
              el.textContent = el.textContent.concat(el.dataset.sym)
            }
          }
        });
      });
    };

    var reset = function reset() {
      console.log($(this).scrollTop())
      if ($(this).scrollTop() > 1300) {
        fx()
        $(this).off("scroll");
      }
    };

    $(window).on("scroll", reset);
  });

//Other scroll script
  $(window).scroll(function() {
    var sT = $(this).scrollTop();
    if (sT > 40) {
      $('.header').addClass('nav-bg');
    } else {
      $('.header').removeClass('nav-bg');
    }
  });

So the tricky part that I'm not sure about is how to get the two scripts to act separately from each other. If I modify the $(this).off("scroll"); in the count up script then the animation keeps triggering every time you scroll. If I leave in $(this).off("scroll"); it nukes all the scroll events on the page. Overall, I know why it's doing what it's doing. I'm just not sure how to get it so that it separates between the two events so I can get the scrolling number animation to trigger and stop and not interfere with the other scrolling header script.

A: You can namespace events which allows you to remove that namespace only using off() and leave other event listeners of same type active
try something like:
var reset = function reset() {
  console.log($(this).scrollTop())
  if ($(this).scrollTop() > 1300) {
    fx()
    $(this).off("scroll.myScrollName");
  }
};

$(window).on("scroll.myScrollName", reset);

A: jQuery's off method accepts a function already attached with on so you can "off" only that callback and not all.
http://api.jquery.com/off/
I'm not sure how can you reference the function inside itself, as a workaround I would do something like...
var reset = function() {
  //your_code...
  offReset(this);
}

var offReset = function(element) {
  $(element).off(reset)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple C# program using arrays throws an error Well I'm trying to write a program in which if you add for example 3 integers in the array, let's say 3 2 1, it will add them again after it so it becomes 321 321.
Here is the code I need to fix. And sorry for the stupid question I am a beginner with arrays.
I get this error

Index was outside the bounds of the array

My code:
using System;

public class Program
{
    public static void Main()
    {
        int arraylength = int.Parse(Console.ReadLine());
        int[] array = new int[arraylength];

        for (int i = 0; i < arraylength + 1 / 2; i++)
        {
            int typed = int.Parse(Console.ReadLine());
            array[i] = typed;

            if (i == arraylength / 2)
            {
                for (int a = arraylength + 1 / 2; a < arraylength + 1; a++)
                {
                    array[a] = typed;
                }
            }
        }
    }
}

A: Array indices in C# start at 0 and end at length - 1. You need to remove the + 1 from each of your for loop conditions:
for (int i = 0; i < arraylenght / 2; i++)

and
for (int a = (arraylenght + 1) / 2; a < arraylenght; a++)

I also suggest that you change arraylenght to arraylength. Since you probably autocompleted this every time you used it, the misspelling occurs consistently throughout your code and the compiler is satisfied. However, misspellings make it difficult for humans to read your code.
p.s. Your code doesn't do what you think it does. I suggest you step away from the computer for a moment and write in words what you are trying to accomplish. Describe each step of your solution in as much detail as you can. Then look at how your words match with the code you wrote. You will probably find that you do not need nested loops.


text:
Q: How to download a file over HTTPS using Indy 10 and OpenSSL? I have the following task: download a file using HTTPS and authentication. Indy seems the way to go but for some reason it doesn't work so far. I have the following in place:

*

*a TIdHTTP component which I use for downloading

*a TIdURI component used to create the URL

*a TIdSSLIOHandlerSocketOpenSSL component which should provide the secure connection. The required DLLs are in the binary folder.

The site also requires authentication and I included the user/pass in the URL as in the example below. In short this is the code:
URI := TIdURI.Create('https://test.example.com/');
URI.Username := ParamUserName;
URI.Password := ParamPassword;

HTTP := TIdHTTP.Create(nil);
if URI.Protocol = 'https' then
begin
  IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  IOHandler.SSLOptions.Method := sslvSSLv3;
  HTTP.IOHandler := IOHandler;
end;

HTTP.Get(URI.GetFullURI([ofAuthInfo]), FileStream);

Using this code I get a "Read Timeout" EIdReadTimeout exception very fast. Testing the URL in a browser works without problem. Any ideas on what's missing or what I did wrong?

A: I have seen the same thing. Setting the TIdHTTP.ReadTimeout to zero fixes the problem for me.
...
HTTP.IOHandler := IOHandler;
HTTP.ReadTimeout := 0;

A: I finally abandoned Indy and OpenSSL and used WinInet for downloading. This is the code that worked for me:
function Download(URL, User, Pass, FileName: string): Boolean;
const
  BufferSize = 1024;
var
  hSession, hURL: HInternet;
  Buffer: array[1..BufferSize] of Byte;
  BufferLen: DWORD;
  F: File;
begin
   Result := False;
   hSession := InternetOpen('', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0) ;

   // Establish the secure connection
   InternetConnect (
     hSession,
     PChar(FullURL),
     INTERNET_DEFAULT_HTTPS_PORT,
     PChar(User),
     PChar(Pass),
     INTERNET_SERVICE_HTTP,
     0,
     0
   );

  try
    hURL := InternetOpenURL(hSession, PChar(URL), nil, 0, 0, 0) ;
    try
      AssignFile(f, FileName);
      Rewrite(f,1);
      try
        repeat
          InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen) ;
          BlockWrite(f, Buffer, BufferLen)
        until BufferLen = 0;
      finally
        CloseFile(f) ;
        Result := True;
      end;
    finally
      InternetCloseHandle(hURL)
    end
  finally
    InternetCloseHandle(hSession)
  end;
end;

A: All SSL related functions for secure connections will fail unless some additional libraries are installed properly.
1.) Download libraries
2.) unzip and copy both DLLs to your project folder (or somewhere in the PATH of your system)
with that your code from the question works fine for me.
--reinhard


text:
Q: printing the entire row with particular given last column criteria Input:
orf00007                    PHAGE_Prochl_MED4_213_NC_020845-gi|472340344|ref|YP_007673870.1|              7665 8618 0.210897481636936
orf00007                    PHAGE_Prochl_MED4_213_NC_020845-gi|472340344|ref|YP_007673870.1|              7665 8618 0.210897481636936
orf00007                    PHAGE_Prochl_P_HM2_NC_015284-gi|326783200|ref|YP_004323597.1|             7665 8618 0.207761175236097
orf00015                    PHAGE_Megavi_lba_NC_020232-gi|448825467|ref|YP_007418398.1|           11594 13510   0.278721920668058
orf00015                    PHAGE_Acanth_moumouvirus_NC_020104-gi|441432357|ref|YP_007354399.1|           11594 13510   0.278721920668058

The script I had implemented:
use feature qw/say/;
use Math::Trig;

open FILE,"out02.txt";
my @file=<FILE>;
close FILE;
my $aa=0;
for(my $i=$aa; $i <=17822; $i++){
    if (($file[$i]>=0.210)){
        open(OUTFILE,'>>OUT_t10-t10.txt');
        print OUTFILE $file[$i];
    }
    else{}
}

Note:

*

*I need to take the last column as the analysing criteria to print the entire row(the float value, eg:0.210897481636936)

*for example if the user input value is '0.210',it has to produce >= values rows ,the expected output is

Output:
orf00007                    PHAGE_Prochl_MED4_213_NC_020845-gi|472340344|ref|YP_007673870.1|              7665 8618 0.210897481636936
orf00007                    PHAGE_Prochl_MED4_213_NC_020845-gi|472340344|ref|YP_007673870.1|              7665 8618 0.210897481636936
orf00015                    PHAGE_Megavi_lba_NC_020232-gi|448825467|ref|YP_007418398.1|           11594 13510   0.278721920668058
orf00015                    PHAGE_Acanth_moumouvirus_NC_020104-gi|441432357|ref|YP_007354399.1|           11594 13510   0.278721920668058

A: A script like the following could work for you:
use strict;
use warnings;
use autodie;

die "Usage: $0 number file\n"
    if @ARGV != 2;

my $minval = shift;

while (<>) {
    my @cols = split;
    print if $col[-1] >= $minval;
}

And execute it like:
perl yourscript.pl 0.210 out02.txt >> OUT_t10-t10.txt

Or using a perl one-liner:
perl -lane 'print if $F[-1] >= 0.210' out02.txt >> OUT_t10-t10.txt

A: Using awk:
awk -v value=0.210 '$NF >= value' file

Or
awk -v value=0.210 '$NF >= value' file > output_file

A: This scripts (inspired on yours) solves the problem:
use strict;
use warnings;

my $user_filter = 0.21;

open my $input_file, "<", "out02.txt" or die $!;   # Modern way of open files
open my $output_file, ">>", "OUT_t10-t10.txtt" or die $!;

while( my $line=<$input_file> ) {
    if( $line =~ / ([\d\.]+)\s*$/ ) {
        # If a number was found at the end of line
        if( $1 > $user_filter ) {  # Check condition
            print $output_file $line;  #Write to output file
        }
    }

}

close $input_file;
close $output_file;


text:
Q: Fill MySQL table with 2-dim array data I want to fill MySQL table with 2-dim array data:
    for($i=0; $i<sizeof($arr); $i++)
    {
    $query1="INSERT INTO `fsTest` (`id`,`xxx`,`yyy`,`zzz`)
        VALUES('$arr[$i][0]','$arr[$i][1]','$arr[$i][2]','$arr[$i][3]');";
    $result1=DatabaseConnector::ExecuteQuery($query1);
    }

When I check the table 'fsTest' I can see just 1 line with the following entries [0] [1] [2] [3].
How to solve this issue?
UPDATE: Another thing is that I use $arr[$i][] = $val; to populate the array. var_dump($arr) returns Arrayint(0).

A: You need curly braces around your variable names:
$query1 = "
    INSERT INTO `fsTest` (`id`,`xxx`,`yyy`,`zzz`)
        VALUES('{$arr[$i][0]}','{$arr[$i][1]}','{$arr[$i][2]}','{$arr[$i][3]}');
";

Otherwise, the parser is lazy and will find $arr[$i] first and attempt to insert that value as a string, instead of $arr[$i][0].
A quick example demonstrates this behavior:
$array = array( array( 'value'));
echo "$array[0][0]"; // Fails, Array to string conversion
echo "{$array[0][0]}"; // Prints value

A: for($i=0; $i<sizeof($arr); $i++)
{
$query1="INSERT INTO `fsTest` (`id`,`xxx`,`yyy`,`zzz`)
    VALUES('".$arr[$i][0]."','".$arr[$i][1]."','".$arr[$i][2]."','".$arr[$i][3]."');";
$result1=DatabaseConnector::ExecuteQuery($query1);
}


text:
Q: PasswordReminder in Laravel I am trying to set a Password reminder in restful way. (Following this tutorial http://laravel.com/docs/4.2/security#password-reminders-and-reset but trying to do it in restful way)
The route looks like this,
Route::group(array('prefix' => 'api/v1'), function(){
    Route::resource(
        'password', 'RemindersController',
        array(
            'only' => array('store', 'show', 'update')
        )
    );
});

RemindersController starts as,
public function update()
{

}

The password reset url is
    http://192.x.x.x:8000/api/v1/password/3adb8b0454144ef5aeaa333faa5c575bd833e03d
From this url loading reset.blade as follows,
<form action="{{ action('RemindersController@update') }}" method="PUT"

...

<input type="submit" value="Reset Password"> </form>

But when loading this page, the form action seems to have some issues, the action url does not seem to be right.
<form action="http://192.x.x.x:8000/api/v1/password/%7Bpassword%7D" method="PUT">

What is the right way to provide action property in the form for this? How can I pass the password reset details to 'update' method in Reminder controller?
In the mentioned tutuorial it is like
action="{{ action('RemindersController@postReset') }}" method="POST"

What will change when using the restful resource way?

A: Got it right by following the suggestion from this site with the following modification,
<form action="{{ URL::to('api/v1/password/update') }}" method="POST">
    <input name="_method" type="hidden" value="PUT">


text:
Q: In Python, can I call the variable from main function - use global variable? In Python, can I call a variable from main function? Use global variable? Any help appreciated!
def main(dataset, n_h, n_y, batch_size, dev_split, n_epochs):
    input_to_state = Linear(name='input_to_state',
                            input_dim=seq_u.shape[-1],
                            output_dim=n_h)
    global RNN # correct?
    RNN = SimpleRecurrent(activation=Tanh(),
                          dim=n_h, name="RNN")

def predict(dev_X):
    dev_transform = main.input_to_state.apply(dev_X) #?  call  "input_to_state", which one is correct?
    dev_transform = input_to_state.apply(dev_X) #?
    dev_h = main.RNN.apply(dev_transform) #? call "RNN", which one is correct?
    dev_h = RNN.apply(dev_transform) #?

if __name__ == "__main__":
    def predict(dev_X): #  one more question: can predict function be added here?
    dataset =  ....
    main(dataset, n_h, n_y, batch_size, dev_split, 5000)
    get_predictions = theano.function([dev_X], predict) # call predict function

A: You have to define 'input_to_state' and 'RNN' outside the 'main' function, and then modify them afterwards. Like this:
input_to_state = None
RNN = None
def main(dataset, n_h, n_y, batch_size, dev_split, n_epochs):
    # Calling 'global' allows you to modify these variables
    global input_to_state
    global RNN
    input_to_state = Linear(name='input_to_state',
                            input_dim=seq_u.shape[-1],
                            output_dim=n_h)
    RNN = SimpleRecurrent(activation=Tanh(),
                          dim=n_h, name="RNN")

def predict(dev_X):
    dev_transform = input_to_state.apply(dev_X)
    dev_h = RNN.apply(dev_transform)

if __name__ == "__main__":
    main(args)
    predict(dev_X)

Howerver, I would not recommend this, global variables should be used as little as possible. more detail here.
A better solution would be to return 'input_to_state' and 'RNN' at the end of the main function, like this:
def main(dataset, n_h, n_y, batch_size, dev_split, n_epochs):
    input_to_state = Linear(name='input_to_state',
                            input_dim=seq_u.shape[-1],
                            output_dim=n_h)
    RNN = SimpleRecurrent(activation=Tanh(),
                          dim=n_h, name="RNN")
    return input_to_state, RNN

def predict(dev_X, input_to_state, RNN):
    dev_transform = input_to_state.apply(dev_X)
    dev_h = RNN.apply(dev_transform)

if __name__ == "__main__":
    input_to_state, RNN = main(args)
    predict(dev_X, input_to_state, RNN)

A: Try with this.
main.py
__dataset__ = main(dataset, n_h, n_y, batch_size, dev_split, 5000)

sub.py
import sys, main
__dataset__ = sys.modules['__main__'].__dataset__

EDIT:
Another method is to use a class with static variables.
mclass.py
class MClass:
    i = 0

MClass.i = 1

main.py
import sub
from mclass import MClass

# In the main file
print(MClass.i) # Outputs 1
MClass.i = 3
print(MClass.i) # Outputs 3

# In a subfile
sub.mPrint() # Outputs 3
sub.set(10)
sub.mPrint() # Outputs 10

# And back in the main
print(MClass.i) # Outputs 10

sub.py
from mclass import MClass

def mPrint():
   print(MClass.i)

def set(n):
   MClass.i = n


text:
Q: Determining upper line https://finviz.com/quote.ashx?t=MLPX&ty=c&p=d&b=1
Does anyone what equation/formula is used to determine that pink upper line?
For detecting channel lines, it was a bit easier, where I've used a regression line, along with 2 standard deviation lines.
I'm not sure what tags to mark this question under.

A: It is a trend line. It is made by drawing a line through three local maxima or minima that happen to lie on a line where most data is below/above the line, respectively. There doesn't seem to be an elegant formula used for finding them.
A randomized approach could be: You could find all the local maxima in your window and repeatedly select three points, testing to see how well a line fits them and how often the prices go above the line, and pick the best one.
A deterministic approach could be: Find the convex hull of your data. Each segment on the hull can be extended in either direction to be a trend line that touches at least two points. Additionally, all points are guaranteed to lie on one side of each of these lines. Choose the line that touches the most points (you can keep track of how many data points each line touches while you're running the convex hull algorithm). Graham scan or the gift-wrapping algorithm will work. You do run into the problem of having to choose your window, but you can solve this buy running the algorithm for multiple window offsets and selecting the best from all of them.
There can be multiple possible trend lines per window, and it is scale-dependent. The blue line in that picture is also a trend line.


text:
Q: How to search by text and value in Kendo Dropdown List. $(document).ready(function() {
                $("#products").kendoDropDownList({
                    filter: "startswith",
                    dataTextField: "ProductName",
                    dataValueField: "ProductID",
                    dataSource: {
                        type: "odata",
                        serverFiltering: true,
                        transport: {
                            read: {
                                url: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Products",
                            }
                        }
                    }
                });
            });

How can i  search by value and text together in kendo dropdown list. a better example you can find here
Now i can search by only text. suppose I want to search by employee id & name together. now i can search by only name.
is it possible? or not. Give me clue to continue digging.
I will appreciate your help.

A: Just on the ServerFiltering to true and handle your query in server side and response the result....
below is my angular controller:
$scope.reportingPersonOptoins = {
            filter: "startswith",
            autoBind: true,
            dataSource: {
                serverFiltering: true,
                transport: {
                    read: {
                        dataType: "json",
                        type: "POST",
                        url: baseurl + "employee/get_employee_list"
                    }
                }
            },
            dataTextField: "first_name",
            dataValueField: "employee_id",
            optionLabelTemplate: "---Select Reporting Person---",
            template: '<span>#: data.employee_id #, #: data.first_name # #: data.last_name # </span>',
            valueTemplate: '<span>#: data.employee_id #, #: data.first_name # #: data.last_name # </span>',
        };

and this is my server wrappers
receive the value by :
 header('Content-Type: application/json');
 $receive = $this->input->post();
if (isset($receive['filter'])) {
        $data = $receive['filter']['filters'][0]['value'];
    } else {
        $data = NULL;
    }

and run the query accordingly
$this->db->select('hr_employee.employee_id, hr_employee.first_name, hr_employee.last_name, hr_employee_employment.branch_id')
            ->join('hr_employee_employment', 'hr_employee.employee_id = hr_employee_employment.employee_id')
            ->where(array("hr_employee.is_active" => 1, "hr_employee.is_admin" => 0));
    if ($data !== NULL) {
        $this->db->or_like("hr_employee.employee_id", $data);
        $this->db->or_like("hr_employee.first_name", $data);
        $this->db->or_like("hr_employee.last_name", $data);
    }
    $query = $this->db->get('hr_employee');

Wow!!! cheers!!


text:
Q: Bash script failing but part running Can anyone see anything wrong with the following?
I have been looking over and over and can't see the issue, but its failing to create the SQL dump and no tar is being created.
The variables would have their details obviously. I have checked these are all correct.
#!/bin/bash

SITE=""
PATH=""
SERVER=""
DBUSER=""
DB=""
DBPW=""

DATE=`date '+%d-%m-%y-%H-%M'`

tar -czf ~/backup/${DATE}-${SITE}.tar.gz \
  /var/sites/${PATH}/public_html

mysqldump -f \
  -u ${DBUSER} ${DB} \
  -p${DBPW} \
  -h ${SERVER} > ~/backup/${DATE}-db-${SITE}.sql

find ~/backup -mtime +3 -exec rm -f {} \;

The purpose of the code is to create the backup of my server files and database. The script is running via CRON.

A: You have a bunch of places in your script that will have a hard time handling spaces. There are also some other improvements that can help you fix the problem (since you didn't give us any failing output...).
General

*

*Used " around parameters for commands where you can end up having spaces.

*Put set -x on the top of your script to see what is happening when it runs. This can also be triggered running it using bash -x script.sh.

*Use set -u on top to let the script die when there is a undefined variable.

*Use set -e on top to let it die if a command fails.

*Use set -eu to combine them both :)

*If your find supports it, use its -delete, instead of -exec rm -f {} \;. If it doesn't, make sure you wrap it in ", or better, use -print0 and xargs with -0 input. Depending on the versions you have, the idea is to use NUL as a separator, instead of whitespaces (default shell).


text:
Q: Cisco ASA 5505 Config I have looked through a lot of these posts on the Cisco ASA5505 as well as gone online. I am looking for some straight forward step by step instructions to complete the following tasks.
I know how to get it functioning with an inside and outside interface so that's great!
I need some step by step for the following tasks

*

*Configuring the firewall.
There will be two servers attached to the inside interface: one is a web server so ports 80, 25, etc... The other is the DC so all standard ports for that need to be opened up. We also need RDP opened to both machines we use a non-standard port. I feel if I saw one example like for port 80 I could replicate that. Are there any other configs I should be aware of to secure the actually firewall or does it come setup pretty well out of the box?

*Setup access to the appliance from our main office and my offsite lab. I could also RDP to the DC on the inside interface then connect if that was more secure.
Here is my current status. Right now it is just setup on my work machine for some testing. So the outside interface just goes to the office network.
Result of the command: "show running-config"
: Saved
:
ASA Version 8.2(1)
!
hostname superasa
domain-name somedomainname
enable password /****** encrypted
passwd ******************** encrypted
names
!
interface Vlan1
 nameif inside
 security-level 100
 ip address 192.168.2.1 255.255.255.0
!
interface Vlan2
 nameif outside
 security-level 0
 ip address 192.168.1.9 255.255.255.252
!
interface Ethernet0/0
 switchport access vlan 2
!
interface Ethernet0/1
!
interface Ethernet0/2
!
interface Ethernet0/3
!
interface Ethernet0/4
!
interface Ethernet0/5
!
interface Ethernet0/6
!
interface Ethernet0/7
!
ftp mode passive
clock timezone EST -5
clock summer-time EDT recurring
dns domain-lookup inside
dns domain-lookup outside
dns server-group DefaultDNS
 name-server 192.168.1.120
 domain-name somedomain
pager lines 24
logging asdm informational
mtu inside 1500
mtu outside 1500
icmp unreachable rate-limit 1 burst-size 1
no asdm history enable
arp timeout 14400
global (outside) 1 interface
nat (inside) 1 0.0.0.0 0.0.0.0
route outside 0.0.0.0 0.0.0.0 192.168.1.1 1
timeout xlate 3:00:00
timeout conn 1:00:00 half-closed 0:10:00 udp 0:02:00 icmp 0:00:02
timeout sunrpc 0:10:00 h323 0:05:00 h225 1:00:00 mgcp 0:05:00 mgcp-pat 0:05:00
timeout sip 0:30:00 sip_media 0:02:00 sip-invite 0:03:00 sip-disconnect 0:02:00
timeout sip-provisional-media 0:02:00 uauth 0:05:00 absolute
timeout tcp-proxy-reassembly 0:01:00
dynamic-access-policy-record DfltAccessPolicy
http server enable
http 192.168.1.0 255.255.255.0 inside
http 192.168.2.0 255.255.255.0 inside
http 192.168.2.4 255.255.255.255 inside
http 192.168.1.108 255.255.255.255 outside
http internetip 255.255.255.255 outside
no snmp-server location
no snmp-server contact
snmp-server enable traps snmp authentication linkup linkdown coldstart
crypto ipsec security-association lifetime seconds 28800
crypto ipsec security-association lifetime kilobytes 4608000
telnet timeout 5
ssh timeout 5
console timeout 0
dhcpd dns 192.168.1.120 208.67.222.222
dhcpd domain somedomain
dhcpd auto_config outside
!
dhcpd address 192.168.2.2-192.168.2.33 inside
dhcpd dns 192.168.1.120 interface inside
dhcpd auto_config outside interface inside
dhcpd enable inside
!
dhcpd dns 192.168.1.120 interface outside
dhcpd domain supernova interface outside
!
dhcprelay timeout 60

threat-detection basic-threat
threat-detection statistics access-list
no threat-detection statistics tcp-intercept
webvpn
!
!
prompt hostname context
Cryptochecksum:abunchofnumbersgohere
: end

A: On your first point, the firewall portion is already setup. Those "security-level" commands that you issued for the interface took care of that. Higher levels are able to communicate with lower levels but lower levels need to be given access to resources at higher levels. To grant access, you create an access-list and assign it to an interface with the access-group command. Since you are NATing as well, you need to create some static mappings so the firewall knows where to send traffic to. I've left the DC out of my instructions because you don't need to expose anything to the DC (it's a security issue to do so). If you have remote offices that need to authenticate, setup a site to site VPN. Here's what it would look like:

access-list outside_access_in extended permit tcp any host 192.168.1.153 eq 80
  access-list outside_access_in extended permit tcp any host 192.168.1.153 eq 25
  access-group outside_access_in in interface outside
  static (inside,outside) 192.168.1.153 192.168.2.5 netmask 255.255.255.255

You could, alternatively, use PAT instead of assigning the server its own external IP address. I recommend not doing this if possible as it is more commands to configure and keeping an email server on its own IP address helps you to not get blacklisted. If you'd like to do this, here's what you'd do (note in this configuration you have to create a static mapping for each port):

access-list outside_access_in extended permit tcp any host [external ip address of firewall] eq 80
  access-list outside_access_in extended permit tcp any host [external ip address of firewall] eq 25
  access-group outside_access_in in interface outside
  static (inside,outside) tcp interface 80 [internal ip address of server] 80 netmask 255.255.255.255
  static (inside,outside) tcp interface 25 [internal ip address of server] 25 netmask 255.255.255.255

In order to enable access you just tell ssh where to listen, how to authenticate (a local database is easiest to setup), and generate a key:

ssh [ip address of main office] 255.255.255.255 outside
  ssh [ip address of remote lab network] [subnet mask of remote lab network] outside
  ssh [subnet of internal network] [subnet mask of internal network] inside
  username companyadmin password [create a good password] privilege 15
  aaa authentication ssh console LOCAL
  crypto key generate rsa

EDIT
You cannot do the type of failover you're looking for on the ASA. It can failover ISP's but not hosts. What you might want to look into is Network Load Balancer on Windows or a dedicated hardware load balancer.
The first snippet of code is not about site-to-site VPN. Sorry for the confusion. It is for forwarding ports with a dedicated IP (also known as static NAT) as opposed to an IP address shared with the firewall. When it's a shared IP, it's called port address translation (PAT) because the port number and type dictates which host it's forwarded to. When you have a dedicated IP address it's called static NAT. You are already using NAT and you can use either PAT or static NAT in combination with NAT.

A: I accomplished both using ASDM and "Public Servers"
How this is not mentioned online anywhere is beyond me. By configuring this one setting it configures all necessary firewall rules! It is simple and straight forward.
I was able to accomplish all my questions with this one section.
Here is a screen shot.


text:
Q: Fitting data to a custom Pareto distribution data = {1.312, 1.314, 1.479, 1.552, 1.700, 1.803, 1.861, 1.865, 1.944,
    1.958, 1.966, 1.997, 2.006, 2.021, 2.027, 2.055, 2.063, 2.098,
   2.14, 2.179, 2.224, 2.240, 2.253, 2.270, 2.272, 2.274, 2.301,
   2.301, 2.359, 2.382, 2.382, 2.426, 2.434, 2.435, 2.478, 2.490,
   2.511, 2.514, 2.535, 2.554, 2.566, 2.57, 2.586, 2.629, 2.633,
   2.642, 2.648, 2.684, 2.697, 2.726, 2.770, 2.773, 2.800, 2.809,
   2.818, 2.821, 2.848, 2.88, 2.954, 3.012, 3.067, 3.084, 3.090,
   3.096, 3.128, 3.233, 3.433, 3.585, 3.585};

I constructed a basic Pareto distribution and fitted it to the data to obtain the best-fit value of the distribution parameter $\lambda$:
dist = ProbabilityDistribution[{"CDF", 1 - x^(-\[Lambda])}, {x, 0, \[Infinity]}, Assumptions -> {\[Lambda] > 0}]

mle = FindDistributionParameters[data, dist]

This returned {\[Lambda] -> 1.14273}
I then wanted to plot fitted vs predicted values so I tried ProbabilityScalePlot[data, dist] but it returned an error:

I ultimately want to calculate this DistributionFitTest[data, dist, {"TestDataTable", "AndersonDarling"}]:

I would like to use my custom distribution, rather than a built-in from Mathematica, and i want to plot its empirical CDF.

A: data = {1.312, 1.314, 1.479, 1.552, 1.700, 1.803, 1.861,
        1.865, 1.944, 1.958, 1.966, 1.997, 2.006, 2.021,
        2.027, 2.055, 2.063, 2.098, 2.14, 2.179, 2.224,
        2.240, 2.253, 2.270, 2.272, 2.274, 2.301, 2.301,
        2.359, 2.382, 2.382, 2.426, 2.434, 2.435, 2.478,
        2.490, 2.511, 2.514, 2.535, 2.554, 2.566, 2.57,
        2.586, 2.629, 2.633, 2.642, 2.648, 2.684, 2.697,
        2.726, 2.770, 2.773, 2.800, 2.809, 2.818, 2.821,
        2.848, 2.88, 2.954, 3.012, 3.067, 3.084, 3.090,
        3.096, 3.128, 3.233, 3.433, 3.585, 3.585};

dist[λ_] = ProbabilityDistribution[{"CDF", 1 - x^(-λ)}, {x, 1, ∞}];

Λ = λ /. FindDistributionParameters[data, dist[λ]]
(*    1.14273    *)

ProbabilityPlot[data, dist[Λ]]

DistributionFitTest[data, dist[Λ], {"TestDataTable", "AndersonDarling"}]

$$
\begin{array}{l|ll}
 \text{} & \text{Statistic} & \text{P-Value} \\
\hline
 \text{Anderson-Darling} & 18.343 & \text{8.698112014204895$\grave{ }$*${}^{\wedge}$-6}
   \\
\end{array}
$$
Notes:
I've modified the domain of the given CDF to $[1,\infty)$ so that it stays within the required range $[0,1]$.
The empirical distribution is EmpiricalDistribution[data]:
datacdf[x_] = CDF[datadist][x];
Plot[datacdf[x], {x, 1, 4}, PlotPoints -> 100]


text:
Q: Is it possible to unistall the dependency package but not the actual package? Use case:
package A
Requires: package B ( B doesn't require A)
$ yum remove package B
will remove package A too
Is there any way to avoid uninstalling package A,modifying somehow the spec file?

A: yum and dnf sit on top of rpm as an interface. You can force rpm directly to erase the RPM.
However, it is probably not the right thing to do and can easily lead you to headaches down the road, unless you very specifically know what you are doing and why.

A: From comments I assume you know what you are doing:
rpm -e --nodeps <pkg>

Other readers: please handle this carefuly as you may shot yourself in your own leg.


text:
Q: http GET request without express var http = require('http');
var fs = require('fs');
var path="";
process.stdin.on('data', function(chunk) {
    var buffer = new Buffer(chunk);
    path = buffer.toString();
    path = path.replace("\n","");
    path = path.replace("\r","");
});
var str="";
var fileRead;
var arrayFiles = [];
function onRequest(request, response) {
    str = "";
    if (request.url === '/favicon.ico') {
        response.writeHead(200, {'Content-Type': 'image/x-icon'});
        response.end();
        return;
    } else if (request.url === '/index.html') {
        console.log("Request received" + path);
        fs.readdir(path, function(err, items) {
        console.log(items);
        arrayFiles = [];
        str += items;
        arrayFiles.push(items);
        console.log("Enter file to be read");
        process.stdin.on('data', function(chunk) {
            var buffer = new Buffer(chunk);
            fileRead = buffer.toString();
            fileRead = fileRead.replace("\n","");
            fileRead = fileRead.replace("\r","");
            if(arrayFiles[0].indexOf(fileRead) != -1) {
                fs.readFile(fileRead, 'utf8', function(err, contents) {
                    response.writeHead(200, {"Context-Type": "text/plain"});
                    response.write(contents);
                    response.end();
                });
            }
        });
    });
}
}
http.createServer(onRequest).listen(8000);

The given program displays the files in the directory given as input. And then inputs a file name whose contents are to be displayed.
In the given program, I need the name of the file as input from the user using GET request instead of reading values from stdin. Is it possible to do this without express module. If yes, please help.
Thanks in advance

A: Yes, you can retrieve the filename sent from HTTP GET request with plain Node.js http code, without any Express stuff.
The method is: pass filename as URL parameter, and parse it in server side. Here is an example:
const http = require('http');
const server = http.createServer((req, res) => {
  let params = req.url.substring(req.url.lastIndexOf('?') + 1).split('&');
  let filename = null;
  for (let p of params) {
    let paramKeyValPair = p.split('=');
    if (paramKeyValPair[0] === 'filename') {
      filename = paramKeyValPair[1];
      break;
    }
  }
  console.log(filename);
  // deal with filename
  res.end('Hello');
}).listen(8327);

For URL like /index.html?filename=test.txt, the filename variable in server side would be test.txt


text:
Q: mySQL replace error for date varchar datatype table:
date
-----
1/3/2012
1/5/2012
1/4/2013

UPDATE table
set date = REPLACE (date, '/', '-');

I want to replace the / for - inside the colunm date. But I'm getting an error.
Note: the data type for date is varchar and is a primary key.


text:
Q: Can I create translucent + dialog theme in android? I want my activity to look like a dialog.
Well, I achieved that using android:theme="@android:style/Theme.Dialog"
Now, I also want it to be translucent as it appears in android:theme="@android:style/Theme.Translucent"
Is there a a way to mix them both using a custom style??
Please any suggestions, thanks
EDIT: achieved something similar with this:
Now i want to add border like a dialogwindow...how can i do that???
<style name="TransparentDialog" parent="@android:style/Theme.Dialog">
      <item name="android:windowBackground">@android:color/transparent</item>
      <item name="android:windowFrame">@android:color/transparent</item>
      <item name="android:windowContentOverlay">@null</item>
      <item name="android:windowIsFloating">true</item>
      <item name="android:backgroundDimEnabled">true</item>
      <item name="android:windowIsTranslucent">true</item>
      <item name="android:alertDialogStyle">@android:style/Theme.Dialog</item>
      <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    </style>

EDIT: Solved this. Check the answer

A: Finally achieved what i wanted with this:
Used this theme for my activity android:theme="@android:style/Theme.Translucent"
and gave this android:background="@android:drawable/dialog_frame"as background to the root element of my layout
That was so easy!

A: You'll need to combine the two themes together. One thing that might work is:
<style name="TranslucentDialog" parent="@android:style/Theme.Dialog">
    <item name="android:background">"#33000000"</item>
</style>


text:
Q: CSS Flexbox divs auto change order to fill empty space I have a grid layout with identical fixed height and fixed width divs, and I need to insert a bigger div in between the lines of this grid without breaking the flow, with a random HTML position.
Here is my HTML:

And the layout I want, with the HTML order of the divs:

The main problem is the responsive behaviour, because I don't know how many elements will be in a row.
My first idea was to use JS to place the big div, but it was not reliable, and not clean.
I can change the flex order of the divs with JS, but a full-css code would be definitely better.

A: After some thinking I came up with this, without script.
It uses media queries and you need to do some calculating of your own, to set all the width's according to your requirements.
Here is a fiddle, which has 2 groups, each with a different big, having the same CSS, showing a way that might work for you, and below a code snippet, with only 1 group though.

.parent {
  display: flex;
  flex-wrap: wrap;
  min-width: 400px;
}
.parent div {
  border: 1px solid black;
  margin: 5px;
  order: 1;
}
.parent div:before {
  content: attr(data-nr);
}
.parent .small {
  width: 80px;
  height: 50px;
}
.parent .big {
  width: 90vw;
  height: 100px;
  min-width: 400px;
  order: 2;
}
.parent .big ~ .small {
  border-color: red;
  order: 3;
}
.parent .big ~ div:nth-of-type(n+0) {
  order: 1;
}

@media screen and (max-width: 900px) {
  .parent .big ~ .small:nth-of-type(n+10) {
    order: 3;
  }
}
@media screen and (max-width: 800px) {
  .parent .big ~ .small:nth-of-type(n+9) {
    order: 3;
  }
}
@media screen and (max-width: 700px) {
  .parent .big ~ .small:nth-of-type(n+8) {
    order: 3;
  }
}
@media screen and (max-width: 600px) {
  .parent .big ~ .small:nth-of-type(n+7) {
    order: 3;
  }
}
@media screen and (max-width: 500px) {
  .parent .big ~ .small:nth-of-type(n+6) {
    order: 3;
  }
}


text:
Q: Twig form theme and DependencyInjection I want to separate my Symfony bundles.
I have created SymfonyFormFontAwesomeBundle and ExtensionClass in DependencyInjection repertory :
SymfonyFormFontAwesomeExtension :
class SymfonyFormFontAwesomeExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container): void
    {
        $loader = new YamlFileLoader(
            $container,
            new FileLocator(__DIR__.'/../Resources/config')
        );
        $loader->load('services.yaml');

        $this->loadTwigTheme($container);
    }

    private function loadTwigTheme(ContainerBuilder $container)
    {
        if (!$container->hasParameter('twig.form.resources')) {
            return;
        }

        $container->setParameter('twig.form.resources', array_merge(
            [
                'SymfonyFormFontAwesomeBundle::theme.html.twig'
            ],
            $container->getParameter('twig.form.resources')
        ));
    }
}

But Symfony search theme in my projet (not in my bundle) :

Unable to find template "SymfonyFormFontAwesomeBundle::theme.html.twig" (looked into: /var/www/symfony/Project/templates, /var/www/symfony/Project/templates, /var/www/symfony/Project/vendor/symfony/twig-bridge/Resources/views/Form).

I want to load the file "theme.html.twig" that is in my bundle.
Can you help me ? :)

A: I suspect you are using Symfony4, while the code you used looks like Symfony 2 code. Since Symfony 3(.2?) the Templating component is not used anymore by Twig, so there may be changes.
I would suggest you 2 modifications:

*

*instead of setting twig.form.resources, use a parameter for the config option twig.form_themes, parameter you will be able to easily modify from your bundle extension

*use the @SymfonyFormFontAwesome::theme.html.twig syntax, otherwise SF4 will look inside templates/


text:
Q: Laravel: How to transfer files via SFTP to Azure Blob Storage without downloading other libraries? I need to be able to transfer files, list files and delete files on a certain directory on my Azure Blob Storage and use existing Laravel Disk commands like put(), allFiles(), delete().
Below is my code for uploading a file:
use Storage;

class SFTPFileUploader
{
    public function uploadFileToAzure($fileName,$content)
    {
        $sftpAzureDisk= Storage::disk('sftp');
        $sftpAzureDisk->put($fileName,$content);
    }
}

A: To be able to do this without having to download other libraries,
First you need make sure you have the following setup in your Azure Portal
1. Azure Storage Account (e.g myprojectstorage)
2. Azure Storage Container (e.g myprojectcontainerfolder)
3. Azure Storage Account -> Settings -> SFTP
      3.1 Create a Local User (If none yet)
          3.1.1 Create User Name
          3.1.2 Generate Password
          3.1.3 Set Permissions
      3.2 Enable SFTP

After setting all of those, you can proceed to your config/filesystems.php and create new connection
'sftp' => [
            'driver' => 'sftp',
            'host' => "<myprojectstorage>.blob.core.windows.net",
            'port' => 22,
            'username' => "<myprojectstorage>.<myprojectcontainer>.<username>",
            'password' => <password>,
            'privateKey' => storage_path('app/public/your.key'),//optional depends on Azure Setup
            'root' => '/',
        ],

then this should already work without having to download any other library,
use Storage;

class SFTPFileUploader
{
    public function uploadFileToAzure($fileName,$content)
    {
        $sftpAzureDisk= Storage::disk('sftp');
        $sftpAzureDisk->put($fileName,$content);
    }
}

P.S (I only have tested working using with Password, not tested yet for Key File)


text:
Q: Factoring a prime over a splitting field and factoring a polynomial over of a finite field Let $f$ be a separable monic polynomials with integer coefficient. Let $K$ be the splitting field of $f$ over $\mathbb{Q}$, and let $p$ be a prime. What is the relationship between the statements
$f$ splits over $\mathbb{F}_p$ and
$p$ is not irreducible in $K$ (there is probably some fancy term for this, like $p$ is inert in $K$?)
There are equivalent for the Gaussian Integers, so probably also for any quadratic extension with trivial class group.
I suspect they are equivalent, and this is probably extremely well known, but I have asked a couple people with no luck.

A: Let's look at a simple example, $f(X)=X^3-2$ and its splitting field $K=\Bbb Q(\lambda,\omega)$, over $\Bbb Q$, where $\lambda=\sqrt[3]2$ and $\omega$ is a primitive cube root of unity. Take $p=5$, and look at $f\in\Bbb F_5[X]$, where it factors as $(X+2)(X^2+3X+4)$, so $f$ doesn't split there.
Calling $\mathscr O$ the ring of algebraic integers of $K$, we can see that $5\mathscr O$ factors as $\mathfrak p_1\mathfrak p_2\mathfrak p_3$, where in each case $\mathscr O/\mathfrak p_i\cong\Bbb F_{25}$.

A: Let $ K = \mathbf Q(\alpha) $ be a number field with ring of integers $ \mathcal O_K $, where $ \alpha $ is an algebraic integer with minimal polynomial $ \pi(X)$. Dedekind's factorization criterion tells us that if $ p $ is a prime which does not divide the index $ [\mathcal O_K : \mathbf Z[\alpha]] $, then the way $ \pi(X) $ splits modulo $ p $ is equivalent to the way $ (p) $ splits in $ \mathcal O_K $, in other words, if we have
$$ (p) = \prod_{i=1}^n \mathfrak p_i^{e_i} $$
in $ \mathcal O_K $ where the inertia degrees of $ \mathfrak p_i $ are $ f_i $, then we have
$$ \pi(X) \equiv \prod_{i=1}^n \pi_i(X)^{e_i} \pmod{p} $$
where the $ \pi_i $ are irreducible in $ \mathbf Z/p\mathbf Z[X] $ with $ \deg \pi_i = f_i $. This is essentially a consequence of the isomorphisms
$$ \mathbf Z[\alpha]/(p) \cong \mathbf Z[X]/(\pi(X), p) \cong \mathbf Z/p \mathbf Z[X]/(\pi(X)) $$
and the fact that you can read off the relevant data from the ring structure alone. As an example of how this fails when the criterion regarding the index is not met, consider $ K = \mathbf Q(\sqrt{5}) $. $ \mathbf Z[\sqrt{5}] $ has index $ 2 $ in $ \mathcal O_K $, and we have $ x^2 - 5 = (x+1)^2 $ in $ \mathbf Z/2\mathbf Z $, which suggests that $ 2 $ would be a totally ramified prime. However, this is not the case: $ \operatorname{disc} \mathcal O_K = 5 $, therefore $ 2 $ is not even a ramified prime in $ \mathcal O_K $. (This is a counterexample to your claim, since $ \mathbf Q(\sqrt{5}) $ is actually the splitting field of $ x^2 - 5 $ over $ \mathbf Q $. Note that $ \mathcal O_K $ is even a principal ideal domain!)


text:
Q: Code crashes on calling delete This may be a stupid question, but why does this code crash when calling delete? From reading other questions I know this probably results in undefined behavior but I don't see exactly why.
#include <iostream>
using namespace std;

char* resize (char* result, int& size){
  char * temp;
  temp = new char [size*10];
  for (int i=0;i<size;i++) temp[i]=result[i];
  size*=10;
  //delete[] result;
  return temp;
}

void transform(char in[], const char p1[], const char p2[]){
  int resultlength=100, inputindex=0, outputindex=0;
  char* result = new char[resultlength];

  while (in[inputindex]){
    result[outputindex++]=in[inputindex++];

    if (inputindex>=resultlength) result = resize (result,resultlength);
  }
  in[outputindex--]=0;
  while(outputindex>=0) in[outputindex]=result[outputindex--];
  //delete[] result;
}

int main(){
  char  t[200]="123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345";
  transform(t,"hfgh","dfsdfds");
  int i=0;
  while(t[i]) cout<<t[i++];
  cout<<endl;
  return 0;
}

A: @WhozCraig's comment is right on the money. The crux of the problem is that
delete[] result;

makes the pointer in the calling function a dangling pointer.
The line
result=temp;

does nothing to the pointer in the calling function. The calling function still has a dangling pointer.
Solution 1
Change the argument to be a reference to a pointer.
void resize (char*& result, int& size){
 ...
}

Solution 2
Return the newly allocated memory as the return value.
char* resize (char* result, int& size){
   char * temp;
   temp = new char (size*10);
   for (int i=0;i<size;i++) temp[i]=result[i];
   size*=10;
   delete[] result;
   return temp;
}

and make sure to use
result = resize(result, resultlength);

in the calling function.
Solution 3
Instead of using char* result, use std::string result or std::vector<char> result.
Update, after seeing the MCVE
The line
while(outputindex>=0) in[outputindex]=result[outputindex--];

causes undefined behavior. By using gcc -Wall, I get the following diagnostic:
socc.cc: In function 'void transform(char*, const char*, const char*)':
socc.cc:22:62: warning: operation on 'outputindex' may be undefined [-Wsequence-point]
   while(outputindex>=0) in[outputindex]=result[outputindex--];

                                                          ^

After changing that to:
while(outputindex>=0)
{
   in[outputindex]=result[outputindex];
   --outputindex;
}

the program ran fine for me.

A: *

*result could be null, be sure to check at the top of the function

*What you are doing is deleting result in resize. But since the pointer isn't passed by reference the result pointer outside of the resize function is pointing to deleted memory. So either pass the pointer by reference or change it to

resize(char ** result,....){
   //Resize stuff
   delete result*;//Deleting the stuff pointed to by result
   result* = temp;// Assigning the pointer outside the function to temp
}

Then you would call resize like
resize(&result,resultlength)

EDIT:
To change the resize to get the pointer by reference change the declaration to
resize(char*& result,...)

and thats it, much simpler that the pointer to pointer method.


text:
Q: How to make svg image to be above other elements I'm making flat selector from floor view with image png with walls of floor and transparent background, i want to <image /> be over o my  so when i change color of polygons inside, walls will be black -  not mix of black and ref and for example rgba(255,255,0.3) over black background fives rgb(139, 101, 101);
TLDR: How to make svg image to be above other elements?
<svg class="floor_svg" version="1.1" preserveAspectRatio="xMinYMin" viewBox="0 0 1080 800" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <image class="area__bck" stroke-width="0" xlink:href="<?=get_template_directory_uri()?>/hood/floor_template/b1-p1.png" preserveAspectRatio="xMinYMin" width="1080" height="800" y="0" x="0"></image>

        <polygon points="388,84.5 388,64.3 253.2,64.3 253.2,84.5 88.3,84.5 88.3,393.1 516.8,393.1 516.8,84.5 "/>
        <polygon class="terrace" points="57.8,10.3 71,10.3 235.3,10.3 235.3,67.8 71,67.8 71,164.7 51.1,164.7 51.1,311
            13.1,311 13.1,164.7 13.1,162.7 13.1,10.3 "/>

        <polygon points="456.8,773.8 219.9,773.8 219.7,615 147.8,615.5 147.8,404.3 517.5,404.3 517.5,479.2
    456.8,478.9 "/>
        <polygon class="logy" points="159,630.7 149.1,630.7 135.2,630.7 135.2,771.8 149.1,771.8 149.1,785.8 203.3,785.8
    203.3,630.7 "/>

        <polygon points="584.6,476 527.1,476.2 526.9,488.2 467.4,488.2 467.4,773.8 612.4,773.8 612.4,703.4
    689.5,703.5 689.6,692.9 695.5,692.9 695.7,558 584.5,558 "/>
        <rect x="618.5" y="703.5" class="logy" width="71.1" height="84.4"/>

</svg>

A: Paulie_D answer:
Put the image last? I think that's the stacking order!
yes it is


text:
Q: wordpress allow only to add comments How do I restrict users only to add comments?
That is, disallow edit or delete of a comment.
I need to do it programmatically from a plugin. It should only affect the currently rendered post.

A: You can use the Role Scoper to disable this permissions.
Or disable the line   $actions['function'] in templates.php
function can be : approve, unapprove, spam, edit, quickedit


text:
Q: how to Invoke directive function from javascript JavaScript function:
 var API = (function(){
        return {
            function invokeDirective(){
                invvoke();
                $scope.setItem() // to directive
            }
        }
    });

Directive:
angular.module('sampleComponents', ['$strap.directives']).directive('titlebar',
function($filter,$timeout)
{
    return {
        restrict: 'AE',
        replace: true,
        scope: true,
        transclude: true,
        template: '<div class="searchBar r  etc ........',
        controller: function($scope,$http,$timeout)
        {
            $scope.setItem = function(){
                // want to invoke this function from api.js -
            }
        }
        link: function(scope, element, attrs){
            // etc:
        }

});

how can I invoke $scope.setItem from api.js? Is it possible? Please suggest.
(currently, I am using timer, but that is creating some performance issue )

A: Yes, you can do that with a very hacky way.
Demo code:
//This is too get scope outside of angular controller/service/directive
//with a hacky way to do that.

var $injector =angular.injector(['ng','MyApp']);
var html = "

";
$injector.invoke(function($compile, $rootScope){
    var $scope = $rootScope.$new();
    var result= $compile(html)($scope);

    var cScope = result.scope(); // This is scope in directive controller. :  )
    //Do anything you want with this scope .
});

This is Jsfiddle.
Happy coding. : )


text:
Q: Sensing analog voltage on Arduino without loading the input circuit I want to design a voltage divider for my Arduino Analog input pin, to be able to sense the change in voltage in a 9V, 250mA circuit (without loading it).
Ive programmed the Arduino so that as soon as a drop in voltage is sensed, my Arduino will perform rest of its job (programmed to create a specific series of delays that I need).
In other words how can I create a signal that is proportional to the changes in the 9V signal that operates at 250mA without drawing any extra current from it nor by creating any voltage drops in the original circuit.
The link below gave great information on how I can use opto-couplers and that would have solved my problem but CNY17 cannot operate over 60mA (otherwise I would have just put that in series with the original circuit?)
How can I use a 12 V input on a digital Arduino pin?
Any help is much appreciated!
edit1:
Let me try to describe the problem better. I had a feeling it came across as vague in my attempt to minimize the description.
The 9V circuit that I was referring to is basically a water flow meter that starts spinning when a flow is sensed and this chops the 9VDC applied across it into pulses, an irrigation controller connected to the other end(this is what applies the 9V across the flow meter) measures the frequency of these pulses and determines the flow of the water(in gpm)
Using Arduino, I am building a circuit that will initiate a series of delays as soon as it senses a flow. 9VDC=no flow, chopped 9V=flow
However since I cannot connect 9V directly to Arduino, I need some sort of a voltage divider, but the reason it needs to be isolated from this 9V flow meter circuit is because the irrigation controller is calibrated to read any changes in the voltage and I don't want it to give false reading. I guess I can use some current from the original circuit -it currently runs at 230mA and I dont know how much I can add on to this without confusing the controller - something that must be tested to find out.
Also I would imagine that a small voltage drop (1-2volts) should be okay?
for example: I was considering using an optocoupler- with the photodiode in series with the flowmeter cicuit, but I dont want to reduce the original current (230mA) by any significant amount lest it give a false input to the irrigation controller. At the same time, the optocouplers I am looking at do not allow anything more than 60mA.
Hope this helps understand the problem a bit better. I am happy to answer any more questions.

A: The easiest, and cheapest, method would be use a voltage divider with large value resistors (both greater than 100k in this case). If you connected your 9V circuit output in series with a 200k resistor and 100k resistor, the voltage in the middle of the resistors would be 3V, comfortably in the middle of the Arduino's 5V operating range.
For practical purposes, a large value voltage divider will not load your source circuit down as, from Ohms Law, 9V divided by the total resistance, 300k, is 30uA. This is 0.01% of your source current, and can thus be ignored.
If this small current cannot be ignored, look into op-amp circuits, which will have input currents in the nA or less range.
EDIT: Yes, loading of the ADC circuit could be a problem. The easiest way to prevent this would be to connect the large value voltage divider, which I describe here, to the op-amp voltage follower shown below. This would both drop the voltage to a level the arduino can handle, and prevent any ADC circuit loading.

A: The best thing for you is to use  the op-amp buffer. You can read about it here:
http://en.wikipedia.org/wiki/Buffer_amplifier#Voltage_buffer

The circuit in designing a buffer is just an operational amplifier, nothing else. Although you might consider reducing the 9V to 5V to prevent any damage to the arduino. Here a voltage divider will be useful. So, first use the buffer amplifier(this will avoid loading the input circuit) and then use a voltage divider configuration to convert the 9V to 5V. This should solve your problem.

A: Given your new enhanced description, you should probably be using DIGITAL TECHNIQUES to look for falling edges on your 9V chopped signal.  Use the signal to drive the base of a transistor, and a fairly big resistor to current limit that.  Power the transistor with 5 Volts.
An optocoupler needs to suck enough current to drive a photoelement, and will probably draw more current than a simple transistor circuit.
Detecting your falling edges is a much more efficient way to deal with all of your issues than sampling of the analog signal.

simulate this circuit – Schematic created using CircuitLab
If you run this simulation, this is actually inverting, so you would detect rising edges.  I used a generic transistor, but a 2n3904 would be fine.

A: You can use analog or digital inputs, since you don't need to measure the exact voltage, only detect interruptions.
The high value voltage divider as suggested is all you need, for either analog or digital.  If you are running your Arduino on 5v, you can just drop the 9V in half.  From what you say, you don't really need to worry much about loading the circuit - you'll need far less than the 230 mA it already draws, to make a measurement.  For example, two 4.7K resistors will only draw about 1 mA.  I might use 10 time that or more tho.
All this assumes your arduino is separately powered, right?  You will need to share the ground of the Arduino with the negative side of the 9v circuit.
You may have bigger problems tho - there could be spikes in the 9V line.  So you might want to use a small cap across the line, and/or add a reversed diode.  But that's not the question you asked - so this is just a heads up.


text:
Q: Higher-dimensional category theory on objects I would like to know if there exists a satisfying generalization of higher-dimensional category theory on objects, that doesn't forget the inner structure of objects. Usually, what people do is to look for higher dimensional arrows, thus remembering the relations between 0-cells but forgetting that $0$-cells can be "made up".
What I want is to "keep track" of the inner structure of my objects (for example, they can be subcategories or categories).
Example: Cat as a 2-category is such that its 0-cells are small categories, 1-cells are functors, 2-cells are natural transformations. As an abstract 2-category, Cat doesn't "see" the inner structure of 0-cells and treat them as pure syntax. It is as if there was some "forgetful inner structure functor" that was applied to a higher dimensional analog on object.
The same happens when one construct a category where objects are diagrams of another category. Indeed, let $\mathcal{C}$ be an abstract category. Let $Grp(\mathcal{C})$ be the category where objects are group objects of $\mathcal{C}$ and arrows are internal homomorphism. In this example, one is once again forgetting the inner structure of group object and see them as 0-cell (i.e., point on the underlying graph).
More formally, one can call $2*$-category a "collection" of categories + functors between them (in order to mimic a subcategory of Cat where one remembers the inner structure of objects). A $2*$-functor would take as input objects, arrows, and functors of a $2*$-category, and maps them respectively to objects, arrows, and functors with obvious axioms (preservation of composition of functors + unit).
The "forgetful inner structure functor" is then the $2*$-functor injective on functors, sending all objects of a given $2*$-category to a constant object of the same category, all arrows to the identity, but keeping tracks of the functors.
PS: my formalization is just done here to clarify the idea, its obviously not the way to go because it doesn't encompass the example of $Grp(\mathcal{C})$. Actually, it would be an even higher dimensional analog. A group object in $\mathcal{C}$ is already a $2*$-category: it is a functor from the sketch of a group object to $\mathcal{C}$, and arrows between them is given by natural transformations between such functors. So basically, $Grp(\mathcal{C})$ is a pretty good example of mix between higher-dimensional category theory both on objects and arrows.

A: Cat does see the inner category structure of its 0-cells. In fact, it sees it in a very direct manner: any small category $C$ is isomorphic to the hom-category $\hom_{\mathbf{Cat}}(\mathbf{1}, C)$, where $\mathbf{1}$ is the terminal category.
This is typical of how category theory thinks of structure: structure is what you see with arrows. If you construct a category and find that there is some aspect of your objects that you can't see with arrows, then that aspect isn't part of the structure you're studying. (or alternatively, you constructed the wrong category)

A: I'm posting an answer to my own thread in order to show that the concept I was looking for is actually easily formalizable and useful.
A  $2$-floor category is a collection of objects $A$, $B$, $C$, $\ldots$ called $0$-arrows and written $\mathcal{C}_0$, a collection of $1$-arrows $f$, $g$, $h$, $\ldots$ between objects written $\mathcal{C}_1$,  and a collection of $2$-arrows $F$, $G$, $H$, $\ldots$ between $1$-arrows written $\mathcal{C}_2$. This comes with two kinds of source and target maps, $s_1, t_1: \mathcal{C}_1 \rightarrow \mathcal{C}_0$ and $s_2, t_2: \mathcal{C}_2 \rightarrow \mathcal{C}_1$, together with two compositions defined as the pullback of source and target maps $\circ_1 : \mathcal{C}_1 \times_{\mathcal{C}_0} \mathcal{C}_1 \rightarrow \mathcal{C}_0$ and $\circ_2: \mathcal{C}_2 \times_{\mathcal{C}_1} \mathcal{C}_2 \rightarrow \mathcal{C}_1$ such that:
1) The $0$-arrows and the $1$-arrows together with $\circ_1$, $(\mathcal{C}_0, \mathcal{C}_1, \circ_1, s_1, t_1)$, form a category. Hence, $\circ_1$ is associative, unital, and is to be seen as horizontal composition of $1$-arrows. We call $Id_A$ the identity arrow at $A$.
2) The $1$-arrows and the $2$-arrows together with $\circ_2$, $(\mathcal{C}_1, \mathcal{C}_2, \circ_2, s_2, t_2))$  form a category. Hence, $\circ_2$ is associative, unital and is to be seen as vertical composition of $2$-arrows. We call $Id_f$ the identity arrow at $f$.
3) We also introduce a functorial horizontal composition of $2$-arrows $\circ_h$ defined for 2-arrows $F$ and $G$ such that $t_1 s_2 F = s_1 s_2 G$, $t_1 t_2 F = s_1 t_2 G$, and is such that it preserves source and target maps. That is, $s_2 \circ_h(F,G) = s_1 G \circ_1 s_1 F $, $t_2 \circ_h(F,G) = t_1 G \circ_1  t_1 F$. Let $F$, $F'$, $G$, $G'$ be four $2$-arrows such that $F' \circ_2 F$, $G' \circ_2 G$ and $\circ_h( (F',G') \circ (F,G))$ makes sense. By functoriality, we have
$\circ_h( (F',G') \circ (F,G)) = \circ_h( F' \circ_2 F, G' \circ_2 G) = \circ_h(F',G') \circ_2 \circ_h (F,G),$
that is in usual notations $(G' \circ_h F')\circ_2 (G \circ_h F) = (G' \circ_2 G) \circ_h (F' \circ_2 F)$ an interchange laws for $2$-arrows.
Example:
Let $\mathcal{C}$ and $\mathcal{D}$ be two different categories and $F: \mathcal{C} \rightarrow \mathcal{D}$ a functor. If we let $\mathcal{C}_0 = Obj(\mathcal{C}) \cup Obj(\mathcal{D})$, $\mathcal{C}_1 = Arr(\mathcal{C}) \cup Arr(\mathcal{D})$ and add $2$-arrows $F_f: f \rightarrow F(f)$ we obtain a $2$-category where the horizontal composition is defined as $F_f \circ_h F_g = F_{f \circ g}$ whenever $F(f \circ g)$ makes sense.
Let $Indisc(3)$ be the category generated by $3$ objects $A$, $B$, $C$ and three arrows$ f: A \rightarrow B$, $g: B \rightarrow C$, and $h: C\rightarrow A$ with relations $h \circ g \circ f = Id$. Any endofunctor induces a 2-floor category with three objects.
Any category that is build "over" another category (say that its objets are some subgraph of it) is a 2-floor category. This concept is interesting when one wants to remember the construction process of categories over categories, because it allows to remember everything.


text:
Q: Zoom-in, Zoom-out and move images in layers of TouchImageViews (one on top of the other) I have a few layers of TouchImageViews, one on top of the other.
The bottom TouchImageView contains the basic image. Then, each layer adds information on top of it. The user can choose which layers should be shown - for example when the user clicks on a button, analysis TouchImageView is set to visible, and thus the user can see this layer on top of the image.
In order to allow the user to zoom-in, zoom-out and move the image, I used TouchImageView. This works great when only one TouchImageView is shown. When there are multiple shown TouchImageViews, I set a transparent TouchImageView on top of them, which listens to touch events and updates the other TouchImageViews under it.
   binding.overlayView.setOnTouchImageViewListener(object : OnTouchImageViewListener {
        override fun onMove() {
            binding.baseView.setZoom(binding.zoomOverlay)
            binding.analysisView.setZoom(binding.zoomOverlay)
            binding.linesView.setZoom(binding.zoomOverlay)
            binding.colorView.setZoom(binding.zoomOverlay)
        }
    })

The problem: the zoom works perfectly, the movement works but not good enough: after zooming in, the movement of the underlying images is limited. They move with the top overlay TouchImageView, but not all the way. They move just a bit, kind of stuck in the middle. I cannot move them all the way to the sides. The top transparent layout moves correctly (I tested it with a background of a ball, and I can move the ball all over the screen).
Here is the layout in xml:
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/image_view_container"
    android:layout_width="match_parentdp"
    android:layout_height="match_parent">

<com.ortiz.touchview.TouchImageView
    android:id="@+id/baseView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:forceHasOverlappingRendering="false"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.ortiz.touchview.TouchImageView
    android:id="@+id/analysisView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.ortiz.touchview.TouchImageView
    android:id="@+id/linesView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.ortiz.touchview.TouchImageView
    android:id="@+id/colorView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.ortiz.touchview.TouchImageView
    android:id="@+id/overlayView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:visibility="visible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Any ideas?


text:
Q: Ignore comments (#) using sed script, but keep the lines untouched This is similar to the following question:
Ignore comments (#) using sed, but keep the lines untouched
However, the difference is that instead of having one substitution I have sed script-file with a couple of substitutions.
I guess I could edit each and every line of the script to be in the form:
/^#/!s/orig/replace/g

However, that seems to be a bit of too much copy-and-pasting to me.
Is there a more elegant way?
The script I am using is:
http://www.cis.upenn.edu/~treebank/tokenizer.sed

A: You can use a block:
/^#/!{s/a/b/;s/c/d/}

A: Can you use awk instead of sed in your script? A sed script of:
s/orig/replace/g
s/\(foo\)bar/\1dog/

can be converted line by line to a GNU awk script of:
{
   $0=gensub(/orig/,"replace","g")
   $0=gensub(/(foo)bar/,"\\1dog","")
}
{ print }

and then if you don't want to process lines that start with a # it's a trivial tweak to the awk script to test for that condition before entering the action block:
!/^#/ {
   $0=gensub(/orig/,"replace","g")
   $0=gensub(/(foo)bar/,"\\1dog","")
}
{ print }

Here's the first few conversions from your sed script to get you going if you want to do this:
# s=^"=`` =g
$0 = gensub(/^"/,"``","g")

# s=\([ ([{<]\)"=\1 `` =g
$0 = gensub(/([ ([{<])"/"\\1 ``","g")

# s=\.\.\.= ... =g
$0 = gensub(/\.\.\./," ... ","g")

# s=[,;:@#$%&]= & =g
$0 = gensub(/[,;:@#$%&]/," & ","g")

# s=\([^.]\)\([.]\)\([])}>"']*\)[       ]*$=\1 \2\3 =g
$0 = gensub(/([^.])([.])([])}>"']*)[    ]*$/,"\\1 \\2\\3","g")

mainly you just change \( in sed to ( in awk, and \1 in sed to \\1 in awk.


text:
Q: Function prototype, without definition I'am developing a library, that can't use Classes. I have a function I call when a get a KeyDown event and i want to call a function that i set the prototype for before in the library.
The thing is, I don't want to be mandatory for the user to define this function if he doesn't want to handle any input. But the linker won't let me define a prototype without a definition or set a default empty definition. What can i do?
I'am using C++ by the way...
This are the prototypes /
void keyDown(int virtual_keyCode);
void keyUp(int virtual_keyCode);

A: Redefining a function is not possible in C++. Read this about the One Definition Rule.

Only one definition of any variable, function, class type, enumeration type, concept (since C++20) or template is allowed in any one translation unit (some of these may have multiple declarations, but only one definition is allowed).

Overloading of class functions is possible with inheritance. Overloading is not the same as redefinition.
You can use function pointers, which you can reassign, e.g.
#include<functional>
#include<iostream>

std::function<void(int)> keyUp = [](int) {};

void unused() {
    keyUp(2);
}

void KeyUp(int i) {
    std::cout << i << i << '\n';
}

int main() {
    unused(); // no print
    keyUp = [](int i) { std::cout << i << '\n'; };
    unused(); // prints 2
    keyUp = KeyUp;
    unused(); // prints 22
}

It doesn't look the same, but effectively its the same...


text:
Q: SOAP services iOS I wanted to call SOAP services, saw many document's over link.
I used one of those like the BestSoaptool from github https://github.com/yillars/BestSoapToolwithafnet, but I am still lacking some where and not able to get the response.
I am using the link as -- "https://aaa.com/Customers.svc?singleWsdl" and then the method name  "xxx" but I don't get a response.
If not this can any one give me some better idea as to how should I implement this?
Thanks.

A: I've added sample SOAP implementation in iOS in my wordpress blog. Hope this will help you https://wordpress.com/post/bharathreddys.wordpress.com/6
Lets assume the following .wsdl url is the source URL.
http://www.webservicex.net/geoipservice.asmx?WSDL

Create a SOAP Envelop and SOAP Header.
NSMutableString * soapHeader = @"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\""

        " xmlns:hom=\"http://www.webservicex.net/">"

        "<soapenv:Header/>";

Be remember that "xmlns:hom", text next to ":" is the word which will be used as the targetnamespace reference for the service call which will be added in SOAP body.
SOAP body will be as follows :
[soapHeader appendString:@"<soapenv:Body>"];

[soapHeader appendString:@"<hom:GetGeoIP>"]; // add the body parameters

[soapHeader appendString:@"<hom:IPAddress>0.0.0.1</hom:IPAddress>"];

[soapHeader appendString:@"</hom:GetGeoIP>"];

[soapHeader appendString:@"</soapenv:Body>"];

[soapHeader appendString:@"</soapenv:envelope>"];

Now the web service is as follows:
NSMutableString * requestStr = [NSMutableStringstring];

[requestStr appendString:soapHeader];

NSString * urlStr = @"http://www.webservicex.net/geoipservice.asmx?WSDL";

NSURL * url = [NSURL URLWithString:urlStr];

NSMutableURLRequest * request = [[NSMutableURLRequestalloc] initWithURL:url];

[request setValue:@"http://www.webservicex.net/GetGeoIP" forHTTPHeaderField:@"SOAPAction"];

[request setValue:@"http://www.webservicex.net/" forHTTPHeaderField:@"targetNamespace"];

[request setValue:@"text/xml;charset=UTF-8"forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:requestBody];

[request setHTTPMethod:@"POST"];

[request setValue:[NSStringstringWithFormat:@"%d",[requestBody length]] forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    BOOL isSuccess = YES;

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

    NSLog(@"received data---%@",response);

    if(connectionError != nil) {

        isSuccess = NO;

        NSLog(@"connection error with code %d",connectionError.code);

    }

    NSDictionary * responseDictionary = [NSDictionary dictionary];

    if([httpResponse statusCode] == 200) {

        isSuccess = YES;

     //Do something with the received dictionary.

}];

This is the basic platform how we can make a simple SOAP based web service calls in iOS.
Happy coding !!!!


text:
Q: How do you pass a sql query to another function in PHP I tried asking this before but didnt really get an answer so Ill try to rephrse it. I cant figure out how to pass the results of a multi line query to another function or page, especially using PDO. Would I execute the loop in the original function?
public function viewGallery(){
    $pQuery = 'SELECT * FROM profiles WHERE  userId = ?';
    $viewGallery = $this-> _db ->prepare($pQuery);
    $viewGallery ->bindParam(1, $id);
    $viewGallery ->execute();

    while ($get_row = $viewGallery ->fetch()){
        $id = $get_row['id'];
    }
}

then another page that accesses this:
 //echo the results of viewGallery();

A: You need to return the results you want from viewGallery() then echo them on the other page.
You could return an array of results (ids by the looks of it) and then whiz through them with a while loop on your other page to display them
while ($get_row = $viewGallery ->fetch()){
    $id = $get_row['id'];
    $myBigArray[] = $id;
}

return $myBigArray;

Then on the other page just loop through and echo each result

A: Assuming that your SQL returns col1, col2 and col3
You can do the following to pass the results:
while ($get_row = $viewGallery ->fetch())
{
    $col1 = $get_row['col1'];
    $col2 = $get_row['col2'];
    $col3 = $get_row['col3'];
    someFunctionNameThatEchoesResults($col1, $col2, $col3);
}

You could also put all the results into an array and then pass it to the other function:
$resArray=array();
while ($get_row = $viewGallery ->fetch())
{
    $col1 = $get_row['col1'];
    $col2 = $get_row['col2'];
    $col3 = $get_row['col3'];
    $resArray[]=array($col1, $col2, $col3);
}
someFunctionNameTheShowsResults($resArray);

A: I would simply return the complete data set with fetchAll()
something like below
try {
    $dbh = PDO(/* Connection Info */);
    $query = "SELECT * FROM foo";
    $stmt = $dbh->prepare($query);

    $stmt->execute();

    return $stmt->fetchAll();
}catch(PDOException $e) {
    echo "ERROR: " . $e->getMessage();
}


text:
Q: How to get page to scroll to a section when a button is clicked I'm trying to get my page to scroll to a specific point on my page if there is errors after submitting a form. My page doesn't scroll down. I'm using Laravel 4.
Jquery
$('.submit_btn').click(function(){
    $('html, body').animate({
        scrollTop: $('#form-messages').offset().top
    }, 2000);
});

my contact.blade.php

        @foreach($errors->all(':message') as $message)

            {{ $message }}

        @endforeach()
        {{ Form:: open(array('url' => 'contact_request')) }}
          {{ Form:: text('name', '', array("class" => "form-control", 'placeholder' => 'Name')) }}
          {{ Form:: email('email', '', array("class" => "form-control", 'placeholder' => 'Email')) }}
          {{ Form:: text('subject', '', array("class" => "form-control", 'placeholder' => 'Subject')) }}
          {{ Form:: textarea ('message', '', array("class" => "form-control", 'placeholder' => 'Your Message')) }}
          {{ Form::submit('SEND', array('class' => 'submit_btn')) }}
        {{ Form:: close() }}

UPDATE:
So I half managed to to what I needed execpt it jumps up after hitting the id. For example when I click the submit button the page scrolls down to the correct section of my page but then it jumps up a bit to another section.
Here is my updated form
{{ Form:: open(array('url' => 'contact_request#contact')) }}
          {{ Form:: text('name', '', array("class" => "form-control", 'placeholder' => 'Name')) }}
          {{ Form:: email('email', '', array("class" => "form-control", 'placeholder' => 'Email')) }}
          {{ Form:: text('subject', '', array("class" => "form-control", 'placeholder' => 'Subject')) }}
          {{ Form:: textarea ('message', '', array("class" => "form-control", 'placeholder' => 'Your Message')) }}
          {{ Form::submit('SEND', array('class' => 'submit_btn')) }}
        {{ Form:: close() }}


text:
Q: Error Handling in Laravel, how can specify on Routes? The basic of this is, I want to handle errors from my API and make sure all errors thrown via the API give json responses but for the website I want HTML responses to be sent.
If there a better way then purely applying the logic from http://laravel.com/docs/requests#request-information and using something like:
if (Request::is('admin/*'))
{
    //
}

This works but seems a tiny bit clunky doing it for each exception type that might be thrown? The documentation doesn't seem to have anything but I was wandering if there's anything that might work so can apply errors for set route wildcards? Something like:
App::error('admin/*', function(Exception $exception)
{
    Log::error($exception);
});

A: You can add an App::error filter and in that filter do the Route check, and then send a response in json. A simple example like this:
App::error(function(Exception $exception) {
    if (Request::is('api/*')) {
        $message = get_class($exception) . ":: message: " . $exception->getMessage();
        return Response::json(["success"=>false,"message"=>$message]);
    }
});

A: You could use a Route Group http://laravel.com/docs/routing#route-groups and apply a filter on the group, or prehaps you could use the App::error method if you declared it inside a prefixed route group http://four.laravel.com/docs/routing#route-prefixing . I'm not 100% whether either method would work, but if you have no luck the Laravel IRC is very active see http://laravel.io/irc for a quick easy web client.


text:
Q: PyMC3: Regression under multivariate Normal I've recently started learning pymc3, and I want to predict multivariate Normal model. There are N sets of M continuous data, and I want to predict the parameters a, b, and their correlations for each set from the observed data x_ob and y_ob. I assumed that x and y are hyperbolic relationships, and the parameters a and b are correlated and normally distributed.
Here is what I have so far.
#  Generate data
np.random.seed(10)
N = 10
M = 5
idx = np.arange(N*M)//M
x_ob = np.arange(N*M)%M+1
a,b = 1,2.5
ro = 0.7
s1,s2=0.1,0.1
cov = [[s1**2,ro*s1*s2],[ro*s1*s2,s2**2]]
ax,bx = np.random.multivariate_normal([a,b],cov,N).T
noise = np.random.normal(1,0.05,N*M)

def func(x,a,b):
    return a*x/(x+b)

y_ob = func(x_ob, ax[idx], bx[idx])*noise

# MCMC
with pm.Model() as model:
    # model
    ab0 = pm.Uniform('ab0', lower=0, upper=5, shape=2)
    sd  = pm.Uniform("sd",lower=0,upper=1, shape=2)
    rh  = pm.Uniform("rh",lower=-1,upper=1)
    cov = pm.Deterministic("cov", pm.math.stack(([sd[0]**2,sd[0]*sd[1]*rh],[sd[0]*sd[1]*rh,sd[1]**2])))

    ab  = pm.MvNormal('ab', mu=ab0, cov=cov, shape=(N,2))
    a = ab[:,0]
    b = ab[:,1]

    # error
    eps_cv = pm.Uniform('eps', lower=0, upper=1)

    # observation
    y0= func(x_ob,a[idx], b[idx])
    y = pm.Normal('y',  mu=y0 , sd=eps_cv*y0, observed=y_ob)

    prior_samples = pm.sample_prior_predictive(100)
pm.model_to_graphviz(model)

This raises the error:
Bad input argument to theano function with name "C:\Users\user\Anaconda3\envs\pymc\lib\site-packages\pymc3\distributions\distribution.py:431" at index 0 (0-based). Wrong number of dimensions: expected 1, got 2 with shape (100, 2).
Since I found sample_prior_predictive["ab"] includeing NAN, I thought the shape of ab was wrong, but I had no idea. How should I do?
Thanks in advance.


text:
Q: accessing to the backend from a subdomain in laravel I am using laravel for crud and cms purposes. I have a frontend and backend. Both backend and frontend is loading from the public folder.
From the Cpanel I have pointed my domain to the public folder. So, the website is loading when I type www.site.com and the backend is loading after login verification when I type www.site.com/dashboard
I would like to seperate my backend from the frontend. I would like to access to the backend from the url admin.site.com or cms.site.com and I would like to access to the front end from the url www.site.com.
How can I manage to do this? I can point the subdomain to the public folder as well and can load the backand from the url cms.site.com/dashboard but the backend still would be accessible from the url www.site.com/dashboard.
I would appreciate if you can give me an idea about seperating the frontend from the backend.

A: I am assuming you have a separate controller to handle back-end and that controller's index method returns the back-end view. In that case you can use Laravel's subdomain routing function to route your sub-domain to your backend site.
like this
Route::group(['domain' => 'admin.site.com'], function () {

   Route::get('/', 'backendController@index');

})

or If you don't have a controller and just have a view to be displayed
Route::group(['domain' => 'admin.site.com'], function () {
   Route::get("/", function(){
          return View::make("backend_view");
    });
})

Note: backend_view refers to a backend_view.blade.php in your resources/views folder.


text:
Q: Loopback js mongdb Null or Missing Fields I'm using loopback js for backend rest api. I'm switching from Mysql to Mongodb.
I have been using query filters like these:
{filter:{where:{fieldName:null}}}

This works fine with mysql but when switching to mongodb it dosen't work.
https://docs.mongodb.com/v3.2/tutorial/query-for-null-fields/  It is supported as document says. Am I missing some configurations for loopback?
My goal is to change mysql to mongodb without updating any queries.

A: The connector is turning your query into command=find [ { fieldName: { '$type': 10 } },
You can add this to your datasource object to use the extended operators and regain your functionality.
"allowExtendedOperators": true
ex
{ "where": { "or": [ { "name": null }, {"name": { "exists": false } } ] } }

A: You do not need the "where" when querying in MongoDB.
Can you try querying this instead?

db.coll.find({fieldName: null})


text:
Q: MySQL: how to get the last record? Say I have the following records:
1, A
1, B
2, A
2, B
2, C
1, C

I want the last record for 1 and 2, which should be 1, C and 2, C. How do I query that?
If I do a GROUP BY on the number, I get 1, A and 2, A.

A: if by 'last' you mean maximum alphabetically, then maybe this:
select id, max(val)
from mytable
group by id

A: Without some sort of index or insertion order, there's no way of getting what you want; SQL queries are order non-deterministic.

A: Now that we've established that you mean "last" as in "chronologically", then I can create a proper answer...
SQL has no concept of chronology.  So you will have to record the insertion order yourself.  Most typically, you would add an autoincrementing field, and then use that in an ORDER BY clause, along with a LIMIT clause.

A: If it's not alphabetic, then you need to use LIMIT and so just do the following.
select @rownum:=@rownum+1 as naturalorder, * from foo, (SELECT @rownum:=0) nat order by naturalorder desc limit 1;

but warning that there is no guarantee from mysql on the order of the records. so you might want to add an extra field with a timestamp fields or an auto_increment which will have the order that you are looking for, i think.
If it is alphabetical, the trick is to order by the code descending and then get the 1st record. And you can limit that by one.
select num, code from thetable order by code DESC limit 1

if you use group by, you have to scan through the entire table. and also it's difficult to get the full record.


text:
Q: Relationship between unit circle and cosine wave? If you plot these two relations:
$$y=cos(x)$$
$$x^2 + y^2 = 1$$
The cosine wave seems to "hug" the unit circle shown below.

I'm wondering the calculus explanation for this, as I believe it must have to do with the relationship between the implicit derivative of the unit circle, where the slope of the tangent line at any point is found using the negative cotangent function.  But this doesn't seem to explain why the unit circle is wrapped around the cosine function like this as the derivative is asymptotic at $\frac{\pi}{2}$. And even then, is there a geometric intuition for why they behave so similarly around 0?

A: What you have here is what is called an osculating circle: a circle tangent to a curve at a point such that the curve has the same curvature as the circle.
To cut a long story short, for a curve of the form $y=f(x)$, the (unsigned) curvature at the point $(x,f(x))$ is given by
$$ \frac{\lvert f''(x) \rvert}{(1+f'(x)^2)^{3/2}}, $$
and the curvature of a circle (i.e. $y=b \pm \sqrt{R^2-(x-a)^2}$) is then easily computed to be $1/R$ (or perhaps more clearly, the curvature is defined as the curvature of osculating circle and the definition that a circle of radius $R$ has curvature $1/R$).
In this case,
$$ \cos'0 = \sin{0} = 0, \quad \cos''0 = -\cos{0} = -1, $$
so the curvature of the cosine is $1$, the same as the circle of radius $1$ you have drawn.

A: Two curves $y=f(x)$ and $y=g(x)$ will meet at a value $x=a$ if $f(a)=g(a)$.  They will have the same tangent (which you could think of as a "very light hug" if also $f'(a)=g'(a)$.  They will hug each other better if also $f''(a)=g''(a)$, which means that the curvatures are equal.  This is also sometimes known as "second order contact".  They will hug even more closely if also $f'''(a)=g'''(a)$, and so on.  In this case you have $a=0$ and
$$\displaylines{
  f(x)=\cos x\ ,\quad g(x)=(1-x^2)^{1/2}\ ,\quad f(0)=1=g(0)\cr
  f'(x)=-\sin x\ ,\quad g'(x)=-x(1-x^2)^{-1/2}\ ,\quad f'(0)=0=g'(0)\cr
  f''(x)=-\cos x\ ,\quad g''(x)=-(1-x^2)^{-3/2}\ ,\quad
    f''(0)=-1=g''(0)\cr
  f'''(x)=\sin x\ ,\quad g'''(x)=-3x(1-x^2)^{-5/2}\ ,\quad
    f'''(0)=0=g'''(0)\cr
  f^{(4)}(x)=\cos x\ ,\quad g^{(4)}(x)=-3(1+4x^2)(1-x^2)^{-7/2}\ ,\quad
    f^{(4)}(0)=1\ne g^{(4)}(0)\ .\cr}$$
So the curves have third order contact.
As you commented, it is related to Taylor series.  From the above calculations you can write down the Taylor series for $f$ and $g$ and see that they are equal up to third order terms.


text:
Q: Using columns with special characters in formulae in R I'm trying to make a decision tree using rpart using a data frame that has ~200 columns. Some of these columns have numbers in their names, some have special characters (e.g. "/"). When I try to generate the tree I get error such as the ones below:
R> gg.rpart <- rpart(nospecialchar ~ Special/char, data=temp, method="class")
Error in eval(expr, envir, enclos) : object 'Special' not found
R> gg.rpart <- rpart(nospecialchar ~ "Special/char", data=temp, method="class")
Error in terms.formula(formula, data = data) : invalid model formula in ExtractVars
R> gg.rpart <- rpart(nospecialchar ~ `Special/char`, data=temp, method="class")
Error in `[.data.frame`(frame, predictors) : undefined columns selected

Do I have to change the names to accommodate R or is there some way to pass column names with special characters to R formulae?

A: This works:
dat <- data.frame(M=rnorm(10),'A/B'=1:10,check.names=F)

> lm(M~`A/B`,dat)

Call:
lm(formula = M ~ `A/B`, data = dat)

Coefficients:
(Intercept)        `A/B`
    -1.0494       0.1214

A: Joran's comment on my question is the answer - I didn't know of the existence of make.names()
Joran, if you reply as an answer I'll mark you as correct. Cheers!

A: I just came across the same problem, and I don't want any change in the name when pass it to R formulae. R allow non-syntactic column names with backticks surrounding them. So I try add backticks to the name and it also works well. My code like below:
lapply(colnames(variable), function(gene){
formula0 <- paste0("gleason_grade", "~" "`", gene, "`")
logit <- clm(as.formula(formula0), data = mydata)
})

and now you can pass the new variable to formula without error.
If you don't expect any change to the variable like me, so just backtick it.


text:
Q: Statistics from nested array using PySpark I want to perform some aggregations on the table using PySpark. My table name is COMPLEX_DATA and is stored in Snowflake. The COORDINATES column's datatype is VARIANT. The nested arrays are not of fixed sizes. I could have 1,000 nested arrays, and there are other cases where there are none. My table is shown below:
| ID |         COORDINATES                  |
|----|--------------------------------------|
| 1  |[[0, 15], [1, 50], [2, 5]], [5, 650]] |
| 2  |[[0, 20], [1, 17]]                    |
| 3  |[[0, 10], [1, 15], [2, 11]]           |

The output should look like the following:
| Index| Min | Max | Mean |
|------|-----|-----|------|
| 0    |  10 |  20 | 15   |
| 1    |  15 |  50 | 27.33|
| 2    |  5  |  11 | 8    |
| 5    |  650|  650| 650  |

A: Lets assume that when you import this table in spark corrdinates column will be of Array type so based on it below code can be used where I have used explode and then group by over Index
from pyspark.sql import functions as F
deta=[(1,[[0, 15], [1, 50], [2, 5], [5, 650]]),(2,[[0, 20], [1, 17]]),(3,[[0, 10], [1, 15], [2, 11]])]
dql1=spark.createDataFrame(deta).toDF("ID","COORDINATES")
dql1.withColumn("ecor",F.explode("coordinates")).withColumn("Index",F.col("ecor")[0]).withColumn("ecor_val",F.col("ecor")[1]).drop("id","coordinates","ecor").groupBy("Index").agg(F.min("ecor_val").alias("Min"),F.max("ecor_val").alias("Max"),F.mean("ecor_val").alias("Mean")).show()

#output
+-----+---+---+------------------+
|Index|Min|Max|              Mean|
+-----+---+---+------------------+
|    0| 10| 20|              15.0|
|    1| 15| 50|27.333333333333332|
|    5|650|650|             650.0|
|    2|  5| 11|               8.0|
+-----+---+---+------------------+

Also from datqa you have provided min of 0 should be 10 not 15 as for ID =3 we have [0, 10] in coordinates

A: You can achieve this with a bit of pre-processing using array functions & Higher Order Functions
Data Preparation
input_list = [
    (1,[[0, 15], [1, 50], [2, 5], [5, 650]])
    ,(2,[[0, 20], [1, 17]] )
    ,(3,[[0, 10], [1, 15], [2, 11]])
]

sparkDF = sql.createDataFrame(input_list,['ID','COORDINATES'])

sparkDF.show(truncate=False)

+---+------------------------------------+
|ID |COORDINATES                         |
+---+------------------------------------+
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|
|2  |[[0, 20], [1, 17]]                  |
|3  |[[0, 10], [1, 15], [2, 11]]         |
+---+------------------------------------+

Extract & Explode Index
sparkDF = sparkDF.withColumn('INDEX',F.transform(F.col('COORDINATES'),lambda x:x.getItem(0)))\
                 .withColumn('VALUES',F.transform(F.col('COORDINATES'),lambda x:x.getItem(1)))\
                 .withColumn('INDEX',F.explode(F.col('INDEX')))\

sparkDF.show(truncate=False)

+---+------------------------------------+-----+----------------+
|ID |COORDINATES                         |INDEX|VALUES          |
+---+------------------------------------+-----+----------------+
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|0    |[15, 50, 5, 650]|
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|1    |[15, 50, 5, 650]|
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|2    |[15, 50, 5, 650]|
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|5    |[15, 50, 5, 650]|
|2  |[[0, 20], [1, 17]]                  |0    |[20, 17]        |
|2  |[[0, 20], [1, 17]]                  |1    |[20, 17]        |
|3  |[[0, 10], [1, 15], [2, 11]]         |0    |[10, 15, 11]    |
|3  |[[0, 10], [1, 15], [2, 11]]         |1    |[10, 15, 11]    |
|3  |[[0, 10], [1, 15], [2, 11]]         |2    |[10, 15, 11]    |
+---+------------------------------------+-----+----------------+

Extract Corresponding Values
Since multiple values are spread across INDEX , you need to extract only the value corresponding to its array-index , using row_number
window = Window.partitionBy('ID').orderBy(F.col('ID'))

sparkDF = sparkDF.withColumn('row_num',F.row_number().over(window) - 1)\
                 .withColumn('VALUES',F.col('VALUES').getItem(F.col('row_num')))

sparkDF.show(truncate=False)

+---+------------------------------------+-----+------+-------+
|ID |COORDINATES                         |INDEX|VALUES|row_num|
+---+------------------------------------+-----+------+-------+
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|0    |15    |0      |
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|1    |50    |1      |
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|2    |5     |2      |
|1  |[[0, 15], [1, 50], [2, 5], [5, 650]]|5    |650   |3      |
|3  |[[0, 10], [1, 15], [2, 11]]         |0    |10    |0      |
|3  |[[0, 10], [1, 15], [2, 11]]         |1    |15    |1      |
|3  |[[0, 10], [1, 15], [2, 11]]         |2    |11    |2      |
|2  |[[0, 20], [1, 17]]                  |0    |20    |0      |
|2  |[[0, 20], [1, 17]]                  |1    |17    |1      |
+---+------------------------------------+-----+------+-------+

Final Aggreagtions
+-----+---+---+------------------+
|INDEX|Min|Max|Mean              |
+-----+---+---+------------------+
|0    |10 |20 |15.0              |
|1    |15 |50 |27.333333333333332|
|2    |5  |11 |8.0               |
|5    |650|650|650.0             |
+-----+---+---+------------------+

A: from pyspark.sql import functions as F

df = df.select(F.explode('COORDINATES'))
df = df.groupBy(F.col('col')[0].alias('Index')) \
       .agg(F.min(F.col('col')[1]).alias('Min'),
            F.max(F.col('col')[1]).alias('Max'),
            F.avg(F.col('col')[1]).alias('Mean'))


text:
Q: How to calculate F-score using libsvm for java I have a training and test data set and they work perfectly with the default SVM code using LibSVM using Java. Can you please tell me how to get the confusion matrix and other values like Precision, Recall or atleast true positive rate(TPR), true negative rate(TNR), false positive rate(FPR) and false negative rate(FNR).
I am using command line so for file1.txt as training and tfile1.txt as test file. I am using the command line syntax which gives me the Accuracy %. The command is:-
Input: C:....\bin> java svm_predict file1.txt.model file1.out
Output: 70.135% Accuracy (157/224)
Is there a command line syntax for the program to display values like Precision, Recall, Fscore, TPR, TNR, FPR, FNR as well? What should I do? Please help!


text:
Q: what is the usage of fork while invoke mongod? ./mongod –shardsvr –replSet shard1 –port 27017 –dbpath /data/shard12 –fork

fork: for server process ( from mongod document).
In plain english, what does fork here mean?
Thank you

A: It starts mongodb as a daemon. Meaning that it will not stop running when you close the terminal.


text:
Q: Given two points and asked to find an exponential function described by $y=ab^x$, how to show that the function is unique? The exponential function had to go through the points $P(0,1)$ and $Q(1,2)$.
I found the function to be $y=2^x$.
How can I show that this is the only such exponential function.

A: Assume there is an other function of the form $f(x)=ab^x$.
then
$f(0)=a=1$
and
$f(1)=ab=b=2$
thus
$2^x$ is the unique one.