text:
Q: HashMap as an ArrayList of Strings first off this is an assignment so I'm more looking for help then coded answers (don't want to cheat!). My assignment is to create a program that processes a train/railway network of stations. The section i'm stuck on adds the stations, their connections, and returns these connections as an Array List of Strings. I've included below the code I have so far, and also an extract from the assignment (related to the section I'm on now). I've been struggling with this bit all weekend, so any help would be hugely appreciated.
It's only the implementation of the interface I need to edit, the "MyNetwork" class. I just feel I've been going in circles, and may not have even gotten off on the right foot?
From the assignment;
Create a class MyNetwork that implements the Network interface.
The getConnections method of this class should return an array containing only those stations directly connected to the fromStation argument.
Hint 1: you can do this using a HashMap, with the keys being  Strings (representing stations) and the values being ArrayLists of Strings (representing the stations to which there is a direct connection).
Hint 2: Although the getConnections method returns an array of Strings, it would be better for the values in the HashMap to be ArrayLists of Strings
The Interface;
public interface Network {

    /**
     * Add a station to the network.
     * @param station The station to be added.
     */
    public void addStation(String station);

    /**
     * Add a direct connection from one station to another.
     * @pre both fromStation and toStation have already been added by the method
     * addStation.
     * @param fromStation The station from which the connection begins.
     * @param toStation The station at which the connection ends.
     */
    public void addConnection(String fromStation, String toStation);

    /**
     * Get a list of all stations directly connected to a given station.
     * @pre fromStation has been added to the network by the method addStation.
     * @param fromStation
     * @return A list of all the stations to which there is a direct connection
     * from fromStation.
     */
    public String[] getConnections(String fromStation);

    /**
     * Search for a station in the network.
     * @param station Station to be searched for,
     * @return true if the Station exists in the network, false otherwise.
     */
    public boolean hasStation(String station);

    /**
     * Get all stations in the network.
     * @return An array containing all the stations in the network, with no
     * duplicates.
     */
    public String[] getStations();

The Implementation:
public class MyNetwork implements Network {

    @Override
    public void addStation(String station) {

        ArrayList<String> Stations = new ArrayList<>();
        Stations.add(station);
    }

    @Override
    public void addConnection(String fromStation, String toStation) {

        Map<String,String> Connections = new HashMap<>();
        Connections.put(fromStation, toStation);
    }

    @Override
    public String[] getConnections(String fromStation) {
        return null; // dummy value!

    }

    @Override
    public boolean hasStation(String station) {
        return false; // dummy value!
    }

    @Override
    public String[] getStations() {
        return null; // dummy value!
    }
}

A: Your network needs to have a state, using one or several instance field(s).
As is, it doesn't have any state. Each method creates a local variable of type List or Map, adds something to this List or Map, and returns. So the List or Map directly goes out of scope and is garbage collected.
private Map<String, List<String>> stations = new HashMap<>();

// now all your methods should use the above map.

See http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html


text:
Q: Cannot avoid tensorflow function retracing I implemented my custom layer to perform resizing of images with padding.
I just want to resize my images (proportionally) that's why I implemented custom layer instead of using tf.image.resize(). And I want to do this using special preprocessing layer instead of doing it manually in Python. Then I can save and load the model that takes images of different sizes. So it will be very portable and so on.
But when I use the predict() method to test the model, I get the following red warnings:
WARNING:tensorflow:6 out of the last 12 calls to <function _make_execution_function..distributed_function at 0x0000026D2E2C53A8> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings is likely due to passing python objects instead of tensors. Also, tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. Please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.
Here is my code
class ResizeWithPad(Layer):
"""Resize an image to the target width and height by keeping the aspect ratio
the same without distortion. If the target dimensions don't match the image dimensions,
the image is resized and then padded with zeroes to match requested dimensions.
The input should be 4-D Tensor of shape [batch, height, width, channels].

Arguments:

height: Integer, the height of the output shape.

width: Integer, the width of the output shape.

name: A string, the name of the layer.
"""

def __init__(self, height, width, name=None, **kwargs):
    super(ResizeWithPad, self).__init__(name=name, **kwargs)
    self.target_height = height
    self.target_width = width
    self.input_spec = InputSpec(shape=(None, None, None, 3))
    print("\nTRACE!!!\n")

@tf.function(input_signature=(tf.TensorSpec(shape=[None, None, None, 3], dtype=tf.float32),),
             experimental_relax_shapes=True)
def call(self, inputs):
    print("\nTRACE!!!\n")
    outputs = tf.image.resize_with_pad(
        inputs, self.target_height, self.target_width)
    return outputs

@tf.function(input_signature=(tf.TensorSpec(shape=[None, None, None, 3], dtype=tf.float32),),
             experimental_relax_shapes=True)
def compute_output_shape(self, input_shape):
    print("\nTRACE!!!\n")
    input_shape = tensor_shape.TensorShape(input_shape).as_list()
    return tensor_shape.TensorShape(
        [input_shape[0], self.target_height, self.target_width, input_shape[3]])

@tf.function(input_signature=(tf.TensorSpec(shape=[None, None, None, 3], dtype=tf.float32),),
             experimental_relax_shapes=True)
def get_config(self):
    print("\nTRACE!!!\n")
    config = {
        'height': self.target_height,
        'width': self.target_width
    }
    base_config = super(ResizeWithPad, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

def main():
    tf.config.experimental_run_functions_eagerly(False)
    img = cv2.imread(file)
    inp = tf.convert_to_tensor(np.expand_dims(roi, axis=0))
    model_output = test_model.predict(inp)[0]

I tried to disable eager execution, use tf.function with different arguments, but nothing helps.
Maybe it's just unavoidable when you have inputs of variable length? And maybe I should not be worried about this, because it's normal. You should rebuild the graph if you have new shape. Of course, it takes time, but preprocessing images in Python function before feeding to the model also takes time. So maybe it doesn't matter. What do you think?

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenSessionInViewFilter and Wicket and still running into LazyInitializationExceptions I'm using Spring's OpenSessionInViewFilter in combination with Wicket and I kept running into LazyInitializationExceptions, which I couldn't get resolved. I could see in the logging that the hibernate session was closed before the exception was thrown, so I was obviously doing something wrong.

A: The OSIVFilter must be above the WicketFilter, or else requests won't reach it. The WicketFilter handles page requests itself, it doesn't delegate to other components, such as another servlet (thus, the filter chain stops there).
Another way to do it is to create an implementation of IRequestCycleListener that does the same as the OSIVFilter. I've created such class by modifying Spring's filter code to comply to the new interface, as below:
import org.apache.wicket.MetaDataKey;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.cycle.AbstractRequestCycleListener;
import org.apache.wicket.request.cycle.RequestCycle;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.orm.hibernate4.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class OpenSessionInViewRequestCycleListener extends AbstractRequestCycleListener {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory";

    private static final MetaDataKey<Boolean> PARTICIPATE = new MetaDataKey<Boolean>() {
    };

    private static final MetaDataKey<SessionFactory> SESSION_FACTORY = new MetaDataKey<SessionFactory>() {
    };

    private String sessionFactoryBeanName = DEFAULT_SESSION_FACTORY_BEAN_NAME;

    private final WebApplication application;

    public OpenSessionInViewRequestCycleListener(WebApplication application) {
        this.application = application;
    }

    /**
     * Set the bean name of the SessionFactory to fetch from Spring's
     * root application context. Default is "sessionFactory".
     * @see #DEFAULT_SESSION_FACTORY_BEAN_NAME
     */
    public void setSessionFactoryBeanName(String sessionFactoryBeanName) {
        this.sessionFactoryBeanName = sessionFactoryBeanName;
    }

    /**
     * Return the bean name of the SessionFactory to fetch from Spring's
     * root application context.
     */
    protected String getSessionFactoryBeanName() {
        return this.sessionFactoryBeanName;
    }

    @Override
    public void onBeginRequest(RequestCycle cycle) {
        SessionFactory sessionFactory = lookupSessionFactory(cycle);
        cycle.setMetaData(SESSION_FACTORY, sessionFactory);
        cycle.setMetaData(PARTICIPATE, false);

        if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
            // Do not modify the Session: just set the participate flag.
            cycle.setMetaData(PARTICIPATE, true);
        }
        else {
            logger.debug("Opening Hibernate Session in OpenSessionInViewRequestCycleListener");
            Session session = openSession(sessionFactory);
            SessionHolder sessionHolder = new SessionHolder(session);
            TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
        }
    }

    @Override
    public void onEndRequest(RequestCycle cycle) {
        if (!cycle.getMetaData(PARTICIPATE)) {
            SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(cycle.getMetaData(SESSION_FACTORY));
            logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
            SessionFactoryUtils.closeSession(sessionHolder.getSession());
        }
    }

    /**
     * Look up the SessionFactory that this filter should use,
     * taking the current HTTP request as argument.
     *
The default implementation delegates to the {@link #lookupSessionFactory()}
     * variant without arguments.
     * @param cycle the current request
     * @return the SessionFactory to use
     */
    protected SessionFactory lookupSessionFactory(RequestCycle cycle) {
        return lookupSessionFactory();
    }

    /**
     * Look up the SessionFactory that this filter should use.
     *
The default implementation looks for a bean with the specified name
     * in Spring's root application context.
     * @return the SessionFactory to use
     * @see #getSessionFactoryBeanName
     */
    protected SessionFactory lookupSessionFactory() {
        if (logger.isDebugEnabled()) {
            logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
        }
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(this.application.getServletContext());
        return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
    }

    /**
     * Open a Session for the SessionFactory that this filter uses.
     *
The default implementation delegates to the
     * {@code SessionFactory.openSession} method and
     * sets the {@code Session}'s flush mode to "MANUAL".
     * @param sessionFactory the SessionFactory that this filter uses
     * @return the Session to use
     * @throws DataAccessResourceFailureException if the Session could not be created
     * @see org.hibernate.FlushMode#MANUAL
     */
    protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
        try {
            Session session = sessionFactory.openSession();
            session.setFlushMode(FlushMode.MANUAL);
            return session;
        } catch (HibernateException ex) {
            throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
        }
    }

}


text:
Q: How to reload a tableview where each cell has a countdown timer that's already started I've created a tableview with custom UITableViewCell subclass that has a countdown timer in each cell.  The user is able to start/stop the timer with a button.  This works fine.
My issue is new cells are supposed to be created and fetched from a server periodically.  I guess I was thinking I can use a NSTimer and keep reloading data to display the new cells but what if I do not want it to affect my countdown timers that have already been started?
Or is there a way my tableview can be updated everytime new data arrives from the server instead of in timed intervals?
Hope that makes sense.  I am not sure what the best method/least expensive way to do this is.

A: You have created a tableview and each cell having countdown timer and its works perfect.
The issue occur when you add a new row (reload tableview) , if it's the issue mean,
You can do the below steps,

*

*create a new mutable array when start a tableview array and load with empty timer.

*When reload table(add a row/cell) make a loop and update a mutable array with updated timer data. also some data to you make understand like BOOL isStarted (do this before reload tableview).

*cellForRowAtIndexPath  should have check with isstarted or not and you can make your own customize code.
4.So you need to check with 2 mutable array , one is data source array and another one is your customize array.
(You can try to do this customize array with in your data source array ,that's also possible).
It may help you if i am understand your issue correct.
If this is not make resolve your issue, please edit your question ith sample coding part will make better solution.   :)


text:
Q: Getting Distinct Words From string via ReGex I need your help in creating a Regex for this. I want that the regex found are placed in an Array.
UPDATE tableName SET fieldA= @param1, fieldB =@param2,
                     fieldC = @param3 , fieldD=@param4
               WHERE fieldE=@param5 and fieldF=@param2 and
                     fieldG = @param6

by using this Regex:
@\w+

i yield these results:
Array[0] = @param1
Array[1] = @param2
Array[2] = @param3
Array[3] = @param4
Array[4] = @param5
Array[5] = @param2
Array[6] = @param6

What will I do to eliminate Array[5] = @param2 so I will have the following result?
Array[0] = @param1
Array[1] = @param2
Array[2] = @param3
Array[3] = @param4
Array[4] = @param5
Array[5] = @param6

A: If you are trying to remove a specific element in an array, see the this question: How can I delete an item from an array in VB.NET?

A: You could use the Enumerable.Distinct() of LINQ.
It would be something like
Dim enu As IEnumerable(Of String) = Array.Distinct()

' If you need an array
Dim array2() As String = enu.ToArray()


text:
Q: How to generate dynamic menu and make it usable? I'm trying to create script that will generate menu with filenames stored in specific folder and then allow me to print that file content with cat after entering number assigned to that file. The loop I have made works perfectly in terms of menu generation, but I don't know how to automaticly set variables and use them in order to print that files content or generate case structure (not sure which approach is better in this situation). My loop looks like this:
number=1
for file in ./menus/*; do
  echo "$number)" `basename -s .sh "$file"`
  let "number += 1"
done

A: Use dialog for that...
apt-get install dialog
Example:
#!/bin/bash

HEIGHT=15
WIDTH=40
CHOICE_HEIGHT=4
BACKTITLE="Backtitle here"
TITLE="Title here"
MENU="Choose one of the following options:"

OPTIONS=(1 "Option 1"
         2 "Option 2"
         3 "Option 3")

CHOICE=$(dialog --clear \
                --backtitle "$BACKTITLE" \
                --title "$TITLE" \
                --menu "$MENU" \
                $HEIGHT $WIDTH $CHOICE_HEIGHT \
                "${OPTIONS[@]}" \
                2>&1 >/dev/tty)

clear
case $CHOICE in
        1)
            echo "You chose Option 1"
            ;;
        2)
            echo "You chose Option 2"
            ;;
        3)
            echo "You chose Option 3"
            ;;
esac

A: Instead of complicated case / if statements, you can make a trick and use an array to store filenames inside, and then just call the file you need using it's  array index:
number=1
for file in ./menus/*; do
fnames+=($(basename -s .sh $file))
#OR just fnames+=( $file )
echo "$number)" `basename -s .sh "$file"`
let "number += 1"
done
read -p "select a file id" fid
fid=$(($fid-1)) # reduce user input by 1 since array starts counting from zero
cat "${fnames[$fid]}.sh" # or just cat "${fnames[$fid]}"

You can also make your jobe with a nice GUI using Yad (an advanced fork of Zenity) like bellow.
In this case you don't need numbering - you just select the file from a GUI list, and by pressing enter or click at ok you cat the selected file and you can see it's content on a new yad window.
As a single line command in bash (for testing):
fc=$(basename -s .sh $(find . -name "*.sh") |yad --list --width=500 --height=500 --center --column="File" --separator="") && cat $fc.sh |yad --text-info --width=800 --height=300

As a script:
yadb=0
while [ $yadb -eq "0" ];do
    fc=$(basename -s .sh $(find . -name "*.sh") |yad --list --width=500 --height=500 --center --column="File" --separator="")
    yadb=$?
    if [ $yadb -eq "0" ]; then
       cat $fc.sh |yad --text-info --width=800 --height=300
    fi
    # If you press cancel on yad window , then yadb will become 1 , file will not be displayed and while loop will be ended.
done


text:
Q: Android Fused Location Provider classes not found Google revealed new Fused location provider API in I/O 2013.
I want to change my code based on this new feature. However, my compiler doesn't find LocationClient class. I searched the references and didn't find this class.
My SDK is fully update (Android SDK Tools 22, Android SDK Platform-Tools 17, Android SDK Build Tools 17).
So, Where is this class? Is there any sample about this new API?
Any comments/suggestion would be appreciated. Thanks.

A: you maybe forgotten import the lib


text:
Q: Get keys from map based on their value c++ I have map with strings as keys and vectors as values:
map<string,vector<int>> myMap;
//("key", value):
("a", {1})
("b", {2,3})
("c", {1})
("d", {1})
("e", {2,3})

Is it possible to get keys based on their values? I want the keys that have the same value i.e
(a,c,d) and (b,e).

A: You have to look at every element
std::vector<std::string> keys_matching(const std::map<std::string, std::vector<int>> & map, const std::vector<int> & value) {
    std::vector<std::string> result;
    for (auto & [k, v] : map) {
        if (v == value) {
            result.push_back(k);
        }
    }
    return result;
}

A: using Data = std::map<std::string, std::vector<int>>;
using ReversedData = std::unordered_map<int, std::vector<std::string>>;

ReversedData reverseValues(const Data& d)
{
    ReversedData r;
    for (const auto &[key, vec] : d) {
        for (auto x : vec) r[x].push_back(key);
    }
    return r;
}

https://godbolt.org/z/7csM36


text:
Q: Fuse Fabric: How to read and maintain a configuration PID per environment? I have configured a fabric profile app-ticketing with the configuration PID using the maven plugin that bundles the dependencies and the configuration PID's. When the camel context is initialized and the camel route starts up it the configuration from the PID file for connection settings port numbers etc. The camel polling route is configured automatically startup as soon as the profile is deployed to a container.
We have 3 environments DEV, QA and Production with different connection parameters, port numbers etc.
How to I setup the profile such that it determines the current environment and uses a different PID file for example com.example.ticketing.dev.properties if it is the DEV environment instead of having to edit the PID everytime I need to deploy to a different environment.

A: I have posted a feature for this using fabric8:maven:plugin , please refer to the example at https://github.com/sundarmr/camelexamples/tree/master/camel-examples/camel-envbased-props .
See if this fits your usecase.


text:
Q: python requests check if a file downloaded correctly I am using requests lib to download some images from a site.
My code would check file size after downloaded.
sample code:
def download(url, store_dir):
    r = requests.get(url, headers=headers, proxies=proxies)

    filename = r.headers.get('content-disposition').split('=')[1]

    real_length = int(r.headers.get('content-length'))

    wholepath = os.path.join(store_dir, filename)

    with open(wholepath, 'wb') as f:
        f.write(r.content)
        f.close()

    if os.path.getsize(wholepath) != real_length:
        print('size error')
        print('status_code: %s' %r.status_code)
        print('headers: %s' %r.headers)
        print('url"%s' % url)
        print('orgin:', r.headers['content-length'], 'now',os.path.getsize(wholepath))
        self.download(url, store_dir)

But I usually found that an image file was broken even if os.path.getsize(wholepath) == real_length .
How can I solve this problem?

A: Nearly 4 years. I forgot this question until recieve a downvote today .
Let me end this question:
There is no perfect way to validate a file without its hash string.
But if you are crawling file from a website, you can try to find if there is a string on the page/url which looks like a md5/sha1, and take it a try. With luck, it is the file hash, you can validate the file by it. With no luck, no way.


text:
Q: Identifying the first element that belongs to different sequences in an array I have an array (A) of sorted integers which contains ascending sequences with gaps.
A = array([1,2,3,4, 7,8,9, 23,24,25, 100])
I have an array (B) that contains a few values selected from A through an external process.
B = array([1,2,23,25,100])
I want to filter out values in B that belong to the same sequence in A so it returns only the first values of each unique sequence
C = array([1,23,100])
I have managed to do it by creating a second list to keep track of what has already been appended, but it seems kind of clumsy. I'm wondering if there is a better way to do this?
import numpy as np

A = np.array([1,2,3,4, 7,8,9, 23,24,25, 100])
B = np.array([1,2,23,25,100])
C = []

already_used_sequence = []

for x in enumerate(A):
    if x[0]-x[1] in already_used_sequence : #did we already group this sequence?
        pass
    elif len(np.intersect1d(B, x[1])) is not None: #is this value in B?
        for h in B:
            if h == x[1]:
                C.append(x[1])
                already_used_sequence.append(x[0]-x[1])
C=np.array(C)

A: You need a groupby operation, which is not easily done with numpy. One option would be to use pandas:
import pandas as pd

# convert to pandas Series
s = pd.Series(A)

# group by successive values
# keep the first found value per group
out = s[np.isin(A, B)].groupby(s.diff().gt(1).cumsum()).first().to_numpy()

Output: array([  1,  23, 100])

A: Some things to point out. First, try using
for i, n in enumerate(my_iter):

instead of just one variable, then having to access the position and value with indexes.
Also, the len() of the intersection1d will never be None, since if it isn't in the B array the length will be 0, and not None. And you don't have to check for for intersection since you will be passing through the array anyway.
Taking all of this into account and adding a break statement after you found the number it should look like this
for i, n in enumerate(A):
if i-n not in already_used_sequence :
    for h in B:
        if h == n:
            C.append(n)
            already_used_sequence.add(i-n)
            break

I changed the already_used_sequence to a set(), that wont make any difference in this small input but its faster then a list in this context when you scale.
If you can guarantee that B will also be in ascending order, you can also do
cur_index = 0
for i, n in enumerate(A):
    if n == B[cur_index]:
        cur_index += 1
        if i-n not in already_used_sequence:
            C.append(n)
            already_used_sequence.add(i-n)

which is a great speed up at larger inputs since you wont be looping through B every time you need to find a number


text:
Q: Show that B is diagonalizable by finding a suitable factorization of B. Suppose $A = PDP^{-1}$, where P is 2 x 2 and $D = \begin{bmatrix} 2&0\\0&7 \end{bmatrix}$.
Let $B = 5I - 3A + A^2.$ Show that $B$ is diagonalizable by finding a suitable factorization of $B$.
I have substituted $A$ for $PDP^{-1}$, so $B = 5I - 3PDP^{-1} + PD^2P^{-1}$, and I have also recognized that an eigenvector $\vec{x}$ for A is an eigenvector for $B$:
$$
(5-3A + A^2)\vec{x} = (5-3\lambda + \lambda^2)\vec{x}
$$
I'm not entirely sure what the question is asking for, but this is what I have done so far.

A: You found $B$ is
$$B=P(5I-3D+D^2)P^{-1}.$$
Observe $(5I-3D+D^2)$ is diagonal and you are done.


text:
Q: Unable to find etc folder in hadoop 2.6.5 installation I am trying to install hadoop 2.6.5 in my linux system but unable to find etc folder which contains the config and env files. I have untared the tar file . File and directeries listing in the hadoop folder are
/home/tcs>cd hadoop
/home/tcs/hadoop>ls -ltr
total 192

-rw-rw-r--  1 tcs tcs  1366 Jul 23  2015 README.txt
-rw-rw-r--  1 tcs tcs 14978 Sep 20  2016 NOTICE.txt
-rw-rw-r--  1 tcs tcs 84853 Sep 20  2016 LICENSE.txt
-rw-rw-r--  1 tcs tcs 12091 Sep 20  2016 BUILDING.txt
-rw-rw-r--  1 tcs tcs 18121 Sep 20  2016 pom.xml
drwxrwxr-x  3 tcs tcs  4096 Mar  9 18:00 hadoop-project
drwxrwxr-x  3 tcs tcs  4096 Mar  9 18:00 hadoop-assemblies
drwxrwxr-x  3 tcs tcs  4096 Mar  9 18:00 hadoop-yarn-project
drwxrwxr-x 10 tcs tcs  4096 Mar  9 18:00 hadoop-common-project
drwxrwxr-x  2 tcs tcs  4096 Mar  9 18:00 hadoop-dist
drwxrwxr-x  2 tcs tcs  4096 Mar  9 18:00 hadoop-client
drwxrwxr-x  3 tcs tcs  4096 Mar  9 18:00 dev-support
drwxrwxr-x  9 tcs tcs  4096 Mar  9 18:00 hadoop-mapreduce-project
drwxrwxr-x  2 tcs tcs  4096 Mar  9 18:00 hadoop-project-dist
drwxrwxr-x  6 tcs tcs  4096 Mar  9 18:00 hadoop-hdfs-project
drwxrwxr-x  2 tcs tcs  4096 Mar  9 18:00 hadoop-build-tools
drwxrwxr-x 15 tcs tcs  4096 Mar  9 18:00 hadoop-tools
drwxrwxr-x  2 tcs tcs  4096 Mar  9 18:00 hadoop-minicluster
drwxrwxr-x  3 tcs tcs  4096 Mar  9 18:00 hadoop-maven-plugins

please help

A: What have you downloaded is hadoop sources. You can build from them hadoop distribution or you can download ready binary distribution.
You can find them for example here: http://hadoop.apache.org/releases.html


text:
Q: A very complex problem in reduction notion I have studied many about reduction but I have a bad problem in it:
I take this from CLRS :
" ... by "reducing" solving problem A to solving problem B, we use the "easiness" of B to prove the "easiness" of A."
And I take this from "Computational Complexity by Christos H. Papadimitriou  " :
" ... problem A is at least as hard as problem B if B reduces to A."
I got confused with these two notion:
when we use easiness , we say that problem X reduces to problem Y and if we have polynomial time algorithm for Y and reduction process is done in polynomial time then problem X is solvable in polynomial time and X is easier than Y or at least is not harder than Y.
But when we use hardness , we say problem X reduces to problem Y and Y is easier than X or at least is not harder than X.
I really got confused, Please help me.
Special thanks.

A: I think you might have missed that the first quote says "reduce A to B", and the second quote says "reduce B to A".
If X reduces to Y, meaning that Y can be used to solve X, then X is no harder than Y. That's because polynomial-complexity reduction is considered "free", so by reducing X to Y we've found a way to solve X using whatever solutions there are to Y.
So, in the first quote, if A reduces to B and B is easy, that means A is easy (strictly speaking, it's no harder).
The second quote uses the logical contrapositive: if B reduces to A and B is hard, then A must be hard (strictly speaking, it's no easier). Proof: If A was easy, then B would be easy (as above but A and B are reversed). B is not easy, therefore A is not easy.
Your statement, "we say problem X reduces to problem Y and Y is easier than X or at least is not harder than X" is false. It is possible for X to reduce to Y (that is, we can use Y to solve X), even though Y in fact is harder than X. So we could reduce addition (X) to a special case of some NP-hard problem (Y), by defining a scheme to construct in polynomial time an instance of the NP-hard problem whose solution is the sum of our two input numbers. It doesn't mean addition is NP-hard, just that we've made things unnecessarily difficult for ourselves. It's unwise to use that reduction in order to perform addition, since there are better ways to do addition. Well, better assuming P!=NP, that is.

A: Think of reduction as reduction of the proof for the problem being in a certain class rather than reducing the problem itself. The relation is more related to logic than to complexity.

A: The theory is simply this.
You have an algorithm to solve problem A that you know can be solved in polynominal time.
If it is possible to convert problem B into a notation that can be solved by problem A and then convert the result back into the notation for problem B in polynominal time, then to solve problem B will also be in polynominal time - as the total time is just the addition of two polynominals - hence no harder.


text:
Q: Proper Way to Use Cron Jobs I am currently developing a website that has to perform a task every 10 seconds. The website checks a database every ten seconds, finds rows that are to be processed, and then run a short script on each row.
The service is working great right now, but I just want to make sure that once the database gets very large, the service will still work efficiently.
I am using a cron job that runs every minute, with sleep functions every 10 seconds.
Thank you for your help!

A: Just make sure your tasks don't overlap, i.e. wait till the previous task is over before launching a new one. Otherwise, if your tasks take more than a minute (or whatever timer you've set for them), you'll end up with tons of those running in parallel and your system will run out of available resources.


text:
Q: JFreechart filling sectors series I am trying to create a filled series over each region of a polar plot. But the colors are not filled out right. Here is an image of what I get: http://i1122.photobucket.com/albums/l539/jpo2/polar-1.gif
Here is the code I have to loop through a given section is as follows:
   if (i < 8) {
    for(int r = 0; r< 20; r+=(NumberAxis) plot.getAxis()).getTickUnit().getSize()){
    for(int theta = 0; theta <= 180; theta+=30){
    XYSeries series = new XYSeries(i + "π/8 " + "< θ < 2π+" + i + "π/8");
        for (int e = theta; e < theta+30; e++) {
            series.add(90-e-i*45, r);
            series.add(90-e-i*45, r- ((NumberAxis) plot.getAxis()).getTickUnit().getSize());
            }
        result.addSeries(series);
        setFilled(result);
        i++;
        }
    }
    }
private void setFilled(XYDataset dataset) {
    for (int i = 0; i < dataset.getSeriesCount(); i++) {
        renderers.setSeriesFilled(i, true);
        }
    }

This is a modification of @trashgod's draw method at JFreechart Loop through polar chart sectors
Please help.
Full code:
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTick;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.renderer.DefaultPolarItemRenderer;
import org.jfree.chart.renderer.PolarItemRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.TextAnchor;

public class tests extends JFrame implements ChartProgressListener {

    private static final String title = "Archimedes' Spirals";
    private XYSeriesCollection result = new XYSeriesCollection();
    private DefaultPolarItemRenderer renderers = new DefaultPolarItemRenderer();
    private int i;

    public tests(String title) {
        super(title);
        JFreeChart chart = createChart(result);
        ChartPanel panel = new ChartPanel(chart);
        panel.setPreferredSize(new Dimension(500, 500));
        panel.setMouseZoomable(false);
        this.add(panel);
    }

    private JFreeChart createChart(XYDataset dataset) {
        ValueAxis radiusAxis = new NumberAxis();
        radiusAxis.setTickLabelsVisible(false);
        PolarItemRenderer renderer = new DefaultPolarItemRenderer();
        PolarPlot plot = new PolarPlot(dataset, radiusAxis, renderer) {

            @Override
            protected List refreshAngleTicks() {
                List<NumberTick> ticks = new ArrayList<NumberTick>();
                int delta = (int) this.getAngleTickUnit().getSize();
                for (int t = 0; t < 360; t += delta) {
                    int tp = (360 + 90 - t) % 360;
                    NumberTick tick = new NumberTick(
                        Double.valueOf(t), String.valueOf(tp),
                        TextAnchor.CENTER, TextAnchor.CENTER, 0.0);
                    ticks.add(tick);
                }
                return ticks;
            }
        };
        plot.setBackgroundPaint(new Color(0x00f0f0f0));
        plot.setRadiusGridlinePaint(Color.gray);
        plot.addCornerTextItem("r(θ) = θ; 0 < θ < 2π; +iπ/8");
        setFilled(dataset);
        plot.setRenderer(renderers);
        JFreeChart chart = new JFreeChart(
            title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        chart.setBackgroundPaint(Color.white);
        chart.addProgressListener(this);
        return chart;
    }

    public static void main(String[] args) {
        tests demo = new tests(title);
        demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        demo.pack();
        demo.setLocationRelativeTo(null);
        demo.setVisible(true);
    }

    @Override
    public void chartProgress(ChartProgressEvent e) {
        if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
            System.out.println(e);
            JFreeChart chart = e.getChart();
            draw();
        }
    }

    public void draw() {
        if (i < 4) {
            for (int g = 0; g < 30; g += 5) {
                for (int h = 0; h < 180; h += 45) {
                    XYSeries series = new XYSeries(i + "π/8 " + "< θ < 2π+" + i + "π/8");
                    for (int t = h; t <= h + 45; t++) {
                        series.add(90 - t, g);
                        series.add(90 - t, g + 5);
                    }
                    result.addSeries(series);
                    setFilled(result);
                    i++;
                }
            }

        }
    }

    private void setFilled(XYDataset dataset) {
        for (int i = 0; i < dataset.getSeriesCount(); i++) {
            renderers.setSeriesFilled(i, true);
        }
    }
}

A: Here's a simplified version the uses PolarPlot directly, without any transformation. It might be easier to experiment with.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.renderer.DefaultPolarItemRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/** @see http://stackoverflow.com/questions/6669734 */
public class PolarArcs {

    private static final String title = "PolarArcs";
    private static final double PI2 = 90d; // π/2 radians = 90°

    private void display() {
        JFrame f = new JFrame(title);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ChartPanel panel = new ChartPanel(createChart(createDataset()));
        panel.setPreferredSize(new Dimension(400, 400));
        f.add(panel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private JFreeChart createChart(XYDataset dataset) {
        JFreeChart chart = ChartFactory.createPolarChart(
            title, dataset, true, false, false);
        PolarPlot plot = (PolarPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setAngleGridlinesVisible(false);
        plot.setRadiusGridlinesVisible(false);
        DefaultPolarItemRenderer r = (DefaultPolarItemRenderer) plot.getRenderer();
        for (int i = 0; i < dataset.getSeriesCount(); i++ ) {
            r.setSeriesFilled(i, true);
        }
        NumberAxis rangeAxis = (NumberAxis) plot.getAxis();
        rangeAxis.setTickLabelsVisible(false);
        return chart;
    }

    private XYDataset createDataset() {
        XYSeriesCollection result = new XYSeriesCollection();
        for (int r = 8; r > 0; r--) {
            XYSeries series = new XYSeries(title + String.valueOf(r));
            for (int t = (int) -PI2; t <= PI2; t++) {
                series.add(t, r);
            }
            result.addSeries(series);
        }
        return result;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new PolarArcs().display();
            }
        });
    }
}


text:
Q: Gray Status Bar when contact email is chosen from ABPersonView I've implemented ABPersonView in my application to allow a contact to be viewed. Upon choosing the email field, the email application is opened as expected except for a gray status bar which is only appearing on the iPad, on the iPhone it is not. I am not using IB and the code is very simple and standard to implement ABPersonView. If anyone needs specific code please specify which code section. I am stumped since this problem is only appearing on the iPad. How can I stop this behavior on the iPad?
Edit: I have recreated this undesired behavior with a dummy project.
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

@interface RootViewController: UIViewController <ABPersonViewControllerDelegate> {

}

@end

and in the .m
#import "RootViewController.h"

@implementation RootViewController

- (void)loadView {

    self.view = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(21, 80, 100, 35);
[myButton setTitle:@"My Button" forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(myButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myButton];

}

-(void)myButtonPressed{

    ABPersonViewController *personViewController = [[[ABPersonViewController alloc] init] autorelease];
personViewController.displayedPerson = [self personObject];
[self.navigationController pushViewController:personViewController animated:YES];

}

- (ABRecordRef)personObject {

ABRecordRef newRecord = ABPersonCreate();

ABRecordSetValue(newRecord, kABPersonFirstNameProperty, CFSTR("John"), nil);
ABRecordSetValue(newRecord, kABPersonLastNameProperty, CFSTR("Doe"), nil);

ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiPhone, @"1-222-333-4444", kABPersonPhoneMainLabel, NULL);
ABRecordSetValue(newRecord, kABPersonPhoneProperty, multiPhone, nil);
CFRelease(multiPhone);

ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiEmail, @"123@abc.com", kABWorkLabel, NULL);
ABRecordSetValue(newRecord, kABPersonEmailProperty, multiEmail, nil);
CFRelease(multiEmail);

ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
NSMutableDictionary *addressDict = [[NSMutableDictionary alloc] init];
[addressDict setObject:@"1234 AnyStreet" forKey:(NSString *)kABPersonAddressStreetKey];
[addressDict setObject:@"AnyTown" forKey:(NSString *)kABPersonAddressCityKey];
[addressDict setObject:@"AnyState" forKey:(NSString *)kABPersonAddressStateKey];
[addressDict setObject:@"55555" forKey:(NSString *)kABPersonAddressZIPKey];
ABMultiValueAddValueAndLabel(address, addressDict, kABWorkLabel, nil);
ABRecordSetValue(newRecord, kABPersonAddressProperty, address, nil);

return newRecord;
}

- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue
{
    return YES;
}

@end

A: What exactly is your desired behaviour?
If you wish to remove the status bar entirely, you could hide it by using:
[[UIApplication sharedApplication] setStatusBarHidden:YES];

You're also able to set its style and frame.  All of this is here in the Apple Developer documentation.  See Controlling App Appearance.


text:
Q: Ionic 5 Capacitor with Microsoft SSO I am trying to implement Microsoft SSO with Ionic 5 but am having no luck. I have tried using @azure/msal-angular @azure/msal-browser method but this seems to only work in web. Has anyone tried to implement this recently?
Here is the error I'm getting in XCODE
[error] - Big ERROR OCCURED! {"errorCode":"popup_window_error","errorMessage":"Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser. Details: BrowserAuthError: empty_window_error: window.open returned null or undefined window object.","subError":"","name":"BrowserAuthError"}


text:
Q: Dynamically Building Object Graph I have an endpoint that allows me to get the top node of my graph. I also allow the client to specify the nodes he wishes to retrieve that are children of the top node:
For example:
/libraries/5?with=banner|videos

This will retrieve me a library with a banner object and a list of videos.
I provide a full query language, that supports nesting. For example if you wanted the same structure but including the covers and chapters for each video you would request this:
/libraries/5?with=banner|videos[cover|chapters]

I need to build the object dynamically when the request comes in. I have had a look at Clay, but the project seems a little old, and I am sure there is a better way to build objects at runtime than using ExpandoObject.
If anyone has any ideas, I would be most grateful?

A: ExpandoObject is the way to go for assigning dynamic properties to an object.
You could use Dictionary but the code can get ugly.  Consider the following example -
Dictionary<string, object> parent = new Dictionary<string, object>();
parent["known_prop"] = new List<object>();
parent["dynamic_prop"] = new Dictionary<string, object>();
parent["dynamic_prop"]["some_value"] = new List<object>();

The same can be written in a very concise way in ExpandoObject -
var a = new ExpandoObject();
a.Prop1 = new List<Object>();
a.Prop2 = new ExpandoObject();
a.Prop2.Val = new List<Object>();

A: C# is not so good in dynamic objects which is by design - its statically typed language. There is a dynamic type that emulates static access to otherwise dynamic (unknown at compile time) structure. You can use it to assign and retrieve values.
If by endpoint you understand so web service that returns json or xml then you do not need to create dynamic object just build the expected structure. Newtonsoft json serializer for-instance can nicely serialize dictionary:
_dictionary.Add("banner", new Banner())

will produce
{
    "banner" : { ... banner properties ... }
}


text:
Q: Display external video on iMac I am considering purchasing an iMac. Our office situation is such that the new computer will be placed where a monitor is presently located for a Windows laptop connected via a docking station.
Is it possible to connect external video to an iMac? Alternatively, is the iMac capable of hooking up to a second monitor? (my monitor has multiple inputs which I could just switch between) Are there other options that I am missing?

A:
Is it possible to connect external video to an iMac?

Yes, the latest 27" iMac can act as a monitor via Mini DisplayPort. From Apple:

Mini DisplayPort output with support for DVI, VGA, and dual-link DVI (adapters sold separately); 27-inch models also support input from external DisplayPort sources (adapters sold separately)

You'll need an adapter to convert your laptop output to Mini DisplayPort. Be careful, as some adapters, such as those provided by Apple, are designed to output DVI/VGA/etc, and aren't capable of being reversed to accept it as input.
further reading: http://support.apple.com/kb/HT3924


text:
Q: What is a very large room in a building called? In our university there are a few very large spaces in a building. In each of these large rooms, something about 100 people work. Each room is partitioned using 1.5 metre high fiberglass walls and has many cubicles in it. What are these large rooms called? Salons, halls or just "very very large rooms"?

A: If it's a room where people are primarily doing work at desks, then I would call that an office.
Merriam-Webster gives this as one of the its three primary senses of office:

: a building or room in which people work at desks doing business or professional activities

A:
Hall

In architecture, a hall is fundamentally a relatively large space enclosed by a roof and walls.
wiki source

A: As mentioned in comments above, what's being described is an open-plan office. A somewhat informal single word for this type of workspace is bullpen:

an open-plan office area

Under "Other uses" of the Wikipedia entry1, it states that "bullpen" is a "reference to a large open work area consisting of desks with no separating walls and private offices. Bullpens were common across many business fields in the first half of the 20th century and are often used by software development teams."

A: In this context, I would be tempted to call it simply a 'space'.
An interesting but typo-filled explanation of architectural space here

A: A "great room" or a "great hall".


text:
Q: is it possible to set stylish jquery scroll on textarea? Is it possible to set stylish jquery scroll on textarea?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery textarea scroll</title>
<style type="text/css">
.my_textarea{
    height:250px;
    width:250px;
    overflow:auto;
}
</style>
</head>

<body>
<textarea name="txt_area" class="my_textarea"></textarea>
</body>
</html>

A: I am using http://jscrollpane.kelvinluck.com/ and it works quite nice

A: textarea
{
    scrollbar-3dlight-color: #444;
    scrollbar-highlight-color: #fff;
    scrollbar-face-color: #444;
    scrollbar-arrow-color: #fff;
    scrollbar-shadow-color: #fff;
    scrollbar-darkshadow-color: #444;
    scrollbar-track-color: #444;
}

A: Here is the jQuery plugin http://www.rshahin.com/jquery-plugin-to-style-scrollbars-cross-browser-compatible/


text:
Q: How can I show that the Lucas numbers are given by the sum of $F_{k-1}+F_{k+1}$ I was wondering how I can show that the Lucas numbers are also given by the formula $F_{k-1}+F_{k+1}$ in terms of Fibonacci numbers. I got the formula for the Lucas numbers to be $L_k=[\frac{1}{2}(1+\sqrt{5})]^k+[\frac{1}{2}(1-\sqrt{5})]^k$ and I know the recurrence relation is just the sum of the two previous numbers (i.e. $L_k=L_{k-1}+L_{k-2}$), but I cannot seem to get how to use this information to show that $L_k=F_{k-1}+F_{k+1}$.

A: Sure, we could use the closed forms for the sequences:
\begin{align}
L_n &= \left(\frac{1+\sqrt{5}}{2}\right)^n + \left(\frac{1-\sqrt{5}}{2}\right)^n\\
F_n &= \tfrac{1}{\sqrt{5}} \left[ \left(\frac{1+\sqrt{5}}{2}\right)^n - \left(\frac{1-\sqrt{5}}{2}\right)^n \right]
\end{align}
So a bit of algebra:
\begin{align}
F_{n-1}+F_{n+1}
&= \tfrac{1}{\sqrt{5}} \left[ \left(\frac{1+\sqrt{5}}{2}\right)^{n-1} - \left(\frac{1-\sqrt{5}}{2}\right)^{n-1} \right] + \tfrac{1}{\sqrt{5}} \left[ \left(\frac{1+\sqrt{5}}{2}\right)^{n+1} - \left(\frac{1-\sqrt{5}}{2}\right)^{n+1} \right]\\
&=\tfrac{1}{\sqrt{5}}\left[ \left(1+\left(\frac{1+\sqrt{5}}{2}\right)^2\right) \left(\frac{1+\sqrt{5}}{2}\right)^{n-1} - \left(1+\left(\frac{1-\sqrt{5}}{2}\right)^2\right)\left(\frac{1-\sqrt{5}}{2}\right)^{n-1}  \right]\\
&=\tfrac{1}{\sqrt{5}}\left[ \left(\sqrt{5}\frac{1+\sqrt{5}}{2}\right) \left(\frac{1+\sqrt{5}}{2}\right)^{n-1} - \left(\sqrt{5}\frac{\sqrt{5}-1}{2}\right)\left(\frac{1-\sqrt{5}}{2}\right)^{n-1}  \right]\\
&=\left(\frac{1+\sqrt{5}}{2}\right)^n + \left(\frac{1-\sqrt{5}}{2}\right)^n
= L_n
\end{align}


text:
Q: Getting closest element by id I have two elements:
<input a>
<input b onclick="...">

When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so document.getElementsByName is out. Looking into the event object, I thought event.target.parentNode would have some function like getElementsByName, but this does not seem to be the case with <td>s. Is there any simple way to do this?

A: If a and b are next to each other and have the same parent, you can use the prevSibling property of b to find a.

A: *

*You should be able to find the element that was clicked from the event object.  Depending on your browser you might want e.target or e.srcElement. The code below is from this w3schools example:
function whichElement(e) {
  var targ;
  if (!e) var e = window.event;
  if (e.target) {
    targ=e.target;
  } else if (e.srcElement) {
    targ = e.srcElement;
  }

  if (targ.nodeType==3) { // defeat Safari bug
    targ = targ.parentNode;
  }

  var tname;
  tname = targ.tagName;
  alert("You clicked on a " + tname + " element.");
}

*You may then use the nextSibling and prevSibling DOM traversal functions.  Some more information here.  And yet again a w3schools reference for XML DOM Nodes.

A: Prototype also has nice functions to move around in the DOM. In your example something like the following would do the trick:
b.up().down('a')

And if there are is more than one a element at that level you have the power of CSS selectors at your hand to specify exactly which element you want

A: Leave your plain vanilla JavaScript behind. Get JQuery--it will save you a ton of time.
http://docs.jquery.com/Selectors


text:
Q: How long to hold key combinations when booting a Mac? I can't believe no one has ever asked this, but I can't seem to find it:
How long should you hold down key combinations, such as Command + S, while your Mac is booting? I can get this iMac to boot into safe mode (sometimes), but not Single User, Verbose, or Diagnostic modes, which seems strange to me, thus I assume I'm not doing something correctly.
Do you just hold the keys briefly or hold the keys for longer? If the latter, how long exactly? This iMac just has that gray boot screen, and there's no indication that anything is happening, so I have no way of knowing when I should stop pressing the key combos or if pressing them is even doing anything.

A: In general, you should hold the key(s) down until they take effect. For single-user and verbose modes, that means hold them until you see text start to appear. For the others, it's generally ok to let go once you see the Apple in the middle of the screen (the Apple is drawn by the booter, which loads after the firmware has detected startup options).
If you have FileVault 2 (full volume encryption) set up, things are a little more complicated, since some key combinations (mainly single-user, verbose, and safe boot) don't take effect until after you've authenticated to unlock the startup volume. It currently seems to do a good job of detecting the key combos before the authentication screen, then having them take effect after you "log in". But if that's not working for you, try holding them down as you press return on the FV2 authentication screen, and keep holding them until you see them take effect.

A: That's because it will differ slightly depending on what hardware and the startup behavior it's being preformed on. From Startup key combinations for Mac it states:

Some Mac features are available by holding down certain keys during
  startup.
Press and hold the keys immediately after you turn on your Mac and
  hear the startup sound. Keep holding until the described behavior
  occurs. These combinations work with Intel-based Mac
  computers.

So the timings will very a little bit although it should be relatively quickly to realize the target behavior it taking place.
As an example my 7 year old MacBook Pro does everything considerable slower then my 2 year old MacBook Pro so to give explicit timings for various startup behaviors will vary as much as there are different speeds of processors, etc. and is why Apple states it in the terms that do and not not in seconds, etc.

A: Make sure you hold down the special key(s) upon hitting the power button, and keep holding the special key(s) down until you hear the startup chime.

A: It used to be simple - If the screen gets drawn with a total grey background, you can let go since the time to have the startup keys modify the boot order has passed.
Now it's complicated with Boot EFI, Recovery HD and FileVault.
Here is the article from Apple documenting the Mac Hardware and OS X startup sequence.
https://support.apple.com/kb/HT204156


text:
Q: Ionic React - How to prevent rerendering routes created by Ionic Tabbar I am using Ionic Framework with React to create an app with four main tabs. One of the tabs is a map component. My problem is that when I switch tabs, React rerenders them every time. For example, lets say user found a location on map and wanted to see another tab, then switched back to the map. User must be able to continue where he left it on map. Is there any way to achieve that?
Code:
<IonTabs>
  <IonRouterOutlet>
    <Route exact path="/map">
      <Map />
    </Route>
    <Route exact path="/second">
      <Second />
    </Route>
    <Route exact path="/Third">
      <Third />
    </Route>
    <Route exact path="/fourth">
      <Fourth />
    </Route>
  </IonRouterOutlet>

  <IonTabBar slot="bottom">
    <IonTabButton tab="map" href="/map">
      <IonLabel>Map</IonLabel>
    </IonTabButton>
    <IonTabButton tab="second" href="/second">
      <IonLabel>Second</IonLabel>
    </IonTabButton>
    <IonTabButton tab="third" href="/third">
      <IonLabel>Third</IonLabel>
    </IonTabButton>
    <IonTabButton tab="fourth" href="/fourth">
      <IonLabel>Fourth</IonLabel>
    </IonTabButton>
  </IonTabBar>
</IonTabs>

A: you need to save the state of the map in the component so that when it is rerendered, the map shows the appropriate information.


text:
Q: How to mount multiple partitions from disk image simultaneously? I am trying to mount root and boot partition of Raspbian image:
mount -v -o offset="70254592" -t ext4 /mnt/X/raspbian-jessie.img /tmp/raspbian
mount -v -o offset="4194304" -t vfat /mnt/X/raspbian-jessie.img /tmp/boot

mounting boot, when root is mounted results in:
mount: /mnt/X/raspbian-jessie.img: overlapping loop device exists

How to mount multiple partitions on one disk image at same time? (for disks it's obviously possible, why not for files?)

A: losetup 2.21 -P option
losetup -P -f --show my.img

Creates one /dev/loopXpY per partition.
Advantage: executable pre-installed in many distros (util-linux package).
Disadvantage: quite recent option, not present in Ubuntu 14.04, before that just use kpartx: https://unix.stackexchange.com/a/405639/32558
losetup -P automation
Usage:
$ los my.img
/dev/loop0
/mnt/loop0p1
/mnt/loop0p2

$ ls /mnt/loop0p1
/whatever
/files
/youhave
/there

$ sudo losetup -l
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE                                                                                DIO
/dev/loop1         0      0         0  0 /full/path/to/my.img

$ # Cleanup.
$ losd 0
$ ls /mnt/loop0p1
$ ls /dev | grep loop0
loop0

Source:
los() (
  img="$1"
  dev="$(sudo losetup --show -f -P "$img")"
  echo "$dev"
  for part in "$dev"?*; do
    if [ "$part" = "${dev}p*" ]; then
      part="${dev}"
    fi
    dst="/mnt/$(basename "$part")"
    echo "$dst"
    sudo mkdir -p "$dst"
    sudo mount "$part" "$dst"
  done
)
losd() (
  dev="/dev/loop$1"
  for part in "$dev"?*; do
    if [ "$part" = "${dev}p*" ]; then
      part="${dev}"
    fi
    dst="/mnt/$(basename "$part")"
    sudo umount "$dst"
  done
  sudo losetup -d "$dev"
)

A: Use kpartx tool. It will map image partitions using /dev/mapper which you can mount directly.
$ sudo kpartx -a disk.img
$ sudo mount -o loop /dev/mapper/loop0p2 /mnt

PS. Do not forget to remove mappings after you are done: sudo kpartx -d disk.img

A: You need to specify the length of the partition(s) to avoid overlap. Option sizelimit, see man mount, man losetup.


text:
Q: Login with facebook sdk shared preference and get information about user i am developing an app where facebook login is there . i am trying to get user information and send that to my server.i am using sdk 4.i am trying to use shared preference to save info but i have no idea about shared preference . This is my facebook login activity . this is launcher activity.
public class LoginActivity extends  AbsRuntimePermission {
private static final int REQUEST_Permission =10;

    private TextView info;
    private LoginButton loginButton;
    private CallbackManager callbackManager;
    private SparseIntArray mErrorString;
    private Button facebook_button;
    ProgressDialog progress;
    private String facebook_id,f_name,m_name,l_name,gender,profile_image,full_name,email_id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    //for permission in manifest file cause it is launch activity

    requestAppPermissions(new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.INTERNET},R.string.msg,REQUEST_Permission);

    //facebook
    info = (TextView) findViewById(R.id.info);
    loginButton = (LoginButton) findViewById(R.id.login_button);
    progress = new ProgressDialog(LoginActivity.this);
    progress.setMessage(getResources().getString(R.string.please_wait_facebooklogin));
    progress.setIndeterminate(false);
    progress.setCancelable(false);

    facebook_id=f_name=m_name=l_name=gender=profile_image=full_name=email_id="";

    //facebook sdk
    FacebookSdk.sdkInitialize(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

    //register callback object for facebook result

    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            progress.show();
            Profile profile = Profile.getCurrentProfile();
            if(profile != null){
                facebook_id = profile.getId();
                f_name=profile.getFirstName();
                m_name=profile.getMiddleName();
                l_name=profile.getLastName();
                profile_image=profile.getProfilePictureUri(400,400).toString();
            }
            //show Toast
            GraphRequest request =GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback(){
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            try {
                                email_id = object.getString("email");
                                gender = object.getString("gender");
                                String Profile_name = object.getString("name");
                                long fb_id = object.getLong("id"); //use this for logout

                                //Starting a new activity using this information
                                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                                i.putExtra("type", "facebook");
                                i.putExtra("Facebook_id", facebook_id);
                                i.putExtra("f_name", f_name);
                                i.putExtra("m_name", m_name);
                                i.putExtra("l_name", l_name);
                                i.putExtra("full_name", full_name);
                                i.putExtra("Profile_image", profile_image);
                                i.putExtra("email_id", email_id);
                                i.putExtra("gender", gender);

                                progress.dismiss();
                                startActivity(i);
                                finish();

                            }catch (JSONException e){
                                e.printStackTrace();
                            }
                        }
                    });
            request.executeAsync();
        }

        @Override
        public void onCancel() {
        Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_canceled_facebooklogin),Toast.LENGTH_SHORT).show();
        progress.dismiss();
        }

        @Override

        public void onError(FacebookException error) {
            Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_failed_facebooklogin),Toast.LENGTH_SHORT).show();
            progress.dismiss();
        }
    });

    //facebook button click
    facebook_button.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile","user_friends","email"));

        }
    });
}

private void logoutFromFacebook(){
    try{
        if(AccessToken.getCurrentAccessToken()==null){
            return;
        }

    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode,resultCode,data);
}

@Override
public void onPermissionGranted(int requestCode) {

    //anything after permission Granted
    Toast.makeText(getApplicationContext(),"Permission granted",Toast.LENGTH_LONG).show();

}

public void goTo(View view) {
    Intent intent = new Intent(this, MainActivity.class);
    this.startActivity(intent);
}

}

A:
Android SharedPreferences allows us to store private primitive
  application data in the form of key-value pair.For More details follow this.

To read from shared preference use something like this.
String dateFromSharedPreferences=getActivity().getPreferences(Context.MODE_PRIVATE);
sharedPref.getString("Username");

To save into shared preference
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("Username", YourUsername);
    editor.putString("Password", YourPassword);
    editor.apply();

You are passing the values from LoginActivity to MainActivity so code in MainActivity at onCreate function like following to get the passed values ans show in textview.
((TextView)findViewById(R.id.tv1)).setText(getIntent().getExtras().getString("full_name"));
((TextView)findViewById(R.id.tv2)).setText(getIntent().getExtras().getString("email_id"));
((TextView)findViewById(R.id.tv3)).setText(getIntent().getExtras().getString("gender"));

A: SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;

Write this code before going to intent.
sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
            editor = sharedPreferences.edit();
            editor.putString("User_Name", f_name);
            editor.putString("User_Email", email_id);
            editor.apply();

A: I know this type of question so many answer but still i am give this question's answer, I hope some one got the help. It's easy if we create method to handle all data.
When receive facebook JSON object then after do as follow.
try {
        Bundle bFacebookData = getFacebookData(object);
        progressDialog.dismiss();
        progressDialog.cancel();
        setSessionData(bFacebookData);

    }catch (JSONException e){
        e.printStackTrace();
    }

//here you can get all facebook data and store in bundle
private Bundle getFacebookData(JSONObject object)
    {
        try {
            Bundle bundle = new Bundle();
            //String id = object.getString("id");

            try
            {
                URL profile_pic = new URL("https://graph.facebook.com/" + object.getString("id") + "/picture?width=200&height=150");
                Log.i("profile_pic", profile_pic + "");
                if (profile_pic.toString() != null)
                {
                    bundle.putString("profile_pic", profile_pic.toString());
                }
                else
                {
                    bundle.putString("profile_pic", "noProfilePic");
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            }

            if (object.has("id"))
            {
                if (object.getString("id") != null)
                {
                    bundle.putString("userId", object.getString("id"));
                    Log.i(TAG, "Info " + object.getString("id"));
                }
                else
                {
                    bundle.putString("userId", "noUserId");
                    Log.i(TAG, "Info " + object.getString("id"));
                }
            }
            if (object.has("first_name"))
            {
                if (object.getString("first_name") != null)
                {
                    bundle.putString("first_name", object.getString("first_name"));
                    Log.i(TAG + "Info", object.getString("first_name"));
                }
                else
                {
                    bundle.putString("first_name", "noFirstName");
                    Log.i(TAG + "Info", object.getString("first_name"));
                }
            }
            if (object.has("last_name"))
            {
                if (object.getString("last_name") != null)
                {
                    bundle.putString("last_name", object.getString("last_name"));
                    Log.i(TAG + "Info", object.getString("last_name"));
                }
                else
                {
                    bundle.putString("last_name", "noLastName");
                    Log.i(TAG + "Info", object.getString("last_name"));
                }
            }

            if (object.has("email"))
            {
                if (object.getString("email") != null)
                {
                    bundle.putString("email", object.getString("email"));
                    Log.i(TAG + "Info", object.getString("email"));
                }
                else
                {
                    bundle.putString("email", "noEmail");
                    Log.i(TAG + "Info", object.getString("email"));
                }
            }

            //this is added dynamically
            bundle.putString("phone", "noPhone");

            if (object.has("gender"))
            {
                if (object.getString("gender") != null)
                {
                    bundle.putString("gender", object.getString("gender"));
                    Log.i(TAG + "Info", object.getString("gender"));
                }
                else
                {
                    bundle.putString("gender", "noGender");
                    Log.i(TAG + "Info", object.getString("gender"));
                }
            }

            if (object.has("birthday"))
            {
                if (object.getString("birthday") != null)
                {
                    bundle.putString("birthday", object.getString("birthday"));
                    Log.i(TAG + "Info", object.getString("birthday"));
                }
                else
                {
                    bundle.putString("birthday", "noDateOfBirth");
                    Log.i(TAG + "Info", object.getString("birthday"));
                }
            }

            if (object.has("location"))
            {
                if (object.getJSONObject("location").getString("name") != null)
                {
                    bundle.putString("location", object.getJSONObject("location").getString("name"));
                    Log.i(TAG + "Info", object.getJSONObject("location").getString("name"));
                }
                else
                {
                    bundle.putString("location", "noLocation");
                    Log.i(TAG + "Info", object.getJSONObject("location").getString("name"));
                }
            }

            return bundle;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return null;
    }

//here you can store data in SharedPreferences and start new activity
String userId = "", userEmail = "", userFirstName = "", userLastName = "",
            userPhone = "", dateOfBirth = "", gender = "", profilePic = "";

    private void setSessionData(Bundle bundle)
    {
        try
        {
            userId = bundle.getString("userId");
            userEmail = bundle.getString("email");
            userFirstName = bundle.getString("first_name");
            userLastName =  bundle.getString("last_name");
            userPhone = bundle.getString("phone");
            dateOfBirth =  bundle.getString("birthday");
            gender =  bundle.getString("gender");
            profilePic =  bundle.getString("profile_pic");

            if (userId !=null)
            {

                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.putString("userId", userId);
                editor.putString("email", userEmail);
                editor.putString("first_name", userFirstName);
                editor.putString("last_name", userLastName);
                editor.putString("phone", userPhone);
                editor.putString("birthday", dateOfBirth);
                editor.putString("gender", gender);
                editor.putString("profile_pic", profilePic);

                editor.apply();

                Intent i = new Intent(activity, MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(i);
            }
            else
            {
                //"Some thing went wrong Please try again"
            }
        }
        catch (Exception e)
        {
            e.printStackTrach();
        }
    }

Your another class to receive data from SharedPreferences
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);

((TextView)findViewById(R.id.tv1)).setText(sharedPreferences.getString("first_name", ""));
((TextView)findViewById(R.id.tv2)).setText(sharedPreferences.getString("last_name", ""));


text:
Q: Grow from center I have been trying to get the bottom circles to grow in Firefox (need to add in other prefixes, still in dev)
They are behaving properly, but my goal is to get them to grow from the center. Any ideas on how i can use CSS to do that? Would it be a positioning thing? The link is here: http://www.catonthecouch.com/feline/
I am simply growing the width/height on hover.

A: If you are using CSS3, you can use the property transform, and scale the element.
Obs: I have omitted the prefixes to avoid too much code, but you should use them.
.circle {
    width: 500px;
    height: 500px;
    border-radius: 100%;
    transform: scale(0.1); /* 1/10 of the original size */
    transition: all 1s ease-in-out;
}
.circle.opened {
    transform: scale(1);
}

Working demo: http://jsfiddle.net/JCMais/eKs59/

A: Add negative left and top margins equal to half of the change in size (-15px)


text:
Q: I want to search and find the location and weather details in weather map I have added one text box and search button into this application.I want enter a location and click search button then it shows the appropriate location with weather details. I tried in many ways but won't works. So any one have the code, then please share with me.
Thank you.
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Weather layer</title>

      <form id="form1" runat="server">

  <asp:Button ID="Button1" runat="server" Text="Proceed" />
          <input id="searchTextField" type="text" size="50"style="height:auto;width:320px;">
          </form>

A: Instead of removing your column, you can hide it by
protected void Button4_Click(object sender, EventArgs e)
{
   GridView1.Columns[2].Visible = False;
}

However, since its giving you an Index was out of range exception, the third column might not exist in your grid. Seems like you want to hide the second column and so you should write
GridView1.Columns[1].Visible = False;

since the index of grid columns start from zero.


text:
Q: Exchanging WebRTC RTCPeerConnection signals manually I read that RTCPeerConnection doesn't care about the transport mechanism chosen to exchange signals (websocket, google channel, etc..). Do you think it would be possible to collect those signals, encode them with JSON and ask the user to send them to the other peer using an external mechanism (chat, email, ...) in order to completely bypass the need of a remote server?
I've done a little POC and this seems working only when both peers are on the same machine; any clue?
Thanks!

A: Yes. As long as each client receives the other client's SDP (which includes the ICE Candidates), you should be able to establish a PeerConnection. WebRTC is decoupled from the Signalling mechanism the application developers adopt. But it is imperative that these signals are transmitted, so that each client knows which IP-Port combination it should be paying attention to.
Now requesting the users to manually exchange and process these signals might turn out to be a tedious task. I'd recommend setting up a simple Server using Socket.io that would let you relay the signals with ease. You can always use AJAX Polling too.

A: Yes you can send it over email or any other transport. I don't think the result for the user will be the best, but it's one way to do it.
I would explain to you that the user that receives the SDP offer, must enter it in the browser, get the SDP answer, and send it back to the user that started the request. But I assume that when you say it works locally, you are doing all that.
You must wait for the ICE candidates too, as you are sending the offer and answers one time only, in order to allow peers to connect.

A: Yes you can. SDP is just a bunch of text, so you can choose any medium you want. An important piece of the SDP are ICE candidates, which I recommend including as part of the SDP; so it can all be send as one big string over medium of your choice(ajax, websockets, etc...).
Note that first SDP that you get from calling createOffer is not going to contain ICE candidates. You have to wait until "onicecandidate" callback gets called at least once to have some ICE candidates. Then you call createOffer again on your peer connection, which will then have all information(ICE candidates plus rest of SDP).
Also note that onicecandidate will be called as many times as needed until all of the local ICE candidates are figured out, so you could wait all for all of them until then to generate a complete SDP offer to send to the other side.

A: Yes. Some points of interest are setLocalDescription(), setRemoteDescription(), createOffer(), and createAnswer().
Here's a proof-of-concept:
https://github.com/cjb/serverless-webrtc/
Live demo:
http://cjb.github.io/serverless-webrtc/serverless-webrtc.html

A: disclaimer: I work at Pusher.
Yes you can send it over any transport. However, websockets is a pretty good option these day since most of the browser support it.
As mention by @Vishnu, you can setup a socket.io server or if you don't want to go through the hassle of setting that up, you can use hosted solutions like Pubnub or Pusher. I wrote a webRTC signaling tutorial using Pusher and thus Webosckets (+fallbacks) if you are interest.
http://pusher.com/tutorials/webrtc_chat

A: No - as I understand it, you can't simply email Session descriptions.
ICE establishes the best route between peers, and I think the amount of ICE candidates may differ according to both client's current network situation.
If ice candidates and session desc are received, and then the client moves physical location (joining a different wifi network, for example), it would render ice candidates useless - meaning that the clients cannot connect.
I'm not an expert, so could easily be wrong. That answer is just from the webrtc knowledge i have gained whilst setting up my own signalling system for 2 clients using webrtc...


text:
Q: How would I make it so that an individual person is the only one who can run a command with a discord bot? I have a debug command for my bot that prints all of the current stacks that are running. Problem is it also prints my bot token. Rather than making it so it doesnt print my token, i'd rather make it so the debug command can only be ran by me.
my program:
import discord
from discord.ext import commands
from discord.ext.commands.core import command
import youtube_dl
import traceback
from tabulate import tabulate

table = [['Song', 'Queued by', 'Duration']]

class music(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def join(self, ctx):
        await ctx.send("Hello!", ctx.author)
        if ctx.author.voice is None:
            await ctx.send("Join a voice channel please.")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)

    @commands.command()
    async def disconnect(self, ctx):
        await ctx.voice_client.disconnect()

    @commands.command()
    async def play(self, ctx, url):
        ctx.voice_client.stop()
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        YDL_OPTIONS = {'format':"bestaudio"}
        vc = ctx.voice_client

        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
            vc.play(source)

    @commands.command()
    async def pause(self, ctx):
        await ctx.voice_client.pause()
        await ctx.send("Music is paused.")

    @commands.command()
    async def online(self, ctx):
        await ctx.send("The bot is online.")

    @commands.command()
    async def debug(self,ctx):
        await ctx.send("You are: ")
        await ctx.send(ctx.author)
        await ctx.send("You are in the channel:")
        if ctx.author.voice:
            await ctx.send(ctx.author.voice.channel)
        else:
            await ctx.send("None")
        await ctx.send("Stack: ")
        for line in traceback.format_stack():
            await ctx.send(line.strip())

    @commands.command()
    async def resume(self, ctx):
        await ctx.voice_client.resume()
        await ctx.send("Music has been resumed.")

    @commands.command()
    async def queue(self, ctx):
        await ctx.send(tabulate(table, headers='firstrow'))

def setup(client):
    client.add_cog(music(client))

A: You can for example return when the user's id that used the command is not yours:
@commands.command()
async def debug(self, ctx):
    if ctx.author.id != "your id":
        return

    # The rest of your debug command


text:
Q: ARMv8: unaligned LDR in EL3 causes exception Data Abort I have the following bare-metal startup code for ARMv8 on FPGA, for testing the data alignment access:
.section .text.boot
.global _start
_start:
    mrs x0, mpidr_el1
    and x0, x0, #0xff
    cbz x0, master
    b proc_hang

master:
    ldr x1, =stack_top
    mov sp, x1

    // test unaligned assess
    mov x4, #0x3e61
    mov x1, xzr
    ldr w0, [x4, x1, lsl #0x2]

    bl main
    b .

proc_hang:
    wfe
    b proc_hang

Upon reboot/reset, EL is 3.
The ldr w0, [x4, x1, lsl #0x2] instruction above will trigger an Exception in EL3, and PC changes to 0x200, which is the 5th entry of the default VBAR_EL3 (0x0). This means the exception is CURR_EL_SPX_SYNC (meaning sync exception in the current EL3, using SP3, according to my current understanding).
At this time, the value of ESR_EL3 is set to 0x96000021, with in which the EC bits (Exception Class, bit 31:26) is 0b100101, means "Data Abort".
The current SCTLR_EL3 value, however, is 0x40c50838, within which the bit 1 is 0, meaning alignment check is disabled. My expectation is that, if alignment check is disabled, then the above LDR instruction should success without raising exceptions.
My questions are:

*

*is this expected behavior?

*is there other system registers to be set/checked?

Btw, I also tested different address for the above case, with the following result:

*

*0x3e60: ok

*0x3e61: Exception (PC=0x200)

*0x3e62: ditto

*0x3e63: ditto

*0x3e64: ok

*0x3e65: Exception (PC=0x200)

*0x3e66: ditto

*0x3e67: ditto

*0x3e68: ok

A: Alignment faults can be configured to fault or no-fault for accesses to Normal memory only by setting SCTLR_ELx.A bit. Unaligned access to "Device" memory cannot be configured and will always cause fault if address is unaligned. In MMU On configuration, Device or Normal memory type can be configured by programming appropriate bits in MAIR_ELx and translation system takes care of assigning these properties to memory.
In case of MMU off, translation system assigns Device-nGnRnE attribute for data accesses and assigns Normal memory attribute for instruction access.
In your case you are running in MMU off configuration, translation system assigns Device-nGnRnE attribute and so the fault. Refer VMSA (Chapter 5, section D5.2.9) in Arm Arm for more details.


text:
Q: How to check if content exists in iframe with external source

I want to detect with JQuery whether i got content from other website in my iframe or not?
I have tried different things, nothing helped.
Thanks.

A: $("#myiframe").contents().find("#myContent")

<title></title>


text:
Q: How to go back to parent array in a reference? $a = [

  [

    [

    ]

  ],

  [

    [

    ]

  ]

];

If I have a reference to an element deep in the array, for example:
$ref = &$a[1][1];

how can I go back to the parent array, in this case &$a[1] ?
I'm assigning the reference by relying on a counter variable that increases or decreases. The problem comes when I decrease, then I need to go back to the parent array :(
I think I got it:
      $new_ref = &$a;
      $i = 0;
      while($i < $counter - 1){
        $new_ref = &$new_ref[count($new_ref) - 1];
        $i++;
      }

      $ref = &$new_ref;

but it doesn't seem to work right lol.
I dont know why, the logic is ok. I'm using a new reference to climb up the array until near the last level :/

A: One cannot "go back" like this.
The child array does not know the of the parent array implicitly, reference or not.
To create such a cyclic dependency requires explicitly establishing the cycle - usually where such is done it is with a custom class (e.g. a control has a Parent control and many Children controls) and not an array.
I would try to avoid such a cyclic graph and restructure the design - this is because it feels (and especially without an actual use-case) that such an approach is creating uncessary complexity.

A: Arrays are simple things. We can put many variables inside an array, we can even name the locations that we store this information - but they are not related in an object sense to one another.
The structure that is used in accessing data in arrays is simply there to make it more intuitive to anyone reading the code.
Any element of an array is in fact simply a snippet of information with a specific address. While it may be intuitive to think that as one bit of information is inside an array, which is inside another array - all it really means that has happened is that the information inside one part of the array is more complex and can be accessed more precisely.
Classes and Objects on the other hand... this is where parent/child relationships can and DO occur.
Passing by reference is no different:
$ref = &$a[1][1];

Simply means - any changes to $ref are changes to $a[1][1]. Whether it is in a function (which would normally make it outside of scope) or whether it is simply a shorter way to write the variable $a[1][1] in the rest of your code.


text:
Q: Efficient incremental hash computation during program interpretation I'd like to write a recursively memoizing Scheme interpreter. At any point during evaluation, the interpreter should be able to detect when it receives as arguments a pair of expression and environment that it has previously seen.
Plain memoization of eval and apply is inefficient. It would require looking up the arguments in a hash table on every call of eval/apply, which would require walking the entire (possibly big) arguments on hash table matches.
For example, assume that the interpreter evaluates the program
(car (list A))

where A evaluates to a big object. When the interpreter evaluates the application (list A), it first evaluates list and A individually. Before it applies list to A, it looks up in its hash table whether it has seen this application before, walking the entire A object to compute a hash. Later on, when the memoizing interpreter applies car to the list containing A, it computes a hash for this list which again involves walking the entire A object.
Instead, I want to build an interpreter that incrementally builds up approximately unique hashes, avoiding recomputation where possible and providing a guarantee that collisions are unlikely.
For example, one could recursively extend each object that the interpreter operates on with the MD5 of its value, or, if it is a compound object, with the MD5 of its component hashes. An environment might store the hash for each of its variable/value entries, and the hash of the environment might be computed as a function of the individual hashes. Then, if an entry in the environment changes, it is not necessary to rewalk the entire environment to compute the new hash of the environment. Instead, only the hash of the changed variable/value pair needs to be recomputed and the global hash of the set of entry hashes needs to be updated.
Does there exist related work on incrementally building up approximately unique hashes, in particular in the context of recursive memoization and/or program evaluation?

A: Note that if expressions are immutable (no self-modifying code allowed) then you can use EQ equality on them. If environments are immutable, you can treat them likewise. EQ equality is fast since you're just taking the bits from the machine pointer to be a hash.
The problem then are assignments which mutate environments, causing expressions values to change. If they are allowed, how do deal with this.
One way would be to make a note of environments that contain destructive code in their lexical scopes and somehow annotate them so that the evaluator can recognize such "polluted environments" and not do the caching for them.
By the way, you obviously want hash tables with weak semantics for this so that any objects that become garbage do not pile up in memory.


text:
Q: Change multiple rows and column values at the same time with Python Pandas I want to change the values of 9 members of a 10x10 pandas dataframe, preferably at the same time. I have a 3x3 matrix of values, let's say:
>>> import numpy as np
>>> import pandas as pd

>>> xx = np.array(range(1, 10)).reshape(3, 3)
>>> xx
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

Now I have a 10x10 zeros Dataframe df:
>>> df = pd.DataFrame(np.zeros(100).reshape(10, 10), index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], columns = ['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y'])
>>> df
     p    q    r    s    t    u    v    w    x    y
a  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
b  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
c  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
d  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
e  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
f  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
g  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
h  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
i  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
j  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0

I want to insert the 3x3 matrix xx at rows "b", "d" and "g", and at columns "t", "v", and "w", where these intersect, so that it looks like this afterwards:
     p    q    r    s    t    u    v    w    x    y
a  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
b  0.0  0.0  0.0  0.0  1.0  0.0  2.0  3.0  0.0  0.0
c  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
d  0.0  0.0  0.0  0.0  4.0  0.0  5.0  6.0  0.0  0.0
e  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
f  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
g  0.0  0.0  0.0  0.0  7.0  0.0  8.0  9.0  0.0  0.0
h  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
i  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
j  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0

Is this doable in a single step or a few efficient steps?

A: You are looking for the update method:
import numpy as np
import pandas as pd

df = pd.DataFrame(np.zeros(100).reshape(10, 10),
                  index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
                  columns = ['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y'])

xx = np.array(range(1, 10)).reshape(3, 3)
xx = pd.DataFrame(xx, index=['b', 'd', 'g'], columns=['t','v','w'])

df.update(xx)
df

Output:
      p   q   r   s   t   u   v   w   x   y
a   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
b   0.0 0.0 0.0 0.0 1.0 0.0 2.0 3.0 0.0 0.0
c   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
d   0.0 0.0 0.0 0.0 4.0 0.0 5.0 6.0 0.0 0.0
e   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
f   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
g   0.0 0.0 0.0 0.0 7.0 0.0 8.0 9.0 0.0 0.0
h   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
i   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
j   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0

The documentation explains more in detail: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html


text:
Q: Issue with returning records back to a web service I am having some issues in attempting to display a recordset from my webservice.
Currently my application involves a client feeding their values into my webservice.
The webservice will then call a vb.net database class, which executes a SQL stored procedure, returns a recordset to the database class, and the class will pass the recordset back to the webservice, which will display it to the client in xml.
The problem I am having passing the recordset from the database class back to the webservice in a format that can be sent back to the client. I can't seem to convert the recordset to string format. Would it be better to have the record returned in XML format?
Any ideas?

A: I think .NET has already done most of the work for you. If your vb.net class returns a DATASET object, you already have an XML object. You may want to do some transformations on it, but the XML is already there.
Look for the dataset.GetXML method.


text:
Q: Can't get textboxes to autofill from a listbox I have a form called frmReferrals that has three text boxes bound to fields on a table called tblReferrals. I'm trying to use a listbox called List_HRPO to autofill the three textboxes. The source for the listbox is three columns from a table called tblStudies. I want the user to click on a row in the listbox and auto fill the three text boxes. I also need those values to be written to frmReferrals. Simple, right?
Here's my code:
Private Sub List_HRPO_Click()
    Me.hrpo_number = Me.List_HRPO.Column(0)
    Me.hrpo_short_title = Me.List_HRPO.Column(1)
    Me.ccir_number = Me.List_HRPO.Column(2)
End Sub

Here's my problem:
With the textboxes bound to the table, when I click on a listbox row I get:

"Run-time error '-2147353567 (80020009)': Cannot enter value into
blank field on 'one' side of outer join"

I'm not basing anything off a query, so I don't understand where this "outer join" is.  I can avoid the error by unbinding the textboxes. The textboxes auto fill as expected, but the values in the textboxes aren't being written to the table.
I'd greatly appreciate any help. I'm missing a deadline because of this! Thanks.

A: I think, error occurs in this code Me.hrpo_number = Me.List_HRPO.Column(0)
Most likely, field hrpo_number is key field (identity) of table tblRefferals. As a rule, this column cannot be updated by the user - will generated by Access as incremental value in this column, before inserting new record to table (in this case tblRefferals).
Private Sub List_HRPO_Click()
    ' comment this row. hrpo_number will be updated on "BeforeInsert" event
    'Me.hrpo_number = Me.List_HRPO.Column(0)
    Me.hrpo_short_title = Me.List_HRPO.Column(1)
    Me.ccir_number = Me.List_HRPO.Column(2)
End Sub

Without seeing the database schema, it's hard to say what needs to be changed. Definitely - do not change the identity field in the tables.
Perhaps the value assigned by Access DBMS is quite suitable.
If this is not the case, add three text boxes datasource to question. May be field ccir_number is link to another table.


text:
Q: Problems with Reflection on winforms I have a winforms application.
I have a Populate method that creates a bunch of controls on each page on my tabcontrol. The Populate method takes two arguments - the tab page and a List with the strings for a bunch of labels. There is a separate List for each tabpage and the names of the Lists are the same as the names of the tabpages. I want to iterate through the pages and pass the appropriate List to the Populate method by name, i.e. to pass the List by a string that is its name. As far as I know I need Reflection for that.
Code:
namespace Test
{
    public partial class Form1 : Form
    {
        List<string> Hongdoe = new List<string>(new string[] { "Chin", "Foa", "Hu", "Dan" });
        List<string> Donfu = new List<string>(new string[] { "Faa", "Su", "Pi", "Mou" });
        //TabPage1.Name = Hongdoe
        //TabPage2.Name = Donfu
        foreach (TabPage tp in Tab_Control.TabPages)
        {
            //I want to tell the program "Find the variable/list that is named as 'tp.Name'
            var ListName = typeof(Form1).GetField(tp.Name)
            Populate(tp, ListName);
        }

    }

    void Populate (TabPage tp, List<string> list)
    {
        for (int i = 0; i < list.Count; i++)
        {
            //Create labels
            Label lab = new Label();
            lab.Text = list[i];
            lab.Location = new Point(i * 10, i * 10));
            tp.Controls.Add(lab);
        }
    }
}

But sofar it returns null. I also tried using "GetProperty", "GetValue" but no success.
(before I edited this question I used a variable to demonstrate my problem simply)

A: You don't need to use reflection. You can use a Dictionary<string, List<string>> and use list names (tab page names) as keys and list of strings as values. Then you can get a list using the key from dictionary.
Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
private void ProductList_Load(object sender, EventArgs e)
{
    //Initialize dictionary with keys and values
    dictionary["page1"] = new List<string> { "string 1", "string 2" };
    dictionary["page2"] = new List<string> { "string 3", "string 4" };
    //...
}

Then you can call your Populate method this way:
Populate(tp, dictionary[tp.Name]);

Note

*

*You don't need to pass list to the method and it's enough to pass TabPage to the method and you can get the list using dictionary[tabPage.Name]

*You can use a TableLayoutPanel or a FlowLayoutPanel in tab pages to add labels to. This way they will be arranged automatically.

*Just for learning purpose if you want to use reflection:
var list = (List<string>)this.GetType().GetField("Hongdoe",
    System.Reflection.BindingFlags.NonPublic |
    System.Reflection.BindingFlags.Instance).GetValue(this);