text:
Q: Is there a way to get the percentage of different landuse types upstream of a given point? I'm a fairly novice GIS user and know just enough to get in trouble in a lot of cases.  I am trying to look at the connection between several measured parameters at a few hundred stations along several rivers and the landuse patterns in the areas drained in ArcGIS 10.  I have created basic watershed analysis layers (flow directions, flow accumulation, catchments, etc) for the entire area of interest.  Is there a way to easily sum up the land usage for the area drained by each station (i.e. get the number of cells of each type of land use along with the total cells drained) so that I could use that for further analysis?  If so, how would be the easiest way to implement that so I don't have to do it individually for each station?  I would assume there would be a way to script it, but I don't know anything about scripting in ArcGIS 10.  Thanks so much!

A: Recompute the flow accumulation by setting the input ("rainfall area") to 1 within the cells of a given land use and 0 elsewhere.  Extract the values at the stations (one operation via the "extract values to points" tool).  Multiply these results by the squared cellsize to estimate the areas.  Repeat for each land type.  Join the results on the station identifiers.  When finished, the percentages are computed in the usual way by renormalizing the areas for each station to sum to 100%.


text:
Q: Exposing class as webservice For an example  I have a webservice class as shown below .This should be exposed to one of the portal.
This portal is having a callbackurl to configure.That means this portal is going to hit my application .
My question is how to create url for this class and do i need to give them Partner WSDL file or the webservice class wsdl file.so that they can hit my class.
global class AccountPlan {

   webservice String area;
   webservice String region;

   //Define an object in apex that is exposed in apex web service
   global class Plan {
      webservice String name;
      webservice Integer planNumber;
      webservice Date planningPeriod;
      webservice Id planId;
   }

   webservice static Plan createAccountPlan(Plan vPlan) {

       //A plan maps to the Account object in salesforce.com.
       //So need to map the Plan class object to Account standard object
       Account acct = new Account();
       acct.Name = vPlan.name;
       acct.AccountNumber = String.valueOf(vPlan.planNumber);
       insert acct;

       vPlan.planId=acct.Id;
       return vPlan;
  }
}

A: You can generate a WSDL specific for calling you Apex web service.
Go to: Setup > App Setup > Develop > Apex Classes.
Find your class. There will be a WSDL link next to the Edit and Del links, or a Generate WSDL button with viewing the Apex Class.
This WSDL will include the required URL.
Note that to call the web service you will need to specify the SessionId in the SessionHeader.

A: You will first need to generate WSDL using

Setup > App Setup > Develop > Apex Classes

There will be a WSDL link use that and generate WSDL.
You will need to share your enterprise WSDL as well as that will have login() call implemented to fetch session Id using password and Username .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not understanding the formula to calculate the execution time of the program task "Suppose your CPU is rated at 2.5 GHz and you execute a program task on your app that requires the execution of 16 million ISA3 instructions. If each ISA3 instructions executes an average of 3.7 mc2 instructions, what is the execution time of the program task?"
I know the answer, its 0.024.
I just dont understand why thats the answer. I dont understand where the numbers ago, if you convert a number to 1000 bts or what.
Someone walk me through it?


text:
Q: How to extract multiple Wikipedia articles at once? I am using Python 2.7 Anaconda.
I have used the Wikipedia Python package to extract a list of article titles:
titles = wikipedia.random(pages=1000).decode('utf-8')
titles_encoded = [x.encode('utf-8') for x in titles]

Is there a way of using
wikipedia.summary(title=titles_encoded,auto_suggest=True, redirect=True).encode('utf-8')

in order to extract multiple articles at once? I have used a for loop but it takes really long:
for n in range(1,500):
    test[n] = wikipedia.summary(title=titles_encoded[n],auto_suggest=True, redirect=True).encode('utf-8')
    print(n,"text extracted")

I am looking for a solution that is more efficient/faster.


text:
Q: Need regular expr. for html element where order of attributes doesn´t matter I need a regular expression to detect a span-element where the order of id and class doesn´t matter. The name of the class is always the same, the id is always a fixed number of digits, for example:

or

My approach for a regular expression in java was:
String pattern = "";

but so i can get only one version. Can sombody help?
Thanks, hansa

A: Don't parse HTML with regular expressions.  HTML isn't regular.

A: This should do it:
String r = "<span (?=[^<>]*\\bclass=\"className\")[^<>]*\\bid=\"(\\d+)\"[^<>]*>";

The lookahead confirms that the span is of the desired class without consuming any characters.  Then the rest of the regex, starting from the same position, searches for the id attribute and captures its value.  The [^<>]* takes care of any other attributes that might be present, while ensuring that all matching occurs within the tag.  (Technically, angle brackets can appear in attribute values, but you probably don't have to worry about that.)

A: I would do a two step version, first finding the span tag with:
]*class=\"classname\"[^>]*>

And then dig out the id from the tags that match the first pattern with
id=\"(\d+)\"

As others have pointed out, it's not a good idea to parse HTML with regular expressions. But for dirty data processing, this is how i would do it.


text:
Q: how to correctly read txt with backslash i have this string in a txt file : "\x16\x07\x11\x10\x1c\x13\x0e\x07\x004"
i try to read it in python and split it.
instead of getting  this result :
['\x16', '\x07', '\x11', '\x10', '\x1c', '\x13', '\x0e', '\x07', '\x00', '4']

i get this :
['\\', 'x', '1', '6', '\\', 'x', '0', '7', '\\', 'x', '1', '1', '\\', 'x', '1', '0', '\\', 'x', '1', 'c', '\\', 'x', '1', '3', '\\', 'x', '0', 'e', '\\', 'x', '0', '7', '\\', 'x', '0', '0', '4']

how can i read this file correctly
code:
TextFile = open(FileName,"r")
ReadFile=TextFile.read()
print(list(ReadFile))

A: You can do this:
TextFile = open(FileName,"r")
ReadFile = TextFile.read()
s = ReadFile.split('\\x')
del s[0]
for i in range(len(s)):
    s[i] = '\\x' + s[i]
print(s)

A: You can do something like this, (skipping the file stuff):
a = "\x16\x07\x11\x10\x1c\x13\x0e\x07\x004"
b = []
for i in range(len(a)):
    b.append(a[i])


text:
Q: Show that if X and Y are sequences such that X and X + Y converges, then Y converges. $Let X=(x_n) -> x$
$Y=y_n$
and
$X + Y -> l$
Now
$|x_n - x| < ϵ/2$ for $n>=k1$
$x-(ϵ/2)<x_n<x+(ϵ/2)$ for $n>=k1$
$(ϵ/2)-x>-x_n>-x-(ϵ/2)$ for $n>=k1$
$-x-(ϵ</2)-x_n<(ϵ/2)-x$ for $n>=k1$ ---> eq 1
Also
$|x_ny_n - l| < ϵ/2$ for $n>=k2$
$l-(ϵ/2) < x_ny_n < l+(ϵ/2)$ for $n>=k2$ ---> eq 2
Let $k=max{k1,k2}$
From 1 and 2
$(l-x)-ϵ<y_n<(l-x)+ϵ$ for $n>=k$
$|y_n - (l-x)|<ϵ$ for $n>=k$
 Hence Y converges.
Is this argument correct?


text:
Q: iOS FIRAuth : Is there any way to get user email from user uid? I'm trying to let users authenticate using usernames. The database stores sensitive data so we're avoiding storing emails in the database (since email is identifying data).
Currently the database stores the user's custom Username with the associated FIRAuth UID.
I'm wondering if there is any way for us to perhaps get user email based on the FIRAuth UID so we can log the users in?
EDIT: this is before user has signed in, so .currentUser won't help
Thanks!

A: To get a user's profile information, use the properties of an instance of FIRUser like below:
let user = Auth.auth().currentUser
if let user = user {
  let uid = user.uid
  let email = user.email
  let photoURL = user.photoURL
  // ...
}

A: It's not possible to do that,the only way is to store the email in the database ,other than that,you can't get user email just with the just id,

A: let userEmail = Auth.auth().currentUser?.email


text:
Q: Sample 50 rows from 27,000 entries? Novice coder here!
I am trying to sample 50 rows from a data frame with about 27,000 rows. I have tried this:
sample <- df %>%
  sample_n(50)

but I get this error message:

Error: "size" must be less or equal than 1 (size of data), set "replace" = TRUE to use sampling with replacement.

It seems like the error is that the data frame is smaller than the sample size, which is obviously not the case. How can I fix this?

A: Check dim(df) to see if it's actually 27k rows. This isn't tidyverse but it will work:
index <-sample.int(nrow(df),50)
sample <- df[index, ]

A: That must be because your data is grouped. Let's take mtcars as an example -
library(dplyr)
mtcars %>% group_by(cyl) %>% sample_n(30)

Error: size must be less or equal than 11 (size of data), set replace = TRUE to use sampling with replacement.

Try ungrouping your data before using sample_n -
sample <- df %>% ungroup %>% sample_n(50)

If you have new dplyr (>= 1.0.0) you can use slice_sample instead of sample_n -
sample <- df %>% ungroup %>% slice_sample(n = 50)


text:
Q: query to aggregat data by day to generate charts - rows unkown I started building a search engine monitor. I'm pulling data from the google rest api into a mysql database with the following fields: date, search-keyword, domain, url, position.
Now I got into trouble querying and outputting the data for charting. The results go up and down, new results from google come into the list which haven't been there on the first day. However for charting I have to assign the first days at least blank values to output a chart.
What I do right now: First I select every domain showing up in the period. Lets say the for the keyword searchengine I get the domains wikipedia.org, ixquick.com, yahoo.com, searchenginewatch.com When I make another request for ever domain to query an array of rankings grouped by day. leading to the ...
Problem: Is where any query (mysql/nosql) which returns for each day an average and if where is no row a default value e.g. blank?
Result should look like:
dates={01/01/2014,02,03,04,05,06,07,08,...,31}
wikipedie={1,1,1,1,1,1,1,1,...,1}
yahoo = {"","",7,5,3,3,3,...,3}

A: You can create a date table, select the date range you'd like, and outer join your data to it, filling in 0s for values that do not exist for a given term/date.
Edit:
Some more details.
1) Create a table that has a row for every date +- 10 years (or whatever is appropriate). You can make this one column if you'd like, or many columns (date, month, year, etc.). The second approach makes this extensible if you want to summarize by various rollups in the future.
2) Outer join your table to the date table and use a NVL statement to coerce any null averages to 0.
3) Profit!

A: If your results are grouped by date, how can MySQL know there's (for example) 31 days in that month?
On the other hand, you can somehow fill the holes in PHP by loop through the array and fill a zero if the value does not exist.


text:
Q: How to use base tag conditionally? I've a angular app. Which is going to deployed in two site (same code).
I'm using the following base tag for site A
<base href="https://A.com/">

But for second site I need
<base href="https://B.com/">

As the repo is same, is there any way to achieve this?
I've tried using
<base href="/">

But this is causing issue when reloading the app in nested state
i.e. If the url is https://A.com/x/y/z
It's causing issues, and trying to get resources from /x/y/z path. But I need to get the resources always from root.
Is there any way to achieve this?
Thanks is advance..

A: Try This
<base href="{{(siteName == 'site A')?'https://A.com/':'https://B.com/'}}">


text:
Q: HealthKit Find Steps for today only I want to be able to find daily steps and put them into a variable from HealthKit. This is the code that I already have.
import UIKit
import HealthKit

let healthKitStore:HKHealthStore = HKHealthStore()

I know it's not much but I wasn't able to find on the internet how to get the steps from today only, not average or anything like that.

A: An app is not allowed to read data from HealthKit without asking for permissions. So asking for relevant permission is the first step. To understand the flow, follow this tutorial


text:
Q: JSch upload with progress monitor I try to implement a SFTP upload with a progress bar.
Unfortunately the progress bar is not updated...
Here is a part of my code:
public class MainView extends JFrame implements SftpProgressMonitor {

    private static final Logger LOG = Logger.getLogger(MainView.class);
    private String _source;
    private JProgressBar _progressBar;
    private JButton _button;

    public MainView() {
        initComponents();
    }

    void initComponents() {
        _button = new JButton("Send");
        _button.addActionListener(new ActionListener() {
            // If clicked, send event to controller...
        });
        _progressBar = new JProgressBar();
        // Do init stuff here
        // ...
    }

    @Override
    public boolean count(long byteTransfered) {
        int transfered = _progressBar.getValue();
        transfered += byteTransfered;
        _progressBar.setValue(transfered);
        return true;
    }

    @Override
    public void end() {
        LOG.info("Transfer of "+_source+" finished!");
    }

    @Override
    public void init(int op, String src, String dest, long max) {
        _progressBar.setValue(0);
        _progressBar.setMinimum(0);
        _progressBar.setMaximum((int) max);
        _source = src;
    }
}

public class Controller {

    private final MainView _view;
    private final SftpClient _ftp;
    private final Server _server;

    public Controller() {
        _server = new Server("192.168.0.1");
        _view = new MainView();
        _ftp = new SftpClient(_server);

        _view.setVisible(true);
    }

    public void send() {
        Executor executor = Executors.newSingleThreadExecutor();
        executor.execute(new Runnable() {
            public void run() {
                File testFile = new File("/PathToFile/file.txt");
                String remoteDir = "/MyRemoteDir/";
                _ftp.put(testFile, remoteDir, testFile.getName(), _view);
            }
        });
    }

    public static void main(String[] args) {
        Controller controller = new Controller();
    }
}

public class SftpClient {
    private static final Logger LOG = Logger.getLogger(SftpClient.class);

    /** Connection port number */
    public static final int PORT = 22;

    /** SECURED protocol name */
    public static final String PROTOCOL = "sftp";

    /** Connection time out in milliseconds */
    public static final int TIME_OUT = 3000;

    private Server _server;
    /** This class serves as a central configuration point, and as a factory for Session objects configured with these settings */
    private JSch _client;
    /** A session represents a connection to a SSH server */
    private Session _session;
    /** Channel connected to a SECURED server (as a subsystem of the SSH server) */
    private ChannelSftp _channelSftp;

    /**
     * Value returned by the last executed command.
     */
    private int _exitValue;

    public SftpClient(Server server) {
        _client = new JSch();
        _server = server;
    }

    protected void connect() throws AuthenticationException, Exception {
        try {
            if (_client == null) {
                _client = new JSch();
            }
            if (_session == null) {
                _session = _client.getSession(_server.getLogin(), _server.getAddress(), PORT);
                _session.setConfig("StrictHostKeyChecking", "no");
                _session.setPassword(_server.getPassword());
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Connecting to "+_server.getAddress()+" with login "+_server.getLogin()+"...");
                }
            }
            if (!_session.isConnected()) {
                _session.connect(TIME_OUT);
            }

            if(_channelSftp == null || _channelSftp.isConnected() == false) {
                Channel c = _session.openChannel(PROTOCOL);
                c.connect();
                // disconnect previous channel if it has not been killed properly
                if (_channelSftp != null && _channelSftp.isConnected()) {
                    _channelSftp.disconnect();
                }
                _channelSftp = (ChannelSftp) c;
            }

            if (LOG.isInfoEnabled()) {
                LOG.info("Connected to "+_server.getAddress()+" with login "+_server.getLogin());
            }
        } catch(JSchException e) {
            if ("Auth fail".equals(e.getMessage())) {
                throw new AuthenticationException(e);
            } else {
                throw new Exception(e);
            }
        }
    }

    protected void connect(String path) throws AuthenticationException, Exception {
        connect();
        if (_channelSftp != null && _channelSftp.isConnected()) {
            _channelSftp.cd(path);
        }
    }

    @Override
    public void disconnect() {
        if (_channelSftp != null && _channelSftp.isConnected()) {
            _channelSftp.disconnect();
            _channelSftp.exit();
        }
        if (_session != null && _session.isConnected()) {
            _session.disconnect();
            if (LOG.isInfoEnabled()) {
                LOG.info("SECURED FTP disconnected");
            }
        }
    }

    @Override
    public void put(File localFile, String destPath, SftpProgressMonitor monitor) throws Exception {
        put(localFile, destPath, localFile.getName(), monitor);
    }

    @Override
    public void put(File localFile, String destPath, String remoteFileName, SftpProgressMonitor monitor) throws Exception {
        if (LOG.isInfoEnabled()) {
            LOG.info("Send file "+localFile+" to "+_server+" in "+destPath);
        }
        if (localFile == null) {
            _exitValue = -1;
            LOG.error("The given local file is null. Aborting tranfer.");
            return;
        }
        if (!localFile.exists()) {
            _exitValue = -1;
            LOG.error("'"+localFile+"' doesn't exist. Aborting tranfer.");
            return;
        }
        if(!localFile.canRead()) {
            _exitValue = -1;
            LOG.error("Cannot read '"+localFile+"'. Aborting tranfer.");
            return;
        }

        final InputStream input = new BufferedInputStream(new FileInputStream(localFile));
        if (input == null || input.available() <= 0) {
            _exitValue = -1;
            LOG.error("Cannot read file "+localFile);
            return;
        }
        try {
            connect(destPath);
            _channelSftp.put(input, remoteFileName, monitor);
            _exitValue = _channelSftp.getExitStatus();

        } catch(SftpException e){
            throw new IOException(e);
        } finally {
            if (_channelSftp != null && _channelSftp.isConnected()) {
                _channelSftp.disconnect();
                _channelSftp.exit();
            }
            IOUtils.closeQuietly(input);
        }
    }
}

The count() method is never called. And the source and destination strings of the init contain both -. Am I doing it wrong?

A: I've changed my code and it works now. I don't use put(InputStream src, String dst, int mode) anymore but put(String src, String dst, SftpProgressMonitor monitor).
I've also implemented a DefaultBoundedRangeModel class. It modifies directly the JProgressBar and it is more interesting for me because I have several files to transfer.
public class ProgressModel extends DefaultBoundedRangeModel implements SftpProgressMonitor {

    /** Logger */
    private static Logger LOG = Logger.getLogger(ProgressModel.class);
    private String _fileBeingTransfered;

    /**
     * Constructs the model.
     */
    public ProgressModel() {
        _fileBeingTransfered = "";
    }

    @Override
    public boolean count(long count) {
        int value = (int) (getValue() + count);
        setValue(value);
        fireStateChanged();
        if(value < getMaximum()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void end() {
        LOG.info(_fileBeingTransfered+" transfert finished.");
        if(getValue() == getMaximum()) {
            LOG.info("All transfers are finished!");
        }
    }

    @Override
    public void init(int op, String src, String dest, long max) {
        LOG.info("Transfering "+src+" to "+dest+" | size: "+max);
        _fileBeingTransfered = src;
    }
}

I don't know what caused my problem. Maybe it was the put method.

A: In order to get updates you have to send reference to monitor to FTP client. And you do this:
_ftp.put(testFile, remoteDir, testFile.getName(), _view);
However what _view is? It is a private final field of class Controller that is never initialized. Therefore it is null. You implemented your callback method count() into class MainView but do not send reference to it to the FTP client. I do not know where do you create instance of Controller but you should pass reference to instance of MainView to it.


text:
Q: The exponential map at $m$ and constant velocity Let $M$ be a geodesically complete manifold and $m\in M$. The exponential map at $m$ is
$$
       \exp_m: T_mM\rightarrow M \\
        v \mapsto \gamma(1)
$$
where $\gamma$ is the geodesic $\gamma:\mathbb{R}\rightarrow M$ such that $\gamma(0)=m$ and $\dot{\gamma}(0)=v$.
Now, I read that
$$
       \int_0^1 \parallel \dot{\gamma}(t) \parallel dt =  \int_0^1 \parallel v \parallel dt = \parallel v \,\,\parallel
$$
I do not know why $\dot{\gamma}(t)=v$ for all $t$. It seems that I am missing something quite fundamental here.

A: The claim is not that $\dot{\gamma}(t) = v$ for all $t$; it's that these two vectors have the same length.
The reason for this equality is that geodesics are constant-speed curves, for otherwise they'd have acceleration in the tangential direction, which is one of the key things that the definition disallows. And since $\|\dot{\gamma}(0) \| = \| v\|$, we get that
$\| \dot{\gamma}(t) \| = \| v\|$ for all $t$.


text:
Q: How to reverse Power Apps Text Recognizer Developing a Power App that will give us the text in a picture. Getting the bounding box records, check.
Now trying to figure out how to use a dropdown to chose one of the text/bounding box records, and have the app highlight just that bounding box.
Any ideas?


text:
Q: Generate thread dump from java code I have the following method which overrides the default sorter in Jenkins:
@Override
public void sortBuildableItems(List<Queue.BuildableItem> items) {
    logBuildQueue(items, "BEFORE");
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future future =  executorService.submit(new Runnable() {
        @Override public void run() {
            items.sort(CustomSorter::compare);
        }
    });
    try {
        future.get(2, TimeUnit.SECONDS);
    }
    catch (InterruptedException e) {
        LOGGER.log(Level.SEVERE, "[INTERRUPTED EXCEPTION] Message:" + e.getMessage() + " StackTrace: " + Arrays.toString(e.getStackTrace()));
        setDefaultSorter();
        e.printStackTrace();
    }
    catch (ExecutionException e) {
        LOGGER.log(Level.SEVERE, "[EXECUTION EXCEPTION] Message:" + e.getMessage() + " StackTrace: " + Arrays.toString(e.getStackTrace()));
        setDefaultSorter();
        e.printStackTrace();
    }
    catch (TimeoutException e) {
        LOGGER.log(Level.SEVERE, "[TIMEOUT EXCEPTION] Sorting the items took more then 2 seconds, Message:" + e.getMessage() + " StackTrace: " + Arrays.toString(e.getStackTrace()));
        setDefaultSorter();
        e.printStackTrace();
    }

    logBuildQueue(items, "AFTER");
}

I'm looking to print all I can get my hands on in case an exception occurs, and I was wondering if there's any way to get a thread dump pushed to the logs, since the error message might be absent.

A:     public void  dumpThreadDump() {
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) {
        System.out.print(ti.toString());
    }
}

This seems to be a nice way of programatically obtaining a thread dump from the current application.


text:
Q: Split two numbers in two arrays I need to split 2 numbers in the form(they are from a text file):
Num1:Num2
Num3:Num4

And store num1 into array X and number 2 in array Y num 3 in array X and num4 in array Y.

A: With bash:
mapfile -t X < <(cut -d : -f 1 file) # read only first column
mapfile -t Y < <(cut -d : -f 2 file) # read only second column
declare -p X Y

Output:

declare -a X='([0]="num1" [1]="num3")'
declare -a Y='([0]="num2" [1]="num4")'

Disadvantage: The file is read twice.

A: You could perform the following steps:

*

*Create destination arrays empty

*Read file line by line, with a classic while read ... < file loop

*Split each line on :, again using read

*Append values to arrays

For example:
arr_x=()
arr_y=()
while IFS= read line || [ -n "$line" ]; do
    IFS=: read x y <<< "$line"
    arr_x+=("$x")
    arr_y+=("$y")
done < data.txt

echo "content of arr_x:"
for v in "${arr_x[@]}"; do
    echo "$v"
done

echo "content of arr_y:"
for v in "${arr_y[@]}"; do
    echo "$v"
done

A: Here is a quick bash solution:
c=0
while IFS=: read a b ;do
 x[$c]="$a"
 y[$c]="$b"
 c=$((c+1))
done < input.txt

We send the input.txt to a while loop, using Input Field Separator : and read the first number of each line as $a and second number as $b. Then we add them to the array as you specified. We use a counter $c to iterate the location in the arrays.

A: Using =~ operator to store the pair of numbers to array $BASH_REMATCH:
$ cat file
123:456
789:012
$ while read -r line
do
    [[ $line =~ ([^:]*):(.*) ]] && echo ${BASH_REMATCH[1]} ${BASH_REMATCH[2]}
    # do something else with numbers as they will be replaced on the next iteration
done < file


text:
Q: How to perform arithmetic to sort a list of lists I have a list of lists consisting of two numbers each.
[[2, 3], [7, 8], [3, 5]]

I would like to sort them based on dividing each:
eg 2 / 3 (0.666), 7 / 8 (0.875) 3 / 5 (0.6)
to output:
[[3, 5], [2, 3], [7, 8]]

I'm assuming I will be using lambda somehow, but I don't know how to write it correctly. Something like this, but this just sorts by the values:
list_of_lists.sort(key=lambda x: (x[0],x[1]))

How do I perform the arithmetic?

A: lists = [[2, 3], [7, 8], [3, 5]]
lists.sort(key=lambda x: (x[0]/x[1]))
print(lists)

A: May this one helpful for you.
a=[[2, 3], [7, 8], [3, 5]]
print (sorted([a[i][0]/a[i][1] for i in range(len(a))]))


text:
Q: How custom activity runs on journey status I am quite new for custom activity.
I am unable to understand , how custom activity runs, when we activated journey what would be the method that will execute the method.
Can we segregate the code on the basis of journey status, Actually we want to insert some data from iframe before the journey is activated and once the journey is activated , I want to fetch the data from data extension and create a JSON with journey data and send that JSON to third party server using REST API
Can anyone help me to understand the flow of custom activity.
Thanks

A: You can insert some data from the iframe before the journey is activated by saving data inputs in the config.js - inArguments. When you click "Done" in the iframe, the Postmonger event connection.on('clickedNext', save) will be fired and you can save the inputs:
customActivity.js
function save() {
    var message = $('#idMessage').val();

    payload['arguments'].execute.inArguments = [{
        "tokens": authTokens,
        "smsMessage": message,
        "phone":"{{Contact.Attribute." + '\"' + eventDefinitionKey + '\"' + ".\"Contact:MobilePhone\"}}",
        "key":"{{Contact.Key}}"
    }];

    payload['metaData'].isConfigured = true;
    connection.trigger('updateActivity', payload);
}

Once the journey is activated, the Execute function will run and there you can get your inputs from the inArguments.
server.js
app.post('/journeybuilder/execute', (req, res) => {
    verifyJwt(req.body, Pkg.options.salesforce.marketingCloud.jwtSecret, (err, decoded) => {
        //verification error -> unauthorized request
        if (err) {
            console.error(err);
            return res.status(401).end();
        }

        if (decoded && decoded.inArguments && decoded.inArguments.length > 0) {

                var phone = decoded.inArguments[0].phone;
                var message = decoded.inArguments[0].smsMessage;
                var data = {
                        auth_id: 'xxxxxxx',
                        auth_secret: 'xxxxxxxx',
                        message: message,
                        phone: phone };
                sendSms (data);

        } else {
            console.error('inArguments invalid.');
            return res.status(400).end();
        }
    });
    return res.status(200).json({success: true});
});

If you want to use data coming from your data extension you can use merge fields:

*

*Data Binding: https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/how-data-binding-works.htm

*Full End-to-end demo of creating a Journey Builder activity: https://youtu.be/BbaUkhdtqTQ

*Accompanying git repo: https://github.com/devsutd/journey-builder-activity-template


text:
Q: E(fx)clipse Hanging Ok folks, I posted a similar message the other day, but was unable to update it . A student of mine is trying to run JavaFX on her mac. We have updated JDK to JDK 11 and eclipse to 2018-09. We then install E(fx)clipse using the help, install new software. When it starts, it asks for home directory, and then hangs
The log is below
!SESSION 2018-11-30 14:41:07.845 -----------------------------------------------
eclipse.buildId=4.9.0.I20180906-0745
java.version=11.0.1
java.vendor=Oracle Corporation
BootLoader constants: OS=macosx, ARCH=x86_64, WS=cocoa, NL=en_GB
Framework arguments:  -product org.eclipse.epp.package.java.product -keyring /Users/izziharper/.eclipse_keyring
Command-line arguments:  -os macosx -ws cocoa -arch x86_64 -product org.eclipse.epp.package.java.product -keyring /Users/izziharper/.eclipse_keyring

!ENTRY org.eclipse.mylyn.bugzilla.core 4 0 2018-11-30 14:41:08.591
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Could not resolve module: org.eclipse.mylyn.bugzilla.core [278]
  Unresolved requirement: Require-Bundle: org.apache.xmlrpc
    -> Bundle-SymbolicName: org.apache.xmlrpc; bundle-version="3.0.0.v20100427-1100"
       org.apache.xmlrpc [68]
         Unresolved requirement: Import-Package: javax.xml.bind
  Unresolved requirement: Require-Bundle: org.eclipse.mylyn.commons.xmlrpc; bundle-version="[3.8.0,4.0.0)"
    -> Bundle-SymbolicName: org.eclipse.mylyn.commons.xmlrpc; bundle-version="3.24.2.v20180904-2231"; singleton:="true"
       org.eclipse.mylyn.commons.xmlrpc [295]
         Unresolved requirement: Require-Bundle: org.apache.xmlrpc; bundle-version="[3.0.0,4.0.0)"
           -> Bundle-SymbolicName: org.apache.xmlrpc; bundle-version="3.0.0.v20100427-1100"


text:
Q: Fill Consecutive NaNs in Pandas Series I want to fill missing values in my pandas series, if there are less than 3 consecutive NANs.
Original series with missing values:
s=pd.Series(pd.np.random.randn(20))
s[[1,3,5,7,12,13,14,15, 18]]=pd.np.nan

Gives:
0     0.444025
1          NaN
2     0.631753
3          NaN
4    -0.577121
5          NaN
6     1.299953
7          NaN
8    -0.252173
9     0.287641
10    0.941953
11   -1.624728
12         NaN
13         NaN
14         NaN
15         NaN
16    0.998952
17    0.195698
18         NaN
19   -0.788995

BUT, using pandas.fillna() with a limit only fills the # of values specified (not number of CONSECUTIVE NANs, as expected):
s.fillna(value=0, limit=3) #Fails to fill values at position 7 and forward

Desired output would fill NANs with 0 at positions 1,3,5,7, and 18. It would leave series of 4 NaNs in place in position 12-15.
The documentation and other posts on SO have not resolved this issue (e.g. here). Documentation seems to imply that this limit will work on consecutive NANs, not the overall # in entire dataset that will be filled. Thanks!

A: We start with finding where the nan values are via pd.Series.notna.
As we use cumsum, whenever we encounter a non-null value, we increment the cumulative sum this generating convenient groups for contiguous nan values.
However, for all but the first group (and maybe the first group) we begin with a non-null value.  So, I take the negation of mask and sum the total number of null values within each group.
Now I fillna and use pd.DataFrame.where to mask the spots where the sum of nan values was too much.
mask = s.notna()
c_na = (~mask).groupby(mask.cumsum()).transform('sum')
filled = s.fillna(0).where(c_na.le(3))
s.fillna(filled)

0     1.418895
1     0.000000
2    -0.553732
3     0.000000
4    -0.101532
5     0.000000
6    -1.334803
7     0.000000
8     1.159115
9     0.309093
10   -0.047970
11    0.051567
12         NaN
13         NaN
14         NaN
15         NaN
16    0.623673
17   -0.786857
18    0.000000
19    0.310688
dtype: float64

Here is a fancy Numpy/Pandas way using np.bincount and pd.factorize
v = s.values
m = np.isnan(v)
f, u = pd.factorize((~m).cumsum())
filled = np.where(
    ~m, v,
    np.where(np.bincount(f, weights=mask)[f] <= 3, 0, np.nan)
)

pd.Series(filled, s.index)

0     1.418895
1     0.000000
2    -0.553732
3     0.000000
4    -0.101532
5     0.000000
6    -1.334803
7     0.000000
8     1.159115
9     0.309093
10   -0.047970
11    0.051567
12         NaN
13         NaN
14         NaN
15         NaN
16    0.623673
17   -0.786857
18    0.000000
19    0.310688
dtype: float64

A: First, build a na cum_count column. Consecutive nas will have same cum_count.
df = s.to_frame('value').assign(na_ct=s.notna().cumsum())

Then we can group by the na cum_count, check the number of rows in each group and decide weather to fill the nas or not.
df.groupby(df.na_ct).apply(lambda x: x if len(x)>4 else x.fillna(0)).value
Out[76]:
0     0.195634
1     0.000000
2    -0.818349
3     0.000000
4    -2.347686
5     0.000000
6    -0.464040
7     0.000000
8     0.179321
9     0.356661
10    0.471832
11   -1.217082
12         NaN
13         NaN
14         NaN
15         NaN
16   -0.112744
17   -2.630191
18    0.000000
19   -0.313592
Name: value, dtype: float64

A: Maybe try this ?
t=s[s.isnull()];
v=pd.Series(t.index,index=t.index).diff().ne(1).cumsum();
z=v[v.isin(v.value_counts()[v.value_counts().gt(3)].index.values)];
s.fillna(0).mask(s.index.isin(z.index))
Out[348]:
0    -0.781728
1     0.000000
2    -1.114552
3     0.000000
4     1.242452
5     0.000000
6     0.599486
7     0.000000
8     0.757384
9    -1.559661
10    0.527451
11   -0.426890
12         NaN
13         NaN
14         NaN
15         NaN
16   -1.264962
17    0.703790
18    0.000000
19    0.953616
dtype: float64

A: You can try it with rolling operator in the following fashion:
1) Create a function that returns 0 only if there are less than X values in a window
fillnaiflessthan(series, count):
    if series.isnull().sum() < count and series.center == pd.NaN:
         return 0

2) Then use it inside rolling
s.rolling(window=5, center=True, min_periods=0).apply(lambda x: fillnaiflessthan(x, 4))


text:
Q: How to add tooltip / hoverbox to jupyter lab extension HoverExample
How to add hover text like that of the above image to a custom extension in jupyterlab. I'm making an extension in jupyter lab using react, but I want to add a description of the extension in a hoverbox. However I cant figure it out.

A: To add a hover box in the extension, you have to pass value to [widgetInstance].title.caption
For example:
const extension: JupyterFrontEndPlugin<void> = {
  id: 'some-id',
  autoStart: true || false,
  activate: async(app: JupyterFrontEnd, palette: ICommandPalette) => {
     const { commands } = app;
      let widget1: widget= new widget(); // create the widget
      widget1.id = 'widget1-id';
      widget1.title.label = 'widget Label';
      widget1.title.caption="widget hovering text description"; // this will show the text when you hover over an extension
      app.shell.add(widget1, 'right', { rank: 1 });
      ...
      ...
      ... rest of your code ...

}


text:
Q: Filterable widget issue with enter key https://api.jquerymobile.com/filterable/
there seems to be a problem with the implementation of this widget in that, if you are typing into the text field, then press enter nothing happens, but then your next key press has no effect. eg:

*

*focus on text field

*press a ('a' appears in field)

*press enter (no change)

*press a (no change)

*press a ('aa' appears in field)

I have logged an issue, however doubt it will get attention in the short term. Anyone suggest a work around?

A: At least we can tell JQM to restore the _preventKeyPress flag by simulating another keypress:
$(document).on("keyup", ".ui-input-search>input", function(e) {
  var key = e.keyCode ? e.keyCode : e.which ? e.which : 0;
  if(key == 13) {
    $(this).trigger(jQuery.Event("keypress", {
      srcElement: this,
      bubbles: true,
      cancelable: true,
      which: 0,
      keyCode: 0,
      charCode: 0,
      target: this,
      currentTarget: this,
      eventPhase: 2, // AT TARGET
      type: "keypress",
      view: e.view,
      returnValue: true
    }));
  }
});

EDIT:
Just for the sake of completeness, here is the solution from Omar:
https://github.com/jquery/jquery-mobile/issues/8571#issuecomment-300430818


text:
Q: Java reading information from a website using Jsoup I've gone through multiple posts about parsing and such. Most of the responses that I saw were recommending the person to use a Library or something else. My problem right now is creating an algorithm that will fetch the exact information I want. My purpose for this is to fetch 2 statuses from the Weather website for school closings. I started using Jsoup as someone recommended but I need help with it.
Webpage: Click here
Image: Click here
Example of webpage source: click here
I could probably figure out how to get a certain line of text within the webpage since I already know the name of the school im looking for, but 2 lines down is the status which is what I need. would be easy if each school had a certain status but they are all either Closed or Two-hour Delay so I can't just make a search for that. I want some ideas or answers on how i can apporach this. I am going to do this 2 times because I am wanting to look up 2 schools. I already have the names which I can use to look them up I just need the status.
Here is an example of what I want to do. (sudo code)
Document doc = connect(to url);
Element schoolName1 = doc.lookForText(htmlLineHere/schoolname);

String status1 = schoolName.getNext().text();//suppose this gets the line right after which should be my status and then cleans off the Html.

This is what I have right now
public static SchoolClosing lookupDebug() throws IOException {
        final ArrayList<String> Status = new ArrayList<String>();

        try {
            //connects to my wanted website
            Document doc = Jsoup.connect("http://www.10tv.com/content/sections/weather/closings.html").get();
            //selects/fetches the line of code I want
            Element schoolName = doc.html("Athens City Schools	");
            //an array of Strings where I am going to add the text I need when I get it
            final ArrayList<String> temp = new ArrayList<String>();
            //checking if its fetching the text
            System.out.println(schoolName.text());
            //add the text to the array
            temp.add(schoolName.text());
            for (int i = 0; i <= 1; i++) {
                final String[] tempStatus = temp.get(i).split(" ");
                Status.add(tempStatus[0]);
            }
        } catch (final IOException e) {
            throw new IOException("There was a problem loading School Closing Status");
        }
        return new SchoolClosing(Status);
    }

A: Document doc = Jsoup.connect(
        "http://www.10tv.com/content/sections/weather/closings.html")
        .get();
for (Element tr : doc.select("#closings tr")) {
    Element tds = tr.select("td").first();
    if (tds != null) {
        String county = tr.select("td:eq(0)").text();
        String schoolName = tr.select("td:eq(1)").text();
        String status = tr.select("td:eq(2)").text();
        System.out.println(String.format(
                "county: %s, schoolName: %s, status: %s", county,
                schoolName, status));
    }
}

output:
county: Athens, schoolName: Beacon School, status: Two-hour Delay
county: Franklin, schoolName: City of Grandview Heights, status: Snow Emergency through 8pm Thursday
county: Franklin, schoolName: Electrical Trades Center, status: All Evening Activities Cancelled
county: Franklin, schoolName: Hilock Fellowship Church, status: PM Services Cancelled
county: Franklin, schoolName: International Christian Center, status: All Evening Activities Cancelled
county: Franklin, schoolName: Maranatha Baptist Church, status: PM Services Cancelled
county: Franklin, schoolName: Masters Commission New Covenant Church, status: Bible Study Cancelled
county: Franklin, schoolName: New Life Christian Fellowship, status: All Activities Cancelled
county: Franklin, schoolName: The Epilepsy Foundation of Central Ohio, status: All Evening Activities Cancelled
county: Franklin, schoolName: Washington Ave United Methodist Church, status: All Evening Activities Cancelled

or in a loop:
for (Element tr : doc.select("#closings tr")) {
    System.out.println("----------------------");
    for (Element td : tr.select("td")) {
        System.out.println(td.text());
    }
}

that gives:
----------------------
Athens
Beacon School
Two-hour Delay
----------------------
Franklin
City of Grandview Heights
Snow Emergency through 8pm Thursday
----------------------
Franklin
Electrical Trades Center
All Evening Activities Cancelled
...


text:
Q: Mouseover event not firing for Polygon On clicking a button, an AJAX request is made to the serverside which returns several polygon paths. These polygons are then drawn onto the map.
Problem: I added event handler for mouseover and mouseout events. However, they do not seem to be firing. The handler contains console.log which does not execute on mouseover. What may have caused this?
JS Code
$("#button").click(function() {
    $.getJSON(base_url + 'main/get',
                function(json) {

                    for( var i = 0; i < json.length; i++) {

                        decoded_path = google.maps.geometry.encoding.decodePath(json[i].encoded_path);

                        var polyOptions = {
                                    strokeColor: "#4794b8",
                                    strokeOpacity: 0.7,
                                    strokeWeight: 1.5,
                                    fillColor: "#000",
                                    fillOpacity: 0.1,
                                    path: decoded_path,
                                    clickable: false,
                                    map: map
                            }
                        var polygon = new google.maps.Polygon(polyOptions);
                        array_polyline.push(polygon);

                        // Add Mouseover/Mouseout Listeners
                        google.maps.event.addListener(polygon, "mouseover", function(){ console.log('Mouseover'); this.setOptions({fillOpacity: 0}); });
                        google.maps.event.addListener(polygon, "mouseout", function(){ this.setOptions({fillOpacity: 0.1}); });

                    }

        });
});

A: You need to either remove clickable: false or make it clickable: true (the default)
You dont have to bind to all events (ie click) but clickable: false disables all mouse events ...


text:
Q: Porting my old plain JavaScript projects to CoffeeScript and BackboneJS iam in a mood right now and thought it would be great to port my existing plain JavaScript projects to CoffeeScript and BackboneJS to get a cleaner structure for future development. I also like the CoffeeScript syntax and its ability to compile Lint-proved JavaScript.
I found some neat Information about how both of them can work together. -> http://spin.atomicobject.com/2011/05/06/using-backbone-js-with-coffeescript/
But my problem is: Iam not quite sure where to start. I usually structured my JavaScript in a pseudo class-based fashion. Like this:
var node = new function() {
    this.add = this.add = function(target) {};
    this.set = function(target, options) {};
};

Iam not very familiar with BackboneJS and CoffeeScript in practice.
Is it better to start off with a BackboneJS structure and refactor my scripts into that. Or should i rewrite my code in CoffeeScript and move it to BackboneJS afterwards?

A: Depending on the size of the codebase, I would first translate all the JS code in question into CoffeeScript (js2coffee & manual clean-up) and make sure everything is still working. After that, start refactoring. It will be easier to fix problems you meet along the way while doing only one type of changes at a time.


text:
Q: Android new Locale("en_US") and Locale.US are different? I just ran into this problem when testing the locale set in the preferences against constant values:
(new Locale("en_US")).equals(Locale.US) == false

When looking at the details it turns out that new Locale("en_us") returns an object with a language code "en_us" and a country code that is a zero length string whereas Locale.US returns an object with language code "en" and country code "US". Locale("en","US") returns the same result as Locale.US so its easy to avoid this problem, but is this the expected behavior of the Locale constructors?

A: Locale constructors are working as expected. You can compare the locale objects like this:

(new Locale("en_US")).toString().equalsIgnoreCase((Locale.US).toString())

It will give you the expected value


text:
Q: WCF "A call to SSPI failed, see inner exception" We have an existing system that uses WCF and was working fine until yesterday, when suddenly it stopped working on both my machine and another developer machine.
I've setup system diagnostics in the client config to write a trace file and we see the following exception:
Throwing an exception

**Basic Information**

Activity Name           Receive bytes on connection 'net.tcp://localhost:8004/'.
Time                    2016-01-06 13:38:45.3958
Level                   Error
Source                  System.ServiceModel
Process                 NServiceBus.Host
Thread                  219
Computer                RL-ZORO-LPT
Trace Identifier/Code   http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx

**Exception**

System.ServiceModel.Security.SecurityNegotiationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    System.Security.Authentication.AuthenticationException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
         System.ComponentModel.Win32Exception, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Exception Type: System.ServiceModel.Security.SecurityNegotiationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Message: A call to SSPI failed, see inner exception.

Stack Trace:  System.ServiceModel.Channels.StreamSecurityUpgradeAcceptorAsyncResult.CompleteAuthenticateAsServer(IAsyncResult result)
              System.ServiceModel.Channels.StreamSecurityUpgradeAcceptorAsyncResult.OnAuthenticateAsServer(IAsyncResult result)
              System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
              System.Net.LazyAsyncResult.Complete(IntPtr userToken)
              System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
              System.Net.Security.SslState.FinishHandshake(Exception e, AsyncProtocolRequest asyncRequest)
              System.Net.Security.SslState.ReadFrameCallback(AsyncProtocolRequest asyncRequest)
              System.Net.AsyncProtocolRequest.CompleteRequest(Int32 result)
              System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
              System.Net.FixedSizeReader.ReadCallback(IAsyncResult transportResult)
              System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
              System.ServiceModel.Channels.ConnectionStream.IOAsyncResult.OnAsyncIOComplete(Object state)
              System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
              System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs e)
              System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(SocketError socketError, Int32 bytesTransferred, SocketFlags flags)
              System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
              System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

Our server configuration looks like this:
<system.serviceModel>
    <services>
      <service name="ServerImpl.RACServiceImpl.RACService" behaviorConfiguration="BILLService.ServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="net.Tcp://localhost:8004" />
            <add baseAddress="http://localhost:8006" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <endpoint address="BILLService" binding="netTcpBinding" bindingConfiguration="netTcpBindingConf" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService">
          <identity>
            <dns value="RACServer" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <client>
      <endpoint address="net.Tcp://localhost:8001/RMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBindingConf" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
    </client>
    <behaviors>
      <serviceBehaviors>
        <behavior name="BILLService.ServiceBehavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="false" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceCredentials>
            <serviceCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <clientCertificate>
              <certificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </clientCertificate>
          </serviceCredentials>
          <serviceThrottling maxConcurrentCalls="40" maxConcurrentInstances="40" maxConcurrentSessions="40" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ClientBehavior">
          <clientCredentials>
            <clientCertificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <serviceCertificate>
              <defaultCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <netTcpBinding>
        <binding name="netTcpBindingConf" closeTimeout="00:11:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxConnections="100" openTimeout="00:20:00">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:15:00" />
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="Certificate" algorithmSuite="Default" />
            <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
</system.serviceModel>

This is our client configuration:
<system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="netTcpBinding_RACService" closeTimeout="00:10:00" openTimeout="00:40:00" receiveTimeout="00:32:00" sendTimeout="00:10:00" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" />
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="Certificate" algorithmSuite="Default" />
            <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
          </security>
        </binding>
      </netTcpBinding>
    <wsHttpBinding>
        <binding name="WSHttpBinding_IThirdPartyRACService" closeTimeout="00:59:00" openTimeout="00:59:00" receiveTimeout="00:59:00" sendTimeout="00:59:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
          <security mode="None">
            <message clientCredentialType="None" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true"></message>
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="net.Tcp://localhost:8004/AMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBinding_RACService" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
      <endpoint address="net.Tcp://localhost:8004/AMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBinding_RACService" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService1">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
    <endpoint address="https://localhost/ThirdPartyWebService/ThirdPartyRACService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IThirdPartyRACService" contract="IThirdPartyRACService" name="WSHttpBinding_IThirdPartyRACService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ClientBehavior">
          <clientCredentials>
            <clientCertificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <serviceCertificate>
              <defaultCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </serviceCertificate>
          </clientCredentials>
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
</system.serviceModel>

If we set the security mode to "None" on both the client and the server then it works.
What can be wrong here?

A: It turns out that what was causing the problem is a windows update that happened that same day (strange coincidence). The update is kb3102467 (aka .NET Framework 4.6.1) - which will eventually find itself on the machine.
As it turns out, the SSL certificate we are using uses RSA/SHA512, which from what I've read caused high CPU usage and was therefor disabled (there was a hotfix for this issue and registry information that I saw was added, but after kb3102467 it still happened).
As a workaround (until we issue new SSL certificates) I have disabled TLS 1.2 in the following manner:

*

*Start regedit and browse to the following location: HKLM\System\CurrentControlSet\Control\SecurityProviders\SChannel\Protocols

*Create the following Key under Protocol: TLS 1.2

*Create the following two Keys under TLS 1.2: Client and Server

*Create the following DWORDs under both the Client and Server Key: DisabledByDefault and Enabled

*Under both Client and Server set the following: DisabledByDefault=1 and Enabled =0

*Reboot the server.

That solved the problem without the need to uninstall kb3102467

A: I got an error while testing this on localhost on windows 10 and thought to share with you all.
In App.Config on the client side i removed/commented below line :
  <!--<identity>
                <userPrincipalName value="AD\7329688" />
            </identity>-->

Now its working


text:
Q: The file "Resource id #11" does not exist I'm trying to create a class that converts an array into plaintext and file. Plaintext works fine however when I try to save it as a tmpfile and share it I'm getting errors.
My controller looks like:
public method index() {
    $props = ['foo'=>'bar']; //array of props;
    return response()->download(MyClass::create($props);
    // I've also tried using return response()->file(MyClass::create($props);
}

And my class looks like:
class MyClass
{
    // transform array to plain text and save
    public static function create($props)
    {

        // I've tried various read/write permissions here with no change.
        $file = fopen(tempnam(sys_get_temp_dir(), 'prefix'), 'w');
        fwrite($file,  implode(PHP_EOL, $props));

            return $file;
    }

    // I've also tried File::put('filename', implode(PHP_EOL, $props)) with the same results.
}

And I'm getting a file not found exception:

The file "Resource id #11" does not exist.

I've tried tmpfile, tempname and others and get the same exception. I've tried passing MyClass::create($props)['uri'] and I got

The file "" does not exist

Is this an error due to my env (valet) or am I doing this wrong?

A: Your code is mixing up usage of filenames and file handles:

*

*tempnam() returns a string: the path to a newly created temporary file

*fopen() accesses a file at a given path, and returns a "resource" - a special type in PHP used to refer to system resources; in this case, the resource is more specifically a "file handle"

*if you use a resource where a string was expected, PHP will just give you a label describing the resource, such as "Resource id #11"; as far as I know, there is no way to get back the filename of an open file handle

In your create definition, $file is the result of fopen(), so is a "resource" value, the open file handle. Since you return $file, the result of MyClass::create($props) is also the file handle.
The Laravel response()->download(...) method is expecting a string, the filename to access; when given a resource, it silently converts it to string, resulting in the error seen.
To get the filename, you need to make two changes to your create function:

*

*Put the result of tempnam(sys_get_temp_dir(), 'prefix') in a variable, e.g. $filename, before calling $file = fopen($filename, 'w');

*Return $filename instead of $file
You should also add a call to fclose($file) before returning, to cleanly close the file after writing your data to it.


text:
Q: Filter logic problems jQuery I have divs that are being dynamically created that contain a variety of article information, most importantly being a unique list of tags for each div.

Blog Post

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

            Last Updated: 01/01/3001 00:00:00
                Author: Kayra

            Project: Kayra CMS:
                Umbraco

            Tags:
Web Forms                     |
Blog

I also have a complete list of tags that are dynamically created to be used as buttons to filter through the divs. I would like them to toggle the divs on and off; so for example if a user clicked the Facebook button only Facebook divs would show, then if the user clicked on Facebook again it would display all the divs. I would also like the buttons to work cumulatively, so if a user clicked Facebook and MVC it would only show Facebook and MVC posts.

        <input type="submit" value="Facebook" class="button" />

        <input type="submit" value="MVC" class="button" />

        <input type="submit" value="Web Forms" class="button" />

        <input type="submit" value="Blog" class="button" />

At the moment my jQuery code is producing some odd behavior. Clicking on one button causes the filter to work fine, but you cannot click it off and display all of the posts as before. Clicking on multiple buttons also works; sometimes clicking a button off will work, but this is not consistent, sometimes it will need to be clicked multiple times before it works.
I feel that there is something wrong with the logic of my code but cannot find any online resources that could help me. Sorry if my question is ambiguous but it's because I'm not exactly sure where the problem is as I have only just started to use jQuery.
$(document).ready(function () {

var tags = new Array();

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function (from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

$("#tagbar .button").click(function () {
    var clickedTag = $(this).val(); //Gets the name of the button clicked

    if (tags.indexOf(clickedTag) !== -1) {
        tags.remove(tags.indexOf(clickedTag));
        console.log("unclick");
    }
    else {
        tags.push(clickedTag);
        console.log("click");
    }
    $(".resultblock").each(function () {
        var theBlock = $(this);
        i = 0;
        $(tags).each(function () {

            var targetTags = theBlock.find(".tag a").text();

            if (!theBlock.hasClass("show") && targetTags.indexOf(tags[i]) !== -1) {
                $(theBlock).show();
                $(theBlock).addClass("show");
            }
            else if (!theBlock.hasClass("show")) {
                $(theBlock).hide();
            };
            console.log(tags[i] + " is comparing to " + targetTags + " and resulting in " + (targetTags.indexOf(tags[i]) !== -1));
            i++;
        });
        if ($(theBlock).hasClass("show")) {
            $(theBlock).removeClass("show");
        }
    });
});
});

A: Not sure if this is the issue, but your i isnt declared with var meaning its global so that could be producing some wierdness. Also you dont need to define i yourself you can get it from .each:
$(".resultblock").each(function (i) {
    // now you can use i - this would replace your i=0; setup.
    // your logic as before
});

A: Your problem is due to the fact that when tags is empty the code inside $(tags).each(...) is not executed. You need to add additional code to clear the filter.

A:

    <input type="button" value="Facebook" class="button "  id="Facebook"/>
    <input type="button" value="Google" class="button "  id="Google"/>
    <input type="button" value="youtube" class="button"  id="youtube"/>
    <input type="button" value="Jquery" class="button "  id="Jquery"/>

     hi i am Facebook

     hi i am Google

     hi i am youtube

     hi i am Jquery


text:
Q: How to handle HTTP basic Authentication on selenium using C# I have a problem on my automation testing on selenium using C#. My application use the IP address as a base URL and use HTTP authentication alert message as a login. Then my features i test on my application is the LAN features i need to change the IP address so every time i change the IP address it ask me again the authentication for that application. My Code i use is like this:
On the first run of my application i call this code and it works, it inputs the user name and password on the HTTP Auth textbox.
 SendKeys.SendWait("user");
 SendKeys.SendWait("{TAB}");
 SendKeys.SendWait("pass");
 SendKeys.SendWait("{Enter}");

Then after i call the method for changing the IP, then call this code again.
 SendKeys.SendWait("user");
 SendKeys.SendWait("{TAB}");
 SendKeys.SendWait("pass");
 SendKeys.SendWait("{Enter}");

It's not work anymore, it show me the pop up but not input the user and password. How can i still used that code after i change my IP?

A: Insert a delay in the beginning of the method.
using System.Threading.Tasks
...
Task.Delay(5000).Wait();


text:
Q: FreeTDS - Unable to connect: Adaptive Server is unavailable or does not exist CENTOS 6.5 x86_64
WHM 11.42.1
unixODBC 2.2.14
freetds v0.91
I'm trying to connect to remote MSSQL server without success - also tried connecting with different tds versions (4.2, 7.0, 7.1, 8.0) but all give the same result.
Using the same servername, port, username and password, I'm able to connect via my desktop using Win7 and SQL Server Management Studio.
Telnet also fails.
Details follow. Please let me know if you need any more. All help/advice appreciated.
========
tsql -C
Compile-time settings (established with the "configure" script)
                            Version: freetds v0.91
             freetds.conf directory: /etc
     MS db-lib source compatibility: yes
        Sybase binary compatibility: yes
                      Thread safety: yes
                      iconv library: yes
                        TDS version: 4.2
                              iODBC: no
                           unixodbc: yes
              SSPI "trusted" logins: no
                           Kerberos: yes

========
tsql -H testDSN -pXXXX -U 'testuser' -P 'testpass'
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF8"
20Error 20009 (severity 9):
        Unable to connect: Adaptive Server is unavailable or does not exist
        OS error 110, "Connection timed out"
There was a problem connecting to the server

=======
isql -v testDSN 'testuser' 'testpass'
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[08S01][unixODBC][FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist
[ISQL]ERROR: Could not SQLConnect

========
osql -S testDSN -U 'testuser' -P 'testpass'
...
Configuration looks OK.  Connection details:

                   DSN: testDSN
              odbc.ini: /etc/odbc.ini
                Driver: /usr/lib64/libtdsodbc.so
       Server hostname: winsrv106.pleskdns.co.uk
               Address: x.x.x.x

Attempting connection as testuser ...
+ isql testDSN testuser 'testpass' -v
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[08S01][unixODBC][FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist
[ISQL]ERROR: Could not SQLConnect
net.c:205:FAILED Connecting to x.x.x.x port XXXX (TDS version 7.1)

========
more freetds.log
log.c:196:Starting log file for FreeTDS 0.91
        on 2014-04-10 15:33:03 with debug flags 0x4fff.
iconv.c:330:tds_iconv_open(0x7233e0, UTF8)
iconv.c:187:local name for ISO-8859-1 is ISO-8859-1
iconv.c:187:local name for UTF-8 is UTF-8
iconv.c:187:local name for UCS-2LE is UCS-2LE
iconv.c:187:local name for UCS-2BE is UCS-2BE
iconv.c:349:setting up conversions for client charset "UTF8"
iconv.c:351:preparing iconv for "UTF8" <-> "UCS-2LE" conversion
iconv.c:391:preparing iconv for "ISO-8859-1" <-> "UCS-2LE" conversion
iconv.c:394:tds_iconv_open: done
net.c:205:Connecting to x.x.x.x port XXXX (TDS version 7.1)
net.c:270:tds_open_socket: connect(2) returned "Operation now in progress"
net.c:306:getsockopt(2) reported: Connection timed out
net.c:316:tds_open_socket() failed
util.c:331:tdserror(0x723140, 0x7233e0, 20009, 110)
util.c:361:tdserror: client library returned TDS_INT_CANCEL(2)
util.c:384:tdserror: returning TDS_INT_CANCEL(2)
mem.c:615:tds_free_all_results()

========
telnet x.x.x.x
Trying x.x.x.x...
telnet: connect to address x.x.x.x:
Connection timed out

A: I had the same problem and solved it by using a custom port:
port = XXXXX
in freetds.conf
This port should be configured in SQL Server Configuration Mgnt
SQL Server Network Configuration -> TCP/IP (enabled) -> IP Addresses -> IPAll -> TCP Dynamic Ports
https://msdn.microsoft.com/en-us/library/ms177440.aspx

A: I run MS Windows in VirtualBox.
So for me to access MS SQLServer from my mac host I must:

*

*Add Port Forwarding entry in VirtualBox > Devices > Network > Network
Settings > Advanced

*Open Port 1444 in MS Control Panel > Windows Firewall > Advanced
Settings > Inbound Rules

*Start SQL Server Browser in SQL Server Configuration Manager > SQL
Server Services

*Enable TCP in SQL Server Configuration Manager > Protocols

*Set TCP Port to 1444 for TCPAll in SQL Server Configuration Manager > Protocols > TCP/IP > Properties...

Note that MS SQL Server is configured to listen on port 1444.

A: I saw this error when using Pymssql for the first time. I had to turn on TCP/IP as the one of the network protocols for my local install of SQL Server.

A: Similar resolution for me on a Cygwin 64 install interfacing FreeTDS to a SQL Server 2008 database on a local machine.  Had to enable the TCP/IP protocol for the MSSQLServer Service and restart the service to resolve.
freetds.log trace activation led me to the solution (log sample follows):
11:16:13.960012 10688 (log.c:167):Starting log file for FreeTDS 0.95.69
    on 2015-11-26 11:16:13 with debug flags 0xffff.

11:16:13.960012 10688 (iconv.c:328):tds_iconv_open(0x60004b500, UTF-8)

11:16:13.960012 10688 (iconv.c:187):local name for ISO-8859-1 is ISO-8859-1

11:16:13.960012 10688 (iconv.c:187):local name for UTF-8 is UTF-8

11:16:13.960012 10688 (iconv.c:187):local name for UCS-2LE is UCS-2LE

11:16:13.960012 10688 (iconv.c:187):local name for UCS-2BE is UCS-2BE

11:16:13.960012 10688 (iconv.c:346):setting up conversions for client charset "UTF-8"

11:16:13.960012 10688 (iconv.c:348):preparing iconv for "UTF-8" <-> "UCS-2LE" conversion

11:16:13.960012 10688 (iconv.c:395):preparing iconv for "ISO-8859-1" <-> "UCS-2LE" conversion

11:16:13.960012 10688 (iconv.c:400):tds_iconv_open: done

11:16:13.960012 10688 (net.c:202):Connecting to ?.?.?.? port 1433 (TDS version 7.3)

11:16:13.963012 10688 (net.c:274):tds_open_socket: connect(2) returned "Operation now in progress"

11:16:14.963069 10688 (net.c:309):getsockopt(2) reported: Connection refused

11:16:14.963069 10688 (net.c:319):tds_open_socket() failed

11:16:14.963069 10688 (util.c:322):tdserror(0x600049ad0, 0x60004b500, 20009, 111)

11:16:14.963069 10688 (odbc.c:2343):msgno 20009 20003

11:16:14.963069 10688 (util.c:352):tdserror: client library returned TDS_INT_CANCEL(2)

11:16:14.963069 10688 (util.c:375):tdserror: returning TDS_INT_CANCEL(2)

11:16:14.963069 10688 (mem.c:648):tds_free_all_results()

11:16:14.964069 10688 (error.c:414):odbc_errs_add: "Unable to connect to data source"

11:16:14.964069 10688 (error_export.h:23):SQLError(0x0, 0x600049b70, 0x0, 0x22ba50, 0x22ba4c, 0x22c540, 513, 0x22ba46)

11:16:14.964069 10688 (error.c:565):SQLGetDiagRec: "[FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist"

11:16:14.964069 10688 (error_export.h:23):SQLError(0x0, 0x600049b70, 0x0, 0x22ba50, 0x22ba4c, 0x22c540, 513, 0x22ba46)

11:16:14.964069 10688 (error.c:565):SQLGetDiagRec: "[FreeTDS][SQL Server]Unable to connect to data source"


text:
Q: Why did Tim not recognize this voice? In Pokémon: Detective Pikachu our protagonist Tim meets up with a Pikachu that he can understand and can understand him.
By the end of the film we find out that...

The Pikachu actually contains the mind of Tim's father (via Mewtwo magic).

So why did Tim not recognize the voice that was speaking to him?
I understand that...

Tim had not seen his father in many (possibly 10+) years

But that doesn't really justify it for me.
Was Tim actually hearing a different voice than the audience or have the filmmakers commented on the matter?

A: Although the movie's director seems to be under the impression that Pikachu's voice is different from Harry's voice, the novelisation (based on the script) indicates that Pikachu and Harry speak with the same exact voice. This at least confirms that the voice that Tim wasn't recognising was his father's own voice.
For the record, the voice reminds him of a TV detective, suggesting that he's been sufficiently estranged from his father to simply not remember what his voice sounds like.

"I know you can't understand me," the Pikachu said slowly in a
  surprisingly deep voice, kind of like the detective from the movie
  that had been playing. "But put down the stapler, or I will
  electrocute you."
  "Did you just talk?!" Tim exclaimed.
  He was so
  shocked, he dropped the stapler.
Detective Pikachu couldn't believe it, either. "Whoa! Did you just
  understand me? Wait—wait, wait, wait, wait. That is heavy eye contact
  right there. You heard me." "No, no, no. No, no, no. Stop, stop, stop,
  stop!" Tim shook his head, refusing to believe the impossible—that he
  could actually understand a Pokemon. "Yes, you did! This is amazing,"
  yelled Pikachu, excitedly. "You can understand me, I've been so
  lonely!"

A: Yep, it's a matter of Tim and his father being estranged. Director Rob Letterman talked about it in an interview given to ETonline:

ET: And you go through Tim's trauma of his father leaving and how young he was because, otherwise, you would think he would recognize his father's voice.
Rob Letterman: We disguise it. We talked about it endlessly, about, "Why doesn't he recognize his dad's voice?" There were debates. Justice and I were talking about it forever. And Ryan, like, it was a real discussion point. [Laughs] Where I ended up in my mind was it's not the voice that he's hearing, it's the connection to his father. The reason he doesn't recognize the voice, it's not the literal voice. It's that Tim is estranged from his dad and through this experience, he's getting closer and closer. That's why this voice in his head is purely an emotional connection to Pikachu. That's sort of my take on it.
'Detective Pikachu': The Director Answers All of Our Question About That Big Twist, John Boone for ET, May 13, 2019


text:
Q: Use jquery datepicker as a static calendar for informational purpose only I want to use the jQuery datepicker for information only.  For this reason I want to disable the "hover" effect and the color change when I click on a specific date.
I've try some combination but without any success.
How can I do this ?

A: You can just use CSS to modify the styles.
jsFiddle example
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-state-hover,
.ui-widget-content .ui-state-hover,
.ui-state-focus,
.ui-widget-content .ui-state-focus {
    border: 1px solid #cccccc;
    background: #f6f6f6 url(images/ui-bg_glass_100_f6f6f6_1x400.png) 50% 50% repeat-x;
    font-weight: bold;
    color: #1c94c4;
    outline: none;
    cursor:default;
}


text:
Q: Django Rest framework how to apply restriction on public api for unauthenticated users? I have an contact forms api for unauthenticated user. So anyone can visit my website and submit forms. I integrated my api in reactjs. But anyone can view the json data if he directly visit the api url. Anyone can also submit post request using POSTMAN using the api url. How to restrict anyone to view the api page and also prevent unauthorized post request.
here is my code:
settings.py:
REST_FRAMEWORK = {
    # Only enable JSON renderer by default.
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',

    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '10/minute',

    }
}

views.py
api_view(['POST', 'GET'])
def farhyn_api(request):
    if request.method == 'POST':
        data = request.data
        serializer = ContactSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            print(serializer.data)
            return Response({
                'status': True,
                'message': 'sucess'
            })

        return Response({
            'status': False,
            'message': serializer.errors

        })
    if request.method == "GET":
        contact = Contact.objects.all()
        serializer = ContactSerializer(contact, many=True)
        return Response(serializer.data)

I used AnonRateThrottle but still now anyone can submit POST request using the api url. How to prevent it? Basically I want to allow post request if it's actually come from my website and also how to restrict access view api page?

A: You have the permission_classes and IsAuthenticated.
Just do the following?
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import permission_classes

api_view(['POST', 'GET'])
@permission_classes((IsAuthenticated, )) # < --------
def farhyn_api(request):
    if request.method == 'POST':
        data = request.data
        serializer = ContactSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            print(serializer.data)
            return Response({
                'status': True,
                'message': 'sucess'
            })

        return Response({
            'status': False,
            'message': serializer.errors

        })
    if request.method == "GET":
        contact = Contact.objects.all()
        serializer = ContactSerializer(contact, many=True)
        return Response(serializer.data)


text:
Q: Assigning command's output to shell variable and get the variables size I have a file consisting of digits. Usually, each line contains one single number. I would like to count the number of lines in the file that begin with digit '0'. If it's the case, then I would like to do some post-processing.
Although I'm able to retrieve correctly the corresponding line numbers, the total number of retrieved lines is not correct. Below, I'm posting the code that I'm using.
linesToRemove=$(awk '/^0/ { print NR; }' ${inputFile});
# linesToRemove=$(grep -n "^0" ${inputFile} | cut -d":" -f1);

linesNr=${#linesToRemove} # <- here, the error
# linesNr=${#linesToRemove[@]} # <- here, the error

if [ "${linesNr}" -gt "0" ]; then
    # do something here, e.g. remove corresponding lines.
    awk -v n=$linesToRemove 'NR == n {next} {print}' ${anotherFile} > ${outputFile}
fi

Also, as for the awk-based command, how could I use a shell-variable? I tried the command below, but it's not working correctly, since 'myIndex' is interpreted as a text and not as a variable.
linesToRemove=$(awk -v myIndex="$myIndex" '/^myIndex/ { print NR;}' ${inputFile});

Given the line numbers starting with 0 found in ${inputFile}, I would like to remove the corresponding lines numbers from ${anotherFile}. An example for both ${inputFile} and ${anotherFile} is given below:
// ${inputFile}
0
1
3
0

// ${anotherFile}
2.617300e+01 5.886700e+01 -1.894697e-01 1.251225e+02
5.707397e+01 2.214040e+02 8.607959e-02 1.229114e+02
1.725900e+01 1.734360e+02 -1.298053e-01 1.250318e+02
2.177940e+01 1.249531e+02 1.538853e-01 1.527150e+02

// ${outputFile}
5.707397e+01 2.214040e+02 8.607959e-02 1.229114e+02
1.725900e+01 1.734360e+02 -1.298053e-01 1.250318e+02

In the example above, I need to delete lines 0 and 3 from ${anotherFile}, given that those lines correspond to the lines starting with 0 in ${inputFile}.

A: I think you have to do the following to assign an array:
linesToRemove=( $(awk '/^0/ { print NR; }' ${inputFile}) )

And to get the number of elements do (as you have in a commented line):
linesNr=${#linesToRemove[@]}

To remove the lines from from the file you could do something like:
sedCmd=""
for lineNr in ${linesToRemove[@]}; do
  sedCmd="$sedCmd;${lineNr}d"
done
sed "$sedCmd" ${anotherFile} > ${outputFile}

A: If you want to count the number of lines in the file that begins with 0, then this line is wrong.
linesToRemove=$(awk '/^0/ { print NR; }' ${inputFile});
The above says to print the line number when the line start with 0, and your linesToRemove variable will contain all the line numbers, not the total number of lines. Use END{} block to capture the total. eg
linesToRemove=$(awk '/^0/ {c++}END{print c}' ${inputFile});
As for your 2nd question on using variable inside awk, use the regex operator ~. And then set your myIndex variable to include the ^ anchor
linesToRemove=$(awk -v myIndex="^$myIndex" '$0 ~ myIndex{ print NR;}' ${inputFile});
finally, if you just want to remove those lines that start with 0, then just simply remove it
awk '/^0/{next}{print $0>FILENAME}' file

If you want to remove lines from another file using what is captured in input file, here's one way
paste -d"|" inputfile anotherfile | awk '!/^0/{gsub(/^.*\|/,"");print}'

Or just one awk command
awk 'FNR==NR && /^0/{a[FNR]} NR>FNR && (!(FNR in a))' inputfile anotherfile

crude explanation: FNR==NR && /^0/ means process the first file whole line starts with 0 and put its line number into array a. NR>FNR means process the next file and if line number not in array, print the line. See the gawk documentation for what FNR,NR etc means

A: In general if you do this:
linesToRemove=$(awk '/^0/ { print NR; }' ${inputFile});

instead of this:
linesToRemove=$(awk '/^0/ { print NR; }' ${inputFile});
linesNr=${#linesToRemove}

use this:
linesToRemove=$(awk '/^0/ { print NR; }' ${inputFile});
linesNr=${echo $linesToRemove|awk '{print NF}'}

POC  :
cat temp.sh
#!/usr/bin/ksh

lines=$(awk '/^d/{print NR}' script.sh)
nooflines=$(echo $lines|awk '{print NF}')
echo $nooflines
torinoco!DBL:/oo_dgfqausr/test/dfqwrk12/vijay> temp.sh
8
torinoco!DBL:/oo_dgfqausr/test/dfqwrk12/vijay>

A: It greatly depends on the post-processing you are doing, but do you really need the actual count?  Why not do something like this:

if grep ^0 $inputfile > /dev/null; then
  # There is at least one line with a leading 0
  :
fi

grep -v ^0 $inputfile | process-lines-without-leading-zero
grep ^0 $inputfile | process-lines-with-leading-zero

Or, even just:

if grep ^0 $inputfile | process-lines-with-leading-zero; then
  # some post processing
  :
fi

--EDIT--
Based on what you've said in your comment, I would recommend a different approach.  If I understand you correctly, you want to read file a, looking for lines of the form ^0[0-9]*,
and then remove those line numbers from file b.  Doing it one line at a time is pretty slow if the files get big.  Just do:

cmd=$( grep '^0[0-9]*$' a | sed 's/$/d;/g' )
sed "$cmd" b

The assignment to cmd forms a sed command to delete the lines.  Invoking sed on b will omit those lines.  You'll need to redirect the sed output appropriately (perhaps to a temp file and then back to b, or just use 'sed -i' if you're using gnu sed.)

A: Given the large number of edits to this question, it seems easiest to start a new answer.  Your problem can be solved with a simple one-liner:

$ sed "$( grep -n ^0 $inputFile | sed 's/:.*/d;/g' )" $anotherFile > $outputFile


text:
Q: How to determine the Publish source for ADFv2? When using a Git-backed ADFv2, I'm trying to detect when a user publishes directly to the Factory vs when a user publishes to the Factory via the Git collaboration branch.
I've tried looking at the Activity Log, but I can't distinguish between events from a Git Publish vs events from a Direct Publish.
I see that this information is at least visible in the UI. Is this persisted anywhere? Is there any way to obtain this message?

Is there another way to do this?

A: According to my observation, the messages don't persisted anywhere.It is just temporarily stored in the browser's cache, and disappears once you refreshes it.

In the ADF active log,you only could see the epitomize of operations.

I supposed that you only can distinguish between events from a Git Publish vs events from a Direct Publish in the Dev ops page.
You could see the direct publish will leave the comments in the commits list.

And if you release any updates in the Git publish, you could remark some prefix,like --from git---.


text:
Q: How to wrap part of the text in a node that has 'display: flex and justify-content: space-between' styling? I am currently writing a Firefox extension that uses fuzzy search to highligth words on a web page.
The highlighting is done by creating a range that contains the match, then wrapping the content of the range around a custom element. This method from my perspective is equivalent to splitting the text node's text and copying it manually to a newly created node.
The pre-release version of the add-on works beautifully, however there's one type of css styling that I cannot deal with: display: flex; justify-content: space-between. The issue here is that when I partially wrap the content of a node styled as such, the rendered text loses its integrity.
Below you can find a simple demonstration. You can see that after 1 sec when the formatting starts, the 1st paragraph gets spaced out, while the 2nd one remains intact.
Could someone suggest a solution/workaround to this problem? I'd like to leave the web page's css intact so modifying the element's style is out of the question. I have checked mark.js API and it cannot handle this situation either. I wonder how the browser's built-in ctrl-f Highlight All searchbar deals with this..

function wrapRange(range){
  const markedNode = document.createElement('mark');
  range.surroundContents(markedNode);
}

setTimeout(() => {
  document.querySelectorAll('p').forEach(node => {
    const range = new Range();
    range.setStart(node.firstChild, 0);
    range.setEnd(node.firstChild, 3);
    wrapRange(range);
  });
}, 1000);
.problematicClass {
  display: flex;
  justify-content: space-between;
}
mark {
  background-color: red;
}

Lorem ipsum

Lorem ipsum

A: Can you modify html? Do you need to keep raw text inside the element with problematicClass?
Easy solution is to wrap block of text in ex. .

A: Flex is always responsible for self- and child-layouts. You have to add a wrapper around the child-nodes (even if they are text-nodes), if you don't want them to be affected by the parents flex-settings.

The specification describes a CSS box model optimized for user interface design. In the flex layout model, the children of a flex container can be laid out in any direction, and can "flex" their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated. Nesting of these boxes (horizontal inside vertical, or vertical inside horizontal) can be used to build layouts in two dimensions.

Source: https://drafts.csswg.org/css-flexbox-1/
The browser marks the highlight from the search (CTRL+F) on a completely different level and does not inject html code.
That what you want to do, can be solved with the Selection API, but keep in mind, that only Firefox supports multiple selection-ranges at once.
Check out the example here: https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange#Result

*

*Firefox: https://i.imgur.com/DnhZJ5y.png

*Webkit Browsers: https://i.imgur.com/sfKriEl.png


text:
Q: How to get this to stop at 20 I would like for this to stop at 20. By which I mean, when it asks you to input another number it should stop after the 20th time.
Currently I have an accumulating counter that when it reaches 20 it prints the "Enter one more number". It does this at the 20th time, but afterwards it keeps going with asking you to input more numbers. I would like it to stop asking for input after the 20th time.
Thanks. This is apart of a larger homework problem.
def main ():
    print()
    print("Finds the lowest, highest, average, and total to 20 numbers.")
    print()
    number, count, numberlist = getnumber()
    print("Stop.")

def getnumber ():
    count = 0
    numberlist = []
    for count in range(20):
        count = count + 1
        number = float(input("Please enter another number : "))
        numberlist.append(number)
    while count != 20:
        number = float(input("Please enter one more number : "))
        numberlist.append(number)

return number, count

main()

A: You could do this as follows:
def get_numbers(count=20):
    numbers = []
    numbers.append(float(input("Please enter a number : "))) # first
    for _ in range(count-2):
        numbers.append(float(input("Please enter another number : "))) # next 18
    numbers.append(float(input("Please enter one more number : "))) # last
    return numbers

Note that with a for loop you don't need to manually increment the loop counter. Also, there is no need to return count; you already know how many there will be.

A: First of all, note that you are not changing value of count inside while loop - that is why it never stops. After for is executed count is exactly 19 and never reaches 20 after that.
Second of all, you do not need while at all - for loop will work for 20 iterations and stop
def getnumber ():
    count = 0
    numberlist = []
    for count in range(20):
        count = count + 1
        number = float(input("Please enter another number : "))
        numberlist.append(number)

    return number, count, numberlist

A: Here is another option (your approach extended)
limit = 5

def main ():
    print("Finds the lowest, highest, average, and total to {} numbers.".format(limit))
    numbs = getnumber()
    print(numbs)
    print("lowest:", min(numbs))
    print("highest:", max(numbs))
    print("avg:", sum(numbs)/len(numbs))
    print("total:", sum(numbs))
    print("Stop.")

def getnumber ():
    numberlist = []
    for count in range(limit):
        if count == limit-1:
            number = float(input("Please enter one more number : "))
            numberlist.append(number)
        else:
            number = float(input("Please enter another number : "))
            numberlist.append(number)
    return numberlist

main()

Output
Finds the lowest, highest, average, and total to 5 numbers.
[6.0, 3.0, 8.0, 4.0, 2.0]
('lowest:', 2.0)
('highest:', 8.0)
('avg:', 4.6)
('total:', 23.0)
Stop.

A: There are some problems with the code you posted. First of you should indent the return statement so it is part of getnumber. Secondly you return two values but unpack three values in main. If I fix those two things the code works. The reason that count is 20 after the for loop is that you declare count outside the loop, so on each iteration count will be set to the next integer and then incremented once more by
count = count + 1

If you did not have the extra increment inside the loop, count would be 19 after the for loop terminates because range(N) does not include N.
And you can rewrite the code with a list comprehension to get a very concise version
def getnumber(prompt, n):
    return [float(input(prompt)) for _ in range(n)]

This will give you a list of the numbers.


text:
Q: What is the "address" being returned from GetProcAddress()? I'm a little bit confused with GetProcAddress().
Quoting the Win32 docs:

If the function succeeds, the return value is the address of the exported function or variable.

I know that for functions, GetProcAddress() returns a function pointer that calls the desired function. However, it isn't clear what GetProcAddress() returns in something like this:
DLL code
typedef struct {
  uint64_t foo;
  double bar;
  char* baz;
} MyStruct;

__declspec(dllexport) MyStruct* my_struct_ptr;

__declspec(dllexport) long long special_global;

Application code
void* my_struct_ptr = GetProcAddress(my_dll_handle, "my_struct_ptr");
void* special_global = GetProcAddress(my_dll_handle, "special_global");

What would my_struct_ptr and special_global in the application point to?
EDIT: Does my_struct_ptr point to the DLL's my_struct_ptr or the struct that the DLL's my_struct_ptr points to?


text:
Q: Report non tested python file in coverage I am writting the test cases for an existing project and there are multiple python files to be tested, I would like to know the coverage report for all the files under project directory even though there is no testcases wrritten for this file. When I run the below command
pytest --cache-clear --cov-report term-missing --cov=services/ tests/
Report only shows the file which has the test cases under tests/ directory but not showing the other yet to tested files.
I have tried with the below command as well coverage run --source=. -m pytest tests/ && coverage report -m
Can anyone please help how it is possible ?


text:
Q: Magento 2.2: Custom product attribute get How to get Custom product attribute in custom phtml file in magento 2.2.2
Example Like Product Attribute
(1) Nouveauté
(2) Meilleure vente
This is my custom phtml file magento 1.9 so how to use in magento 2.2.2
<?php
/**
 * Product list template
 *
 * @see Mage_Catalog_Block_Product_List
 */
?>
<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>

<?php if(!$_productCollection->count()): ?>

<?php echo $this->__('There are no products matching the selection.') ?>

<?php else: ?>

        <?php echo $this->__('Ours products') ?>

        <?php
            $_collectionSize = $_productCollection->count();
            $_columnCount    = $this->getColumnCount();
            $i               = 1;
            foreach ($_productCollection as $_product):
        ?>
        <li<?php if ($i++%$_columnCount==0): ?> class="last"<?php endif; ?>>

            <?php if($_product->getNouveaute()): ?>
                Nouveauté
            <?php endif; ?>
            <?php if($_product->getMeilleureVente()): ?>
                Meilleure vente
            <?php endif; ?>

            <?php if(!$_product->isSaleable()): ?>
            Rupture de stock
            <?php endif; ?>
            <?php if($_product->getSpecialPrice()): ?>
            Promotion
            <?php endif; ?>
            <a class="picture" href="<?php echo $_product->getProductUrl() ?>">
                <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(283,172); ?>" alt="" />

                    <a href="<?php echo $_product->getProductUrl() ?>" class="name"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>

                    <?php if($_product->getTypeId() == 'configurable' || !$_product->isSaleable()): ?>
                    <a href="<?php echo $this->getAddToCartUrl($_product) ?>" class="btn-type-02"><?php echo $this->__('Add to Cart') ?>
                    <?php else: ?>
                    <form action="<?php echo $this->getAddToCartUrl($_product) ?>" method="post" id="product_addtocart_form_<?php echo $i; ?>">
                        <input type="submit" value="<?php echo $this->__('Add to Cart') ?>" class="btn-type-02" onclick="productAddToCartForm.submit(this,'<?php echo $this->getAddToCartUrl($_product) ?>');return false;" />
                    </form>
                    <?php endif; ?>

<?php echo $this->getPriceHtml($_product, true) ?>

                    <?php if($_product->isSaleable()): ?>
                        <?php echo $this->__('In stock') ?>
                    <?php else: ?>
                        <?php echo $this->__('Out of stock') ?>
                    <?php endif; ?>

        <?php endforeach; ?>

<?php endif; ?>

A: $_product = $block->getProduct();

$myattribute = $_product->getResource()->getAttribute('Your_Attribute_Code')->getFrontend()->getValue($_product);

echo $myattribute;


text:
Q: Connect to Microsoft SQL Server PHP on Mac I have a Macbook with Yosemite. I download an app from apple store to try to run PHP code. I want to connect to a Microsoft SQL Server and this is the code:
$serverName = "astidbs";
$connectionInfo = array( "Database"=>"generale1", "UID"=>"xxxx", "PWD"=>"xxxx");
$conn = sqlsrv_connect($serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.
";
}else{
     echo "Connection could not be established.
";
     die( print_r( sqlsrv_errors(), true));
}

This is the error:
Fatal error: Call to undefined function sqlsrv_connect() in /private/var/folders/t5/zjgg2nv149x48bqqdhvnllcw0000gn/T/com.kukosk.PHP-Code-Tester/PHP_Code_Tester_tempfile.php on line 5

I can't understand if it was an app problem so I tried the code on an online tester but it doesn't work either. The error is the same but without the path. It seems that there isn't the lib for the specified call so I have searched on Google on how to install that but I wasn't able to solve the problem. Anyone have a solution?

A: Try the following:
<?php
$myServer = "astidbs";
$myUser = "your_name";
$myPass = "your_password";
$myDB = "examples";

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer");

//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
  or die("Couldn't open database $myDB");

//close the connection
mssql_close($dbhandle);
?>