text:
Q: Particular WiFi network not detected I installed yesterday Ubuntu 18.04 in dual boot on a computer usually used with Windows 7.
Everything went fine, except that I am unable to connect to my WiFi network. The weirdest thing being that my Network card seems to work perfectly: Ubuntu's Network Manager detects all the surrounding WiFi networks, except for mine, which is called "WiFi-2.4-68B7".
I already tried different solutions, none worked:

*

*I configured "WiFi-2.4-68B7" in the "known networks" and tried to access it through the "Connect to hidden network tool".

*I checked whether Ubuntu was detecting my Network chipset correctly, which appears to be the case:

dd@dd:~$ sudo lspci
Network controller: Broadcom Inc. and subsidiaries BCM4313 802.11bgn Wireless Network Adapter (rev 01)

*I tried reinstalling the Broadcom driver for my BCM4313

dd@dd:~$ sudo apt-get --reinstall install bcmwl-kernel-source

*I also tried the solution proposed here, but with no result.

I am out of ideas to solve the problem. It should be noted I can connect just fine to my WiFi network when I boot from Windows 7, the problem is thus not from the hardware.
Does anyone have an idea?
Thank you!

A: Thanks to Jeremy31, it appeared that the problem came from the fact that my WiFi network was set to channel 13. After switching it back to a channel <11, I can now see the network and connect to it without problem.

A: Changing Channel fixed my problem. To see which channel is good for you, run this command on ubuntu.
sudo iwlist wlan0 scan | grep Frequency | sort | uniq -c | sort -n
if you encounter an error say, wlan0 doesn't support scanning then, run this command
ifconfig
make sure you have installed net-tools if you can't run ifconfig
sudo apt install net-tools
look for output -  two words wl mine was wlp2s0, so the command would be
sudo iwlist wlp2s0 scan | grep Frequency | sort | uniq -c | sort -n
The "sort -n" command will rank the channels in order of fastest to slowest
In the router, you change your channel.
then restart your network-manager
sudo service network-manager restart
Alternatively, you can also check if wifi is blocked -
https://unix.stackexchange.com/a/309753/330133

A: Perhaps its an issue over the type of Network? Are you connecting to a 5gHz or a 2.4gHz network? I know that I sometimes have issues with the 5gHz networks being picked up.  I had to you Wine to set up my drivers.  It sounds like you are technically more adept than I am so I won't bother giving you instructions on how I did that...unless you arent sure how to use wine. Then I would be happy to help/   Also check to see that windows is disconection from your network so the router knows to allow you to connect. You wouldnt be using static IP would you? if so that could be the case...


text:
Q: How to get Bootstrap Grid without gaps per row Attached is a screenshot of my bootstrap grid. I am wondering how to make the divs in the lower row to sit underneath the ones above without sitting on a new row.

This is a code snippet of each item

            <img class="img-responsive" src="<?php echo $row['ProductImage']; ?>" width="100%" alt="">

<?php echo $row['ProductName']; ?>

<?php echo $row['ProductText']; ?>

Thanks heaps

A: Place the ones you want to have aligned vertically in the same col and make their width 100%. They will wrap in that columns then. You might want to add some top margin at the top and bottom to simulate the gutter

redpajama_set_name: RedPajamaStackExchange


text:
Q: Something is fishy in this way of solving this equation in $\mathbb{C}$. While solving the equation
\begin{equation}
x^2 + a = 0
\end{equation}
in $\mathbb{C}$, where $a$ is a complex number, i wanted to explicitate the geometrical intuition behind this and overthought the whole thing as follows.
Let $z_1$ and $z_2$ be the solutions to the equation: we know that $z_1+z_2 = 0$ and $z_1z_2 = a$. So $z_1$ and $z_2$ are opposite points wrt the origin, and it has to be possible to get to them by rotating and scaling the points $(1,0)$ and $(-1,0)$, i.e. we can surely find a real number $\lambda$ and a rotation matrix $R_\theta$ such that
\begin{equation}
\lambda R_\theta\cdot\left(\begin{matrix}1\\0\end{matrix}\right)
 = z_1\qquad\text{and}\qquad \lambda R_\theta\cdot\left(\begin{matrix}-1\\0\end{matrix}\right)
 = z_2
\end{equation}
All seems nice and tame until I multiply the two equations:
\begin{equation}
\lambda
\left(
    \begin{matrix}
    \cos\theta & -\sin\theta\\
    \sin\theta & \cos\theta
    \end{matrix}
\right)
\left(\begin{matrix}1\\0\end{matrix}\right)
\cdot
\lambda
\left(
    \begin{matrix}
    \cos\theta & -\sin\theta\\
    \sin\theta & \cos\theta
    \end{matrix}
\right)
\left(\begin{matrix}-1\\0\end{matrix}\right)
= z_1z_2 = a
\end{equation}
because I get
\begin{equation}
\lambda
\left(
    \begin{matrix}
    \cos\theta\\
    \sin\theta
    \end{matrix}
\right)
\cdot
\lambda
\left(
    \begin{matrix}
    -\cos\theta\\
    -\sin\theta
    \end{matrix}
\right)
= -\lambda^2(\cos^2\theta+\sin^2\theta)=-\lambda^2=a
\end{equation}
which of course is true, but this equation tells us that $a$ is a negative real. It seems to me that this calculation hides the angle information in $\lambda$: indeed, if we allow $\lambda$ to be complex then of course we get the two solutions simply by solving $\lambda^2 = -a$.
At which step did the information on the angle get erased?
If I want to keep $\lambda$ real as a scaling factor, how can I retrieve the information on $\theta$?


text:
Q: Minimum width (CSS) I've got a header (width 100%) containing some links. When you resize the browser, the links will be displayed beneath each other when there is little space. I know I can use min-width for this problem, but I don't know the exact amount of space that the links will use, because they are dynamic. How can I solve this problem?

A: If your code is like this

   Link
   Link
   Link

You could have this CSS:
#links {
   white-space: nowrap;
}

This will prevent the links from wrapping to another line.
If your code not like this, you should post it with your question.

A: You haven't given a lot of detail, but it sounds to me like you need something to stop them wrapping.
In that case, you could try this:
.parentelement {
    white-space:nowrap;
}

which would apply to the container element of the fields you wanted to keep in line.


text:
Q: Install pymongo on macosx I want to install pymongo on my macosx. Using python -m pip install pymongo, I get this error message :
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/commands/install.py", line 317, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_set.py", line 732, in install
**kwargs
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_install.py", line 835, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_install.py", line 1030, in move_wheel_files
isolated=self.isolated,
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/wheel.py", line 344, in move_wheel_files
clobber(source, lib_dir, True)
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/wheel.py", line 315, in clobber
ensure_dir(destdir)
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir
os.makedirs(path)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/bson'

I get an other error message using easy_install
The following error occurred while trying to add or remove files in the installation directory:

[Errno 13] Permission denied: '/Library/Python/2.7/site-packages/test-easy-install-526.pth'

The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was:

/Library/Python/2.7/site-packages/

Perhaps your account does not have write access to this directory?  If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account.  If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable.

A: It's because you're not running it as root. The safest thing to do is use the "user" mode to install your requirements in your home directory.
E.g.:
python -m pip install --user pymongo


text:
Q: React Native: Change color of navigation tab On my navigation tab, I want to change the color of the label + the color of the icon when its active, so what I did is created an if and else statement:
<MealsFavTabNavigator.Screen
                    name="Favorites"
                    component={FavoritesScreen}
                    options={({ route }) => ({
                        tabBarIcon: (tabInfo) => {
                            if (route.name === 'Favorites'){
                                return <Ionicons name="ios-star" size={25} color='tomato'/>
                            } else {
                                return <Ionicons name="ios-star" size={25} color='black' />
                            }

                        }
                    })}

My label color is also fixed above the Navigator level:
    <MealsFavTabNavigator.Navigator
        tabBarOptions={{
            activeTintColor: Colors.primaryColor,
            inactiveTintColor: 'black',
        }}>

Here's my full code:
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import { Ionicons } from '@expo/vector-icons';

import CategoriesScreen from '../screens/CategoriesScreen';
import CategoryMealsScreen from '../screens/CategoryMealsScreen';
import MealDetailScreen from '../screens/MealDetailScreen';

import FavoritesScreen from '../screens/FavoritesScreen';

import HeaderButton from '../components/HeaderButton';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

import { CATEGORIES } from '../data/dummy-data';

import Colors from '../constants/colors';

const MealsNav = createStackNavigator();

const MealsNavigator = () => {
    return (
        <MealsNav.Navigator
            mode="modal"
            screenOptions={{
                headerStyle: {
                    backgroundColor: Colors.primaryColor,
                },
                headerTintColor: '#fff',
                headerTitleStyle: {
                    fontSize: 17
                }
            }}
        >
            <MealsNav.Screen
                name="Categories"
                component={CategoriesScreen}
                options={{
                    title: 'Meals Categories'
                }}

            />
            <MealsNav.Screen
                name="CategoryMeals"
                component={CategoryMealsScreen}
                options={({ route }) => {
                    const catId = route.params.categoryId;
                    const selectedCategory = CATEGORIES.find((cat) => cat.id === catId);

                    return {
                        title: selectedCategory.title,
                    };

                }}
            />
            <MealsNav.Screen
                name="MealDetail"
                component={MealDetailScreen}
                options={{
                    title: 'Meal Detail',
                    headerRight: () => (
                        <HeaderButtons HeaderButtonComponent={HeaderButton}>
                            <Item
                                title='Favorite'
                                iconName='ios-star'
                                onPress={() => console.log('Mark as the favorite')}
                            />
                        </HeaderButtons>
                    ),
                }}
            />
        </MealsNav.Navigator>
    );
};

const MealsFavTabNavigator = createBottomTabNavigator();

const MealsTabNav = () => {
    return (
        <NavigationContainer>
            <MealsFavTabNavigator.Navigator
                tabBarOptions={{
                    activeTintColor: Colors.primaryColor,
                    inactiveTintColor: 'black',
                }}>
                <MealsFavTabNavigator.Screen
                    name="Meals"
                    component={MealsNavigator}
                    options={({ route }) => ({
                        tabBarIcon: ({ color }) => {

                            if(route.name === 'Meals'){
                               color = 'tomato'
                            } else if (route.name === 'Favorites') {
                                color = 'black'
                            }
                             return <Ionicons name="ios-restaurant" size={25} color={color}/>
                        }
                    })}
                />
                <MealsFavTabNavigator.Screen
                    name="Favorites"
                    component={FavoritesScreen}
                    options={({ route }) => ({
                        tabBarIcon: (tabInfo) => {
                            if (route.name === 'Favorites'){
                                return <Ionicons name="ios-star" size={25} color='tomato'/>
                            } else {
                                return <Ionicons name="ios-star" size={25} color='black' />
                            }

                        }
                    })}
                />
            </MealsFavTabNavigator.Navigator>
        </NavigationContainer>
    );
};

export default MealsTabNav;

How can I change the color of the label and color of the iconicons when its active? My solution doesnt work.

A: By default there are parameters for colors in tabbar icon and tabbar label and these are set to the active tint color and inactive tint color.
But if you have a requirement to override this you can do the following
 <Tab.Screen
    name="Feed"
    component={Feed}
    options={{
      tabBarLabel:({ focused,color })=>(<Text style={{color:focused?"red":"aqua"}}>1232</Text>),
      tabBarIcon: ({ focused,color, size }) => (
        <MaterialCommunityIcons name="home" color={focused?"green":"blue"} size={size} />
      ),
    }}
  />

References on the props
tabBarLabel can be a text or a react node, and you get the focused and the color as arguments, The color will be the color you set as activetintcolor or inactivetintcolor.
focused is a boolean on whether the tab is focused or not.
Same arguments are passed to the tabBarIcon only difference is the size which is the size of the icon.
If you see the code above, I have given custom colors based on focused without using the color that is passed. You can do this as per your requirement.

A: https://stackoverflow.com/a/63033684/17735463 - This is a valid answer but mine works fine too (react-navigation-v5)
<Tab.Navigator
     screenOptions={({ route }) => ({

          tabBarIcon: ({ focused }) => {
            let iconName;
            let size=25;
            let color = focused ? 'black' : 'gray';
            if (route.name === 'HomeScreen') {
              iconName = 'ios-home';

              return <Ionicons name={iconName} size={size} color={color} />;
            } else if (route.name === 'FavoritesScreen') {
              iconName = 'star';

              return <AntDesign name={iconName} size={size} color={color} />;
            }

          tabBarLabel: ({ focused }) => {
            let titleStyle = {
              fontSize: 12,
              fontWeight: focused ? 'bold' : '500',
              color: focused ? 'black' : 'gray',
            };
            if (route.name === 'HomeScreen') {
              return <Text style={titleStyle}>Home</Text>;
            } else if (route.name === 'FavoritesScreen') {
              return <Text style={titleStyle}>Favorites</Text>;
            }
          },

})}>

<Tab.Screen name='Home' component={HomeScreen}/>
<Tab.Screen name='Favorites' component={FavoritesScreen}/>

</Tab.Navigator>


text:
Q: GraphViz, Zest, JUNG2 et cetera for Java Firstly, my goal is to use a library ONLY for laying out nodes in a JavaFx application, so that the size of the node (or box, in my case) is taken in account in laying out.
I tried JUNG2, but wasn't very impressed by it's layout methods.. I would've needed to write one myself to have the results I wanted, which is precisely what I am trying to avoid (because I'm probably not smart enough to write a good one..).
So, now I am looking at GraphViz and Zest.
GraphViz looks like a very impressive and complex beast.
Zest looks interesting too, but how Eclipse-centric is it? Can I use this in a JavaFx application?
Are there others out there? What would you recommend in my case?

A: OK, I have investigated and implemented a Zest-based approach to my problem. Zest runtime is only 800kb, has a nice API and very little dependencies, and, with my own simple collision detection method, works like a wonder. I can post the code if anyone is interested..

A: I am on the same topic as you are. I recommend GraphViz. Its complex but very powerful and the outcome is very good. I also used Zest, Jung and graphX. The results of all those did not impress me very much. The resulting layout depends on the size of your graph. If you have a complex graph GraphViz would lead to the best results.


text:
Q: Firebase Functions - cannot read req.body I'm having a problem with my Firebase Functions https request.
This is my code to trigger it:
  const express = require('express');
  const bodyParser = require('body-parser');
  const app = express();
  app.use(bodyParser.json());
  app.use(function(req, res, next) {
    res.setHeader('Content-Type', 'application/json');
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "GET, POST");
    next();
  });
  app.use((err, req, res, next) => {
    if (err instanceof SyntaxError) {
      return res.status(400).send();
    };

    next();
  });
  app.post('/fetchPosts', (req, res) => {
    exports.fetchPosts(req, res);
  });

  exports.widgets = functions.https.onRequest(app);

  const cors = require('cors')({ origin: true })
  exports.fetchPosts = (req, res) => {
      console.log(req.body)
      console.log(res)
    let topics = req.body.topics || ['live'];
    let start = req.body.start || 0;
    let num = req.body.num || 10;
    let next = start+num;
    // setting up the response.
  });

That looks good as far as I can tell..
Now when I do my api call I do:
   var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Content-Type', 'application/json; charset=UTF-8');
    const request = new RequestOptions({ headers: headers });
    const url = 'https://my-link.cloudfunctions.net/widgets/fetchPosts';
    let payload = {
        topics: ["live", "pets"]
    }
    console.log(JSON.stringify(payload))
    this.http.post(url, JSON.stringify(payload), request)
    .pipe(map((res:Response) => {
      console.log(res.json())
    }))
    .subscribe(
      data => console.log(data),
      err => console.log(err),
      () => console.log('Got feed')
    );

and it just returns topics with just ['live'].. because of the failsafe that I set up on the backend.. but why isn't getting my topics that I'm sending?
Also, when I console.log(req.body) on the backend it just shows {}.. an empty object..
Any ideas why the req.body doesn't seem to work? I do it with start and num as well, but they all revert back to the failsafe.

A: You must use POST method to handle req.body . In your case, you can handle your variable with req.query
To handle req.body . You can use Postman, then select POST method and post data as JSON . You can read more to use Postman well.


text:
Q: react-syntax-highlighter is not working with TailwindCSS I am displaying sanity block content using [@sanity/block-content-to-react](@sanity/block-content-to-react). The BlockContent component is wrapper by div with class of "prose".

     <BlockContent
         // Pass in block content straight from Sanity.io
          blocks={singleBlog.body}
          serializers={serializers}
      />

In my serializers, I am passing custom  component.
  const serializers = {
    types: {
      code: (props) => ,
    },
  };

In my custom code component, I am using Syntax Highlighter to wrap by code content.
      <SyntaxHighlighter style={theme} language={props.node.language}>
        {props.node.code}
      </SyntaxHighlighter>

But, no matter which theme I choose, it only changes the background colors and font sizes but has no effect in text colors.

I thought 'prose' class on wrapper div was causing the problem. But remove that didn't work either.
          {/*
 */}
          <BlockContent
            // Pass in block content straight from Sanity.io
            blocks={singleBlog.body}
            serializers={serializers}
          />
          {/*
 */}

Does anyone have any solution ?

A: I am not sure if you are using a custom theme or if you are using one of the many option. But if you are using the available one that you can find here: https://react-syntax-highlighter.github.io/react-syntax-highlighter/demo/prism.html
Then it may be a problem with your imports.
If I import the theme like that (using the hljs ): import {dark} from "react-syntax-highlighter/dist/esm/styles/hljs"; I only get background color.
If I import the theme like this using the 'prism' option I get the text color too: import {dark} from "react-syntax-highlighter/dist/esm/styles/prism";


text:
Q: What makes excimer lasers so complex, rare and expensive? We all can agree that UV lasers are extremely useful, but we (poor majority) are still struggling with 355nm DPSS ones, while excimer lasers being prohibitively expensive (let's say at 1-10W average power, or 100Hz @ 0.1J pulse).
What is the reason for this? What is the complexity, making excimer lasers (namely, 248nm KrF / 308 XeCl ones) so complex?
Mirrors & optics is simpler than for CO2 ones, gas is not expensive too... What am I missing?
Just reread my laser optics book - it needs aggressive laser pumping (50kV @10-30ns pulses), forced 'gas mixing' (just like in high-power CO2 ones), also needs preionization, but nothing too scary...

A: Interestingly exicmer laser development was originally funded, in part, due to interest in inertial confinement fusion.
Original excimer lasers required: rare-gas atoms (e.g., Xe) at high pressures, 10 atm; very high voltages, 400 keV, were required to create an electron beam through a metal foil; high current densities, on the order of 1000 amps/cm$^2$, were required to reach sufficient laser gain. Unfortunately they did not scale appropriately so fast-discharge lasers were then pursued.
The Navy, for communication applications, as well as interest in molecular laser isotope separation, helped spur development of laser discharge technology. Pre-ionized laser discharge requires a very fast high-voltage pulse that is controlled by a very fast and complex circuit. The problem with sparking is the creation of dust and erosion of the spark source and that they cannot sustain long-term operation. Thyratrons in combination with a magnetic switch are required to reach 100 Hz. Reaching 10 W in a KrF lasers was reached by replacing the pre-ionization source with a corona discharge.
Thyratrons were gradually replaced by thyristors. New pulsed power circuitry has been developed. New ways of delivering the gases, specifically the halides, has been developed. The expenses have been dropping over time, but the expensive parts today are the circuitry required for handling the fast pulses and high voltages, the gas handling system (halides are dangerous and corrosive and must be replenished often during operation), cooling systems, a sufficiently inert laser discharge chamber and the parts of the laser must be designed to be easy to repair and replace.

A: This laser is a type of ultraviolet laser often used in UV photolithography in eye surgery.
The term excimer comes from excited dimer English (excited dimer)
This uses a combination of inert gas such as argon, krypton or xenon, with reactive gas. Under appropriate conditions of electrical stimulation, a pseudo-molecule is formed, which exists only in an excited state and can cause laser light in the ultraviolet range.
The excimer laser removes tissue with an accuracy of 0.25 microns. Currently in the second decade of use, the technologically sophisticated Excimer Laser has added a tremendous range of precision, control and security for the correction of vision errors. Using this remarkable technology, the cornea is reshaped to suit the requirements of your glasses or lenses, while reducing or eliminating dependence on corrective lenses for life.
Ultraviolet light from the excimer laser is absorbed well into tissues and organic compounds. Instead of cutting or burning, the excimer laser has enough energy to separate the bonds between molecules of the tissues. The excimer laser has the ability to lift or remove small and thin layers of cells without damaging tissue. is rare because most of excimer lasers (like this) are of noble gas halides.
and is complicated by the action of laser excimer molecule is because it has an associated state excited but also has a non-associative.
this is because the noble gases like xenon and krypton are inert and do not tend to form chemical compounds. However, in an excited state molecules can be temporarily linked with themselves (dimers) or halogen atoms such as fluorine and chlorine (forming complexes excited). I hope this serves as an answer.


text:
Q: Replacing values in column with values in lookup table of column names conditionally I am working with two tables:
t1<-data.frame(Name=c("Waldo","Mark","Harold","Earl"),Number=c(1,4,3,9))

and
t2<-data.frame(Whatever=c("does","not","really","matter","at","all"),Waldo=c(0,1,1,0,0,1),Mark=c(1,0,1,1,0,0),Harold=c(0,1,0,0,0,0),Earl=c(1,1,1,1,0,0),Extra=c("another","column","appearing","in","this","table"))

What I would like to do is replace the 1's in t2 with the lookup values from t1.  The column names for t2 appear as records in t1. All 0 values in t2 should stay intact.
In my true data, there are hundreds of columns in t2, and hundreds of rows in t1.
There are also several columns in t2 that should not be impacted by this coding, but should remain in the final output.
Is there a best practice for coding this?
Desired output for the example is below:
Whatever   Waldo  Mark  Harold  Earl  Extra
does       0      4     0       9     another
not        1      0     3       9     column
really     1      4     0       9     appearing
matter     0      4     0       9     in
at         0      0     0       0     this
all        1      0     0       0     table

Thank you in advance!

A: This should be flexible enough for your actual dataset:
my_function <- function(df, lookup) {
  for(i in names(df)) {
    df[[as.character(i)]][df[[as.character(i)]] == 1] <- lookup$Number[lookup$Name == as.character(i)]
  }
  return(df)
}

my_function(t2, t1)
#   Whatever Waldo Mark Harold Earl     Extra
# 1     does     0    4      0    9   another
# 2      not     1    0      3    9    column
# 3   really     1    4      0    9 appearing
# 4   matter     0    4      0    9        in
# 5       at     0    0      0    0      this
# 6      all     1    0      0    0     table

A: Here's a tidyverse workflow that may be a little excessive for this example, but should scale well for larger datasets. I'll break it into steps so it isn't too convoluted going from wide-shaped data to long to wide again:
First I reshape t2 into a long format and filter for observations with 1:
library(tidyverse)

t2 %>%
  gather(key = Name, value = value, -Whatever, -Extra) %>%
  filter(value == 1)
#>    Whatever     Extra   Name value
#> 1       not    column  Waldo     1
#> 2    really appearing  Waldo     1
#> 3       all     table  Waldo     1
#> 4      does   another   Mark     1
#> 5    really appearing   Mark     1
#> 6    matter        in   Mark     1
#> 7       not    column Harold     1
#> 8      does   another   Earl     1
#> 9       not    column   Earl     1
#> 10   really appearing   Earl     1
#> 11   matter        in   Earl     1

Then I join that with t1, using left_join in case there are any observations in t2 that don't have matches in t1. That gets me the Number column from t1, so now I can drop the value column from gathering:
t2 %>%
  gather(key = Name, value = value, -Whatever, -Extra) %>%
  filter(value == 1) %>%
  left_join(t1, by = "Name") %>%
  select(-value)
#>    Whatever     Extra   Name Number
#> 1       not    column  Waldo      1
#> 2    really appearing  Waldo      1
#> 3       all     table  Waldo      1
#> 4      does   another   Mark      4
#> 5    really appearing   Mark      4
#> 6    matter        in   Mark      4
#> 7       not    column Harold      3
#> 8      does   another   Earl      9
#> 9       not    column   Earl      9
#> 10   really appearing   Earl      9
#> 11   matter        in   Earl      9

Then I use spread to bring it back to a wide format. Note that these functions create factors to order them, so at the end the spread columns are in alphabetical order. You can use select to change the order of columns if you need to.
The start to finish process:
t2 %>%
  gather(key = Name, value = value, -Whatever, -Extra) %>%
  filter(value == 1) %>%
  left_join(t1, by = "Name") %>%
  select(-value) %>%
  spread(key = Name, value = Number, fill = 0)
#>   Whatever     Extra Earl Harold Mark Waldo
#> 1      all     table    0      0    0     1
#> 2     does   another    9      0    4     0
#> 3   matter        in    9      0    4     0
#> 4      not    column    9      3    0     1
#> 5   really appearing    9      0    4     1

Created on 2018-08-14 by the reprex package (v0.2.0).


text:
Q: Unable to transfer local file wsl ubuntu terminal to remote server using windows subsystem I have a file called test1.zip in /mnt/c/Users/test/ folder of my local laptop [in which ubuntu windows subsystem for linux is installed]. Local ubuntu terminal WSL name is lauda
Now, I would like to transfer this zip file called test1.zip to my remote server named stuff.
PLEASE NOTE THAT ALL COMMANDS ARE TRIED FROM MY LOCAL LAPTOP WSL SCREEN [ubuntu screen]
So, I tried the below command from my WSL [local laptop ubuntu WSL terminal]
scp user1@lauda:/mnt/c/Users/test/test1.zip user1@stuff:/home/test/codes/test1

and got the error ssh: Could not resolve hostname lauda: Name or service not known
So I tried the below [replacing the lauda local laptop ubuntu terminal hostname with its IP]
scp user1@172.xx.xxx.xxx:/mnt/c/Users/test/test1.zip user1@stuff:/home/test/codes/test1

this resulted in error as ssh: connect to host 172.xx.xxx.xxx port 22: Connection refused
Now I tried the same command as above but in opposite way as shown below
scp user1@stuff:/home/test/codes/ user1@lauda:/mnt/c/Users/test/test1.zip

and got the below error
ssh: Could not resolve hostname lauda: Temporary failure in name resolution
Later, I tried with IP address
 scp user1@stuff:/home/test/codes/ user1@172.xx.xxx.xxx:/mnt/c/Users/test/test1.zip

And I got the below error
ssh: connect to host 172.xx.xxx.xxx port 22: No route to host lost connection
Later, I tried the below commands as well
scp /mnt/c/Users/test/test1.zip user1@stuff:/home/test/codes/

and got an error scp: /home/test/codes/test1.zip: Permission denied
So, I again tried like below
scp user1@stuff:/home/test/codes/ /mnt/c/Users/test/test1.zip

and got an error scp: /home/test/codes: not a regular file
PLEASE NOTE THAT ALL COMMANDS ARE TRIED FROM MY LOCAL LAPTOP WSL SCREEN [ubuntu screen]
How can I transfer local files/folders from my local ubuntu WSL terminal to remote server?

A: scp /mnt/c/Users/test/test1.zip user1@stuff:/home/test/codes/ is the closest attempt to working. The error you get could be due to one of two reasons:
Firstly user1 does not have permissions to write to /home/test on stuff - makes sense as usually only the test user would be able to write there. (Note that the test user on your WSL instance is not the same profile the test user on the remote.)
Secondly the /home/test/codes/ folder may not even exist yet.
Instead (if you know test's password) copy as the test user :
scp /mnt/c/Users/test/test1.zip test@stuff:/home/test/codes/

Or copy to user1's home directory (after ensuring you have created /home/user1/codes/
scp /mnt/c/Users/test/test1.zip user1@stuff:/home/user1/codes/


text:
Q: Regex with a variable number of match groups I would like to be able to write patterns to recognize filenames in a list:
import re

NOTES = ["c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b"]

filelist1 = ["piano c3.wav", "piano c#3.wav", "piano d4.wav"]
pattern1 = "piano %notename.wav"

filelist2 = ["72__54.wav", "60__127.wav", "48__61.wav"]
pattern2 = "%midinote__%velocity.wav"

The keywords :

*

*%midinote and %velocity should be integers

*%notename should be a string like in the list NOTES
The following code works and parses the filenames, but only if the 3 keywords are present in the pattern, in the order %midinote, %velocity, %notename:
pattern1 = pattern1.replace("%midinote", r"(\d+)").replace("%velocity", r"(\d+)").replace("%notename", r"([A-Ga-g]#?[0-9])")
for fname in filelist1:
    m = re.match(pattern1, fname)
    if m:
        midinote = int(m.groups()[0])
        velocity = int(m.groups()[1])
        notename = m.groups()[2]
        notenametomidi = NOTES.index(notename[:-1].lower()) + (int(notename[-1])+2) * 12
        print fname, midinote, velocity, notename, notenametomidi

But if a pattern:

*

*has only 1 or 2 keywords

*or has the 3 keywords but in another order the the order defined before,
then the code fails.
How to be able to regex with a variable number of match groups?

A: I think what you're looking for are named capturing groups. Try this:
pattern1 = pattern1.replace("%midinote", r"(?P<midinote>\d+)").replace("%velocity", r"(?P<velocity>\d+)").replace("%notename", r"(?P<notename>[A-Ga-g]#?[0-9])")
for fname in filelist1:
    m = re.match(pattern1, fname)
    if m:
        info = m.groupdict()
        midinote = int(info.get('midinote',0))
        velocity = int(info.get('velocity',0))
        notename = info.get('notename', 'c')
        notenametomidi = NOTES.index(notename[:-1].lower()) + (int(notename[-1])+2) * 12
        print fname, midinote, velocity, notename, notenametomidi

Of course you have to change the standard values according to your needs.

A: You want to be using named capture groups. Here are a couple functions that do it all, and some demo code:
# extract_midi_info.py

# For Python 2/3 compatibility
from __future__ import print_function

import re

NOTES = ("c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b")

def notename_to_midi(notename):
    return NOTES.index(notename[:-1].lower()) + (int(notename[-1])+2) * 12

def extract_midi_info(pattern, s):
    pattern = pattern.replace("%midinote", r"(?P<midinote>\d+)")
    pattern = pattern.replace("%velocity", r"(?P<velocity>\d+)")
    pattern = pattern.replace("%notename", r"(?P<notename>[A-Ga-g]#?[0-9])")

    m = re.match(pattern, s)

    if m:
        info = m.groupdict()
        if 'midinote' in info:
            info['midinote'] = int(info['midinote'])
        if 'velocity' in info:
            info['velocity'] = int(info['velocity'])
        if 'notename' in info:
            info['notename_midi'] = notename_to_midi(info['notename'])
    else:
        info = {}

    return info

def main():
    filelist_a = ["bonjour c3.wav", "bonjour c#3.wav", "bonjour d4.wav"]
    pattern_a = "bonjour %notename.wav"

    filelist_b = ["72__54.wav", "60__127.wav", "48__61.wav"]
    pattern_b = "%midinote__%velocity.wav"

    samples = [('A', filelist_a, pattern_a), ('B', filelist_b, pattern_b)]

    for name, filelist, pattern in samples:
        print()
        print('Filelist {0}'.format(name))
        for filename in filelist:
            info = extract_midi_info(pattern, filename)
            print(info)

    print()

if __name__ == '__main__':
    main()


text:
Q: C# bot Framework Replace Luis Dialog with other NLP Service I have created my own NLP api service using Apache OpenNlp. It will return json data (sample)
{"intent": "Feedback",  "entity": {}, "status": true}
Previously I used LUIS, So Bot framework having inbuilt reference class for processing  LUIS api call and providing us Intent and result. Based on the Intent our method will be like below
[LuisIntent("Feeback")]
    public async Task Feedback(IDialogContext context, LuisResult result)
    {

But, If I'm not using LUIS service. What will be the best way or how can we do the Intent process and remaining Bot Process. Something like
case "Feeback"
Public async Task Feedback(IDialogContext Context) {

in my existing bot framework project.

A: You can follow the same paradigm.
Here's an example of using Wit.ai instead of LUIS
https://github.com/q3blend/BotBuilder-Wit.ai/
Hope that helps


text:
Q: Failed to load rescue target after fsck Things happened:

*

*Get stuck on the black screen, press the power button to shutdown and reboot.

*Get the message "filesystem on /dev/sda3 requires a manual fsck".

*Run command fsck -yf /dev/sda3 and exit.

*Get the message "Failed to load rescue target, freezing".
Things I have tried for solving this problem:

*

*Add systemd.unit=rescue.target in the kernel line and boot. Still got the "Failed to load rescue target, freezing" message.

*Add systemd.unit=emergency.target in the kernel line and boot. Still got the "Failed to load rescue target, freezing" message.

*In GRUB, run commands set boot=(hd0,gpt3), set prefix=(hd0,gpt3)/boot/grub, insmod normal and normal, back to the menu, get additional "Ubuntu" and "Ubuntu Advanced Options", choose either of the four options (two "Ubuntu" and two "Ubuntu Advanced Options") will get the "Failed to load rescue target, freezing" message.

*Add init=/bin/bash in the kernel line, boot, and run the command mount -n -o remount,rw /. Not able to run fsck: "cannot execute binary file: Exec format error". Not able to run passwd: "Permission denied password unchanged".
The full error message when trying to boot normally: (typed manually)
[0.048909] ACPI Exception: AE_BAD_PARAMETER, Could not install PciConfig handler for Root Bridge PCI0 (20170831/evrgnini-245)
[1.226507] Couldn't get size: 0x800000000000000e
/dev/sda3: recovering journal
/dev/sda3: clean, 139776/6545408 files, 1649034/26163200 blocks
[4.271298] systemd[260]: /lib/systemd/system-generators/netplan failed with exit status 127.
[4.420902] systemd[1]: Failed to load default target: No such file or directory
[4.420938] systemd[1]: Failed to load rescue target: No such file or directory
[!!!!!!] Failed to load rescue target, freezing.
[4.429053] systemd[1]: Freezing execution.

Environment:
Windows 10 / Ubuntu 18.04 dual systems
If more information is needed, please tell me.

A: I had a very similar problem when accidentally removed whole folder /usr/lib/systemd/system.
I eventually succeeded to fix it:

*

*created the twin-VM version (Ubuntu 20.04 in my case),

*mounted into it the original VM's file system as virtual disk,

*simply copied the /usr/lib/systemd/system folder into mounted file system.

In 2nd step I made use of the following: How to mount a virtual hard disk?.

A: *

*Make ubuntu<your_ubuntu_version> live usb

*boot using live usb then choose "Try ubuntu"

*"search the missing file path on internet"

*Open folder in ubuntu and go to " + other locations "

*copy missing files from usb to your ubuntu drive

*if ask permission to copy then use " sudo -H nautilus " in terminal. A new
folder is open with root access...use this folder to copy-paste.

*""""""""""""""""""""""""reboot"""""""""""""""""""""""""""""

*follow same for other missing files.....


text:
Q: "Warning: Prop `className` did not match..." when use formik-material-ui TextField and material-ui TextField in one component When I use formik-material-ui TextField and original material-ui TextField (which is bound to Formik with fieldToTextField function) in one component I have a warning

Prop className did not match. Server: "PrivateNotchedOutline-legendLabelled-11 PrivateNotchedOutline-legendNotched-12" Client: "PrivateNotchedOutline-legendLabelled-7 PrivateNotchedOutline-legendNotched-8".

This warning is shown only if component's variant is outline.
Here is an example which produces the warning.
//Form.jsx
import React from 'react'
import { TextField } from 'formik-material-ui'
import TextFieldFormik from '../TextFieldFormik.jsx'
import { Formik, Form, Field } from 'formik'

export default function MyForm(props) {
  return (
    <Formik
      enableReinitialize
      initialValues={{ first: 'first', second: 'second' }}
      onSubmit={(values, { setSubmitting }) => {
        console.log(values)
      }}
    >
      {({ submitForm, isSubmitting, errors, touched, values }) => {
        return (
          <Form>
            <Field
              component={TextField} //This is a formik-material-ui TextField
              name="first"
              variant="outlined"
              fullWidth
              label="first"
            />

            <Field
              component={TextFieldFormik} //This is a material-ui text field bound to Formik with fieldToTextField function
              name="second"
              variant="outlined"
              fullWidth
              label="second"
            />
          </Form>
        )
      }}
    </Formik>
  )
}

//TextFieldFormik.jsx
import React from 'react'
import TextField from '@material-ui/core/TextField'
import { fieldToTextField } from 'formik-material-ui'

export default function TextFieldFormik(props) {
  return <TextField {...fieldToTextField(props)} />
}

My configuration:

*

*"next": "^11.1.0",

*"react": "^17.0.2",

*"react-dom": "^17.0.2"

*"@material-ui/core": "^4.11.4",

*"formik": "^2.2.9",

*"formik-material-ui": "^4.0.0-alpha.1"

A: Changing import TextField from '@material-ui/core/TextField' to import {TextField} from '@material-ui/core' in the TextFieldFormik.jsx file fixed the issue.


text:
Q: Loading dynamic link in iframe I have an iframe that I want to load the id from a variable. The issue is structuring the link so that it works. If I hardcode the actual number its fine, but if I add the variable to the end, it comes back as undefined. Any help would be great.

$(document).ready(){
var path='https://url.com?ou='+youvariable;
var youvariable=6606;
console.log(path);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<iframe src="" width="600px" height="400px"></iframe>

A: You are accessing the variable before intialization, that's why it returns undefined.
try this:
$(document).ready(function () {
   var youvariable=6606;
   var path='https://url.com?ou='+youvariable;
   console.log(path);
})

just declare the variable before using it.

A: Firstly, your document.ready() needs a function as an argument, like...
$(document).ready(() => {
  //your code here
});

secondly, the variable needs to be declared before it is used.
$(document).ready(() => {
  var youvariable=6606;
  var path='https://url.com?ou='+youvariable;
  console.log(path);
});

Output:
"https://url.com?ou=6606"


text:
Q: Setting EntityKey in EF6 DbContext I have upgraded my project from EF5 to 6 - I also decided to use the new code generation strategy.
This means a bit of pain for me - I need to go through all my DALs and switch them from ObjectContext to  DbContext.
After making the following code change, I get the error "Cannot resolve symbol 'EntityKey':
using (var ctx = DbContextManager<MyDataContext>.GetManager("MyDataContext"))
{
   var label = new Label()
   {
      Id = item.Id,
      EntityKey = new EntityKey("MyDataContext.Labels", "Id", item.Id)
   };

   ctx.DbContext.Labels.Attach(label);
   this.WriteNonKeyData(label, item);
   ctx.DbContext.SaveChanges();
   return ReadData(label);
}

Is there another accessor for EntityKey in DbContextManager, or another strategy that's recommended for this situation?

A: You could always use this approach:
https://stackoverflow.com/a/15896086/61164
However, it's still based on ObjectContext, as EntityKeys are not used in DbContext.  I'd suggest rewriting your code to not use them, especially since ObjectContext is essentially going away in EF7.


text:
Q: How to use SEXTANTE in a script outside QGIS? I´m trying to do some geoprocessing using the QGIS Sextante plugin outside of the QGIS application (and integrate it with different other libraries like arcpy, etc.).
import sys, os
from PyQt4.QtGui import QApplication
QApplication(sys.argv)
from qgis.core import *
import qgis.utils

sys.path.append("C:/Users/.../.qgis/python/plugins")

import sextante
sextante.core.Sextante.Sextante.initialize()
input = "D:/Python_Test/a.shp"
output = "D:/Python_Test/b.shp"

sextante.runalg("qgis:convexhull",input,None,None,output)
print "Finished!"

Unfortunately the process fails with the following error:
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:/Users/.../.qgis/python/plugins\sextante\core\Sextante.py", line 376, in runalg
    alg = Sextante.runAlgorithm(algOrName, None, *args)
  File "C:/Users/.../.qgis/python/plugins\sextante\core\Sextante.py", line 276, in runAlgorithm
    if not param.setValue(args[i]):
  File "C:/Users/.../.qgis/python/plugins\sextante\parameters\ParameterVector.py", line 59, in setValue
    layers = QGisLayers.getVectorLayers(self.shapetype)
  File "C:/Users/.../.qgis/python/plugins\sextante\core\QGisLayers.py", line 79, in getVectorLayers
    layers = QGisLayers.iface.legendInterface().layers()
AttributeError: 'NoneType' object has no attribute 'legendInterface'

What am I doing wrong? Sextante seems to be initialized correctly because
sextante.alghelp("qgis:convexhull")

gives me
ALGORITHM: Convex hull
    INPUT <ParameterVector>
    FIELD <ParameterTableField from INPUT>
    METHOD <ParameterSelection>
    OUTPUT <OutputVector>

I´m using Windows 7 Professional 64Bit and the OsGeo4W installation with QGIS 1.8.0 and python 2.7.4.

A: There is a way of running QGIS processing algorithms in standalone PyQGIS scripts. Check answers to Import error for qgis.core when running OSGeo4w shell script and How can I access `processing` with Python?, which provide you with tested examples.

A: The accepted answer to the following question answers this question as well:
Access Sextante (processing) in standalone QGIS app?


text:
Q: Php get method - what for? Can U tell me what are the advantages and reasons of using GET method in php?
Why even use it if there is POST? Why do some websites use both GET and POST at the same time?
Can U name main reasons?
cheers

A: One main advantage is, when you have parameters sent with GET, you URL contains all the information for the page to handle. So, you can Bookmark that link. You cannot do that if the data is sent with POST.
More technical details here: What is the difference between POST and GET?

A: The GET method is useful in situations where the GET variable is used to display particular data from your website, such as maybe the results of a movie lookup or something, because the GET variable is part of the URL, thus it can be bookmarked.  POST variables are passed invisibly to the user, so can't be used for this purpose.  Typically, you would use GET variables to request data from a database, and POST variable to send data to your database.


text:
Q: django-rest-framework + django-polymorphic ModelSerialization I was wondering if anyone had a Pythonic solution of combining Django REST framework with django-polymorphic.
Given:
class GalleryItem(PolymorphicModel):
    gallery_item_field = models.CharField()

class Photo(GalleryItem):
    custom_photo_field = models.CharField()

class Video(GalleryItem):
    custom_image_field = models.CharField()

If I want a list of all GalleryItems in django-rest-framework it would only give me the fields of GalleryItem (the parent model), hence: id, gallery_item_field, and polymorphic_ctype. That's not what I want. I want the custom_photo_field if it's a Photo instance and custom_image_field if it's a Video.

A: Here's a general and reusable solution. It's for a generic Serializer but it wouldn't be difficult to modify it to use ModelSerializer. It also doesn't handle serializing the parent class (in my case I use the parent class more as an interface).
from typing import Dict, Type

from rest_framework import serializers

class PolymorphicSerializer(serializers.Serializer):
    """
    Serializer to handle multiple subclasses of another class

    - For serialized dict representations, a 'type' key with the class name as
      the value is expected: ex. {'type': 'Decimal', ... }
    - This type information is used in tandem with get_serializer_map(...) to
      manage serializers for multiple subclasses
    """
    def get_serializer_map(self) -> Dict[str, Type[serializers.Serializer]]:
        """
        Return a dict to map class names to their respective serializer classes

        To be implemented by all PolymorphicSerializer subclasses
        """
        raise NotImplementedError

    def to_representation(self, obj):
        """
        Translate object to internal data representation

        Override to allow polymorphism
        """
        type_str = obj.__class__.__name__

        try:
            serializer = self.get_serializer_map()[type_str]
        except KeyError:
            raise ValueError(
                'Serializer for "{}" does not exist'.format(type_str),
            )

        data = serializer(obj, context=self.context).to_representation(obj)
        data['type'] = type_str
        return data

    def to_internal_value(self, data):
        """
        Validate data and initialize primitive types

        Override to allow polymorphism
        """
        try:
            type_str = data['type']
        except KeyError:
            raise serializers.ValidationError({
                'type': 'This field is required',
            })

        try:
            serializer = self.get_serializer_map()[type_str]
        except KeyError:
            raise serializers.ValidationError({
                'type': 'Serializer for "{}" does not exist'.format(type_str),
            })

        validated_data = serializer(context=self.context) \
            .to_internal_value(data)
        validated_data['type'] = type_str
        return validated_data

    def create(self, validated_data):
        """
        Translate validated data representation to object

        Override to allow polymorphism
        """
        serializer = self.get_serializer_map()[validated_data['type']]
        return serializer(context=self.context).create(validated_data)

And to use it:
class ParentClassSerializer(PolymorphicSerializer):
    """
    Serializer for ParentClass objects
    """
    def get_serializer_map(self) -> Dict[str, Type[serializers.Serializer]]:
        """
        Return serializer map
        """
        return {
            ChildClass1.__name__: ChildClass1Serializer,
            ChildClass2.__name__: ChildClass2Serializer,
        }

A: For sake of completion, I'm adding to_internal_value() implementation, since I needed this in my recent project.
How to determine the type
Its handy to have possibility to distinguish between different "classes"; So I've added the type property into the base polymorphic model for this purpose:
class GalleryItem(PolymorphicModel):
    gallery_item_field = models.CharField()

    @property
    def type(self):
        return self.__class__.__name__

This allows to call the type as "field" and "read only field".
type will contain python class name.
Adding type to Serializer
You can add the type into "fields" and "read only fields"
(you need to specify type field in all the Serializers though if you want to use them in all Child models)
class PhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Photo

    fields = ( ..., 'type', )
    read_only_fields = ( ..., 'type', )

class VideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Video

    fields = ( ..., 'type', )
    read_only_fields = ( ..., 'type', )

class GalleryItemModuleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.GalleryItem

    fields = ( ..., 'type', )
    read_only_fields = ( ..., 'type', )

    def to_representation(self, obj):
        pass # see the other comment

    def to_internal_value(self, data):
    """
    Because GalleryItem is Polymorphic
    """
    if data.get('type') == "Photo":
        self.Meta.model = models.Photo
        return PhotoSerializer(context=self.context).to_internal_value(data)
    elif data.get('type') == "Video":
        self.Meta.model = models.Video
        return VideoSerializer(context=self.context).to_internal_value(data)

    self.Meta.model = models.GalleryItem
    return super(GalleryItemModuleSerializer, self).to_internal_value(data)

A: So far I only tested this for GET request, and this works:
class PhotoSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Photo

class VideoSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Video

class GalleryItemModuleSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.GalleryItem

    def to_representation(self, obj):
        """
        Because GalleryItem is Polymorphic
        """
        if isinstance(obj, models.Photo):
            return PhotoSerializer(obj, context=self.context).to_representation(obj)
        elif isinstance(obj, models.Video):
           return VideoSerializer(obj, context=self.context).to_representation(obj)
        return super(GalleryItemModuleSerializer, self).to_representation(obj)

For POST and PUT requests you might want to do something similiar as overriding the to_representation definition with the to_internal_value def.


text:
Q: Show Date with DateTimePicker from MySQL I'm at the moment having a problem with my program I want to retrieve the Date that is in MySQL DB to show the Date/Week/Year I choose in the DateTimePicker in my ListView but I encountered a problem and can't see the solution nor have I found something that looks like it:
Try
    conn.Open()
    Dim Reader As MySqlDataReader
    Dim Query As String
    Query = "Select * from farm.sales where datesale= ('" & DateTimePicker1.Text & "') "
    command = New MySqlCommand(Query, conn)
    Reader = command.ExecuteReader
    While Reader.Read

        Dim Datesale = Reader.GetString("datesale")
        Dim Clients= Reader.GetString("clients")
        Dim Bank= Reader.GetString("bank")
        Dim Revenue= Reader.GetString("revenue")
        Dim Total = Reader.GetString("total")

        Dim LV As New ListViewItem
        LV.Text = Reader("Datesale").ToString
        LV.SubItems.Add(Reader("Clients").ToString)
        LV.SubItems.Add(Reader("Bank").ToString)
        LV.SubItems.Add(Reader("Revenue").ToString)
        LV.SubItems.Add(Reader("Total").ToString)
        ListView1.Items.Add(LV)
    End While

    conn.Close()

Catch ex As MySqlException
    MessageBox.Show(ex.Message)

Finally
    conn.Dispose()
End Try

The problem I'm getting is in this line LV.Text = Reader("Datesale ").ToString, which I assume its because of the format I'm retrieving but I can't find a solution can someone pls help me get to a solution
Thanks
Edit:
My bad didn't post the error the problem the program crashes and I get the error An unhandled exception of type System.IndexOutOfRangeException occurred in MySql.Data.dll
Additional information: Could not find specified column in results: Datesales

A: this is how I use listview. I hope this helps.
    conn.Close()
    conn.Open()
    cmd.CommandText = "SELECT * FROM tblUser"
    cmd.Connection = conn
    dr = cmd.ExecuteReader

    While dr.Read
        Dim itm = frmAdminMain.lvUser.Items.Add(dr("UserID"))
        itm.SubItems.Add(dr("Username"))
        itm.SubItems.Add(dr("Password"))
        itm.SubItems.Add(dr("FName"))
        itm.SubItems.Add(dr("LName"))
        itm.SubItems.Add(dr("Title"))
        itm.SubItems.Add(dr("Department"))

    End While
    dr.Close()
    conn.Close()

i used lvUser.Items.Add(dr("UserID"))
in your case, you used LV.text..
just change it to LV.Items.Add(Reader.GetString("datesale")
goodluck! :)

A: Finally resolved it don't know what the error actually was I simply changed the name of the variable and the name on the listview and it solved it
Thanks so much for the replys and


text:
Q: Getting the Number that an Object is located in an ArrayList I have two ArrayLists, one contains the letters a - z, the other has for example, the letters a, b, and c. How do I find, for example, the index in the ArrayList that "b" is at (which in this case is 1)?
here's an example of code:
public static ArrayList<String> ARRAYLETTERS = new ArrayList<String>();

ARRAYLETTERS.add("a");
ARRAYLETTERS.add("b");
ARRAYLETTERS.add("c");

//now I need to get the number spot that b is at (1)

A: You can use:
int position = ARRAYLETTERS.indexOf("a");

As an aside, you really should stick to standard java naming conventions and use camel case (arrayLetters) instead of all-caps for member names.

A: You use ARRAYLETTERS.indexOf("b").

A: use ArrayList.indexOf()  to get get index of object.
eg:
int index=ARRAYLETTERS.indexOf("b");


text:
Q: Overriding backslash for custom Julia struct I'm creating a custom matrix library by extending the functionality present in the LinearAlgebra module. I have been doing this by creating custom structs in a custom MyLinearAlgebra module that directly imports the default Linear Algebra structs and overrides many of the common LA functionalities. My question is specifically about how to override the backslash function. Here is my "MyLinearAlgebra.jl":
module MyLinearAlgebra

import LinearAlgebra
import Base: getindex, setindex!, size

export
# Types
LocalMatrix,
SolutionVector,
# Functions
lp_error!,
lp_norm,
true_size

include("SolutionVector.jl")
include("LocalMatrix.jl")

end

Focusing solely on LocalMatrix.jl now, I have:
"""
    struct LocalMatrix{T} <: AbstractMatrix{T}
Block diagonal structure for local matrix. `A[:,:,iS,iK]` is a block matrix for
state iS and element iK
"""
struct LocalMatrix{T} <: AbstractMatrix{T}
    data::Array{T,4}
    factorizations::Array{Any,2}

    function LocalMatrix(data::Array{T,4}) where {T}
        new{T}(data,Array{Any}(undef, size(data,3), size(data,4)))
    end
end

# [... a lot of things that are already working including: ldiv!]

"""
    ldiv!(A::LocalMatrix, x::SolutionVector)
In-place linear solve A\\x using block-diagonal LU factorizations. Compute this
block-diagonal factorization if not yet computed.
"""
function LinearAlgebra.ldiv!(A::LocalMatrix, x::SolutionVector)
    println("my ldiv! works fine")
    x
end

# [ ... and yet this does not work ]
"""
    A::LocalMatrix \\ x::SolutionVector
Linear solve A\\x using block-diagonal LU factorizations. Compute this
block-diagonal factorization if not yet computed.
"""
function (\)(A::LocalMatrix, x::SolutionVector)
    println("my \\ never prints out in any tests")
    (m,n,ns,ne) = size(A.data)
    (nx,nsx,nex) = size(x.data)
    @assert n == nx && ne == nex && m == n
    b = deepcopy(x)
    LinearAlgebra.ldiv!(A, b)
end

In my tests, I can use the ldiv! function exactly as expected, but I cannot use the \ function - it simply uses some standard implementation written somewhere else. I believe this is presumably because my backslash function is not qualified as the LinearAlgebra backslash function, but I'm not sure. Trying to qualify the function as LinearAlgebra.(\)(A::LocalMatrix, x::SolutionVector) fails with a syntax error invalid function name. Is there another way to do this, or am I missing something more fundamental about modules here?

A: \ is defined in Base, so:
julia> "a" \ "b"
ERROR: MethodError: no method matching adjoint(::String)

julia> Base.:\(::String, ::String) = "hello"

julia> "a" \ "b"
"hello"

However, as it is imported to LinearAlgebra the following also works for me (I am using a fresh session):
julia> using LinearAlgebra

julia> "a" \ "b"
ERROR: MethodError: no method matching adjoint(::String)

julia> LinearAlgebra.:\(::String, ::String) = "hello"

julia> "a" \ "b"
"hello"

as Julia will add a method to the same function (defined in Base).


text:
Q: Excel2010/VBA: Store and Usage of Worksheet Variable during Userform Session
*

*In Worksheet1 is a button that is calling a Userform

*I want to use the current Worksheet during the Userform Session but I'm not able to use this.

*I want to use a variable for further usage.

*The Button on Worksheet1 is Calling this Macro

Option Explicit
Public GlbVarBaseSheet As String
------------
Sub Formularaufruf_Worksheet1()
    GlbVarBaseSheet = ActiveSheet.Name
    with Userform1
    .MultiPage1.Value = 1
    .Show 0
End With
End Sub

Within the Userform, there's a Sub Called Uebernahme, which fills out the Textboxes reading the column number which is stored in the .tag of the TextBox.
How can I Use the Worksheet Variable in this line to use is during the Userform Session: This is not working and I don't know why.
With Workbooks("KVP.xlsm").Worksheets(GlbVarBaseSheet)

The Full Sub:
Sub Uebernahme()

Dim Zeilenindex As Long
Dim OBcB As MSForms.Control
Dim VarTypeName As String
Sheets(GlbVarBaseSheet).Activate
'
'
'
Workbooks("KVP.xlsm").ActiveSheet.Rows(spinbutton1.Value).Activate
Zeilenindex = spinbutton1.Value
'
'
With Workbooks("KVP.xlsm").Worksheets(GlbVarBaseSheet)

    If .Cells(ActiveCell.Row, 1).Value <> "" Then
        For Each OBcB In MultiPage1.SelectedItem.Controls
            VarTypeName = TypeName(OBcB)
            If OBcB.Tag <> "" Then
                Select Case VarTypeName
                    Case Is <> "Checkbox"
                        'OBcB.Value = .cells(Left(OBcB.Tag, 1) & ActiveCell.Row)
                        OBcB.Value = .Cells(ActiveCell.Row, Int(Left(OBcB.Tag, 1))).Value
                End Select
            End If
        Next
    End If
End With
End Sub

A: Try
dim GlbVarBaseSheet as Worksheet


text:
Q: How can an Outlook add-in check if an appointment has a Teams meeting? I'm developing a meeting provider add-in for Outlook. One issue my customers have is Outlook automatically enabling a Teams meeting when composing appointments, which users are not aware of. It's reportedly common for users to send an event with two sets of meeting details attached (Teams and my add-in).
When a user opens my add-in I would like to notify them that they already have a Teams meeting enabled. How can an Outlook add-in check if an appointment has a Teams meeting?

A: Currently, there is no Office JS API which can provide this information about "Teams Meeting" enabled.
Currently the feature, you requested, is not a part of the product. We track Outlook add-in feature requests on our Tech Community Page. Please submit your request there and choose the appropriate label(s). Feature requests on Tech Community are considered, when we go through our planning process.


text:
Q: SKNode children with array of classes I'm trying to write a method to find children of an SKNode which are of a particular class - but I'm getting an EXC error here
Anyone any ideas about why this might be?
import SpriteKit

extension SKNode {
  func children(#klasses: [AnyClass]) -> [SKNode] {
    var matchedNodes = [SKNode]()
    for child in children as [SKNode] {
      for klass in klasses {
        if child.isKindOfClass(klass) {
          matchedNodes.append(child)
        }
      }

      matchedNodes += child.children(klasses: klasses)
    }
    return matchedNodes
  }

}

class Apple: SKNode {}
class Orange: SKNode {}

let apple = Apple()
let orange = Orange()

apple.addChild(orange)

let fruits = apple.children(klasses: [Apple.self, Orange.self])

Error:
Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_i386_INVOP, subcode=0x0).

A: Try this code
extension SKNode {
    func children(#klasses: [AnyObject]) -> [SKNode] {
        var matchedNodes = [SKNode]()
        for child in children as [SKNode]{
            for klass in klasses {
                if child.dynamicType === klass {
                    matchedNodes.append(child)
                }
            }
            matchedNodes += child.children(klasses: klasses)
        }
        return matchedNodes
    }
}


text:
Q: Android Get UTC time from ntp server i'm trying to get the current UTC time of a server, but it give me  te zone time (UTC+6), Is there any way to have the UTC time without using the device time?
My code:
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName("time1.google.com");
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getMessage().getOriginateTimeStamp().getTime();
long returnTime2 = timeInfo.getReturnTime();
Date current = new Date(returnTime);
Date current1 = new Date(returnTime2);
Log.i("actualtime", current.toString()); //it give me UTC+6
Log.i("actualtime",current1.toString()); //it give me UTC+6

Thanks!

A: Date.toString() always returns timezone-specific output. Your returnTime variable is probably actually the proper epoch time: if you want to print out UTC, use SimpleDateFormat to do it. Something like this:
SimpleDateFormat fmt = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ssZ");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + fmt.format(current));


text:
Q: Discrete Sum of Function over a Region I might have completely missed something in my search. I want to discretely sum over a function, $f(x_i,y_j)$ multiplied by some other function $g$ over a general region $S$.
$$\sum_{(x,y)\in S}f(x,y)g\Delta x \Delta y$$
where the region S is given, for example, by a polygon $P$.

*

*For the polygon case, I know Mathematica can do this for an Integral as seen in the following example:
pol = Polygon[CirclePoints[4 \[Pi]/3, 6]];
Integrate[1, {x, y} \[Element] pol]
But this wont work if I try to do the same with Sum[].
I think one solution is to calculate the boundary of the polygon by hand, and then plug it into the Sum[] function. But there must be a better solution, given the complexity of the Polygon[] function?

*What if it's a general region, for example by an inequality $f(x_i,y_j)<0$. Is there an easy way to do the sum over this region?

Thanks in advance! Any thoughts would be appreicated!
Update:
Henrik suggested DiscretizeRegion, it looks like it does discretize the region into triangles. But still, it won't work inside the Sum[] function.


text:
Q: How can I get the x, y dimensions of a PDF Image
As you can see in the image above, the dimensions are embedded somewhere, but I know not where.  Is there a utility which I could call through shell to determine the dimensions of the PDF?
Any help is appreciated.
I used Visual FoxPro above with a browser ActiveX in a form to display PDFs HTMLs etc..., I can use any shellScript or EXEs, dlls etc, if anyone knows how to do this....
Is Javascript able to look into a browser like FireFox which has a PDF displayed, to get the dimensions???
DKean


text:
Q: Convert binary file to image I need to find a fast way to convert a binary file to an image.
The binary file consist of a NNN matrix  and I want to associate 0 to a color and 1 to a different color.
I need to perform this operation to more then 1000 binary files.
If possible I'd like to avoid using MatLab, is there any tool/software (for unix) that would help me?
EDIT:
This is exactly what I was looking for!
On the bottom of the page it says: "TIP: To process many files, use a shell script to pass this URL and your desired parameters to wget and then direct the output to file"
Yet I can't do this.
I tried with:
 wget --post-data="blocksize=10&width=10&offset=0&markval=-1&autoscale=0"  \
      --post-file="userfile=/path.../filename" http://www.ryanwestafer.com/stuff/bin2img.php \
      > output

but all I get is the original page downloaded in my local folder!

A: If you have python with the PIL (Image) library installed:
import Image
def colormap(s):
    s_out = []
    for ch in s:   # assume always '\x00' or '\x01'
        if s == '\x00':
            s_out.append('\x00')  # black
        else:
            s_out.append('\xFF')  # white
    return ''.join(s_out)

N= 50   # for instance
fin = open('myfile.bin','rb')
data = fin.read(N*N)    # read NxN bytes
data = colormap(data)

# convert string to grayscale image

img = Image.fromstring('L', (N,N), data )
# save to file
img.save('thisfile.png')

data = fin.read(N*N)   # next NxN bytes
data = colormap(data)

img = Image.fromstring('L', (N,N), data )
img.save('thisfile2.png')

This can be easily modified to loop and sequence filenames, etc as needed

A: For 3D matrixes, I would usually convert them to VRML3D and look at them using ParallelGraphics/Cortona3D.
Otherwise, you need some sort of projection or "slicing" of the matrix in order to see all of the matrix.
This is a C implementation to dump a 3D matrix to a PNG file. Compile with
gcc -W -Wall -o bin2png bin2png.c -lpng

Code:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <png.h>

static png_structp png_ptr;
static png_infop info_ptr;

/**
                      |<--- W ---->|

                      +------------+       -
                      | 18  19   20|       |
                  +-------------+  |       |
                  | 9   10   11 |  |       |
              +-------------+   |23|       +--> H
              | 0    1    2 |   |  |       |
              |             |14 |  |       |
              |             |   |26|       |
              | 3    4    5 |   |--+   +   -
              |             |17 |     /
              |             |---+    +--> D
              | 6    7    8 |       /
              +-------------+      +

        @param matrix   a 3D matrix. Element [i,j,k] is A[H*(D*k + j) + i]
        @param W        width
        @param H        height
        @param D        depth
        @param WW       width in W-sized chunks of target image
        @param HH       height in H-sized chunks of target image
        @param filename output filename in PNG format

        Output image:

        |<----- WW = 2 --->|
        +------------------+ -
        |  0  1  2  9 10 11| |
        |  3  4  5 12 13 14| |
        |  6  7  8 15 16 17| HH = 2
        | 18 19 20         | |
        | 21 22 23  blank  | |
        | 24 25 26         | |
        +------------------+ -

        NOTE: W*WW and H*HH may not exceed 32760.

        Return:
                0       success
                -1      cannot create PNG structure (write)
                -2      cannot create PNG structure (info)
                -3      out of memory
                -4      cannot create output file

*/

int matrix3D_to_png(uint8_t *matrix, size_t W, size_t H, size_t D, size_t WW, size_t HH, char *filename)
{
        FILE            *fp;
        png_color       palette[16];
        png_byte        transparencies[16];
        uint32_t        y;
        size_t          x;
        uint8_t         *row;

        if( !(png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) )
                return -1;

        if( !(info_ptr = png_create_info_struct(png_ptr)) || setjmp(png_jmpbuf(png_ptr)) ){
                /* If we get here, libpng had a problem writing */
                png_destroy_write_struct(&png_ptr, &info_ptr);
                return -2;
        }

        if (NULL == (row        = malloc(WW*W + 7)))
        {
                return -3;
        }

        /* Create 16-color palette for representation */
        #define SETPAL(i,r,g,b,a)       \
        palette[i].red  = r; palette[i].green   = g; palette[i].blue    = b; transparencies[i] = 255-a;

        // We will draw the matrix in red if points are nonzero, black if zero; outside the matrix
        // we use transparent white.
        #define         INDEX_IF_ZERO           0
        #define         INDEX_IF_NONZERO        3
        #define         INDEX_IF_BLANK          15

        SETPAL(0,       0, 0, 0, 0);            // Black
        SETPAL(1,       255, 255, 255, 0);      // Opaque white
        SETPAL(2,       192, 192, 192, 0);      // Light gray

        SETPAL(3,       255,    0,      0, 0);  // Red
        SETPAL(4,       0,      255,    0, 0);  // Green
        SETPAL(5,       0,      0,      255, 0);// Blue

        SETPAL(6,       255,    0,      0,      128);   // Halftransparent red
        SETPAL(7,       0,      255,    0,      128);   // green
        SETPAL(8,       0,      0,      255,    128);   // blue

        SETPAL(9,       255, 0, 0, 0);          // red again :-)
        SETPAL(10,      0, 255, 0, 0);
        SETPAL(11,      0, 0, 255, 0);
        SETPAL(12,      255, 0, 0, 0);
        SETPAL(13,      0, 255, 0, 0);
        SETPAL(14,      0, 0, 255, 0);

        SETPAL(15,      255, 255, 255, 255);    // Transparent white
        /* End palette */

        /* Create filename */
        if (NULL == (fp = fopen(filename, "w")))
        {
                fprintf(stderr, "cannot open output '%s': %s\n", filename, strerror(errno));
                return -4;
        }
        png_init_io(png_ptr, fp);
        png_set_IHDR(png_ptr, info_ptr, W*WW, H*HH, 8, PNG_COLOR_TYPE_PALETTE,
                                 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
        png_set_PLTE(png_ptr, info_ptr, palette, 16);
        png_set_tRNS(png_ptr, info_ptr, transparencies, 16, NULL);
        png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
        png_write_info(png_ptr, info_ptr);
        for (y = 0; y < H*HH; y++)
        {
                size_t  mx = y/H;
                mx      = (mx*H*WW + (y%H))*W;
                for (x = 0; x < WW; x++)
                {
                        if (mx+x*H >= H*D)
                                memset(row+x*W, INDEX_IF_BLANK, W);
                        else
                        {
                                size_t ii;
                                for (ii = 0; ii < W; ii++)
                                        row[x*W+ii] = (matrix[mx+x*W*H+ii]) ? INDEX_IF_NONZERO : INDEX_IF_ZERO;
                        }
                }
                png_write_row(png_ptr, row);
        }
        png_write_end(png_ptr, NULL /*info_ptr*/);
        png_destroy_write_struct(&png_ptr, &info_ptr);
        fclose(fp);
        free(row);
        return 0;
}

int main(int argc, char **argv)
{
        FILE    *fp;
        uint8_t *matrix;
        size_t  W, H, D, WW, HH, i;
        if (8 != argc)
        {
                fprintf(stderr, "Syntax: %s input output.png width height depth TileX TileY\n", *argv);
                return EXIT_FAILURE;
        }
        W       = atol(argv[3]);
        H       = atol(argv[4]);
        D       = atol(argv[5]);
        WW      = atol(argv[6]);
        HH      = atol(argv[7]);

        if ((W * WW > 32767)||(H * HH) > 32767)
        {
                fprintf(stderr, "Output image would be too large\n");
                return EXIT_FAILURE;
        }
        if (WW*HH < D)
        {
                fprintf(stderr, "WARNING: matrix does not fit into output image\n");
        }
        if (WW*HH > D*2)
        {
                fprintf(stderr, "WARNING: output image is far larger than input matrix\n");
        }
        if (NULL == (fp = fopen(argv[1], "r")))
        {
                fprintf(stderr, "Input file not found\n");
                return EXIT_FAILURE;
        }
        if (NULL == (matrix = malloc(W*H*D)))
        {
                fprintf(stderr, "Out of memory: matrix too large\n");
                return EXIT_FAILURE;
        }
        for (i = 0; i < D; i++)
        {
                int ret;
                if ((int)H != (ret = fread(matrix + W*H*i, W, H, fp)))
                {
                        fprintf(stderr, "Read error at plane %d (reading %d rows of %d elements, expecting %d, got %d)\n",
                                (int)i, (int)W, (int)H, (int)H, ret);
                        fclose(fp);
                        return EXIT_FAILURE;
                }
        }
        if (matrix3D_to_png(matrix, W, H, D, WW, HH, argv[2]))
        {
                fprintf(stderr, "Error in creating output PNG '%s'\n", argv[2]);
                return EXIT_FAILURE;
        }
        return EXIT_SUCCESS;
}

A: GNU Octave is a free Matlab-like program that a lot of people seem to like.
This site has a whole list of free alternatives: http://www.math.tu-berlin.de/~ehrhardt/matlab_alternatives.html


text:
Q: Is it possible to create indexes in Mongodb for dynamic fields? My site has several "domains" which represent sub-sections of the site. Each "domain" has its own users with profiles, and a search page where you can search for users based on profile fields that the users fill out.
User data from the 'users' collection is structured like so:
{
    username: 'shawnmichaels',
    first_name: 'Shawn',
    last_name: 'Michaels',
    domains: [
        {
            name: 'domain1',
            user_fields: {
                'bio': 'Short bio related to domain 1',
                'skills': 'Pertinent skills for domain 1'
            }
        },
        {
            name: 'domain2',
            user_fields: {
                'bio': 'Short bio related to domain 2',
                'skills': 'Pertinent skills for domain 2'
            }
        }
    ]
}

So, users have field data across multiple domains. The domain names and field names are dynamic. There could potentially be hundreds of domains for a user and dozens of fields in a domain.
Is it possible to have some sort of dynamic index so that I can search for fields under 'domain1' without getting any matches in 'domain2'?
For example, if a user1 has "skills": ["karate", "judo"] under 'domain1', and I want to search domain2 for "karate", I don't want a match for user1.

A: For anyone interested, I've answered my own question after a day of research.
I'm pretty new to MongoDB and didn't realize you can query arrays by treating them like any other keys, like so:
db.users.find({domains.title: 'domain1'})
// where 'domains' is an array of object each with a 'title' key

With this knowledge, I added a text index for each field I want to be searchable:
db.users.ensureIndex({
  'username': 'text',
  'first_name': 'text',
  'last_name': 'text',
  'domains.fields.bio': 'text',
  'domains.fields.skills': 'text',
  'domains.fields.title': 'text',
  'domains.fields.training': 'text'
}, {name: 'domain_search'})

And I structured search queries in each domain like so:
db.users.find({
  'domains.title': DOMAIN_NAME,
  '$text': {'$search': SEARCH_TERM}
})


text:
Q: How to reproduce JSF web.xml vulnerability There is a known web.xml vulnerability exist in javax.faces 2.1 jar.
Please consider below URL to reproduce this issue and that was given by client side to reproduce this issue.
https://example.com/javax.faces.resource.../WEB-INF/web.xml.jsf (dummy URL)

but we are unable to reproduce this issue at our end.
We tried using below URLs to reproduce this issue at our end.
https://<external IP>:8181/javax.faces.resource.../WEB-INF/web.xml.jsf
https://<Localhost>:8181/javax.faces.resource.../WEB-INF/web.xml.jsf
https://<Localhost>:8181/ABC/javax.faces.resource.../WEB-INF/web.xml.jsf

Please note that deployed application structure are same at both ends.
So please any early help  to reproduce this issue would be highly appreciated as this issue high priority issue.
Thanks in advance

A: This is a very common issue with javax.faces 2.1 jar which is faced by various web applications.
But reproduction steps are not found clearly on following 1) upto how much depth would be achieved by putting how many ../../ should be put in URLfor  path traversal 2) sometimes not reproducible via local host or ip(intranet) why? is Java faces see any difference here?
Above points are very critical from the understanding. if some body can take time and explain would be helpful.


text:
Q: ui-sref link to external url / make ng-href link to display with in template I have menu, when i click on menu i want html page to be displayed within the same page. I am displaying html content in body of my parent html.I used ui-sref and it works fine when i link to html page but it does not work when i link to external site eg: google.com. Please let me know how to open external link using ui-sref. Is there any other way to do other than ui-sref? i used ng-href, but the problem is it will open new page . i want content of google.com inside my html page with menu bar displaying and in body i should be able to display google.com site . Please let me know is there any way to do this.
Note: i dont want to redirect to new page. I want html content to be displayed inside parent html . In my case i have menu bar in parent html. when i click on link in menu bar child html should be displayed inside parent template and i should be seeing both menu bar and child html page . Is there any way to do this in angular js?
 $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'home.html' //working fine
        })
         .state('about', {
             url: '/about',
             templateUrl: 'http:google.com' //not working
         })

here is the plunker https://plnkr.co/edit/RB5rxEvxxeN7T5fufSeV
Please let me know is there any way to do this. If it is not possible in ui-sref then please let me know alternate way to do this in angular


text:
Q: ncurses' has_colors() returns false. What is the problem? I want to use color attributes in ncurses mode. But as stated in the topic, has_colors() returns false, meaning that the terminal does not support color manipulation. But using printf() and ansi color codes (not in ncurses mode), I can print color texts. I think this means that the terminal supports color manipulation. Am I wrong? What is the problem?
This is the code I use:
int main()
{
    initscr();

    if (has_colors() == false)
    {
        endwin();
        printf("No color support!\n");
        return -1;
    }

    start_color();
    init_pair(1, COLOR_RED, COLOR_BLACK);

    attron(COLOR_PAIR(1));
    printw("This is a test!");
    attroff(COLOR_PAIR(1));

    endwin();

    return 0;
}

A: Terminal configuration in ncurses comes from two flavours, depending on if ncurses was compiled with terminfo support or termcap support.
Either way, has_colors() is a function that consults the curses database (a terminal controls database based on how your terminal behaves) based on the value you use for your TERM environment variable.
A value of xterm is possible to include no color controls and probably what is making your terminal software not able to display colors.  Just change your TERM variable to something like:
TERM=xterm-color

and try again.  That terminal definition includes color support and makes has_colors() to return true.
EDIT
from my own termcap file (based on a FreeBSD 12.1 system):
xterm-clear:\
        :te=\E[?1049l:ti=\E[?1049h:\
        :tc=xterm-new:
xterm-new|modern xterm:\
        :@7=\EOF:@8=\EOM:F1=\E[23~:F2=\E[24~:K2=\EOE:Km=\E[M:\
        :k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:k5=\E[15~:k6=\E[17~:\
        :k7=\E[18~:k8=\E[19~:k9=\E[20~:k;=\E[21~:kI=\E[2~:\
        :kN=\E[6~:kP=\E[5~:kd=\EOB:kh=\EOH:kl=\EOD:kr=\EOC:ku=\EOA:\
        :tc=xterm-basic:
#
# This chunk is used for building the VT220/Sun/PC keyboard variants.
xterm-basic|modern xterm common:\
        :am:bs:km:mi:ms:ut:xn:AX:\
        :Co#8:co#80:kn#12:li#24:pa#64:\
        :AB=\E[4%dm:AF=\E[3%dm:AL=\E[%dL:DC=\E[%dP:DL=\E[%dM:\
        :DO=\E[%dB:LE=\E[%dD:RI=\E[%dC:UP=\E[%dA:ae=\E(B:al=\E[L:\
        :as=\E(0:bl=^G:cd=\E[J:ce=\E[K:cl=\E[H\E[2J:\
        :cm=\E[%i%d;%dH:cs=\E[%i%d;%dr:ct=\E[3g:dc=\E[P:dl=\E[M:\
        :ei=\E[4l:ho=\E[H:im=\E[4h:is=\E[!p\E[?3;4l\E[4l\E>:\
        :kD=\E[3~:kb=^H:ke=\E[?1l\E>:ks=\E[?1h\E=:kB=\E[Z:le=^H:md=\E[1m:\
        :me=\E[m:ml=\El:mr=\E[7m:mu=\Em:nd=\E[C:op=\E[39;49m:\
        :rc=\E8:rs=\E[!p\E[?3;4l\E[4l\E>:sc=\E7:se=\E[27m:sf=^J:\
        :so=\E[7m:sr=\EM:st=\EH:\
        :ue=\E[24m:up=\E[A:us=\E[4m:ve=\E[?12l\E[?25h:vi=\E[?25l:vs=\E[?12;25h:

# The xterm-new description has all of the features, but is not completely
# compatible with vt220.  If you are using a Sun or PC keyboard, set the
# sunKeyboard resource to true:
#       + maps the editing keypad
#       + interprets control-function-key as a second array of keys, so a
#         12-fkey keyboard can support vt220's 20-fkeys.
#       + maps numeric keypad "+" to ",".
#       + uses DEC-style control sequences for the application keypad.
#
xterm-vt220|xterm emulating vt220:\
        :*6=\E[4~:@7=\E[4~:K2=\EOu:Km=\E[M:kH=\E[4~:kh=\E[1~:\
        :tc=xterm-basic:

xterm-24|xterms|vs100|24x80 xterm:\
        :li#24:tc=xterm-old:
xterm-65|65x80 xterm:\
        :li#65:tc=xterm-old:
xterm-bold|xterm with bold for underline:\
        :so=\E[7m:us=\E[1m:tc=xterm-old:
xterm-boldso|xterm with bold for standout:\
        :se=\E[m:so=\E[1m:tc=xterm-old:
xterm-mono|monochrome xterm:\
        :ut@:\
        :Co@:NC@:kn#20:pa@:\
        :AB@:AF@:Sb@:Sf@:op@:st@:tc=xterm-old:
#
# Alternate terminal description that "works" for interactive shells such as
# tcsh and bash.
xterm-noapp|xterm with cursor keys in normal mode:\
        :kd=\E[B:ke=\E>:kl=\E[D:kr=\E[C:ks=\E=:ku=\E[A:te@:ti@:\
        :tc=xterm:
#
# This should work for the commonly used "color xterm" variations (XFree86
# xterm, color_xterm, nxterm, rxvt).  Note that it does not set 'bce', so for
# XFree86 and rxvt, some applications that use colors will be less efficient,
# and in a few special cases (with "smart" optimization) the wrong color will
# be painted in spots.
xterm-color|generic "ANSI" color xterm:\
        :Co#8:NC@:pa#64:\
        :AB=\E[4%dm:AF=\E[3%dm:ac=:op=\E[m:tc=xterm-r6:
#
# These aliases are for compatibility with the terminfo; termcap cannot provide
# the extra features such as color initialization, but termcap applications
# still want the names.
xterm-16color|xterm alias 1:\
        :tc=xterm-new:

xterm-88color|xterm alias 2:\
        :Co#88:pa#7744:tc=xterm-256color:

xterm-256color|xterm alias 3:\
        :Co#256:pa#32767:\
        :AB=\E[48;5;%dm:AF=\E[38;5;%dm:tc=xterm-new:

xterm-nrc|xterm alias 4:\
        :tc=xterm:
xterm-rep|xterm alias 5:\
        :tc=xterm:
xterm-xmc|xterm alias 6:\
        :sg#1:tc=xterm:
#
# An 8-bit description is doable with termcap, but there are probably no
# termcap (or BSD curses) applications that are able to use it.
#
# Add the capability to "clear the screen" after exiting vi, more/less, etc.
#
xterm-8bit-clear:\
        :te=\233?1049l:ti=\233?1049h:ue=\23324m:\
        :tc=xterm-8bit:
xterm-8bit|xterm terminal emulator 8-bit controls (X Window System):\
        :am:km:mi:ms:xn:\
        :co#80:it#8:li#24:\
        :AL=\233%dL:DC=\233%dP:DL=\233%dM:DO=\233%dB:IC=\233%d@:\
        :K2=\217y:Km=\233M:LE=\233%dD:RI=\233%dC:UP=\233%dA:\
        :ae=\E(B:al=\233L:as=\E(0:bl=^G:bt=\233Z:cd=\233J:ce=\233K:\
        :cl=\233H\2332J:cm=\233%i%d;%dH:cr=^M:cs=\233%i%d;%dr:\
        :ct=\2333g:dc=\233P:dl=\233M:do=^J:ei=\2334l:ho=\233H:\
        :im=\2334h:\
        :is=\E[62"p\E G\233m\233?7h\E>\E7\233?1;3;4;6l\2334l\233r\E8:\
        :k1=\23311~:k2=\23312~:k3=\23313~:k4=\23314~:k5=\23315~:\
        :k6=\23317~:k7=\23318~:k8=\23319~:k9=\23320~:kD=\2333~:\
        :kI=\2332~:kN=\2336~:kP=\2335~:kb=^H:kd=\217B:\
        :ke=\233?1l\E>:kh=\2331~:kl=\217D:kr=\217C:ks=\233?1h\E=:\
        :ku=\217A:le=^H:mb=\2335m:md=\2331m:me=\233m:mr=\2337m:\
        :nd=\233C:rc=\E8:sc=\E7:se=\23327m:sf=^J:so=\2337m:sr=\215:\
        :st=\210:ta=^I:ue=\23324m:\
        :up=\233A:us=\2334m:vb=\233?5h\233?5l:ve=\233?25l\233?25h:\
        :vs=\233?12;25h:vi=\233?25l:
#
xterm-hp|xterm with hpterm function keys:\
        :@7=\EF:k1=\Ep:k2=\Eq:k3=\Er:k4=\Es:k5=\Et:k6=\Eu:k7=\Ev:\
        :k8=\Ew:kC=\EJ:kD=\EP:kI=\EQ:kN=\ES:kP=\ET:kd=\EB:kh=\Eh:\
        :kl=\ED:kr=\EC:ku=\EA:tc=xterm-basic:
#
xterm-sco|xterm with SCO function keys:\
        :@7=\E[F:F1=\E[W:F2=\E[X:F3=\E[Y:F5=\E[a:F6=\E[b:F7=\E[c:\
        :F8=\E[d:F9=\E[e:FA=\E[f:FB=\E[g:FC=\E[h:FD=\E[i:FE=\E[j:\
        :FF=\E[k:ac=:k1=\E[M:k2=\E[N:k3=\E[O:k4=\E[P:k5=\E[Q:\
        :k6=\E[R:k7=\E[S:k8=\E[T:k9=\E[U:k;=\E[V:kD=\177:kI=\E[L:\
        :kN=\E[G:kP=\E[I:kd=\E[B:kh=\E[H:kl=\E[D:kr=\E[C:ku=\E[A:\
        :tc=xterm-basic:
#
xterm-vt52|xterm emulating vt52:\
        :bs:\
        :co#80:it#8:li#24:\
        :ae=\EG:as=\EF:bl=^G:cd=\EJ:ce=\EK:cl=\EH\EJ:cm=\EY%+ %+ :\
        :cr=^M:do=\EB:ho=\EH:kb=^H:kd=\EB:kl=\ED:kr=\EC:ku=\EA:\
        :le=\ED:nd=\EC:nw=^M^J:sf=^J:sr=\EI:ta=^I:up=\EA:
#
xterm-sun|xterm with Sun functionkeys:\
        :%1=\E[196z:&8=\E[195z:@0=\E[200z:@5=\E[197z:@7=\E[220z:\
        :F1=\E[192z:F2=\E[193z:K2=\E[218z:Km=\E[M:k1=\E[224z:\
        :k2=\E[225z:k3=\E[226z:k4=\E[227z:k5=\E[228z:k6=\E[229z:\
        :k7=\E[230z:k8=\E[231z:k9=\E[232z:k;=\E[233z:kD=\E[3z:\
        :kI=\E[2z:kN=\E[222z:kP=\E[216z:kh=\E[214z:\
        :tc=xterm-basic:
#
# vi may work better with this entry, because vi doesn't use insert mode much.
# |xterm-ic|xterm-vi|xterm with insert character instead of insert mode:\
xterm-ic|xterm-vi|xterm with insert char:\
        :mi@:\
        :IC=\E[%d@:ei@:ic=\E[@:im@:tc=xterm:
#
# Compatible with the X11R6.3 xterm
#
# Add the capability to "clear the screen" after exiting vi, more/less, etc.
#
xterm-r6-clear:\
        :te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:ue=\E[m:\
        :tc=xterm-r6:
xterm-r6|xterm-old|X11R6 xterm:\
        :am:bs:km:mi:ms:pt:xn:\
        :co#80:kn#20:li#24:\
        :*6=\E[4~:@0=\E[1~:@7=\E[4~:AL=\E[%dL:DC=\E[%dP:DL=\E[%dM:\
        :DO=\E[%dB:F1=\E[23~:F2=\E[24~:F3=\E[25~:F4=\E[26~:\
        :F5=\E[28~:F6=\E[29~:F7=\E[31~:F8=\E[32~:F9=\E[33~:\
        :FA=\E[34~:LE=\E[%dD:RI=\E[%dC:UP=\E[%dA:ae=^O:al=\E[L:\
        :as=^N:bl=^G:cd=\E[J:ce=\E[K:cl=\E[H\E[2J:cm=\E[%i%d;%dH:\
        :cs=\E[%i%d;%dr:ct=\E[3g:dc=\E[P:dl=\E[M:eA=\E)0:ei=\E[4l:\
        :ho=\E[H:im=\E[4h:\
        :is=\E[m\E[?7h\E[4l\E>\E7\E[r\E[?1;3;4;6l\E8:\
        :k1=\E[11~:k2=\E[12~:k3=\E[13~:k4=\E[14~:k5=\E[15~:\
        :k6=\E[17~:k7=\E[18~:k8=\E[19~:k9=\E[20~:k;=\E[21~:\
        :kD=\E[3~:kI=\E[2~:kN=\E[6~:kP=\E[5~:kb=^H:kd=\EOB:\
        :ke=\E[?1l\E>:kh=\E[1~:kl=\EOD:kr=\EOC:ks=\E[?1h\E=:\
        :ku=\EOA:md=\E[1m:me=\E[m:ml=\El:mr=\E[7m:mu=\Em:nd=\E[C:\
        :rc=\E8:rs=\E[m\E[?7h\E[4l\E>\E7\E[r\E[?1;3;4;6l\E8:\
        :sc=\E7:se=\E[m:sf=^J:so=\E[7m:sr=\EM:\
        :ue=\E[m:up=\E[A:us=\E[4m:
#
# Compatible with the R5 xterm
#
# Add the capability to "clear the screen" after exiting vi, more/less, etc.
#
xterm-r5-clear:\
        :te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:ue=\E[m:\
        :tc=xterm-r5:
xterm-r5|X11R5 xterm X11R5:\
        :am:bs:km:mi:ms:pt:xn:\
        :co#80:kn#4:li#24:\
        :@7=\E[4~:AL=\E[%dL:DC=\E[%dP:DL=\E[%dM:DO=\E[%dB:\
        :IC=\E[%d@:UP=\E[%dA:al=\E[L:cd=\E[J:ce=\E[K:cl=\E[H\E[2J:\
        :cm=\E[%i%d;%dH:cs=\E[%i%d;%dr:ct=\E[3g:dc=\E[P:dl=\E[M:\
        :ei=\E[4l:ho=\E[H:im=\E[4h:\
        :is=\E[r\E[m\E[2J\E[H\E[?7h\E[?1;3;4;6l\E[4l:\
        :k1=\E[11~:k2=\E[12~:k3=\E[13~:k4=\E[14~:kb=^H:kd=\EOB:\
        :ke=\E[?1l\E>:kh=\E[1~:kl=\EOD:kr=\EOC:ks=\E[?1h\E=:\
        :ku=\EOA:md=\E[1m:me=\E[m:mr=\E[7m:nd=\E[C:rc=\E8:\
        :rs=\E>\E[?1;3;4;5;6l\E[4l\E[?7h\E[m\E[r\E[2J\E[H:\
        :sc=\E7:se=\E[m:sf=^J:so=\E[7m:sr=\EM:\
        :up=\E[A:us=\E[4m:
#
# Customization begins here.
xterm-xfree86|xterm terminal emulator (XFree86):\
        :tc=xterm-new:
#
# This is the only entry which you should have to customize, since "xterm"
# is widely used for a variety of incompatible terminal emulations including
# color_xterm and rxvt.
xterm|X11 terminal emulator:\
        :tc=xterm-new:
#       :tc=xterm-r6:


text:
Q: current_user and destroying comments (refined) I recently posted a question similar to this but I've narrowed down the problem and wanted to refine the question. Anyway, I have a blog with recipes (equivalent of posts or articles) and comments on those recipes. I've put in my application_controller.rb file the code for current_user:
def current_user
  return unless session[:user_id]
  @current_user = User.find_by_id(session[:user_id])
end

# Make current_user available in templates as a helper
helper_method :current_user

I tried to make it so that you had to be logged in to delete a comment on an article. That code is in my comments_controller.rb file:
def destroy
  @recipe = current_user.recipes.find(params[:recipe_id])
  @comment = @recipe.comments.find(params[:id])
  @comment.destroy
  redirect_to @recipe, notice: 'Comment Deleted'
end

I've narrowed it down to that first line of code within the destroy method. I believe that my application can't associate the recipe with the current_user and so can't save @recipe properly, so the @comment won't delete. Each recipe has a user_id parameterHere's the error, from the server console, when I try to delete a comment with a logged in user:
Started DELETE "/recipes/4/comments/4" for 127.0.0.1 at 2015-02-12 13:42:54 -0500

Processing by CommentsController#destroy as HTML
Parameters: {"authenticity_token"=>"+0pWfNOPJXLOzgUhA//q4ySh5rk01SlKmTRQx0qdDOrvkUOcIzF8GCb5jKwjsDlUvQsxxGTOOtJv6rPjn3jfoA==", "recipe_id"=>"4", "id"=>"4"}

User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 6]]
CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 6]]

Recipe Load (0.1ms)  SELECT  "recipes".* FROM "recipes" WHERE "recipes"."user_id" = ? AND "recipes"."id" = ?  ORDER BY published_at DESC, title ASC LIMIT 1  [["user_id", 6], ["id", 4]]

Completed 404 Not Found in 50ms

ActiveRecord::RecordNotFound (Couldn't find Recipe with 'id'=4 [WHERE "recipes"."user_id" = ?]):
app/controllers/comments_controller.rb:15:in `destroy'

Anyone have any ideas?
NOTE: when I change the first line of code within the destroy method of my comments_controller to:
@recipe = Recipe.find(params[:recipe_id])

it works. I don't want that to be the code though bc then a non-logged in user can delete comments. AND, that revised code is the same code as a private method i put within my comments_controller:
private
def load_recipe
  @recipe = Recipe.find(params[:recipe_id])
end

There is also a before_filter on that method in my comments_controller:
before_filter :load_recipe, :except => :destroy
before_filter :authenticate, :only => :destroy


text:
Q: Para que serve a classe EmptyIterator? Na documentação do PHP, tem uma classe chamada EmptyIterator
Quando olho a documentação do método EmptyIterator::rewind(), lá está escrito:

No operation, nothing to do. (Nenhuma operação, nada a fazer)

E os outros métodos lançam exceções ou retornam FALSE.
Qual é o objetivo de se ter um iterator vazio no manual? Pois, se eu tivesse que estender essa classe, os métodos herdados não serviriam para nada !?!?

A: Creio que a solução para essa pergunta pode ser encontrada nessa resposta dada pelo @Maniero, aqui no SOPT, Pra que serve o padrão Null Object?
Provavelmente o EmptyIterator foi criado como uma forma de fazer esse objeto atenderem os requisitos da interface Iterator, sem realizar nenhuma operação com os métodos de contrato.
Ou seja, se encaixaria perfeitamente no pattern Null Object.
Exemplo:
function required_iterator(Iterator $it)
{
   // Faz um paranauê aqui
}

required_iterator(new ArrayIterator([1, 2, 3]))

//Atende o requisito da função: Uma classe que implemente iterator

required_iterator(new EmptyIterator);

É um exemplo muito simples, que não mostra totalmente a eficácia desse método, mas que exemplifica o que o padrão Null Object representa.