text:
Q: Getting undefined when I call the props of ReactNative GooglePlacesAutocomplete api on another component I'm new to working with RN and I'm trying to use the
ReactNativeGooglePlaceAutocomplete module on the GoogleMapSearch class component to pass its data object props to another GoogleMapView class component that uses the ReactNativeMaps module. After numerous tries (Majorly wired the props as stateful objects) but still unsuccessful
, I keep getting this error: Cannot read property 'geometry' of undefined (i.e the props passed to GoogleMapView component is undefined). Overall, my intuition is that with the help of these two libraries, a user can type in the name of a place and the map will refocus to the searched location or return places around the searched location. Any help will be appreciated. Thanks. Below are the snippets of code from the two components:
1st Component:
import React, { Component } from 'react';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import GoogleMapView from './GoogleMapView';

class GoogleMapSearch extends Component {

//   constructor(props){
//   super(props);
//   this.state = {
//     data:[],
//     details:null
//   };
//   this.onSearchPress = this.onSearchPress.bind(this);
//
// }
//
// onSearchPress(data,details){
//   return(
//         (data,details = null) => {
//         console.log("dataObj Log: ",data);
//         console.log("detailsObj Log: ",details);
//         this.setState({ data: data , details: details })
//        <GoogleMapView searchRegion= {this.state.details} />
//       }
//     );
// }

  render(){

    const homePlace = {description: 'Home', geometry: { location: { lat: 48.8152937, lng: 2.4597668 } }};
    const workPlace = {description: 'Work', geometry: { location: { lat: 48.8496818, lng: 2.2940881 } }};

    return(
      <GooglePlacesAutocomplete
        placeholder='Enter Location'
        minLength={2}
        autoFocus={false}
        fetchDetails={true}
        onPress={(data,details = null) => {
                console.log("dataObj Log: ",data);
                console.log("detailsObj Log: ",details);
                // this.setState({ data: data , details: details })
               <GoogleMapView searchRegion= {details} />
              }}
        query={{
                // available options: https://developers.google.com/places/web-service/autocomplete
                key: API_KEY,
                language: 'en', // language of the results
                types: '(cities)', // default: 'geocode'
              }}
        styles={{
          textInputContainer: {
            backgroundColor: 'rgba(0,0,0,0)',
            borderTopWidth: 0,
            borderBottomWidth:0
          },
          textInput: {
            marginLeft: 0,
            marginRight: 0,
            height: 38,
            color: '#5d5d5d',
            fontSize: 16
          },
          predefinedPlacesDescription: {
            color: '#1faadb'
          },
        }}
        currentLocation={true}
        nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
        // GoogleReverseGeocodingQuery={{
        //   // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
        // }}
        GooglePlacesSearchQuery={{
          // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
          rankby: 'distance',
          // type: 'gym',
        }}
        predefinedPlaces={[homePlace, workPlace]}
      />
);
}

};

export default GoogleMapSearch;

2nd component:
import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions, Image, TextInput } from 'react-native';
let {height, width} = Dimensions.get('window');
import MapView from 'react-native-maps';
import Hamburger from 'react-native-hamburger';
import somethingSearch from './SearchBar';
import { connect } from 'react-redux';
import { fetchLocation } from '../actions';
import GoogleMapSearch from './GoogleMapSearch';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

class GoogleMapView extends Component {

  constructor(props){
     super(props);
     this.state = {
       region: {
         latitude: 34.034818,
         longitude: -118.456037,
         latitudeDelta: 0.005,
         longitudeDelta: 0.005,
       },
       markers:[
         {latlng: {latitude: 34.011927, longitude: -118.467255},
           image: require('./images/something.png'),
           photo: require('./images/something.png'),
           title: "something accepted" , description: "we are here"},
         {latlng: {latitude: 34.034818, longitude: -118.456037},
           image: require('./images/something.png'),
           photo: require('./images/something.png'),
           title: "something accepted" , description: "we are here"},
         {latlng: {latitude: 34.01536, longitude: -118.496945},
          image: require('./images/something.png'),
           photo: require('./images/something.png'),
           title: "something accepted" , description: "we are here"},
       ],
       active: true,
       term: "",

     };
     this.onRegionChange = this.onRegionChange.bind(this);
     this.onInputChange = this.onInputChange.bind(this);
    //  this.onSearchSubmit = this.onSearchSubmit.bind(this);
   }

   onInputChange(text){
     console.log("onInputChange text obj: ",text)
     this.setState({ term: text })
   }

   onRegionChange(region) {
     console.log("onRegionChange 1st region obj: ",region)
     this.setState({ region:{ latitude:this.props.searchRegion.geometry.location.lat ,longitude: this.props.searchRegion.geometry.location.lng } });
   }

  //  onSearchSubmit(){
  //    console.log("onSearchSubmit fetchLocation obj: ", this.state.term)
  //    console.log("inside onSearchSubmit")
  //    this.props.fetchLocation(this.state.term);
  //      this.setState({term:''});
  //         console.log("after fetchLocation")
  //  }

   render() {
  let coordinates = this.state.markers.map(marker => marker.latlng);
  // const rad_num = 100;
  return (
    <View style={styles.container}>
        <View style={{ flex: 1, flexDirection: "row" }}>
        <Hamburger active= { this.state.active } type="cross" onPress={() => this.setState({ active: !this.state.active })} />
          <GoogleMapSearch />
        </View>
      <MapView style={styles.map} region={this.state.region}
        onRegionChange={this.onRegionChange}>
        <MapView.Circle center={this.state.markers[0].latlng}
         radius={1000} strokeWidth={5} fillColor="#0f0a"/>
        <MapView.Polyline coordinates={coordinates}
          strokeWidth={5} strokeColor="#00fa"/>
        <MapView.Polygon coordinates={coordinates}
          strokeWidth={5} strokeColor="#00fa" fillColor="#0aaa"/>
        {this.state.markers.map((marker, i) => (
          <MapView.Marker key={i} coordinate={marker.latlng} title={marker.title} description={marker.description}>
            <View style={styles.pin}>
              <Image style={styles.pinImage} source={marker.image}/>
              <Text style={styles.pinText}>
                {marker.title}
              </Text>
            </View>
            <MapView.Callout>
              <View style={styles.callout}>
                <Image style={styles.calloutPhoto} source={marker.photo}/>
                <Text style={styles.calloutTitle}>{marker.title}</Text>
                <Text>{marker.description}</Text>
              </View>
            </MapView.Callout>
          </MapView.Marker>
        ))}
      </MapView>
      <View style={styles.container}>
        <Text>
          Latitude: {this.state.region.latitude}{'\n'}
          Longitude: {this.state.region.longitude}{'\n'}
          LatitudeDelta: {this.state.region.latitudeDelta}{'\n'}
          LongitudeDelta: {this.state.region.longitudeDelta}
        </Text>
      </View>
    </View>
  );
}
}

const styles = StyleSheet.create({
container: {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
  backgroundColor: '#F5FCFF'
},
burger: {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
},
map: {
  width: width,
  height: height*2/3
},
pin: {
  backgroundColor: '#fffa',
  justifyContent: 'center',
  alignItems: 'center',
  borderColor: 'black',
  borderWidth: 2,
  padding: 5,
  borderRadius: 10
},
pinImage: {
  width: 25,
  height: 25
},
pinText: {
  color: 'green'
},
callout:{
  flex: 1,
  paddingRight: 10,
  paddingBottom: 10,
  marginRight: 10,
  marginBottom: 10
},
calloutPhoto:{
  flex: 1,
  width: 166,
  height: 83
},
calloutTitle:{
  fontSize: 16,
}
});

// function mapStateToProps(state){
//
//   return { location:state.location };
// };

export default GoogleMapView;


text:
Q: Can we talk about the $k$-planes in the product of two projective spaces? I am thinking about is there a natural way to define $k$-planes in $\mathbb{P^n}\times\mathbb{P^m}$. Here is some candidates I can come up with:

*

*Being a $k$-plane is a local condition, so we can check it locally. And locally $\mathbb{P^n}\times\mathbb{P^m}$ looks the same as $(n+m)$-vector space, hence gives us a natural definition.

*Except for some base points, there is a natural morphism $$\mathbb{P^{n+m}}\backslash B\to\mathbb{P^n}\times\mathbb{P^m}$$ so we can define a $k$-plane in $\mathbb{P^n}\times\mathbb{P^m}$ if it is the image for some $k$-plane in $\mathbb{P^{n+m}}$.

*Using Segre embedding $$\mathbb{P^n}\times\mathbb{P^m}\to \mathbb{P^{nm+n+m}}$$ to define the $k$-planes as in $\mathbb{P^{nm+n+m}}$.
I don't know if these difinitions are equivalent. And in fact I am not satisfied with any of them. I want to know if there is a more natural way to define it?

A: Usually, to speak of a $k$-plane on an algebraic variety $X$, one needs to fix its projective embedding. If an embedding $X \subset \mathbb{P}^N$ is chosen, then a $k$-plane on $X$ is a subvariety, which when considered as a subvariety of $\mathbb{P}^N$ is a $k$-plane. This is also equivalent to its Hilbert polynomial being equal to $(t+1)(t+2)\cdots(t+k)/k!$.
In case $X = \mathbb{P}^n \times \mathbb{P}^m$, it is natural to consider the Segre embedding $\mathbb{P}^n \times \mathbb{P}^m \subset \mathbb{P}^{nm+n+m}$. Then it is easy to see that every $k$-plane lies in a fiber of either of the two natural projections of $X \to \mathbb{P}^n$ or $X \to \mathbb{P}^m$.
EDIT. The restriction of $O(1)$ from $\mathbb{P}^{nm+n+m}$ to $\mathbb{P}^k$ should be isomorphic to $O(1)$. But it restricts to $\mathbb{P}^n \times \mathbb{P}^m$ as $O(1,1)$, hence its restriction to $\mathbb{P}^k$ is the tensor product of the restriction of $O(1,0)$ and $O(0,1)$. Both these bundles are globally generated, hence so are their restrictions to $\mathbb{P}^k$. Thus, the restrictions are isomorphic to $O(k_1)$ and $O(k_2)$ with $k_1,k_2 \ge 0$, and their tensor product is $O(k_1+k_2) \cong O(1)$, hence $k_1 + k_2 = 1$. This means that either $k_1 = 0$ or $k_2 = 0$. In the first case the composition $\mathbb{P}^k \to \mathbb{P}^n \times \mathbb{P}^m \to \mathbb{P}^n$ is given by line bundle $O$, hence is constant, hence $\mathbb{P}^k$ sits in the fiber. Similarly in the second case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android make a resizable split screen inside a contraintlayout I want to have a splitter inside a contraintlayout to be able to change the relative size of 2 images view.
Example : when dragging the double arrow below should resize image1 / image2 according to arrow position.

For this here is my layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/main_divider_img" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/main_divider_img"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/main_divider_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/divider" />

</androidx.constraintlayout.widget.ConstraintLayout>

And a have an onTouchListener on my divider image :
 View.OnTouchListener dividerTouchListener = new View.OnTouchListener() {

        private float  mInitialY;

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    mInitialY = view.getY() - motionEvent.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    view.animate().y(motionEvent.getRawY() + mInitialY).setDuration(0).start()
                    break;
                default:
                    return false;
            }
            return true;

        }
    };

At start my spliter image is between images, but when I move it, the constraints on imageView1 and imageView2 are not updated and they are not resized, and my splitter images moves on screen independently of imageView1 and imageView2.
This is what I get

And this is what I want :

How can I acheive this ?

A: After trying more I found a somution using guide lines :
Both imageView and splitview are now constraint to the guideline
When moving the split image I change the guideline percent
Here is the layout :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:background="@color/rejectedRed"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/acceptedGreen"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/image1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.41" />

    <ImageView
        android:id="@+id/main_divider_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toTopOf="@+id/guideline"
        app:srcCompat="@drawable/divider" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here is the touchListener much simpler :
 @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            int height = 0;
            switch (motionEvent.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    break;
                case MotionEvent.ACTION_MOVE:
                    height = ((ConstraintLayout) findViewById(R.id.main)).getHeight();
                    Guideline guideLine = (Guideline) findViewById(R.id.guideline);
                    ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) guideLine.getLayoutParams();
                    params.guidePercent = (motionEvent.getRawY()) / height;
                    guideLine.setLayoutParams(params);

                    break;
                default:
                    return false;
            }
            return true;

        }

I hope it can help somebody.


text:
Q: How to override the radio.phtml in custom module? I have created a custom module which change the template for the bundle product option, it is in the radio.phtml.
I am now overriding the radio.phtml on a new theme xxx/template/bundle/catalog/product/view/type/bundle/option/radio.phtml.
But I want to put the radio.pthml into my custom module folder, that is
template/mycompany/mymodule/radio.phtml
I understand that I can do in the mymodule.xml layout by using <action method="setTemplate">, but how can I know the <reference> name for the radio.phtml?

A: you need to rewrite this block because the theme are set in block..
Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option_Radio

you  can in this function
protected function _construct()
    {
        $this->setTemplate('bundle/catalog/product/view/type/bundle/option/radio.phtml');
    }

you can rewrite block module like that
<global>
        <blocks>
            <bundle>
                <rewrite>
                    <catalog_product_view_type_bundle_option_radio>Spacename_Modulname_Block_Adminhtml_Radio</catalog_product_view_type_bundle_option_radio>
                </rewrite>
            </bumdle>
        </blocks>
    </global>

and call your phtml file
class Spacename_Modulname_Block_Adminhtml_Radio extends Mage_Core_Block_Template
{
  protected function _construct()
        {
            $this->setTemplate('test/radio.phtml'); //your file path link here
        }
}


text:
Q: base R plot to ggplot I am trying to put a base R plot I have into ggplot format. The base R version looks great but I have a lot of white space and when I try to save to PDF it keeps the white space and doesn't fit in well in a document.
I like the plot the way it is but I would also like to add a title, annotations and label the x and y axis along with being able to apply a ggplot theme.
(I am happy to remain in base R for this but I have more familiarity with ggplot) - any help would be great in translating this plot into ggplot since the plot is created in a for loop I am not sure how this translates to a data frame suitable for plotting in ggplot.
plot(0,0,xlim=c(0,28),ylim=c(0,1),
     xaxt="n",yaxt="n",bty="n",xlab="",ylab="",type="n")
i <- 1
j = 1
for(j in 1:7)
{
  test <- (6+j):13
  train <- (0+j):(5+j)
  arrows(0,1-j/20,15,1-j/20,0.05)

  x_dark <- seq(0,min(train)-1, by  = 1)
  y_dark <- rep(1-j/20,length(x_dark))
  points(x_dark,y_dark,pch = 19,col = "black")

  points(train,rep(1-j/20,length(train)),pch=19,col="blue")
  if(length(test) >= i)
    points(test[i], 1-j/20, pch=19, col="red")
  if(length(test) >= i)
    points(test[-i], rep(1-j/20,length(test)-1), pch=19, col="gray")
  else
    points(test, rep(1-j/20,length(test)), pch=19, col="gray")
}
text(17,.95," time")

The result:

A: In ggplot you usually keep data for symbols of the same type in one data frame. Here you have dots and arrows, which means two data frames should be the ideal organization. Adding of the text is left as an exercise for the reader. I believe that the code is much more legible like this:
library(tidyverse)

tibble(y = 1:7, x = 1, xend = 16) %>%
  mutate(y = -y, yend = y) ->
  darrows

expand.grid(x = 1:14, y = 1:7) %>%
  mutate(color = case_when(
    x < y + 1 ~ "black",
    x < y + 7 ~ "blue",
    x < y + 8 ~ "red",
    T ~ "gray70"
  ),
  y = -y) %>%
  ggplot(aes(x, y)) +
  geom_segment(aes(xend = xend, yend = yend), data = darrows,
               lineend = "butt", linejoin = "mitre",
               arrow = arrow(length = unit(.1, "inches"), type = "closed")) +
  geom_point(aes(color = color), size = 3) +
  coord_equal() +
  scale_color_identity() +
  theme_void()

The result

A: Your data looks like it's born from a matrix, where all nodes in a square are used/defined.
There are many ways you could take "some data source" into a matrix like this. I just typed numbers quickly into excel and then copied it into R, resulting in this:
m <- structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 3L, 2L, 2L, 2L,
2L, 2L, 4L, 4L, 3L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 3L, 2L, 2L, 2L,
4L, 4L, 4L, 4L, 3L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 3L, 2L, 4L, 4L,
4L, 4L, 4L, 4L, 3L), .Dim = c(7L, 14L))

While the next few lines convert these numbers to solid colors, the same effect could be done with ggplot2::scale_color_manual. After converting to literal colors, I convert into a 3-column frame using reshape2::melt (also works with data.table::melt, might work with tidyr:: funcs).
m[] <- c("black", "blue", "red", "gray")[m]
m[1:3, 1:3]
#      [,1]    [,2]    [,3]
# [1,] "black" "blue"  "blue"
# [2,] "black" "black" "blue"
# [3,] "black" "black" "black"

d <- reshape2::melt(t(m))
head(d)
#   Var1 Var2 value
# 1    1    1 black
# 2    2    1  blue
# 3    3    1  blue
# 4    4    1  blue
# 5    5    1  blue
# 6    6    1  blue

From here:
d %>%
  ggplot(aes(x = Var1, y = -Var2)) +
  geom_segment(data = arrows, aes(x = xmin, xend = xmax, yend = -Var2),
               arrow = arrow(length = unit(0.01, "npc"))) +
  geom_point(aes(color = value), size = 3) +
  scale_color_identity() +
  geom_text(data = data.frame(Var1 = ncol(m) + 2L, Var2 = 1, label = "time"),
            aes(label = label)) +
  labs(x = NULL, y = NULL) +
  theme_void()

A: An alternative way is to use a similar for loop than the one you use for building your base plot to build your dataframe as this:
y_dark <- NULL
y_blue <- NULL
y_red <- NULL
y_grey <- NULL

x_dark <- NULL
x_blue <- NULL
x_red <- NULL
x_grey <- NULL

for(x in 1:6)
{
  # Sequence for black points
  y_dark <- c(y_dark,1:x)
  x_dark <- c(x_dark,rep(x,x))

  # Sequence for blue points
  j <- x+1
  jmax <- j+6
  y_blue <- c(y_blue,j:jmax)
  x_blue <- c(x_blue, rep(x,length(j:jmax)))

  # Sequence for red points
  r <- jmax +1
  y_red <- c(y_red,r)
  x_red <- c(x_red, rep(x,length(r)))

  # sequence for grey points
  g <- r+1
  if(g > 14)
  {

  }
  else
  {
    y_grey <- c(y_grey,g:14)
    x_grey <- c(x_grey, rep(x,length(g:14)))
  }
}

df_dark <- data.frame(x = x_dark, y = y_dark, color = "black")
df_blue <- data.frame(x = x_blue, y = y_blue, color = "blue")
df_red <- data.frame(x = x_red, y = y_red, color = "red")
df_grey <- data.frame(x = x_grey, y = y_grey, color = "grey")

And then, you can plot it using:
library(tidyverse)
DF <- bind_rows(df_dark, df_blue, df_red, df_grey)
DF_arrow <- data.frame(x = 1:6, x_end = 1:6,
                       y = rep(1,6), y_end = rep(15,6))
ggplot() +
  geom_segment(data = DF_arrow,
               aes(x = -x, xend = -x_end, y = y, yend = y_end),
               arrow = arrow(length = unit(0.03, "npc")))+
  geom_point(imherit.aes = FALSE, data = DF, aes(x = -x, y = y, color = color),
             size = 4)+
  coord_flip()+
  scale_color_identity()+
  theme(axis.text = element_blank(),
        axis.title = element_blank())+
  annotate(geom = "text", x = -1, y = 16, label = "time")


text:
Q: How do I keep a div visible when the user goes to a different page? So, the user clicks something and then a div pops out from the left side.
Then I save via a cookie whether or not the div is "visible" or "hidden" in JavaScript.
$('#click').click(function()
{
    save_cookie('div', 'visible');

    $('.class').animate({'margin-right': '-20px'});

    return false;
});

if(get_cookie('div') != null)
{
    if(get_cookie('div') == 'visible')
    {
        $('.class').css({'margin-right': '-20px'});
    }
    else
    {
        $('.class').css({'margin-right': '0px'});
    }
}

So, if the user decides to go to a different page, I check whether or not I should display the div or not.
And the problem I'm having is that the div "blinks" for a second, when the user goes to a different page. And I know this is due to the fact that it takes a few seconds before the HTML, CSS and JavaScript is loaded.
But I was wondering if there is a better technique on how to do this? So it doesn't "blink."
BTW, I also tried to move the JavaScript to the head (from the bottom), but this also didn't change anything. :/

A: A simple solution could be to apply display:none in css as default value for div and change it then accordingly from jQuery.

A: is your javascript inside document.ready? It shouldn't be really, not if you want to avoid the flicker. I'd add it to the head just in it's own little script and use it to add a class to the html element. Then style the div to appear when that class is present.

A: You are close to the right code methodology - what you may want to change though is to start the page with the DIV visible, then animate it retracting. This hints to the user that there is something else that can appear (your div) and also makes it load properly.

A: you can use an iFrame that is the size of the browser window for main navigation, and have the overlay work happen outside the iFrame.


text:
Q: p4 shelve after editing the shelved files along with other files I have shelved files a.txt, b.txt, c.txt.
Now I want to make some changes to a.txt and b.txt and shelve along with a new file d.txt
So,

*

*As First step unshelve the shelved a.txt, b.txt and c.txt by using p4 unshelve -s <changelist>

*Make changes to the a.txt, b.txt and c.txt

*Now  what to ????? (Till here I am good, now what should be next step to shelve the a.txt ,b.txt, c.txt with changes along with d.txt)

Note: As after the step 2 , as a step 3,if I try to just give p4 shelve again , it just shows d.txt to shelve but not a.txt b.txt and c.txt.
Is there any easy way to do it?

A: You should gotten a change number when you did the p4 shelve. If you can't remember it, p4 opened will tell you. You need to re-open d.txt and give it that change number using p4 reopen -c <change#> d.txt. Then run p4 shelve -r to update the shelved files.

A: As others have noted in their answers, all of the files must be in the same changelist when you shelve them, so you'll need to reopen them into the correct changelist in order to update the original shelf.
I want to encourage you, though, to avoid the habit of updating shelves.
In my experience, it is almost always nicer to create a new shelf, and keep the old shelf around as the original "version" of your changes.
Shelves themselves aren't versioned, so when you update your shelf, you overwrite the previous copy of the shelf with the latest copy.
When you are making iterative changes, and capturing snapshots of them using shelves, it is very nice to create multiple shelves, one for each snapshot, so that you can go back and forth between the different approaches to your overall change.
After all, you might decide that you didn't want d.txt after all, and you want to get back to the approach that you had with just a.txt, b.txt, and c.txt.
If you've created two separate shelves, you can move back and forth between them to your heart's content.
Then, once you've finally decided (and submitted the shelf that you decided upon using 'submit -e'), you can discard the other shelves by running 'shelve -d -c NNN' and 'change -d NNN' and the server will entirely clean up all the resources used by those no-longer-wanted shelves.

A: Below picture will show it pictorially


text:
Q: Installing MySQL+Smarty I'd like to start learning WWW-programming in my Linux Mint. I have installed PHP and now I'd like to install MySQL. I tried to follow instructions on http://www.cyberciti.biz/faq/install-mysql-server-5-on-ubuntu-linux/ but I got the following error message:
sudo /etc/init.d/apache2 restart
* Restarting web server apache2
apache2:    Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName

... waiting .apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName

What am I doing wrong? And how can I install Smarty on my computer?

A: Define a variable ServerName in your http.conf file. When a name isn't defined apache uses 127.0.0.1(loopback) address as the server name.
This is not an error and apache is running despite through these.


text:
Q: Box2D with UIKit - Body Physics I followed this tutorial on how to add Box2D to my existing ViewBased Application.
http://www.cocoanetics.com/2010/05/physics-101-uikit-app-with-box2d-for-gravity/
Now when my body/UIButton is above half way my screen, it flies upward. and when it's half way downward, it flies downward. Also the physics are not seeming to be very realistic. I built my world the same way it is (with a couple of modifications to make it Xcode 4.0 compatible) built in the tutorial. Same goes for the timer, and the body creation. Anyone know what's wrong? (let me know if you need more detail)
Here is my code for body creation:
// Define the dynamic body.

b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

CGPoint p = physicalView.center;
CGPoint boxDimensions = CGPointMake(physicalView.bounds.size.width/PTM_RATIO/2.0,physicalView.bounds.size.height/PTM_RATIO/2.0);

bodyDef.position.Set(p.x/PTM_RATIO, (self.stage.frame.size.height - p.y)/PTM_RATIO);
bodyDef.userData = (__bridge void *)physicalView;

// Tell the physics world to create the body
b2Body *body = world->CreateBody(&bodyDef);

// Define another box shape for our dynamic body.
b2PolygonShape dynamicBox;

dynamicBox.SetAsBox(boxDimensions.x, boxDimensions.y);

// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 3.0f; // 0 is a ball, and 1 is a rock
fixtureDef.friction = 0.3f; // 0 is a lubercated ball, 1 is rough as sand paper
fixtureDef.restitution = 0.5f; // 0 is a lead ball, 1 is a super bouncy ball
body->CreateFixture(&fixtureDef);

Here is my code for setting up the world:
CGSize screenSize = self.stage.bounds.size;

screenSize.width = 368;
// Define the gravity vector.
b2Vec2 gravity;
gravity.Set(0.0f, -9.81f);

// Do we want to let bodies sleep?
// This will speed up the physics simulation
bool doSleep = false;

// Construct a world object, which will hold and simulate the rigid bodies.
world = new b2World(gravity);
world->SetAllowSleeping(doSleep);

world->SetContinuousPhysics(true);

// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0); // bottom-left corner

// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2Body* groundBody = world->CreateBody(&groundBodyDef);

// Define the ground box shape.
b2EdgeShape groundBox;

// bottom
groundBox.Set(b2Vec2(0,0), b2Vec2(screenSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox, 0);

// top
groundBox.Set(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox, 0);

// left
groundBox.Set(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox, 0);

// right
groundBox.Set(b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox, 0);

// a dynamic body reacts to forces right away
body->SetType(b2_dynamicBody);

// we abuse the tag property as pointer to the physical body
physicalView.tag = (int)body;

A: The problem was I had an invisible UIView that programically pops into the view and started colliding with the other objects.


text:
Q: windows store app how to get back values from databinded usercontroles how can i get back values from data binder view elements
am using a list view and data binded it to collection
<ListView.Resources>
            <DataTemplate x:Key="DataTemplate1">
                <Grid Height="20" Width="100" Background="#FFF5F3F3" Tapped="Grid_Tapped">
                    <TextBlock Text="{Binding Name}" Foreground="#FF0E0303"/>
                    <TextBlock Text="{Binding Age}" Foreground="#FF0E0303"/>
                </Grid>
            </DataTemplate>

now what i want is get the values back at gridtapped event

A: Try this
<ListView x:Name="lv" IsItemClickEnabled="True" ItemClick="lv_ItemClick_1">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Height="20" Width="100" Background="#FFF5F3F3">
                <TextBlock Text="{Binding Name}" Foreground="#FF0E0303"/>
                <TextBlock Text="{Binding Age}" Foreground="#FF0E0303"/>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    lv.ItemsSource = new List<Person>
    {
        new Person("Charles", 25),
        new Person("Mark", 27),
        new Person("John", 22),
    };
}

private void lv_ItemClick_1(object sender, ItemClickEventArgs e)
{
    var objPerson = (Person)e.ClickedItem;
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}


text:
Q: How to animate two figures in Matplotlib? I am using Matplotlib 2.0.2 in a Python 3.6 script on Windows 10 to plot data received over a network connection.  New data arrives 4 times per second.  I need to update two figures, each containing 8 subplots.  I do this using animation:
anim = []

anim.append( matplotlib.animation.FuncAnimation(fig_A, updatePlots_A, frames=None, interval=100, repeat=True) )
anim.append( matplotlib.animation.FuncAnimation(fig_B, updatePlots_B, frames=None, interval=100, repeat=True) )

plt.show()

My question is whether it is ok to make two FuncAnimation calls in this way?  Is that the most efficient way of handling the plots?
The figures are not very responsive to user input.  Moving a figure by dragging it with the mouse is very sluggish.
I've chosen:
frames=None, interval=100

because I want each of my update functions to be called at 10Hz. Will the code achieve this (machine performance permitting)?
I tried using matplotlib.pyplot.pause() instead of FuncAnimation() but found the update rate was then worse, so went back to using FuncAnimation().
Any comments for improvement would be appreciated.


text:
Q: How to call javascript function from ASP hidden value? i want to call javascript function which is already defined in ASP HiddenValue in server side(.ie in .cs file).
I have defined like below
in .cs side :
    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Attributes.Add("onclick", "javascript:return CallFun();");
        HF2.Value = " function() { alert('yes its working.... Woooww')};";
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       Response.Write("Yea its working woooooowww...");
    }

in aspx:
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <asp:HiddenField ID="HF2" runat="server" />

in js side:
function CallFun() {
    var hf2val = document.getElementById('HF2');
    //var hf2val = document.getElementById('HF2').value;
    hf2val();
    //window[hf2val]();
    return false;
}

I tried many times and searched on google also but i am not get the correct answer.
but it will works if i write like below
in .cs
    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Attributes.Add("onclick", "javascript:return yes();");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("Yea its working woooooowww...");
    }

in js:
function yes() {

    var just = function() { alert('yes its working.... Woooww')};
    just();
    return false;
}

in aspx:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

But I don't want to show like above. My aim is to hide javascript functionality like calendar functions in View source, Firebug.

A: You're not going to be able to work with values from a HiddenField within your Javascript code, because those values don't actually get rendered in the HTML that is sent to the client's browser.  Technically, they are persisted in the ViewState that is sent back and forth between the client, but that's not really something that Javascript can make use of.
Javascript code executes on the client's machine, which means you are required to send all of the code (and the values needed to run that code) to the client.  The simplest way to hide a value would be to put it in a hidden HTML element like so:
MyValue
but as you already know, this is easily visible by a user simply by viewing the source of the page.  The most you can hope for is to obfuscate your Javascript code, which makes it basically unreadable to humans while still being functional.  It's not foolproof, and could probably be reversed by anyone using a minimal amount of effort.  In many cases, obfuscation would also offer a side benefit of compressing your code, making it much smaller and decreasing your page load times.
Take a look at this question for some good examples of how you could accomplish this.


text:
Q: Android Not Granting Dump Permission For the purposes of monitoring Battery usage etc. I have code that executes a few dumpsys calls, reads and parses the output to extract data that I am interested in.
dumpsys battery, dumpsys statusbar, and dumpsys power all give me an error message for output like "Permission Denial: can't dump Battery service from pid..."
Also, when the application is launched there is an item in the log tagged with "PackageManager" statingNot granting permission android.permissionDUMP to package.... (protectionLevel = 3 ...)"
However, dumpsys cpuinfo and dumpsys netstat work and give me the correct output, which seems to be inconsistent.
I am able to generate dumpsys battery and the like from the adb shell, but when I try to call it programmatically it does not work.
I have tried running this on a HTC Nexus One phone as well as the emulator and get the same results for each.  The weird thing is that this code worked on my Nexus One a day ago (before I upgraded from 2.2 to 2.3), and now it does not.  Is this because of the upgrade?
An example of the code I am trying to run is as follows:
        String command = "dumpsys battery";
    try {
        String s = null;
        Process process = Runtime.getRuntime().exec(command);

          BufferedReader stdInput = new BufferedReader(new
                     InputStreamReader(process.getInputStream()));

                BufferedReader stdError = new BufferedReader(new
                     InputStreamReader(process.getErrorStream()));

                // read the output from the command
                System.out.println("Here is the standard output of the command:\n");
                while ((s = stdInput.readLine()) != null) {
                    System.out.println(s);
                }

                // read any errors from the attempted command
                System.out.println("Here is the standard error of the command (if any):\n");
                while ((s = stdError.readLine()) != null) {
                    System.out.println(s);
                }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

How do I get the dumpsys to give me the correct output programmatically and how to I get the dump permission to be granted?
*The Nexus One is not rooted and I would like to get this working without having to root it for the purposes of my project
Thank you for your help

A: Regular applications cannot get the DUMP permission. It is reserved to system applications.

A: android.permission.Dump is protected by system, signature, and development permission protection levels. Line 1993 of the source shows you this. If your APK is signed with the framework cert, is in the priv-app directory, or debuggable (see below) you can use the pm service to grant the permission, but otherwise the code specifically prevents what you're asking for (line 2624 of source).
Debuggable APKs can be created through setting the debuggable attribute on a buildType via build.gradle. Sample Android DSL:
android {
    ...
    buildTypes {
        debug {
            debuggable true
            ...
        }
        quality_assurance {
            debuggable true
        }
    ...
}

A: If your handset had been rooted, 'dumpsys activity' will work on Android2.3:
private static void dumpIT0(String sCmd) {
    try {
        String s = null;
        String command = "su -c " + sCmd;
        Process process = Runtime.getRuntime().exec(command);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                process.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(
                process.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e);
    }
}
sCmd = "dumpsys activity";


text:
Q: set of string to be search in another set What is the best way to search a group of sentences in a larger predefined group of sentences?
Larger predefined groups of sentences can hold 20000 sentences and one sentence may constitute of maximum 250 characters.
There is a scenario where the size of both become the same.
My Approach -
Stored both the groups in a list. Used binarysearch from java api.

A: Maybe something like this?
val customers: Set[String] = Set(
  "Luis",
  "Oliver",
  "abhi"
)

def thirdPartyService(): List[String] =
  List(
    "Luis",
    "Miguel",
    "Oliver"
  )

val result = thirdPartyService().filter(customers)
// result: List[String] = List(Luis, Oliver)

Or, if you can get the result from the third party service also as a Set, you can do this:
val customers: Set[String] = Set(
  "Luis",
  "Oliver",
  "abhi"
)

def thirdPartyService(): Set[String] =
  Set(
    "Luis",
    "Miguel",
    "Oliver"
  )

val result = thirdPartyService() & customers // Also known as intersect.
// result: Set[String] = Set(Luis, Oliver)

(in any case, make sure to check the scaladoc next time, you will find it has a lot of useful methods)


text:
Q: How to prevent hystrix fallbacks triggerd by certain exceptions in a @FeignClient interface?  Recently I've been instructed to define some fallback for our existing feign clients in our spring boot projects. I did some research and apparently Hystrix is the way to go. After integrating it with the project, I noticed that every time I don't received desired response from the target service (for example when I receive a response with http status 403 instead of 200) , client switches to fallback method.
Well, That is not the desired flow in our case. After searching for solutions I did find out that HystrixCommands are the proper way to handle this problem. According to this I could use @HystrixCommand to prevent triggering the fallback.  I did so but it does not appear to be working.
My question is how can I configure hystrix to suite my needs.
Here is simple version of what I've came up with so far:
@FeignClient(name="test-client", fallback=TestClientFallback.class)
public interface TestClient
{
   //---I have emplemented a custom FeignDecoder to throw TestException
   @HystrixCommand(ignoreExceptions=TestException.class)
   Boolean isUserActive(Integer userId);

   public class TestClientFallback implements TestClient
   {
      @Override
      public Boolean isUserActive(Integer)
      {
          //---default fail over scenario
      }
   }

}

Thanks in advance.


text:
Q: restrict coupon codes for only one time use in magento 1.9.0 For orders above 200, we are giving free shipping on our site.
We would also like to have a "Free Shipping " coupon code applicable to orders below 200
I gave Uses per Coupon : 1 , Uses per Customer : 1
(see attached image) but still for registered customers also, can use coupon codes many times and buy the product.
Where is the problem?

A: To apply that rules to guest  user, you need to also select NOT LOGGED IN at  Customer group multiple options.
Magento counts this as guest customer.
Uses per Coupon
The number of times the coupon code can be used.
Uses per Customer
Determines how many times the coupon code can be used by the same registered customer who belongs to any of the selected customer groups. The setting does not apply to guest shoppers who are members of the NOT LOGGED IN customer group, or to customers who shop without logging in to their accounts. If there is no limit, leave the field blank.
See at here


text:
Q: auto complete in command minibuffer of emacs Which setting needs to be done in init.el file, which allows completing the rest of command if one hit M-x and initial letter of the command.
Infact in need something similar as ido-mode for minibuffer too

A: The ido-mode for the "M-x minifuffer" is called smex (smex use ido).
Available on the main package repos of Emacs.  Homepage here

A: I think you are talking about incremental completion, i.e., having Emacs automatically complete what you type in the minibuffer, without your having to explicitly request completion (e.g., using TAB).
Incremental completion is available in Icicles, as well as Ido and IswitchB. And icomplete-mode shows you completion candidates in a similar way to Ido and IswitchB.
Icicles incremental completion has two aspects:

*

*When buffer *Completions* is displayed and updated, showing you the candidates matching your input -- how soon that happens and what triggers updating

*Whether and how much your minibuffer input is expanded (completed) to reflect the set of matching completions
Wrt *Completions* display (#1):
You can use C-# to cycle among the levels (normal, eager, off) at any time.

*

*Normal means that *Completions* is not displayed until you ask for it, but thereafter it is automatically updated as you type/edit your input.

*Eager means that *Completions* is displayed as soon as you type something that matches at least two candidates.
(There is also an option to show  *Completions* from the outset, before you type anything -- useful as a kind of menu.)  You can also specify how long to wait after you type or delete a character before updating *Completions*.
Wrt input expansion (#2):
Icicles is unique in expanding your input to (typically) the longest common match among all completions, even when completion uses apropos matching (that is, regexp or substring -- S-TAB), not just prefix matching (TAB).
There are 4 levels/behaviors for this expansion, plus off (no expansion):

*

*Off -- this is like Ido and IswitchB: completions are shown, but your input is not completed

*On request -- expand your input only when requested (TAB or S-TAB)

*On request or sole candidate -- on request or when there is only one match

*Always for TAB, on request for S-TAB -- TAB expands whenever possible; S-TAB is like previous

*Always -- expand input whenever possible

C-" toggles between two of the input-expansion behaviors that you choose (a user option), and C-M-" cycles among all of the behaviors.


text:
Q: C# Minio PutBucket Request: A WebException with status NameResolutionFailure was thrown I'm working on an Amazon s3 Compatible Object Storage solution (Minio).
I have an Minio server on e.g 192.168.235.143:9000
I have tried to get List of buckets on C# version of Amazon s3 Api.
Everything works fine.
When I try to Put a Bucket into this server e.g test1, Visual studio throws this request into an Exception:
Amazon.Runtime.AmazonServiceException:
'A WebException with status NameResolutionFailure was thrown.'

WebException: The remote name could not be resolved: 'test1.192.168.235.143'

here is my code:
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "192.168.235.143:9000";
AmazonS3Client client = new AmazonS3Client(AccessKey, SecretKey, config);
PutBucketRequest request = new PutBucketRequest();
request.BucketName = "test1";
// this Line will throws above exception :
client.PutBucket(request);

but ListBuckets works for make me confused:
AmazonS3Client client = new AmazonS3Client(AccessKey, SecretKey, config);
var response = client.ListBuckets();
foreach (S3Bucket b in response.Buckets)
{
    MessageBox.Show(string.Format("{0}\t{1}", b.BucketName, b.CreationDate));
}

What i have tested to check this Exception's cause:

*

*I have Installed it on a Virtual machine and a local Version for doubly check this issue but it still persists.

*I Even Changed Minio port to the port #80

*I Even used "play.min.io" but has no difference

I need to use a known interface so we be able to port into another Object Storage Platform e.g Ceph, ....
I have no Idea to get it resolved yet.
Please Help me to find my mistake or a better solution

A: Here i have found a sample working code, Thanks to Minio GitHub Community:
using Amazon.S3;
using System;
using System.Threading.Tasks;
using Amazon;

class Program
{
     private const string accessKey = "PLACE YOUR ACCESS KEY HERE";
     private const string secretKey = "PLACE YOUR SECRET KEY HERE"; // do not store secret key hardcoded in your production source code!

     static void Main(string[] args)
     {
         Task.Run(MainAsync).GetAwaiter().GetResult();
     }

     private static async Task MainAsync()
     {
         var config = new AmazonS3Config
         {
             RegionEndpoint = RegionEndpoint.USEast1, // MUST set this before setting ServiceURL and it should match the `MINIO_REGION` enviroment variable.
             ServiceURL = "http://localhost:9000", // replace http://localhost:9000 with URL of your MinIO server
             ForcePathStyle = true // MUST be true to work correctly with MinIO server
         };
         var amazonS3Client = new AmazonS3Client(accessKey, secretKey, config);

         // uncomment the following line if you like to troubleshoot communication with S3 storage and implement private void OnAmazonS3Exception(object sender, Amazon.Runtime.ExceptionEventArgs e)
         // amazonS3Client.ExceptionEvent += OnAmazonS3Exception;

         var listBucketResponse = await amazonS3Client.ListBucketsAsync();

         foreach (var bucket in listBucketResponse.Buckets)
         {
             Console.Out.WriteLine("bucket '" + bucket.BucketName + "' created at " + bucket.CreationDate);
         }
         if (listBucketResponse.Buckets.Count > 0)
         {
             var bucketName = listBucketResponse.Buckets[0].BucketName;

             var listObjectsResponse = await amazonS3Client.ListObjectsAsync(bucketName);

             foreach (var obj in listObjectsResponse.S3Objects)
             {
                 Console.Out.WriteLine("key = '" + obj.Key + "' | size = " + obj.Size + " | tags = '" + obj.ETag + "' | modified = " + obj.LastModified);
             }
         }
     }
 }


text:
Q: Assignment of a 2 dimensional struct array I have defined a new struct type called RGBTRIPLE but I'm not able to assign values to it.I'm trying to create a test file to test the different parts of blur code in cs50.
#include <stdio.h>
#include <stdint.h>

typedef uint8_t  BYTE;

typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
}
RGBTRIPLE;

int main(void)
{
    int height = 3;
    int width = 3;
    RGBTRIPLE image[3][3];

    image[2][2].rgbtRed = {{10, 40, 70},{110, 120, 130},{200, 220, 240}};
    image[2][2].rgbtGreen = {{20, 50, 80},{130, 140, 150},{210, 230, 250}};
    image[2][2].rgbtBlue = {{30, 60, 90},{140, 150, 160},{220, 240, 255}};

}

I am getting a error
2.c:22:24: error: expected expression
        image[2][2].rgbtRed = {{10, 40, 70},{110, 120, 130},{200, 220, 240}};
                              ^
2.c:23:26: error: expected expression
        image[2][2].rgbtGreen = {{20, 50, 80},{130, 140, 150},{210, 230, 250}};
                                ^
2.c:24:25: error: expected expression
        image[2][2].rgbtBlue = {{30, 60, 90},{140, 150, 160},{220, 240, 255}};

A: You should initialize the values at the time of declaration. You cannot initialize like that ( as in your code). That is a invalid C syntax.
#include <stdio.h>
#include <stdint.h>

typedef uint8_t  BYTE;

typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
}
RGBTRIPLE;

int main(void)
{
    int height = 3;
    int width = 3;
    RGBTRIPLE image[3][3] = {{{10, 40, 70},{110, 120, 130},{200, 220, 240}},{{20, 50, 80},{130, 140, 150},{210, 230, 250}},{{30, 60, 90},{140, 150, 160},{220, 240, 255}}};

    printf("%d ",image[2][2].rgbtBlue);
    printf("%d ",image[2][2].rgbtGreen);
    printf("%d ",image[2][2].rgbtRed);

    return 0;
}

The output is :
220 240 255


text:
Q: ORDER BY discrete values of text column on [My]SQL[ite] I would like to sort the rows in a table based on an arbitrary ordering of a limited set of values of a text (or enum) column. For instance, if column "Classes" can have the values A, B, C, D, I would like to be able to sort rows by A > C > B > D or by some other combination, and not just alphabetically or by the native order of the enum. Is that even possible?
Ideally, I would like a solution that works on SQLite, but a MySQL one would also be useful. Many thanks!

A: ORDER BY field(column, 'A', 'C', 'B', 'D')

FIELD function in MySQL docs

A: If mySQL and sqlite sllow the use of CASE in ORDER BY clauses (MSSQL does and I see no reason why other systems won't), you could use something like:
ORDER BY CASE
         WHEN classes ='A' THEN 1
         WHEN classes ='C' THEN 2
         WHEN classes ='B' THEN 3
         WHEN classes ='D' THEN 4
         ELSE 5
         END CASE

If the column can contain more than one of the options in any particular order you could also do:
ORDER BY CASE
         WHEN classes LIKE '%A%' THEN 1
         WHEN classes LIKE '%C%' THEN 2
         WHEN classes LIKE '%B%' THEN 3
         WHEN classes LIKE '%D%' THEN 4
         ELSE 5
         END CASE

though overloading a field like that is not a normal form and is generally not recommended.

A: Yet another variant - add a new (temporary?) table such as
class | rank
A     | 1
B     | 2
C     | 3
D     | 4

Then you can join the table by the class column and order by the rank.


text:
Q: Remove the caption on my Homepage allotted to an image without deleting the image itself I would like to remove the caption from an image on my home page which was originally used as a navigation tool.  I would like to keep the image on my home page but just remove the fonts

A: You can remove caption from the image with the following two ways:

*

*The caption will be inside a tag like <caption></caption> or span etc..
so you can add css display: none; for that tag.

*You can give font-size: 0; or text-indent: -9999px; to the image's parent class.


text:
Q: Shell script to test ls output for directories I am trying to make a BASH script to test the files in the working directory and return the files that are directory files.
One approach that I can think of is, starting with ls and feeding the output into test -d.
I'm not sure what sort of looping would be best for testing each variable. And, how I can design the loop so that it can handle an unlimited amount of input from ls, not just designed for a maximum of say 20 variables.

A: Don't parse the output of ls.
Instead, use find(1):
find . -type d


text:
Q: Why does my release build fail with error APPX0002: Task 'ValidateAppxManifest' failed? I am trying to develop a UWP app for Windows desktop machines. Everything has been going well, but within the last few days I've lost the ability to build a release version (building a debug version still works fine).
I get the following error messages:
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VisualStudio\v16.0\AppxPackage\Microsoft.AppXPackage.Targets(2810,5): error APPX0002: Task 'ValidateAppxManifest' failed. Unspecified error
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VisualStudio\v16.0\AppxPackage\Microsoft.AppXPackage.Targets(2810,5): error APPX0002: [My App] violates pattern constraint of '\bms-resource:.{1,256}'.
I've tried a number of "fixes" that worked for people over the last few years. Some people report the problem fixed itself in the latest version of Visual Studio. Unfortunately, the versions they mention are older than the version I'm using, which is
Microsoft Visual Studio Community 2019
Version 16.6.3
Many fixes from the net are similar to the ones below, from the URL
https://social.msdn.microsoft.com/Forums/en-US/4cc2cbfb-fa0d-4f12-a0a1-9072d78e26d6/vs2019-error-task-validateappxmanifest-failed-unspecified-error-again-and-again?forum=msbuild
One fix was:

*

*Clear nuget packages,

*Clean solution

*Close VS

*Delete bin & obj folders of the main (startup) project

*Open VS - solution

*Restore solution nuget packages

*Rebuild 'n go

Another fix was:

*

*uninstalling vs & sdks,

*removing every nuget folder,

*clean the registry and restart the system,

*the last step once more,

*reinstall vs.

I have tried all of these (several times) except for "clean registry." I'm not sure what part of the registry we're talking about.
So, has anyone overcome this problem in a different way, or know what the registry idea is?
Oh, some other data is

*

*Maybe my machine is too old (about 6 years old). I'm speculating that even if my machine seems to have the latest version of Windows an Visual Studio, maybe it doesn't have exactly the latest code.

*Things went bad while I was adding two new features. The first was to ask the user for a rating, via _storeContext.RequestRateAndReviewAppAsync();  The second was allowing the user to share some data via DataTransferManager.ShowShareUI();
I was thinking maybe these APIs might require some declarations in the manifest that I don't have, but I don't see from the documentation that they do.
Any ideas would be greatly appreciated. I'm out of ideas at the moment.

Dan

A: Here is the answer, for me. I'm not confident that this as the answer for all cases, but all is good now.
You may remember that I said I had the latest version of Windows, and I did. However, when I checked with Windows Update last night, it confirmed I was "up to date" but it offered me a "Feature update" to Windows 10, version 2004. I decided to go for it.
The update took hours to complete, and this morning it was still only 94% complete when Nico Zhu suggested to  try using Visual Studio 2017. I figured I'd install VS 2017 after the update, but when it was finally complete, I decided to try VS 2019 one more time with my fresh new version of Windows. Amazingly, it worked the first time.
I should mention that my new procedure for making an app package now includes

*

*close VS 2019

*delete the project's obj folder

*delete the project's bin folder (I used to just delete the obj folder, but after seeing others suggestions I've added this step)

*launch VS 2019

*create the App Package

I wanted to do another build/package so I fixed a couple of cosmetic bugs and tried again. On the second try I fell back into my old pattern and I did NOT delete the bin folder. Immediately VS 2019 popped up with an error message something like "Cannot complete build. Fix problem with your app manifest." Rather than pouring over the manifest file as I've been doing for the last couple of days, I deleted both the obj and bin folders and tried again. The build/package process then worked perfectly.
So, I want to say that the app manifest file was not the culprit (in this case anyway) and I'm now a fan of deleting both the obj and bin folders, and having Win 10 version 2014, before attempting a release build with VS 2019.
Dan

A: Try this:
Launch visual studio "runas administrator"
Clean Solution
Rebuild
Good Luck


text:
Q: How to send each item of response in Java Method (karate framework)? I have to send to my Java method each item in reponse, I have to do smth like this :
    response from GET/cars request
 * def wheels = response[*].wheels
    * def JavaM = Java.Type('foo.bar.JavaMethods')
    * def modifiedWheels = JavaM.modifyWheels(wheels)

I've read about call-table.feature but I can't figure out if I have to send each wheel one by one in my java method or if I have to send an array of wheels and my Java method should treat this array? Thanks

A: A JSON array becomes a Java List.
A JSON object becomes a Map<String, Object>.
Refer to this section in the doc: https://github.com/intuit/karate#calling-java, there is even an example cats-java.feature


text:
Q: Python 3 Action Chains click on element behaves as right click when mobile phone touch screen is enabled I have a driver using selenium.
If you enter the inspect mode you can toggle the mobile pone view in which window size imitates a mobile phone and instead of a mouse there is a touch simulator.
My problem is that sometimes when I use ActionChains to perform some clicks instead of a left click it performs a right click and I don't know neither why is that nor how to solve it.
Using ActionChains is mandatory by the way. Here are some examples of what I tried
element = driver.find_element(By.XPATH, "xpath to it")

action=ActionChains(browser)
action.move_to_element(element).click().perform()

#Alternative way from the above
action.w3c_actions.pointer_action.click(element)
action.perform()

While this work on some elements it is not consistent and sometimes it acts as a right click. What am I doing wrong?
By the way, to reach this mobile emulation I do the following
browser.execute_cdp_cmd('Emulation.setDeviceMetricsOverride', emulation) #emulation is a dict with heigh and width of screen
browser.execute_cdp_cmd('Page.setDeviceMetricsOverride', emulation)

config, enabled = 'mobile', True
browser.execute_cdp_cmd('Emulation.setEmitTouchEventsForMouse', {'enabled': enabled, 'configuration': config})

maxpoints = 3
browser.execute_cdp_cmd('Emulation.setTouchEmulationEnabled', {'enabled': enabled, 'maxTouchPoints': maxpoints})


text:
Q: Java Program to get desired input from sum of two random numbers I want to make a small program to get the desired result by adding two random numbers. For example our desired number is 30 then random no 1 and no 2 should be 15-15, 13-17, 10-20 or anything else.  I made this program which shows the sum of random numbers but not desired sum.
import java.util.*;
import java.util.Random;

public class Problem {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Random rand = new Random();
        Random random = new Random();
        int r = rand.nextInt(100) + 1;
        int r1 = random.nextInt(100) + 1;

        int sum = r + r1;
        System.out.println(r + " + " + r1 + " sum is: " + sum);
    }
}

Solved it by.
import java.util.*;
 import java.util.Random;
 public class Problem {
public static void main(String[] args) {

    Scanner sc= new Scanner(System.in);
    Random rand= new Random();
      Random random= new Random();
     int r= rand.nextInt(100)+1;
      int n=0;
      int sum= sc.nextInt();
      n= sum-r;
       sum= r+n;

     System.out.println(r +" + "+n+ " sum is: " + sum);
   }
}

A: Your problem isn't really in your code; but your logic/math is flawed: you see, when you got three numbers, like
m + n = o
and m is a random number, and o is fixed; then n = o-m.
Thus: you only need one random number, not two!

A: Just choose the first number in the range with an upper limit of the sum, and then retain the second number as the difference of the sum and the first number:
Random rn = new Random();
int max = 30;
int first = rn.nextInt(max) + 1;
int second = max - first;

Now first and second are guranteed to sum to the maximum number.  I assumed that, for a given sum max, the smallest number is 1.

A: I think you are looking for this:
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

Random rand = new Random();
int r1 = rand.nextInt(n) + 1; // only one random number is needed
int r2 = n-r1; // other will be subtract of n and r1

System.out.println(r1 + " + " + r2 + " sum is: " + n);

A: Given the desired number, generate one random number and subtract this from the desired number to get the other random number. The code -
import java.util.*;
import java.util.Random;
import java.util.Scanner;

public class Problem {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int desiredNumber = sc.nextInt();
        Random random = new Random();

        int r1 = desiredNumber>0?(random.nextInt(desiredNumber)+1):0;
        int r2 = desiredNumber - r1;

        System.out.println("The desired number is : " + desiredNumber);
        System.out.println("The two random numbers are : " + r1 + " and " + r2);
   }
}

A: Your problem isn't really in your code; but your logic/math is flawed: you see, when you got three numbers, like
m + n = o
and m is a random number, and o is fixed; then n = o-m.
Thus: you only need one random number, not two!


text:
Q: Google Chrome "warn to quit" not warning on Cmd + Tab quit As a Mac poweruser, I often use Cmd + Tab to switch between applications.  Tab is unfortunately close to Q, so I often end up jamming Cmd + Q as well by accident.  On most applications, this isn't a problem; a popup appears confirming if I want to quit, and I just click "cancel."
However, this isn't the case with Google Chrome.  I checked "warn before quitting", and when I press Cmd + Q a box saying "Hold Cmd + Q to quit" pops up.  But when jamming Cmd + Q while switching to Chrome using Cmd + Tab, it completely ignores the "warn before quitting" policy and quits immediately.
Any way to fix this annoyance?  Switching either of the shortcuts to something else would fix the problem, but I'm not able to find a way to do so.

A: When Chrome is open, on the Menu bar on the very top of the screen, click "Chrome", then "Confirm to quit" (Cmd+Q).


text:
Q: Using an if statement to replace NA values in a column So I am trying to fill a column Name from an existing character string. Most of the character strings look like this:
;Parties;John, Smith;Defendant;

And so I've been able to extract names using this code
data$name <- str_to_upper(str_extract(data$column, "(?<=;Parties;)(\\D){4,60}(?=;Defendant)"))

However, there are a few NA values in my name column
name
JOHN, SMITH
JANE, DOE
BOB, ROSS
NA

sum(is.na(data$name))
[1] 888

When I look at these NA rows with data$column[4], it looks like this:
Agency;Michael, Scott;Defendant

I'm trying to fill the NAs in the name column. Here is my code:
data$name <- if(is.na(data$name)) {
str_to_upper(str_extract(data$column, "(?<=Agency;)(\\D){4,60}(?=;Defendant)"))
}

But I get this error:
In if (is.na(data$name)) { :
the condition has length > 1 and only the first element will be used

Any ideas? Thank you!

A: The answer is fully based on the comment by @r2evans, but I think it is good to mark questions as solved to leave them closed.
isna <- is.na(data$column)
data$column[isna] <- str_to_upper(
                       str_extract(data$column[isna],
                                   "(?<=Agency;)(\\D){4,60}(?=;Defendant)"))


text:
Q: C++ Searches with strings in array Hi so I am having trouble figuring out how to search though arrays, in particular with string. I have more than one question but here goes for now.
My first question is linear search.
Modify the searchList function given below so that it searches for a given name (not an int) the functions returns an int which is the index of the name found. If -1 is returned then say name is not found otherwise write out the name and the mark for that name.
So this is what I did and I have no clue whether it is correct.
I am also confused because the wording of this sounds like a 2D array, how does it store the name AND the mark?
int searchList (const string list[], int numElems, string value)
{
int index = 0;      // Used as a subscript to search array
int position = -1;  // To record position of search value
bool found = false; // Flag to indicate if value was found

while (index < numElems && !found)
{
    if (list[index] == value) // If the value is found
    {
    found = true; // Set the flag
    position = index; // Record the value's subscript
    }
    index++; // Go to the next element
}
if (position ==-1)
{
cout << " Name not found." << endl; << endl;
}
else
{
cout <<  list[position]; // Confused here, how do I output the name and mark?
}
return position; // Return the position, or -1

I cannot really build it in VS because I don't know how I would at this point. My book doesn't touch on string searches so I am confused.

A: A C++ approach using algorithms:
1) Searches for values in arrays can be accomplished by using std::find() and std::find_if()
2) I suggest to not name your variables "list", since there already is a std::list class in C++, and your code will just confuse someone taking a quick glance at it.
#include <algorithm>
//...
int searchList (const string thelist[], int numElems, string value)
{
   string* pPos = std::find(theList, theList + numElems, value);
   if ( pPos != theList + numElems )
      return std::distance(theList, pPos);
   return -1;
}

The above searches the array for a value, and if found, returns a pointer to the value.  If not found, then the pointer will point to one item after the last item.  Note the usage of distance() to return "how far" the found position is from the beginning position.
You then just call this function and test the return value.  If it's -1, then the name is not found, otherwise the return value is the index of the found name.
I believe your original attempt was doing too much in terms of input/output.  All you needed to do was write a function that either returned -1 or an index value, nothing more, nothing less.  Then you were supposed to call that function and whatever it returned, you output the results.
Using your code:
int searchList (const string list[], int numElems, string value)
{
    int index = 0;      // Used as a subscript to search array
    while (index < numElems)
    {
       if (list[index] == value) // If the value is found
          return index;
       ++index;
    }
    return -1;
}

You see how simple that is?  You return as soon as you find a match.  Now given that, how do you call it and process the return value?
The algorithm approach is more verbose, but less chance of a careless error from happening (such as not looping enough or looping too much, forgetting to increment the index, or some other stupid error that compiles fine but then running the program, it fails).


text:
Q: Cannot see UTF8-characters in Delphi 2010 Memo I read an UTF8-File, made with Winword, into a Tmemo, using the code below (tried all 2 methods). The file contains IPA pronunciation characters. For these characters, I see only squares. I tried different versions of tmemo.font.charset, but it did not help.
What can I do?
Peter
// OD is an TOpenDialog

procedure TForm1.Load1Click(Sender: TObject);

{
var fileH: textFile;
    newLine: RawByteString;

begin
   if od.execute (self.Handle) then begin
      assignFile(fileH,od.filename);
      reset(fileH);
      while not eof(fileH) do begin
        readln(fileH,newLine);
        Memo1.lines.Add(UTF8toString(newLine));
      end;
      closeFile(fileH);
   end;
end;
}

var
  FileStream: tFileStream;
  Preamble: TBytes;
  memStream: TMemoryStream;
begin
  if od.Execute then
  begin
    FileStream := TFileStream.Create(od.FileName,fmOpenRead or fmShareDenyWrite);
    MemStream := TMemoryStream.Create;

    Preamble := TEncoding.UTF8.GetPreamble;
    memStream.Write(Preamble[0],length(Preamble));
    memStream.CopyFrom(FileStream,FileStream.Size);
    memStream.Seek(0,soFromBeginning);

    memo1.Lines.LoadFromStream(memStream);

    showmessage(SysErrorMessage(GetLastError));

    FileStream.Free;
    memStream.Free;
  end;
end;

A: First, you are doing too much work.  Your code can be simplified to this:
procedure TForm1.Load1Click(Sender: TObject);
begin
  if od.Execute then
    memo1.Lines.LoadFromFile(od.FileName, TEncoding.UTF8);
end;

Second, as David said, you need to use a font that supports the Unicode characters/glyphs that are stored in the file.  It is not enough to set the Font.Charset, you have to set the Font.Name to a compatible font.  Look at the fonts that loursonwinny mentioned.

A:
For these characters, I see only squares.

The squares indicate that the font does not contain glyphs for those characters. You'll need to switch to a font that does. Assuming that your file has been properly encoded and that you are reading in the code points that you intend to.
You can pass TEncoding.UTF8 to the LoadFromFile method to avoid having to add a BOM to the content. Finally, don't call GetLastError unless the Win32 documentation says it has meaning. Where you call it, there is no reason to believe that the value has any meaning.


text:
Q: Token endpoint with AllowInsecureHttp=false still accepting http requests Hope anyone can help me with the following highly frustrating problem.
I have .NET WebApi which I secured with jwt authentication. In setting up the OAuthAuthorizationServerOptions-object I set the property AllowInsecureHttp for my token end point to false. Running my API locally on IISExpress and testing it with Postman works like a charm. If I set the property to true and ask for a token on my end point it works, if I set it to false I get a 404 as expected. But when I publish the API to my production environment (Windows 2012/IIS8) and set the property to false, I can get a token over both https and http. It just doesn't seem to listen to the property.
I run the API as an application with alias Api under a domain with just one https-binding. I use the following helper base class for my API's:
public class BaseWebApi<TDerivedOAuthProvider> where TDerivedOAuthProvider : BaseOAuthProvider, new()
{
    public BaseWebApi(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ExternalBearer));

        ConfigureOAuth(app);

        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
    }

    private static void ConfigureOAuth(IAppBuilder app)
    {
        var allowInsecureHttp = Convert.ToBoolean(ConfigurationManager.AppSettings["jwt::allowInsecureHttp"].ToString());
        var issuer = ConfigurationManager.AppSettings["jwt::issuer"].ToString();
        var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["jwt::secret"].ToString());
        var clients = ConfigurationManager.AppSettings["jwt::clients"].ToString().Split(new char[] { ',' });

        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = allowInsecureHttp,
            AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(10),
            Provider = new TDerivedOAuthProvider(),
            RefreshTokenProvider = new BaseRefreshTokenProvider(),
            AccessTokenFormat = new BaseJwtFormat(issuer),
        };

        // OAuth 2.0 Bearer Access Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);

        // Api controllers with an [Authorize] attribute will be validated with JWT
        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = clients,
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
            }
        });
    }

}

Variables allowInsecureHttp, issuer, secret and clients are filled from a configuration file. Setting the value for allowInsecureHttp hardcoded to false or true does not change anything. This base class is then instantiated by my actual API which (next to the actual API functions) also provides a CustomOAuthProvider class handling the actual implementation of the credential checking for this particular API:
[assembly: OwinStartup(typeof(MyCustomAPI.Startup))]
namespace MyCustomAPI.API
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            BaseWebApi<CustomOAuthProvider> webApi = new BaseWebApi<CustomOAuthProvider>(app);
        }
    }
}

Hope anyone can point me in the right direction. Set aside this issue the API itself is working flawlessly, but I really want to force SSL on my production tokens.
Cheers,
Nyquist

A: For anyone ever encountering the same issue. Figured it out eventually. Worked like a charm, but the HSTS policy on the domain I configured my virtual application redirected all http Postman traffic automatically to https. Installed the application on a simple domain without SSL and on that domain SSL was perfectly enforced. sigh :)


text:
Q: Click Button - No Action I am trying to retrieve information from database. User enters id of the person he is looking for to ID textbox, than press display button. The grid view should show the result. But when button is pressed, nothing happens. Could anyone help or tell me what I should check?
Code for button:
protected void btnDisplay_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True");
            SqlCommand cmd = new SqlCommand("displayData", conn);
            conn.Open();
            cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataReader rd = cmd.ExecuteReader();
            grvResults.DataSource = rd;
            grvResults.DataBind();
        }

Here is stored procedure:
USE ["Name"]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[displayData] (@ID int)
as
begin
SELECT * FROM Customers WHERE ID = @ID
end

Here is display data method:
public List<Customer> displayData()
        {
            List<Customer> lst = new List<Customer>();
            SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True");
            SqlCommand cmd = new SqlCommand("Select * From Customers", conn);
            conn.Open();
            SqlDataReader rd = cmd.ExecuteReader();
            while (rd.Read())
            {
                lst.Add(new Customer()
                {
                    ID = rd.GetInt32(0),
                    FName = rd.GetString(1),
                    LName = rd.GetString(2)

                });
            }
            return lst;
        }

aspx for button:
<asp:Button ID="btnDisplay" runat="server" Text="Display" OnClick="btnDisplay_Click" />

A: Give the following code a try in your codebehind. It should bind properly and fill a gridview. If it works, add more code from there. If it doesn't work, look at things like your connection string. Let me know.
        SqlConnection conn = new SqlConnection("Data Source="?";Initial Catalog="?";Integrated Security=True");

        SqlCommand cmd = new SqlCommand("SELECT * FROM Customers WHERE ID = @ID", conn);
        cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);

        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;

        DataTable dt = new DataTable();

            conn.Open();
            da.Fill(dt);
            conn.Close();

        grvResults.DataSource = dt;
        grvResults.DataBind();

A: have you tried to put a breakpoint in button click. Is it hitting breakpoint. If not then I will say remove
OnClick="btnDisplay_Click"

from your aspx page. And then add default click event from .cs page by selecting control and it events. Them try to debug line by line.

A: I think you are complicating yourself too much
First do this:

That should make it work. You already have a stored procedure which makes it easier. (Sorry for the pictures, I wanted to make sure you understood this)


text:
Q: Vlookup search in a comma separated field Excel worksheet with 2 columns.
Cell A1 has values like 111,222-225,333 then cell A2 almost same format data like 010,011,444-499.
How can we lookup a value, say 333 and output corresponding value on adjacent column --(in column B or C etc)?
Vlookup doesn't seem to be a good choice as the first column value needs to be unique.
Secondly, how could we tackle the same above scenario if the lookup value is in that range (say 224, which is in the range of 222-225)

A: I am not sure what value you want to have, but if you want to have the whole cell u might use:
    =LEFT(A1;FIND("333";A1)+3)
in B1 and simply fill it to the rest of column B.

A: You could share a worksheet with Googledocs with data people could share.
But in essence you would be doing something like string manipulation on A1, to extract the 333.
a1=111,222-225, 333
b1=VALUE(RIGHT(TRIM(A1),3))
c1==VLOOKUP(B1,E1:F2,2,FALSE)   // a
d1==IF(ISNA(C1),"",C1)          // a
e1=333 e2=a
f1=444 f2=b

The // a - represents the calculated content of the cell


text:
Q: Any disadvantage to calling _documentSession.Store when updating existing documents in RavenDB? When creating new or updating existing documents in RavenDB, the documentation says to do it along these lines:
public string Save(Blogpost post)
{
    Blogpost model;

    if (String.IsNullOrEmpty(post.Id))
    {
        model = new Blogpost();
        _documentSession.Store(model);
    }
    else
    {
        model = _documentSession.Load<Blogpost>(post.SimpleId);
    }

    model.Text = template.Text;
    model.Name = template.Name;
    _documentSession.SaveChanges();

    return model.Id;
}

Someone on my team is doing saves another way for both creating new documents or updating existing ones:
public string Save(Blogpost post)
{
    _documentSession.Store(post);
    _documentSession.SaveChanges();
    return post.Id;
}

Is there any disadvantage to always calling .Store() even if the document already exists?

A: Jason,
Your code will always overwrite the document. Is that something that you want to do?

A: If you are doing a rich client app and serializing the full BlogPost to the client like so:
//GET BlogPost/1
public BlogPost Get(int id)
{
    return _documentSession.Load<BlogPost>(id)
}

Then rehyrdating a full BlogPost on the server after a user has made changes. The below code appears to be more efficient than doing a Load and then a Store:
//POST BlogPost/
public void Post(BlogPost post)
{
    //blog post already has an Id in this example
    _documentSession.Store(post)
    _documentSession.SaveChanges();
}

When you do a
documentSession.Load<Blogpost>(id)

RavenDB returns the full JSON for the blog post that you already have just for you to overwrite it, turn around and re-save sending the full JSON for the blog post back again over the wire to Raven.
This means that doing a Load and Store when you already have all the data results in twice the network traffic to Raven for no added benefit that I can see using Fiddler.
Even if you were only changing a part of the object (say the Name of the BlogPost) the RavenDB .NET API still sends the full object over the wire when doing a:

*

*Load()

*make some changes (but not changes to everything)

*Store()

*SaveChanges()

Perhaps Ayende Rahien can enlighten us on anything I missed here?

A: Store will store this object in a new document. Use the change tracking feature built-in in the session object aka the Unit of Work pattern, like the docs suggest.


text:
Q: How can I store in a variable certain lines in python? I have this code:
with open("/etc/network/interfaces", "r") as file:
    content = file.read()
    print content

it's working and showing this:

How can I store in a variable any word and print that word?

A: with open("/etc/network/interfaces", "r") as file:
for line in file:
    words=line.split(' ')#break the line into a list of words.
    print(words[0],words[1]) #

I have not tested it, but gives you an idea.

A:
For example, I want to store the word (lo) in the second line in a variable and then print that variable.

Use the re module in Python's builtin library:
import re

with open("/etc/network/interfaces", "r") as file:
    content = file.readlines()

target_word = re.findall("lo()", content[3]) # save the string 'lo' into target word
print ''.join(target_word) # prints: lo

If you plan on trying to find more words, just add more words to the regular expression. For example, if you wanted to find the words lo and auto, you would say re.findall("lo|auto", content). If you use this method, I recommend reading the official documentation on the re module.


text: Q: There is no application set to open the URL data:text/calendar I'm trying to include a 'Add to Calendar' button in an email I'm sending out but Apple Mail just doesn't seem to see the link as a download. This works on every other mail provider though.


text:
Q: Multiple Possible Output Types in Perl6 I'd like to make a function that returns either a Range or an any Junction made up of multiple Ranges.
Eg :
sub foo (Range $a, Range $b) {
  if $a.min <= $b.max && $b.min <= $a.max {
    ($a.min < $b.min ?? $a.min !! $b.min)..($a.max < $b.max ?? $a.max !! $b.max)
  } else {
    ($a|$b)
  }
}

Is there an easy way of adding a Type constraint to the sub to say it could return a Range or a Junction?
Thought's I've had include

*

*Multi sub that does the checking in the where clause.

*Subset Any.

*Always return a junction and just use one() (But I'd like to keep Ranges of possible)

But if there's a simpler way that someone can think of.

A: Just create a subset that accommodates both results, and use it as if it were a type.
Note that since a Junction is not a subtype of Any, you have to mark it as being Mu.
(Junction specifically can't be Any and work the way it does)
my subset Range-or-Junction of Mu where Range|Junction;

proto sub foo ( Range, Range --> Range-or-Junction ) {*}

multi sub foo (Range $a,Range $b where $a.min ~~ $b || $a.max ~~ $b --> Range){
  # note that this is wrong as it doesn't takes into consideration
  # :excludes-min or :excludes-max
  min($a.min,$b.min) .. max($a.max,$b.max)
}
multi sub foo (Range $a,Range $b --> Junction){
  $a | $b
}


text:
Q: Spring Boot RestTemplate post without response type I need to call another api and I am trying to use postForEntity as below:
restTemplate.postForEntity(postUrl, request, responseType)

Now, the api that I am calling is returning an object of a particular type, let's say CustomerDto. But I am not interested in this object. I just want to post and I don't want anything in return so I don't want to create this CustomerDto class in my application. So, for this scenario, in the above statement, what should i replace for responseType. In case, I had wanted the returned object, I would have given CustomerDto.class in case of responseType, but I dont want anything in return, so what do I do?

A: You can use postForLocation instead of postForEntity.
restTemplate.postForLocation(postUrl, request)

A: Another way is to use Void.class as response-type


text:
Q: How to run cv::dnn::blobFromImages on multiple images and interpret it I need to run cv::dnn::blobFromImages on multiple images in c++, in order to detect objects, faster than one image for cv::dnn::blobFromImage. But as you know blob  is a Mat file, so how could I check result on second , third and ... images?
cv::Mat blob = cv::dnn::blobFromImages(letterboxStack, 1.0, cv::Size(inputW, inputH),
                                   cv::Scalar(0.0, 0.0, 0.0), false, false);

hint: I used Yolo::decodeDetections in trt_utils.cpp and yolov3.cpp. Is there any possible alternative for this issue?
Thanks in advance.


text:
Q: How can I get nokogiri to select node attributes and add them to other nodes? Is it possible to grab a following element's attributes and use them in the preceding one like this?:
<title>Section X</title>
<paragraph number="1">Stuff</paragraph>
<title>Section Y</title>
<paragraph number="2">Stuff</paragraph>

into:
<title id="ID1">1. Section X</title>
<paragraph number="1">Stuff</paragraph>
<title id="ID2">2. Section Y</title>
<paragraph number="2">Stuff</paragraph>

I have something like this but get nodeset or string errors:
frag = Nokogiri::XML(File.open("test.xml"))

frag.css('title').each { |text|
text.set_attribute('id', "ID" + frag.css("title > paragraph['number']"))}

A: next_sibling should do the job
require 'rubygems'
require 'nokogiri'

frag = Nokogiri::XML(DATA)
frag.css('title').each { |t| t['id'] = "ID#{t.next_sibling.next_sibling['number']}" }
puts frag.to_xml

__END__
<root>
<title>Section X</title>
<paragraph number="1">Stuff</paragraph>
<title>Section Y</title>
<paragraph number="2">Stuff</paragraph>
</root>

Because whitespace is also a node, you have to call next_sibling twice. Maybe there is a way to avoid this.
Alternatively you can use an xpath expression to select the number attribute of the next paragraph
t['id'] = "ID#{t.xpath('following-sibling::paragraph/@number').first}"


text:
Q: R - Function that selects specific character in a column in data frame and replaces it I am trying to create a function in R that takes four arguments, namely:
data frame, number, character 1 and character 2.
What I am trying to have as an output is this:
test_df <- data.frame(col1 = c("matt", "baby"), col2 = c("john", "luck"))

my_function(test_df, 1, "u", "o")

col1 col2
mutt john
buby luck

I was just wondering how should I specifically define the function to take the [number] column the user is entering? For the renaming, I guess the function rename() would be fine. Do I need to substitue with [x,x]?
Thank you!

A: If you have to create a function that takes a column as an argument you need to split out the data frame and column specification (using gsub() to do the actual replacement):
my_function <- function(df, column, pattern, replacement) {

  gsub(pattern, replacement, df[[column]])

}

Which would work like:
my_function(df = test_df, column = 1, pattern = "a", replacement = "u")
## [1] "mutt" "buby"

But, this has the downside that if you want to loop over multiple columns, for example with lapply(), the list specification becomes more complicated:
test_df[] <- lapply(colnames(test_df), my_function, df = test_df, pattern = "a", replacement = "u")
test_df
#   col1 col2
# 1 mutt john
# 2 buby luck

Which is much more complicated than:
test_df   <- data.frame(test_df, stringsAsFactors = FALSE)
test_df[] <- lapply(test_df, gsub, pattern = "a", replacement = "u")
test_df
#   col1 col2
# 1 mutt john
# 2 buby luck

(Note: ensure stringsAsFactors = FALSE for this to work. It's a good idea to use this as the default unless you explicitly want factors anyway)


text:
Q: Using same database table with different alias to retrieve data Here what I am trying to do is to get the values for P1,P2,P3 that should comes from A3,
this works well for two tables but not for three...
SELECT x.A1,x.A3,x.A4,A5,A6, x.A2 as P1,y.A2 as P2,z.A2 as P3
FROM Contact x,Contact y,Contact z
WHERE (x.id = y.id) AND (y.id = z.id)   AND
(x.A3 ='pre-sale') AND (y.A3= pos-sale') AND(z.A3='current-sale')
 ORDER by x.A4 DESC

For example
     the CONTACT table will look like this with some expected results for P1,P2, P3
 A1   A2       A3         A4     A5   A6   P1  P2 P3
 ----------------------------------------------------
 1    22     pre-sale     9     kk    8    22  31  2
 2    31     pos-sale     4     yy    6    44  61  11
 3    2      current-sale 1     hh    2    null null null
 4    44     pre-sale     2     kk    8
 5    61     pos-sale     1     yy    6
 6    11     current-sale 1     hh    2

For P1, P2 using twice same table works well, adding the third table the values
     for P1, P2 are   the same and for P3 all null

A: I suspect that what you are trying to do might best be done with conditional aggregation.  It is a bit hard to tell what you are really trying to accomplish, because not all the columns are aliased.  Here is an example
SELECT c.id,
       max(case when c.A3 = 'pre-sale' then A4 end) as PreSale_A4,
       max(case when c.A3 = 'pos-sale' then A2 end) as PosSale_A2,
       max(case when c.A3 = 'current-sale' then A4 end) as CurrentSale_A2
FROM Contact c
group by c.id
order by PreSale_A4 desc;

Your original query has some fundamental problems.  For instance, you are using implicit joins via the where clause, which are always inner joins.  The solution to your problem might be using outer joins instead.  Conditional aggregation probably solves the problem, though.


text:
Q: Using Guzzle to call Stackoverflow api is not working I am using  Guzzle to work with the Stackoverflow API . My code is as follows
$client = new GuzzleHttp\Client();
$response = $client->get('api.stackexchange.com/2.2/search/advanced',['pagesize'=>'2','order'=>'desc','sort'=> 'activity','q'=>['laravel eloquent'],'site'=>'stackoverflow'])->send();

but I am getting this excpetion

InvalidArgumentException No method is configured to handle the
  pagesize config key

the complete url (on stackoverflow) that works is posted here. Note you will need to run it.
Can you please help me out with this , please ?

A: From documentation, you need to add query key:
$parameters = ['pagesize'=>'2','order'=>'desc','sort'=> 'activity','q'=>['laravel eloquent'],'site'=>'stackoverflow'];
$response = $client->get('api.stackexchange.com/2.2/search/advanced',['query' => $parameters ])->send();


text:
Q: Prisma FindMany input type Hi I am currently using prisma 2 to query a database by using the findMany Method, example of how I do this is here
const data = await prisma.user.findMany({
    take: 10000,

    select: {
      A: {
        select: {
          B: true,
          C: true,
          D: true,
        },
      },
    }
}

I would like to implement it where I can define the object that this findMany takes externally, like
const obj = {
    take: 10000,

    select: {
      A: {
        select: {
          B: true,
          C: true,
          D: true,
        },
      }
    }

const data = await prisma.user.findMany(obj)

However I am having an issue as to getting the type for obj, hovering over the findMany function, it tells me that the type it takes is of type UserFindManyArgs however I cant seem to find a way to import this.
Any advice on how to do this will be greatly appriciated

A: You can find these types under the Prisma namespace. So this should work:
import { Prisma } from '@prisma/client'

type T = Prisma.UserFindManyArgs