text:
Q: Manipulate rows of a data frame with specific variables per row I'm trying to standardize my fish numbers in different columns by an unique sampled area.
I've got the following simplified data set:
Year <- c(1990:2019)
Location_nr <- c(1:30)
df <- data.frame(Year,Location_nr)
df$Sample_surface <- sample(10, size = nrow(df), replace = TRUE)
df$Fish1 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish2 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish3 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish4 <- sample(0:500, size = nrow(df), replace = TRUE)

I would like to standardize fish numbers (column: Fish1, Fish2, Fish3 and Fish4) per row by:
(/"Sample_surface")/100
I've been stuck on this issue for more than a day now. I sincerely hope somebody can help me with this. Many thanks in advance!

A: We can use sweep to apply all the "Fish" column in row by corresponding Sample_surface.
cols<- grep('Fish', names(df))
sweep(df[cols], 1, df$Sample_surface, `/`)/100

head(df)
#  Year Location_nr Sample_surface  Fish1 Fish2 Fish3 Fish4
#1 1990           1              3 1.0967 0.050 1.410 1.530
#2 1991           2              3 0.0733 0.383 1.223 0.703
#3 1992           3             10 0.4100 0.093 0.285 0.173
#4 1993           4              2 2.2150 1.305 1.975 1.360
#5 1994           5              6 0.5133 0.390 0.263 0.742
#6 1995           6              5 0.2680 0.910 0.240 0.602

Or we can use apply row-wise
df[-c(1:3)] <- t(apply(df[-c(1:2)], 1, function(x) x[-1]/x[1]/100))

data
set.seed(123)
Year <- c(1990:2019)
Location_nr <- c(1:30)
df <- data.frame(Year,Location_nr)
df$Sample_surface <- sample(10, size = nrow(df), replace = TRUE)
df$Fish1 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish2 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish3 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish4 <- sample(0:500, size = nrow(df), replace = TRUE)

A: Another option would be to use dplyr and tidyr. In most cases, it is recommended to manipulate data in a tidy format.
df %>%
  pivot_longer(-c(Year:Sample_surface), names_to = 'Fish', values_to = 'Value') %>%
  mutate(Value = Value / Sample_surface / 100) %>%
  pivot_wider(names_from = Fish, values_from = Value)

or
cbind(df %>% select(-starts_with('Fish')),
      df %>% select(starts_with('Fish')) / df$Sample_surface / 100)

A: We can  do this in a vectorized way
cols<- grep('Fish', names(df))
df[cols] <- (df[cols]/df$Sample_surface)/100
head(df)
#  Year Location_nr Sample_surface      Fish1     Fish2     Fish3     Fish4
#1 1990           1              3 1.09666667 0.0500000 1.4100000 1.5300000
#2 1991           2              3 0.07333333 0.3833333 1.2233333 0.7033333
#3 1992           3             10 0.41000000 0.0930000 0.2850000 0.1730000
#4 1993           4              2 2.21500000 1.3050000 1.9750000 1.3600000
#5 1994           5              6 0.51333333 0.3900000 0.2633333 0.7416667
#6 1995           6              5 0.26800000 0.9100000 0.2400000 0.6020000

data
set.seed(123)
Year <- c(1990:2019)
Location_nr <- c(1:30)
df <- data.frame(Year,Location_nr)
df$Sample_surface <- sample(10, size = nrow(df), replace = TRUE)
df$Fish1 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish2 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish3 <- sample(0:500, size = nrow(df), replace = TRUE)
df$Fish4 <- sample(0:500, size = nrow(df), replace = TRUE)


text:
Q: Is there an easier way to show the selected item from SQL in the drop box using PHP? I am trying to retrieve the country's name from the database and show the selected country, and I am using this approach, but using this approach will require me to do it for all 193 countries. Is there an easier way to achieve this?
<select name="nationality" class="form-control" id="nationality">
   <option value="Afganistan"
      <?php if($row['nationality']=="Afganistan") echo 'selected="selected"'; ?>
      >Afghanistan
   </option>
   <option value="Albania"
      <?php if($row['nationality']=="Albania") echo 'selected="selected"'; ?>
      >Albania
   </option>
   <option value="Algeria"
      <?php if($row['nationality']=="Algeria") echo 'selected="selected"'; ?>
      >Algeria
   </option>
</select>

A: First you have to make dynamic select option like below.
I pick below array from https://gist.github.com/DHS/1340150
You can save this in your database and display
$countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe");

<select name="nationality" class="form-control" id="nationality">
<?php foreach($countries as $key => $country) { ?>
 <option value="<?php echo $country; ?>"
      <?php echo ($country == $row['nationality']) ? 'selected' :'' ?>
      ><?php echo $country; ?>
   </option>
   <?php } ?>
</select>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can RBP point any number of local_variable or parametes? I am novice in assembly (NASM). I know that RBP points to any parameters and local variable in function. It's implemented by simple offset. If we wanna get first variable we rbp-4, if we wanna get fist parameter we add to rbp 4. But how can we do this if any function can have any number of local variable or parameters? If we want we can have 100 variable in one function and how does we can points to any variable by simple constant offset?
Thank you. Sorry for my English. I am not native speaker.

A: You can't have a variable number of variables in languages like C, so the compiler always knows where it put them.  Thus it knows the right constant offset for every variable.
If you're talking about variadic functions like printf(char *, ...), then you have rules from the calling convention for how they're laid out, and you would normally increment a pointer.  To index by arg-number, you need to know the width of all previous args.  They're at least 8, but depending on the calling convention can be wider instead of using a hidden pointer in x86-64 System V.  printf has conversions for long double among other things (which is wider than 8 bytes), so it does have to support keeping track of which arg is where in case a conversion references an arg by number

If you're talking about using the stack as a stack data structure, with push / pop potentially inside loops, then you need to keep a pointer to know when your stack data structure is "empty", and further pops would eat into other local vars.
Having some of your local variables be variable-length arrays makes things trickier, like C int foo[n] where n is another variable.  Many C compilers handle it by inventing a pointer to each VLA.  The pointers have known fixed width so the compiler knows where to find them, and they can get initialized as space is reserved for the VLAs with sub rsp, rax / mov [rbp-16], rsp for example.

A: Addressing of function parameters and local variables depends on the chosen calling convention. Your to get first parameter we add to rbp 4 is certainly wrong, because in 64bit mode (implied by using RBP or RSP for addressing) can items be pushed on stack with 64bit granularity only. Perhaps you had 32bit StandardCall convention on your mind, where typical prologue of a function looks like this:
Function: PUSH EBP
          MOV EBP,ESP
          SUB ESP,LocalsSize

Register EBP can be used inside the Function for addressing of unlimited number of  parameters and Local variables (I used three parameters and four DWORD locals in this example):
Invokation      Stack   Address

PUSH Param3     Param3  EBP+4*4
PUSH Param2     Param2  EBP+3*4
PUSH Param1     Param1  EBP+2*4
CALL Function   return
                 EBP
                Local1  EBP-1*4
                Local2  EBP-2*4
                Local3  EBP-3*4
                Local4  EBP-4*4

See also this 32bit and 64bit StdCall convention examples.


text:
Q: Handiling variables in react native I'm trying to make an app where when a button is pressed, it loads a random screen.
const Slides = [Slide0, Slide1, Slide2, Slide3, Slide4, Slide5];

randomNumber = Math.floor(Math.random() * 6);

class HomeScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      randomNumber: 1,
    };
  }

  _onPressButton = () => {
    randomNumber = Math.floor(Math.random() * 6);
    this.setState({randomNumber: randomNumber});
    this.props.navigation.navigate('NextScreen');
  }

  static navigationOptions = {
        header: null,
  }

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
      <Image
        source={require('./assets/icons/app-icon.png')}
        style={{width: 50, height: 50}}
      />
        <Text style={{ marginTop: 100 }}>Welcome to Dementia Care Activities.</Text>
        <Text>Next slide should be: {this.state.randomNumber}</Text>
        <Text>{randomNumber}</Text>
        <Button
          onPress={this._onPressButton}
          title="Get New Activity"
        />
      </View>
    );
  }
}

const SimpleAppNavigator = StackNavigator({
  Home: { screen: HomeScreen },
  NextScreen: { screen: Slides[randomNumber] }
});

const AppNavigation = () => (
  <SimpleAppNavigator  />
);

export default class App extends React.Component {
  render() {
    return (
        <AppNavigation/>
    );
  }
}

The issue here is that the value for randomNumber never gets updated again when the button is clicked, however the rest of the code in _onPressButton runs as expected.
When I reload the app, I get a different randomly assigned value for randomNumber but then that value cannot be overridden.
How do I make it so that the value is updated?

A: If you want to update a variable inside your render function then you need to declare that in state. if you want this line
<Text>{randomNumber}</Text>
in your render to reflect new random number then you need to use
<Text>{this.state.randomNumber}</Text>
instead. Let me know if this isn't what you are looking for :)

A: Try this :
this.props.navigation.navigate('NextScreen', randomNumber);


text:
Q: Attaining desired input snr in noisy signal I have taken a clean speech signal and need to get an input SNR of 0dB, 5dB and 10dB by adding certain amount of white noise.
Can anyone explain what 0dB, 5dB... is? Is it the power of white noise in the command
noise=wgn(1,20115,0);

and if not, how do I achieve input SNR of 0dB, 5dB and 10dB?

A: The signal to noise ratio (SNR) is the signal power relative to the noise power. The easiest way to achieve a given SNR while adding White Gaussian Noise to a clean signal is with awgn:
input_snr_db = 5; % Choose input SNR in dB
noisy_signal = awgn(clean_signal, input_snr_db, 'measured');

This computes the required level of noise given a signal which may not have unitary power.


text: Q: I want to implement radial blur in swift/swiftui I want to implement radial blur in swift/swiftui. Found Radial gradient on cifilter. Is is possible to make radial blur using radial gradient and cimaskedvariableblur? Or any other apporch?


text:
Q: Want to transfer file from private on-premise Instance (VM) to google cloud storage without internet I want to transfer 2TB of files from my on-premise VM(which does not have internet connection)  to google cloud storage. I have established shared VPC and my private connectivity are there. I don't want to enable internet on my on-premise VM , How can I transfer the files from On-premise VM to google cloud storage without internet.

A: Google Cloud offers the Transfer Appliance to transfer data to the cloud without using a network connection to the Internet.
Google Cloud Transfer Appliance
Order the device. Once it arrives, copy your data to the device and ship back to Google. Google then loads the data into Cloud Storage.
Pricing: varies. The base fee is $300.00 plus shipping ($120+)


text:
Q: Pointer difficulties... what's the difference between these snippets? Hopefully this example will help out any one else having trouble wrapping their heads around pointers.
Please point me in the right direction here- I'm not sure why these two snippets of code behave differently. Option 1 works fine without any memory leaks, but option 2 loses reference to other trie nodes. Looking at them, however, I can't seem to pick out what makes them different.
Here's the code:
add_word adds a node to a trie data structure.
create_trie mallocs a new node and returns a pointer to that node
void add_word(trie_node **node, char *word, int i)
{
    // Option 1
    trie_node *new_node;

    if ((*node)->branches[(int) word[i]] == NULL) {
        (*node)->branches[(int) word[i]] = create_trie();

    }

    new_node = (*node)->branches[(int) word[i]];

    if (word[i + 1] == '\0') {
        new_node->end_of_word = 1;
    } else {
        i++;
        add_word(&new_node, word, i);
    }

    // Option 2
    trie_node *new_node = (*node)->branches[(int) word[i]];

    if (new_node == NULL) {
        new_node = create_trie();

    }

    if (word[i + 1] == '\0') {
        new_node->end_of_word = 1;
    } else {
        i++;
        add_word(&new_node, word, i);
    }

}


text:
Q: Convert time hh:mm:ss into GMT time format in Angular 2 Input:-
time: 21:00:00
Output Should Be:-
time: Wed Dec 20 2017 21:00:00 GMT+0530 (IST)
OR
time: 2017-12-20 21:00:00

A: Your input is : 21:00:00
Split your input by ':' using JS code below:
let timeArr = "21:00:00".split(':');

then, use new date function to add date to the time i.e,
let newDateTime = new Date().setHours(timeArr[0], timeArr[1],0,0);

then you can convert your time to,
let finalDate = new Date(newDateTime);

and you will get the finalDate = Wed Dec 20 2017 21:00:00 GMT+0530 (IST)


text:
Q: load more posts in Wordpress with Ajax this is my loop of posts:
<?php query_posts($query_string . '&showposts=8'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

          <?php
            $categories = get_the_category();
            $separator = ' ';
            $output = '';
            if($categories){
                    foreach($categories as $category) {
                       $output .= 'cat_name.'">term_id ).'" title="' . esc_attr( sprintf( __( "Veja todos os posts em %s" ), $category->name ) ) . '">'.$category->cat_name.''.$separator;
                    }
            echo trim($output, $separator);
            }
?>

          <?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
          <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?> | <?php bloginfo('name') ?> | <?php bloginfo('description') ?>"><figure class="thumb-post" style="background: url('<?php echo $url; ?>') center center no-repeat;" >

<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?> | <?php bloginfo('name') ?> | <?php bloginfo('description') ?>"><?php the_title(); ?>

<?php the_field('sub_titulo'); ?>

            Compartilhe

            <time class="post-time" datetime="<?php the_time('d-m-Y'); ?> <?php the_time('G:i'); ?>"><?php the_time('d/m/Y'); ?></time>

<a href="http://www.linkedin.com/shareArticle?mini=true&url=<?php the_permalink() ?>" title="Compartilhar <?php the_title(); ?> no LinkedIn" target="_blank"><img src="<?php bloginfo('template_url'); ?>/img/in.png" alt="" width="24" />

<a href="https://plus.google.com/share?url=<?php the_permalink() ?>" title="Compartilhar <?php the_title(); ?> no Google Plus" target="_blank"><img src="<?php bloginfo('template_url'); ?>/img/gp.png" alt="" width="24" />

<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink() ?>" title="Compartilhar <?php the_title(); ?> no Facebook" target="_blank"><img src="<?php bloginfo('template_url'); ?>/img/fb.png" alt="" width="24" />

<a href="http://twitter.com/share?url=<?php the_permalink() ?>&text=<?php the_title(); ?>&via=chocoladesign" title="Compartilhar <?php the_title(); ?> no Twitter" target="_blank"><img src="<?php bloginfo('template_url'); ?>/img/tw.png" alt="" width="24" />

      <?php endwhile; else: ?>

<?php _e("Nenhum chocolate encontrado! :(", ''); ?>

                <?php endif; ?>

at below, i have this:

  Load more posts

my question is: how i can load 6 more posts with ajax just clicking at the link "load more posts".
i've tried a lot of plugins, but, unsuccessful. :/
i want to do just like that: http://designerthemes.com/preview/?theme=adapt

A: try pbd-ajax-load-posts plugin.
And some fixes that I posted here to this plugin.
My code of "load more posts" on wordpress misses some pages. What's wrong with it?


text:
Q: How to test a post request which returns a URI with spring boot, junit 5 and mockito I'm creating a REST API in spring boot where I have a post request end point. If it succeeds it returns the URI of the newly created resource in the location header.
I wanted to write tests for the endpoint. I'm using JUnit v5, and Mockito.
The problem is I have mocked the call to the service function but it still returns a NullPointerException
In the controller class, in the post end point I have this function:
@PostMapping(value = "/new")
    public ResponseEntity<String> registerNewDoctor(@RequestBody @Valid DoctorPOJO doctor) {
        Doctor savedDoctor = doctorService.addNewDoctor(doctor);
        if (doctor != null) {
            log.debug("DOCTOR SAVED: {}",savedDoctor);
            URI location = ServletUriComponentsBuilder.fromCurrentContextPath().path("/id/{id}").buildAndExpand(savedDoctor.getDocId()).toUri();
            return ResponseEntity.created(location).build();
        } else {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Object can not be processed");
        }
    }

In the unit Test I have:
@WebMvcTest
@Slf4j
class DoctorControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private DoctorService doctorService;
@MockBean
private SlotService slotService;
@Test
void registerNewDoctorTest() throws Exception {
        // given - set up
        SlotPOJO slot1 = new SlotPOJO("monday", LocalTime.parse("09:00:00.00"), LocalTime.parse("13:00:00.00"), LocalTime.parse("00:15:00.00"));
        SlotPOJO slot2 = new SlotPOJO("tuesday", LocalTime.parse("09:00:00.00"), LocalTime.parse("13:00:00.00"), LocalTime.parse("00:15:00.00"));
        List<SlotPOJO> slotPOJOList = new ArrayList<>(Arrays.asList(slot1, slot2));
        DoctorPOJO doctorPOJO = new DoctorPOJO(1, "doctor1", "doc1email@gmail.com", "1234567890", "123", "MBBS", "Orthopedics", "4y", slotPOJOList);
        Doctor doc = new Doctor(1, "doctor1", "doc1email@gmail.com", "1234567890", "123", "MBBS", "Orthopedics", "4y");

       // mocking the service method
        given(doctorService.addNewDoctor(doctorPOJO)).willReturn(doc);

        // when - perform actions to be tested
        ResultActions response = mockMvc.perform(post("/doctor/new").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(doctorPOJO)).accept(MediaType.APPLICATION_JSON));

        // then - verify the results
        response.andDo(print()).andExpect(status().isCreated());
    }
}

As you can see I have mocked the addNewDoctor method using mockito to return doc when called but I still get this error:

Request processing failed; nested exception is
java.lang.NullPointerException: Cannot invoke
"project.doctorservice.entity.Doctor.getDocId()" because "savedDoctor"
is null

Please help me sort out this mistake and guide me a little to how to do it correctly because I'm new to unit testing


text:
Q: xarray.Dataset.where() method force-changes dtype of DataArrays to float Problem description
I have a dataset with ints in them, and I'd like to select a subdataset by some criteria but I would like to preserve the integer datatype. It seems to me that Xarray force-changes the integer data to float datatype.
Example setup
Code
import numpy
import xarray

nums = numpy.random.randint(0, 100, 13)
names = numpy.random.choice(["babadook", "samara", "jason"], 13)
data_vars = {"num": xarray.DataArray(nums), "name": xarray.DataArray(names)}
dataset = xarray.Dataset(data_vars)
print(dataset)

Output
<xarray.Dataset>
Dimensions:  (dim_0: 13)
Coordinates:
  * dim_0    (dim_0) int64 0 1 2 3 4 5 6 7 8 9 10 11 12
Data variables:
    num      (dim_0) int64 93 99 49 35 92 14 41 57 28 59 74 1 15
    name     (dim_0) <U8 'babadook' 'samara' 'samara' 'samara' 'jason' ...
In [16]:

Example problem
Code
subdataset = dataset.where(dataset.num < 50, drop=True)
print(subdataset)

Output
<xarray.Dataset>
Dimensions:  (dim_0: 7)
Coordinates:
  * dim_0    (dim_0) int64 2 3 5 6 8 11 12
Data variables:
    num      (dim_0) float64 49.0 35.0 14.0 41.0 28.0 1.0 15.0
    name     (dim_0) <U32 'samara' 'samara' 'jason' 'babadook' 'jason' ...

A: That's because with numpy (which xarray uses under-the-hood) ints don't have a way of representing NaNs. So with most where results, the type needs to be coerced to floats.
If drop=True and every value that is masked is dropped, that's not actually a constraint - you could have the new array retain its dtype, because there's no need for NaN values. That's not in xarray at the moment, but could be an additional feature.


text:
Q: Can a variable expansion in python work like shell expansion of variable I have a legacy python code that reads from a shell script for variable values like in a properties file. For example, say, I have a shell program x.sh for variable declaration as:
Y_HOME=/utils
Y_SPCL=$Y_HOME/spcl
UTIL1=$Y_SPCL/u1
Y_LIB=$Y_HOME/lib

Now, from within python program abc.py, I read x.sh file line by line and use line.split("=")[1] to get the value of the variable, say, UTIL1 as $Y_SPCL/u1 in non-expanded form and not in expanded form as /utils/spcl/u1.
Can I have sone mechanism in python to have vafiable expandion like in a shell program execution. I think, since I am using x.sh not as a shell program, rather as a configuration file like properties, there should be all variables in expanded form to let the python program run properly, such as:
Y_HOME=/utils
Y_SPCL=/utils/spcl
UTIL1=/utils/spcl/u1
Y_LIB=/utils/lib

This will have no change on the legacy python part of code and changing the configuration file as an external properties data.
Please pass your opinions.

A: There is a package dotenv that can do that.
pip install --user python-dotenv

Then, in Python:
import dotenv, os
dotenv.load_env("x.sh")
print(os.environ["Y_LIB"])

Important: Make sure your variable substitutions read like ${VAR}. So your x.sh would look like this:
Y_HOME=/utils
Y_SPCL=${Y_HOME}/spcl
UTIL1=${Y_SPCL}/u1
Y_LIB=${Y_HOME}/lib

A: Assuming variables must be declared before use and they form a correct path when expanded, you could do something like this.
There is the file fileName that contains the variables:
Y_HOME=/utils
Y_SPCL=$Y_HOME/spcl
UTIL1=$Y_SPCL/u1
Y_LIB=$Y_HOME/lib

So, For each "variable", you search for it in the next variables "values" and replace it for the proper "value". You could have a .py like this:
variables = []
with open("fileName", 'r') as f:
    while True:
        line = f.readline()[:-1] # Get the line minus '\n'
        if not line:
            break
        variables.append(line.split('='))

    for i in range(len(variables)):
        current =  "$" + variables[i][0]
        for j in range(len(variables)):
            replaced = None
            while replaced != variables[j][1]:
                # We replace until no further replaces happen
                replaced = variables[j][1].replace(current, variables[i][1])
                variables[j][1] = replaced

for var in variables:
    print(var[0] + "=" + var[1])

Output:
Y_HOME=/utils
Y_SPCL=/utils/spcl
UTIL1=/utils/spcl/u1
Y_LIB=/utils/li


text:
Q: PrimeFaces dialog box not appearing Iam using primefaces 4.0 .I want to use dialog box . When i used it its printing the dialog content in the same page on load itself  .Dialog box not opening
<h:panelGrid columns="1" cellpadding="5">
    <p:commandButton id="basic" value="Basic" onclick="dlg.show()" type="button" />
</h:panelGrid>

<p:dialog id="basicDialog" header="Basic Dialog" widgetVar="dlg1">
   <h:outputText value="Resistance to PrimeFaces is futile!" />
</p:dialog>

also tried

in facesconfig.xml
       org.primefaces.application.DialogActionListener
       org.primefaces.application.DialogNavigationHandler

       org.primefaces.application.DialogViewHandler
Thanks in advance

A: I missed adding
       h:head
Thanks all for your response


text:
Q: app engine java.security.AccessControlException when i  use app engine to develop my apps,and i just want to read the file stored in the gaevfs using the code : this.shpAccessFile = new RandomAccessFile(this.shpFileName, "r"); but it throw new AccessControlException("access denied "+perm, perm);so can someone tell me how to solve the problem?
java.security.AccessControlException: access denied (java.io.FilePermission gae:\F:\workspace\GeoCloud\war\gaevfs\cecc8aa0-7405-102e-b976-026d7f000001\longrive.shp read)
    at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
    at java.security.AccessController.checkPermission(AccessController.java:546)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
    at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:166)
    at java.lang.SecurityManager.checkRead(SecurityManager.java:871)
    at java.io.RandomAccessFile.<init>(RandomAccessFile.java:203)
    at java.io.RandomAccessFile.<init>(RandomAccessFile.java:98)
    at com.vobject.appengine.java.io.RandomAccessFile.<init>(RandomAccessFile.java:90)

A: Are you following this guideline?


text:
Q: How can I use existing chapter select functionality in AngularJS/Ionic I am currently writing a new Ionic/AngularJS app against an existing PHP backend and database.  Currently the api/database has HTML documents stored in the database which then have fields replaced by customer data much the way standard reporting tools do it (it could also be described as a mail merge).  They also have used # Anchor tags to describe chapters and have a select/option dropdown for a quick jump to different chapters.  All of the chapter options are in a separate field from the document itself.
Problem: AngularJS removes the Anchor and Option tags when populating the content and chapter dropdown via ng-bind-html.  I need to figure out how to process this on the front end if possible because changing the back end is going to be costly in both time and money.
Example 1: Partial HTML Text in the Javascript Object before ng-bind-html

PRE-EMPLOYMENT

The Application Process:

The application process is the initial opportunity to avoid individuals prone to workplace violence and terror activities. Employers often overlook this opportunity to prevent problems. Look for discrepancies, individuals with poor employment histories often fabricate information on their applications. Be cautious of:

• Gaps in employment.

– Potential problem employees often leave with no substitute employment.

– Gaps in employment are often explained with, “I could not find a job,” or a similar statement.

Example 2: Content in web page after using ng-bind-html:

PRE-EMPLOYMENT

The Application Process:

The application process is the initial opportunity to avoid individuals prone to workplace violence and terror activities. Employers often overlook this opportunity to prevent problems. Look for discrepancies, individuals with poor employment histories often fabricate information on their applications. Be cautious of:

• Gaps in employment.

– Potential problem employees often leave with no substitute employment.

Notice the id in the anchor block has been removed in the text.  I have researched a number of things here and have not yet found a solution to this issue.  The discovery of the removal came as we were implementing the select dropdown for the chapters where AngularJS removes all of the  tags from the existing chapter dropdown as shown in examples 3 and 4.
Example 3: Object Data for Table of Contents

<option value="#1">Pre-Employment</option>
<option value="#2">The Interview Process</option>
<option value="#3">Drug Testing</option>
<option value="#4">Violence Prevention Program</option>
<option value="#5">Responsible Person</option>
<option value="#6">Crisis Team</option>

Example 4: Processed Data from ng-bind-html

Pre-Employment
The Interview Process
Drug Testing
Violence Prevention Program
Responsible Person
Crisis Team

A: My solution was to add an Angular Filter for "unsafe".
.filter('unsafe', function($sce) {
  return function(val) {
    return $sce.trustAsHtml(val);
  };
})

This allowed me to filter the ng-data-bind-html as truly unsafe html.


text:
Q: Inheriting a base class from Modbus static library causes invalid stack pointer on return, but works fine when using base class directly I'm using VC++2017 to write a program to communicate with a PLC using Modbus. Ideally, I want to create a class that inherits from the MbusAsciiMasterProtocol but it's looking like that will be impossible. My current header file for it is:
#pragma once
#include "MbusAsciiMasterProtocol.hpp"

class PlcModbus
    : public MbusAsciiMasterProtocol {
public:
    /* Also tried without calling MbusAscii constructor and doesn't work*/
    PlcModbus() : MbusAsciiMasterProtocol() {}
    ~PlcModbus() {}

};

and the part in the main function that uses it is
/* Doesn't work */
int dataArr[18];
PlcModbus plc;
plc.openProtocol("COM3", 19700L, 8, 1, 0);
plc.readMultipleLongInts(1, 1, dataArr, sizeof(dataArr) / sizeof(int)); // Breaks here
plc.closeProtocol();

Which throws a null pointer exception when it gets to plc.readMultipleLongInts (it successfully calls openProtocol and opens the connection). I did some digging with the debugger and found that the stack pointer after the function is called is 12 spaces away from where it was prior to the function call.
Now, if I don't inherit from MbusAsciiMasterProtocol and instead use the class directly, everything works fine.
/* Works fine */
int dataArr[18];
MbusAsciiMasterProtocol plc;
plc.openProtocol("COM3", 19700L, 8, 1, 0);
plc.readMultipleLongInts(1, 1, dataArr, sizeof(dataArr) / sizeof(int));
plc.closeProtocol();

There is no runtime error and I am able to communicate with the PLC. This makes absolutely no sense to me because up until this point I assumed that inheriting from a base class essentially gave you access to the same public and protected member functions within the base class. But this seems to imply otherwise.
I also tried to use MbusAsciiMasterProtocol as an object in PlcModbus and write wrappers around the functions I need, but that didn't work either and it gave the error "- The value of ESP was not properly saved across a function call.  This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention."
#pragma once
#include "MbusAsciiMasterProtocol.hpp"

class PlcModbus {
public:
    PlcModbus() : myModbus(MbusAsciiMasterProtocol()) {}
    ~PlcModbus() {}

    int openProtocol(const TCHAR *portName, long baudRate, int dataBits, int stopBits, int parity) {
        return myModbus.openProtocol(portName, baudRate, dataBits, stopBits, parity);
    }
    int readMultipleLongInts(int slaveAddr, int startRef, int *int32Arr, int refCount) {
        return myModbus.readMultipleLongInts(slaveAddr, startRef, int32Arr, refCount);
    }
    void closeProtocol() {
        myModbus.closeProtocol();
    }
public:
    MbusAsciiMasterProtocol &myModbus;
};

I feel there must be something going wrong with the calls to the static library based off of that error,  but why it works when I use the base class and not when I inherit from it is beyond me. Any explanation about what's going on would be extremely helpful.
Cheers.

A: I don't know why inheriting from  MbusAsciiMasterProtocol doesn't work for you.
However in your last code example where you write wrappers around functions you have one subtle error:
MbusAsciiMasterProtocol &myModbus; creates a reference to  MbusAsciiMasterProtocol object.
In the constructor you are initializing it with MbusAsciiMasterProtocol() - a temporary object thus creating a reference to a temporary. This is probably the source of the errors you are getting. Remove the reference and make the object private instead of public.


text:
Q: Failed binder transaction in android widget
Possible Duplicate:
failed binder transaction on widget update

i am having a problem when i try to update a bitmap in my android widget. JAVA FAILED BINDER TRANSACTION error start looping in my logcat after 10 to 12 updates of bitmap and my widget stop updating after that. All i am doing is showing current seconds in my widget at the moment.
This is how i am creating a bitmap
public static Bitmap buildUpdate(String time,Context ctx)
    {
Bitmap myBitmap=null;
    myBitmap = Bitmap.createBitmap(160, 84, Bitmap.Config.ARGB_4444);
    Canvas myCanvas = new Canvas(myBitmap);
    Paint paint = new Paint();
    Typeface clock = Typeface.createFromAsset(ctx.getAssets(),"AladinRegular.ttf");
    paint.setAntiAlias(true);
    paint.setSubpixelText(true);
    paint.setTypeface(clock);
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.WHITE);
    paint.setTextSize(65);
    paint.setTextAlign(Align.CENTER);
    myCanvas.drawText(time, 80, 60, paint);
    return myBitmap;
    }

and this is where i am calling it to update my imageview
   remoteViews.setImageViewBitmap(R.id.label_fg, Drawing.buildUpdate(seconds+" ",ctxt));

I dont know what i seem to be doing wrong here , all i got after two days of research is that i am hitting IPC memory limit. Why so and how to avoid this ?

A: Yes, you're hitting the size limit for bitmaps passed through a binder call. More recent versions of Android use newer mechanisms for this and the limits are higher.
You can avoid the error by using smaller bitmaps. :)


text:
Q: Prevent re-rendering when child components list expands In the following example, every click of the button should only render the next Number component, but instead it re-renders the whole list again. I would like to know the best practice to prevent the previous one from re-rendering. Thank you.
const Number = (props) =>{return (<div> {props.number} </div>)}

const NumberListUpTo = () =>{

 const [listLength, setListLength] = useState(1);

 return(
 <>
  <button onClick = {() => setListLength(listLength + 1)}>add one more</button>
  {
   Array.from({length: listLength}, (v, i) => i).map(
   (i) => (<Number number = {i} />))
  }
 </>)
}

A: *

*Use React.memo to memoize your components.

*You should always provide a key for React components when you are rendering an array of elements.

Edit:
As React documentation says:

This method only exists as a performance optimization. Do not rely on it to "prevent" a render, as this can lead to bugs.

Do not try to prevent renders or memoize every component. Try to optimize your code whenever you there is a performance issue. Optimization in React, using memo, useMemo, useCallback, etc) comes at a price; they take resources and may even slow down your app.


text:
Q: Some strangeness with agda-mode for Agda 2.5.1 So like other Agda enthusiasts, with the release of the new version of Agda, I quickly cabal-force-installed the latest and greatest. However, after compiling and setting-up agda-mode (the new one), my emacs is giving me some strange settings.
I no longer have an include dirs menu when I attempt to customize agda, I've circumvented this by using the program args menu and adding --include-dir=<stuff>. However, the colour scheme is bothersome. In a literate agda file, everything outside of \begin{code} and \end{code} is coloured salmon-red and I want it to be black as was in older versions.
I've played around with the highlight settings, but just could not get this to change. Any advice would be most appreciated!
Thank-you!
Edit : the removal of the include-dirs is no error, the change log under the emacs section mentions this and more.


text:
Q: Setting permissions through Azure DevOps API throws bad request (400) I'm trying to write a script to change permissions to my Azure DevOps resources using its API.
The error i get is BAD REQUEST.
My credentials are working (i'm using them in other functions to get all the parameters to build the body).
Maybe there's something wrong with the body that i'm not seeing.
This is my function:
function Set-Permission {
    param(
        [Parameter(Position=0, Mandatory = $true, ValueFromPipeline = $true)] `
        [string]$organization,
        [Parameter(Position=1, Mandatory = $true, ValueFromPipeline = $true)] `
        [string]$namespaceId,
        [Parameter(Position=2, Mandatory = $true, ValueFromPipeline = $true)] `
        [string]$token,
        [Parameter(Position=3, Mandatory = $true, ValueFromPipeline = $true)] `
        [string]$groupDescriptor,
        [Parameter(Position=4, Mandatory = $true, ValueFromPipeline = $true)] `
        [int]$allowMask,
        [Parameter(Position=5, Mandatory = $false, ValueFromPipeline = $true)] `
        [int]$denyMask = 0
    )
       $body =
       @"
          {
             "token": "$token",
             "merge": true,
             "accessControlEntries": [
                {
                   "descriptor": "$groupDescriptor",
                   "allow": $allowMask,
                   "deny": $denyMask,
                   "extendedinfo": {}
                }
             ]
          }
"@
       Post-RestAPICall -url $url -body $body
}

These are the sample URLs and body i'm using.
URL
https://dev.azure.com/myAccount/_apis/accesscontrolentries/2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87?api-version=5.0

Body
"          {
             "token": "repoV2\827a6631-8685-4a0e-b53f-b54742e505fa",
             "merge": true,
             "accessControlEntries": [
                {
                   "descriptor": "Microsoft.TeamFoundation.Identity;S-1-9-1551374245-828799618-2240155210-3040851271-1122305530-1-2397848184-1658408774-2559123938-1159016780",
                   "allow": 32,
                   "deny": 0,
                   "extendedinfo": {}
                }
             ]
          }"

The Post-RestAPICall function is just error handling for these calls.
Any advice?

A: Found the solution.
The token uses a regular slash (/) instead of backslash (\).
Changing that makes the request work properly.
Cheers!


text:
Q: How to get Steam user inventory online ok so i found out how to get the json after searching for an answer i could not find for like 5 hours.
http://steamcommunity.com/profiles/{steamid}/inventory/json/730/2/?trading=1
this brings up the json.
im wondering how can i get the picture of the weapon, name and price and store be able to show it on a webpage...this is for csgo
here if my question isnt clear enough
Picture of online inventory
thats from csgopowerball.com if you were wondering.
here is what im talking about, thats my inventory, and it grabbed my gun, with name and price and wear. im wondering how im able to grab info from the json to that. cause i dont know what the price or wear is on there.
if you are still confused please add me on skype: pannduuh


text:
Q: Ansible: Pbrun not able to execute I have the below inventory file
[server]
abc.com
[server:vars]
ansible_user="user1"
ansible_ssh_pass="pwd"
ansible_pbrun_exe="pbrun"
ansible_pbrun_password="pqa"
ansible_pbrun_user="root"

and the playbook file
---
- name: Upgrade Java Version to all the hosts
  hosts: all
  tasks:
    - name: run simple command
      shell: java -version 2>&1 | grep version | awk '{print $3}' | sed 's/"//g'
      register: javav

    - name: remove the currently installed java
      become: true
      become_method: "pbrun"
      shell: |
        mv /usr/bin/java  ~/bckup_java_exe
        mv /usr/java/ ~/bckup_java

Now when I run the ansible playbook it connects to the ssh host and is also able to run the java -version .. command successfully but not able to run the mv command as it needs pbrun
when I remove become: true from playbook it shows Permission error
```
: Permission denied", "mv: cannot move `/usr/java/' to
````

And when I do not remove become: true it gives some other error, and it is not working either

A: I do not see that you have set become_method: pbrun anywhere. This is required.

A: The solution i have found is below
  become: "yes"
  become_method: "pbrun"
  become_user: "root"
  become_flags: "sa"

as we ran pbrun sa -u root
also do not forget to set ansible_become_pass into inventory file or --ask-become-pass
thanks


text:
Q: Oracle adf form not resetting new data from iterator I have an issue with oracle adf form that always keeping same data in form from an iterator. Even though i am resetting the data but its still keeps same data when we come back from previous page with table of an iterator.

A: When you come back to the form, along with resetting the data you have to re-execute the iterator and do partial triggers on the table and the form.
When you re-execute the iterator the cursor will be pointing to the before first row and the partial triggers on table and form will be refreshed based on the current row in iterator (before first row = no row selected).
To give more specific inputs, how you are coming back to this form? if you share code snippet of jsff and the bean then it will be easy to suggest the solution.


text:
Q: mysql update script not updating database I have an update query that is not updating the database.  I have verified that the if condition is meet, and verified that the data is getting posted.  I believe it is a syntax error, but I cna not see it.  Can anyone see any mistakes?
if(isset($_POST['account_id']) && isset($_POST['account_id']) !="") {
    $request_id  = $_POST['request_id'];
    $account_id = $_POST['account_id'];
    $class_id = $_POST['class_id'];
    $sub_account_id = $_POST['sub_account_id'];
    $amount = $_POST['amount'];
    $justification = $_POST['justification'];
    $last_edited_by_uid = $_POST['last_edited_by_uid'];
    $last_edited_date = $_POST['last_edited_date'];
    try{
        $stmt3 = $db->prepare("UPDATE budget_request SET account_id=:account_id, class_id=:class_id, sub_account_id=:sub_account_id, amount=:amount, justification=:justification, last_edited_by_uid=:last_edited_by_uid, last_edited_date=:last_edited_date WHERE request_id=:request_id");
        $stmt3->bindParam(':request_id',$request_id,PDO::PARAM_INT);
        $stmt3->bindParam(':class_id',$class_id,PDO::PARAM_INT);
        $stmt3->bindParam(':account_id',$account_id,PDO::PARAM_INT);
        $stmt3->bindParam(':sub_account_id',$sub_account_id,PDO::PARAM_INT);
        $stmt3->bindParam(':amount',$amount,PDO::PARAM_STR);
        $stmt3->bindParam(':justification',$justification,PDO::PARAM_STR);
        $stmt3->bindParam(':last_edited_by_uid',$last_edited_by_uid,PDO::PARAM_STR);
        $stmt3->bindParam(':last_edited_date',$last_edited_date,PDO::PARAM_STR);
        $stmt3->execute();
        header(sprintf('Location: budget_worksheet.php?class_id='.$class_id));
        exit();
}
    catch(PDOException $e){
        //$db->rollBack();
        //echo $e->getMessage();
        exit();
    }
}


text:
Q: Sending body in HttpClient delete method (Angular 5) I'm migrating Http to HttpClient in an Angular 5 application and everything went fine until I got to this method of one of the services:
deleteMultipleObjects(userId: number, officeId : number, objectsData : any) {
  const url = `${APP_URL}/delete-objects/${userId}/${officeId}`;

  let headers = new Headers({ 'Content-Type': 'application/json' });

  this.appOptionsService.log("Deleting multiple objects.....", url, objectsData);

  return this.http
    .delete(url, { headers : headers, body : objectsData } )
    .map(this.extractData)
    .catch(this.handleError);
}

As you can see, I pass an object objectsData in the body of the delete call that basically has this structure:
{
  objectIds: [id1, id2, id3, ...]
}

I see that the delete method in the HttpClient doesn't allow to include a body, so how could I send the array of object ids to delete with the call? I have a lot of delete calls that are the same as this one, so I'll have to change a lot of things in the code to adapt it...
Thanks!

A: You can not send body in DELETE http request in Angular.
HTTP specification on MDN says that this possible.  documentation page.
If you need this functionality, you should use PUT as workaround. Another method to allow multiple e.g. id's on your delete API endpoint. For example:
https://server.com/api/delete?ids=1,2,3,4,5

That requires some changes on your api.


text:
Q: Difference of the length according to dimension of the coordinate system We know that the length of a vector does not depend on the coordinate system we choose. It's always the same. But is it still true when we add additional dimensions to our coordinate system? As long as logically we do not experience for example four or five dimension, which mathematics prove that the length is the same in all coordinate system with dimensions more than three?

A: Not sure I understand you question, but I'll try to answer it. Let's assume we have an arbitrary number of dimensions $N$. Then the length of a vector in this $N$-dimensional space is given by the $L_2$-norm:
$$ \ell = \left(\sum_{n=1}^N a_n^2\right)^{1/2} , $$
where $a_n$ are the components of the vector.
If we actually had a smaller space, one with fewer dimensions, say $M<N$, then we would still have the same $L_2$-norm, but where the sum only runs to $M$. All the vectors in the smaller space have only (or at most) $M$ nonzero components.
Now we embed this smaller space into the original space with $N$-dimensions. In other words, we add $N-M$ dimensions. So we need to use the original $L_2$-norm with $N$ components, but because only $M$ of these components are nonzero, the expression for the length of the vectors would reduce to the one for the $M$-dimensional space. Hence, the length of the vectors remains the same even though we've added extra dimensions.


text:
Q: Mask sub-directory URL/Re-direct URL with .htaccess Hi Stack Overflow community,
I have a question regarding a web setup. My main website is in the root of my "public_html" directory. Within this directory, I have created a subfolder called "subsite". So the file address to this is: "public_html/subsite". To access my main site, I go to www.example.com. I also have an add-on domain that points to my 'subsite' directory, which is www.subsite.com.
My urls are not behaving correctly. When I go to www.subsite.com, it points to the appropriate subdirectory within my main site's root folder for the homepage only. However, once I start navigating to other pages with my subsite, the url changes back to www.example.com/subsite/about.php for instance. I would like to mask all urls for visitors so when a user goes to a page on my subsite, the page url would be www.subsite.com/about.php.
When a user navigates to the site in this way: "www.example.com/subsite/..." it will re-direct them to www.subsite.com with the appropriate address. If pages could redirect as well, that would be great! Ex. "www.example.com/subsite/about.php" redirects to "www.subsite.com/about.php".
Also, I'm having similar problems with my subdomains. "customers.example.com" rewrites to "www.example.com/customers/..." when I navigate to inner pages. I think this is a similar problem to my main site stuff happening above.
Thanks for any help! If you have a good tutorial that answers this, point me there. If not, I'd appreciate any self-help you might offer!!

A: As a temporary fix, try adding these lines ot your root .htaccess file :
RewriteEngine on

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^subsite(/(.*))?$ http://www.subsite.com/$2 [L,QSA,R=301]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^customers(/(.*))?$ http://customers.subsite.com/$2 [L,QSA,R=301]

But you should realy try to fix the source problem of the redirection.


text:
Q: Evaluation of $\int_0^\infty \frac{1}{\left[x^4+(1+\sqrt{2})x^2+1\right]\cdot \left[x^{100}-x^{98}+\cdots+1\right]}dx$
Evaluation of $\displaystyle \int_0^\infty \frac{1}{\left[x^4+(1+\sqrt{2})x^2+1\right]\cdot \left[x^{100}-x^{98}+\cdots+1\right]}dx$

$\bf{My\; Try::}$ Let $$I= \int_{0}^{\infty}\frac{1}{\left[x^4+(1+\sqrt{2})x^2+1\right]\cdot \left[x^{100}-x^{98}+\cdots+1\right]}dx \tag 1 $$
Let $\displaystyle x=\frac{1}{t}\;,$ Then $\displaystyle dx = -\frac{1}{t^2}$ and changing limit, we get
So $$I = \int_0^\infty \frac{t^{102}}{\left[t^4+(1+\sqrt{2})t^2+1\right]\cdot \left[t^{100}-t^{98}+\cdots+1\right]}dt$$
So $$\displaystyle I = \int_0^\infty \frac{x^{102}}{\left[x^4+(1+\sqrt{2})t^2+1\right]\cdot \left[x^{100}-x^{98}+\cdots+1\right]}dx \tag 2$$
So we get $$2I = \int_0^\infty \frac{1+x^{102}}{\left[x^4+(1+\sqrt{2})x^2+1\right]\cdot \left[x^{100}-x^{98}+\cdots+1\right]} \,dx$$
Now Using Geometric Progression series,
We can write $$ 1-x^2+x^4-\cdots-x^{98}+x^{100} = \left(\frac{x^{102+1}}{1+x^2}\right)$$
so we get $$2I = \int_0^\infty \frac{1+x^2}{x^4+ax^2+1}dx\;,$$ Where $a=(\sqrt{2}+1)$
So we get $$2I = \int_0^\infty \frac{1+\frac{1}{x^2}}{\left(x-\frac{1}{x}\right)^2+\left(\sqrt{a+2}\right)^2} dx = \frac{1}{\sqrt{a+2}}\left[\tan^{-1}\left(\frac{x^2-1}{x\cdot \sqrt{a+2}}\right)\right]_0^\infty$$
So we get $$2I = \frac{\pi}{\sqrt{a+2}}\Rightarrow I = \frac{\pi}{2\sqrt{3+\sqrt{2}}}$$
My Question is can we solve the Integral $\bf{\displaystyle \int_0^\infty \frac{1+x^2}{x^4+ax^2+1}dx}$ Using any other Method
Means Using Complex analysis or any other.
Thanks.

A: I think your way of evaluating the integral is very short and elegant. Nevertheless, you can do partial fraction decomposition. You'll end up with (as long as I did not do any mistakes)
$$
\frac{1}{\sqrt{2+a}}\biggl[\arctan\Bigl(\frac{\sqrt{2-a}+2x}{\sqrt{2+a}}\Bigr)+\arctan\Bigl(\frac{\sqrt{2-a}-2x}{\sqrt{2+a}}\Bigr)\biggr]
$$
as a primitive.
Edit
That way of writing it is not so good, since $a>2$. It is better to write
$$
x^4+ax^2+1=\Bigl(x^2+\frac{a}{2}-\frac{\sqrt{a^2-4}}{2}\Bigr)\Bigl(x^2+\frac{a}{2}+\frac{\sqrt{a^2-4}}{2}\Bigr)
$$
and then do partial fraction decomposition. The resulting primitive then reads (watch out for typos!)
$$
\begin{aligned}
\frac{1}{\sqrt{2}\sqrt{a^2-4}}\biggl[&\frac{2-a+\sqrt{a^2-4}}{\sqrt{a-\sqrt{a^2-4}}}\arctan\Bigl(\frac{\sqrt{2}x}{\sqrt{a-\sqrt{a^2-4}}}\Bigr)\\
&\qquad+\frac{a-2+\sqrt{a^2-4}}{\sqrt{a+\sqrt{a^2-4}}}\arctan\Bigl(\frac{\sqrt{2}x}{\sqrt{a+\sqrt{a^2-4}}}\Bigr)\biggr].
\end{aligned}
$$


text:
Q: Android: Multiple selection dialog assign name to element from array
I'm converting my multiple selection checkbox dialog to come from a public property & public class (so I can pull it from anywhere).
However, normally when I do something from a class I have whatever.ID availble to me, and whatever.Name, I guess just a normal multi dimensional array. However I can't work out the syntax in this situation.
Here is my custom class:
package com.directenquiries.assessment.tool.Globals;

public class clsNameID {
    public String Name;
    public String ID;

}

Heres what's creating the array:
public static List<clsNameID> assetHelperTypes(){
    Log.e("Asset Helper Types:", "Started");
    clsNameID AssetDetails = null;
    List<clsNameID> mHelperNames = new ArrayList<clsNameID>();
    File dbfile = new File(Global.currentDBfull);

    SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
    Cursor f = db.rawQuery("select * from assetobservationtypes", null);
    Log.e("Asset Helper Types:", "Cursor run");

    if(f.getCount() > 0) {
        f.moveToFirst();
           while(!f.isAfterLast()) {
               AssetDetails     = new clsNameID();
               AssetDetails.ID = f.getString(f.getColumnIndex("AssetObsID"));
               AssetDetails.Name = f.getString(f.getColumnIndex("Observation"));
               mHelperNames.add(AssetDetails);
               Log.e("Found Item:", AssetDetails.Name);
                f.moveToNext();
           }
    }

    f.close();

    return mHelperNames;
}

Heres where I am trying to use the array:
public void addCondition(View view){

          List<clsNameID> mHelperNames = DBFunctions.assetHelperTypes();

            final List<Integer> mSelectedItems = new ArrayList<Integer>();

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("My Title")
                    .setMultiChoiceItems(mHelperNames.toArray(new CharSequence[mHelperNames.size()]), null,
                            new DialogInterface.OnMultiChoiceClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which, boolean isChecked) {
                                    if (isChecked) {

                                        mSelectedItems.add(which);
                                    } else if (mSelectedItems.contains(which)) {

                                        mSelectedItems.remove(Integer
                                                .valueOf(which));
                                    }
                                }
                            })

   .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int id) {
                        //Create onlcick method
                   }
               })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int id) {
                        //Create onlcick method
                   }
               });
        builder.show();

}

I guess what I really need to be doing is something like .setMultiChoiceItems(mHelperNames.toArray.Name(new CharSequence[mHelperNames.size()])
But clearly that wont work. How do I assign the name value to my setMultiChoiceItems array?
Tom


text:
Q: Why is the little o(h) in the Poisson Process dissimilar to other field's? I learned about little oh notation in Algorithm class last year.
$$
\mbox{if } \lim_{n\to\infty}\frac{f(n)}{g(n)}=0
\mbox{, then } f(n)\in o\big(g(n)\big) \mbox{ or } f(n)=o\big(g(n)\big) \mbox{.}
$$

However, in the Poisson process definition,
\begin{align}
&(1)~N(0)=0\\
&(2)~\mbox{has Independent increments and Stationary increments}\\
&(3)~P\big[\mbox{one event happens between time } t\in(t, t+\Delta{t}\big] = \lambda\Delta{t} + o(\Delta{t})\\
&(4)~P\big[\mbox{two or more events happen between time } t\in(t, t+\Delta{t}\big] = o(\Delta{t}),\\
\end{align}
where
\begin{align}
&N(t) \mbox{ is the number of events occured between time } t\in(0, t]\\
&o(\Delta{t}) = \left\{ f(\Delta{t}): \lim_{\Delta{t}\to0}\frac{f(\Delta{t})}{\Delta{t}}=0\right\}
\end{align}

Why is the little-oh notation used differently?
That is, while little-oh notation is used in Algorithm field like $\displaystyle\lim_{n\to\infty}$, it is used in Stochastic process field $\displaystyle\lim_{n\to0}$.
Thank you for reading my question.

A: It's mostly a context thing - big- and little-oh notation are best at explaining behaviour at large and small scales. Typically for algorithm and complexity applications, you're looking at the behaviour of something on large sets, and this leads to the $n\to\infty$ definition given early in your post.
However, much like defining limits of functions, you can define them as $x\to\infty$ just as well as $x\to a$ for constants $a$. For example, $f\in o(g(x))$ as $x\to a$ says that $\lim_{x\to a}\frac{f(x)}{g(x)}=0$.
This can be used in

*

*Differentiation: $f(x)=f(a)+f'(a)(x-a)+o(x-a)$ tells us that the best linear approximation to $f(x)$ has slope $f'(a)$

*

*Taylor Series: You'll often see things written like: "$\sin(x)=x-\frac{x^3}{6}+O(x^5)$ as $x\to0$"

On the other hand, you'll see non-local use of the notation elsewhere in stochastic processes. For example the law of the iterated logarithm tells us that a random walk (under suitable assumptions) satisfies $S_n=O(n\log\log n)$ as $n\to\infty$.
People use this notation to control error terms, and whether it's a case of $n\to0,\infty,$ or $n\to$ constant depends on where you're trying to bound errors.
In the case of the Poisson process, it's about showing continuity (sort of), which is a local property, so it makes sense to consider $\Delta t\to0$, whereas in algorithms it tends to be about long-term feasibility, which corresponds to taking larger and larger $n$.


text:
Q: How can I improve my Laravel performance? My website is in Laravel 5.4. Last month it was good in speed and it was loading fast, But this month I started getting traffic. Now my website is slow. It takes 3-7 seconds to load the website.
Please guide me how can I improve my website traffic.

A: You need to know about the standard of the Laravel so that we can make our application optimal in the term of speed, performance and so on.

*

*first we need to add all the database communication in the model i.e. all the db queries

*Try to use Eloquent relationship/query to get/set the data

*do not use maximum for each loop

*image must be well optimised and should be less size. If images are excessive MBs then it takes more time to load

*server health should be good. If you are using AWS, Digital Ocean then you need to keep checking the server health, like RAM, CPU, storage, bandwidth..

A: There are number of things you have to consider to improve your Laravel website.

*

*You have to look all database queries. For monitoring database
queries you install Laravel debugbar or the new package Laravel
telescope.

*You must using eager loading in your application

*optimised your images, and use lazy loading to load images.

*compress your Asserts (CSS, JS)

*use CDNs

*If these all not works then you need to increase your server resources and use load balancer.

*And always keep checking the server health, like RAM, CPU, storage, bandwidth.

You must also watch this "Quick Laravel performance improvement" video tutorials. Which will definitely help you to improve your website.
https://www.youtube.com/playlist?list=PL1TrjkMQ8UbWRZ4tv4GW_KwbyavOxt6bc

A: There are number of things you have to consider to improve your Laravel website.
Using eager loading in your application
Using ->cursor() in your query instead of get() method.
for example:
$data = DB::table("users")
->select('*')
->cursor();

Use Caching
$data_key = "any-key-variable";

    if (Cache::has($data_key)) {
          $getData = Cache::get($data_key);
    }
   else {
     $getData = DB::table("users")
                    ->select('*')
                    ->cursor();
       Cache::put($data_key, $getData,720);
    }
}

Also, Use this in your constructor in the controller or calling a function
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '3000');
ini_set('request_terminate_timeout', '3000');

for example
public function __construct()
{
    ini_set('memory_limit', '-1');
    ini_set('max_execution_time', '3000');
    ini_set('request_terminate_timeout', '3000');
}


text:
Q: Understanding subcommands with go-flags I'm building a CLI tool to start learning some Go.  I found this popular package that I wanted to use for some commands like this:
http://godoc.org/github.com/jessevdk/go-flags#Group
https://github.com/jessevdk/go-flags
ex list todos
ex list todos --completed
ex list events
ex list todos events
ex authenticate

The way I understand it is ex would be my main command.
list and authenticate are subcommands.
But what are todos and events in this scenario?  And what would be --completed be.  Is --completed called an Option?  That's the verbage I see around, but not sure if I'm reading it correctly.  I'm trying to find an example that has the different options for something like this scenario, but I could not find one.
I tried using urfave/cli which worked at well at first, until I found a requirement to be able to pass multiple entities to ex list like ex list todos events.

A: I have used jessevdk/go-flags on multiple projects and really like it. The documentation is sparse, but the code is clean so self-documenting in many ways.
I will try and address your questions as best I can:
ex would be your binary, and would usually be a 'master' struct of all the top level commands (eg https://github.com/concourse/concourse/blob/master/fly/commands/fly.go). This will get parsed in your main function (eg https://github.com/concourse/concourse/blob/master/fly/main.go).
todos and events would actually be the first level of subcommands. You would define those on the first level command (list) in the same way you define commands on the 'master' command struct.
--completed is indeed an option.
One example of an open source project that uses go-flags in the Concourse CI CLI https://github.com/concourse/concourse/tree/master/fly. Although it doesn't you nested commands like you want to do, it gives a pretty solid foundation for go-flags usage.


text:
Q: PostgreSQL - find all functions and stored procedures with permissions granted to PUBLIC In Postgres SQL how can I find (via an SQL query) all functions and stored procedures for which PUBLIC has any permissions on them (e.g. to execute them or to do anything with them)?
If it matters my Postgres version is this one:
PostgreSQL 11.13 on x86_64-pc-linux-gnu
In other words when a function/procedure is scripted out, sometimes I see this line in its source code:
GRANT ... ON FUNCTION some_function() TO public;
So I want to find all such functions in my DB which when scripted out show this line.

A: I just found a solution myself. Here it is.
select routine_schema, routine_name, *
from information_schema.role_routine_grants rrg
where
grantee  ilike '%public%'
order by routine_schema asc, specific_name asc, routine_name asc


text:
Q: What file is setting CSS to body tag in NextJS Can someone explain what file in NextJS is setting those settings that are shown as "inherited from body"? Is there any way to change them?
Could not find any such files in my project tree or any relevant answers to that question.


text:
Q: how to detect if any web extensions are being used I want to detect using vanilla javascript if the end-user has any webextensions enabled at all. Is there a way to query for a list of browser enabled webextensions? Hopefully there is another way besides checking for injected scripts, css and image tags that the page was never intended to load.
This question was shut down for not entering enough security reasons. I can understand why that's a concern but it is not a reason to burn a technical question. Regardless, here are security reasons to want to eliminate web-extensions from a website:
web-extensions allow people to break CSP
https://chrome.google.com/webstore/detail/disable-content-security/ieelmcmcagommplceebfedjlakkhpden
scrape your business data, install key loggers to harvest passwords and other information, install image tracking beacons to track private and sensitive end-user information - all unbeknownst to your average end-user.
In addition, deliberate or self-made web-extensions can automate scraping your business data, attempt to spoof captcha logins and other malicious purposes.

A: some way is
you can check number of script tag that document has (also css)
then if there were more than your resource
user use extension
... some extension does not add script or css


text:
Q: Create string of n characters without loop In Python I can use:
s = "x" * 10
xxxxxxxxxx

How in JavaScript, do I create a string n characters long without a loop?

A: use String.repeat
"x".repeat(10);

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
On old browsers you could do
new Array(10).join('x')

A: Use repeat method.
'x'.repeat(10);

A: new Array(11).join('x')

For 10 x you need 11 in new Array so that 10th x is visible.


text:
Q: How strong is Earth's magnetic field in space? I've been searching around Google and Youtube about the strength of Earth's magnetic field. By the help of wikipedia, I have found out that it's magnitude is 25 to 65 microtesla or 0.25 to 0.65 Gauss while at the Earth's surface. In Youtube I've seen a man named Richard Garriot showed that small magnets with the size of 1 inch in diameter actually works in space and is able to align itself from Earths magnetic pole.
But here is the question. How strong is Earths magnetic field in space?
is it stronger than 25 to 65 microtesla or even less? disregarding the strength of gravity, would it be strong enough to attract any sort of magnets back to the Earth? or repel it away if it's facing the similar magnetic pole?
I am also drawn by the fact that neodymium magnets has stronger magnetism with the strength of 1.4 tesla compared to Earth's 25 to 65 microtesla magnitude. If Earth is able to protect us from Solar Wind, Does that mean a neodymium magnet with the strength of 1.4 tesla and hypothetically the same size of the Earth can protect itself far much better from Solar Wind?
This questions might have sound very silly, but an answer would be wonderful and much appreciated.

A:
How strong is Earths magnetic field in space?

At what distance?  The Earth's magnetic field is roughly modeled as a tilted dipole (i.e., the magnetization axis is tilted with respect to the spin axis of rotation).  The magnitude at the magnetic equator is given by the approximation:
$$
\lvert \mathbf{B} \rvert \left( r \right) \approx B_{o} \left( \frac{R_{E}}{r} \right)^{3} \tag{1}
$$
where $R_{E}$ is the Earth's radius, $B_{o}$ is roughly 31,200 nT (i.e., the average field magnitude at the Earth's surface near the magnetic equator), and $r$ is the distance from the center of Earth.
As you can see, by the time you reach ~4 $R_{E}$ the magnetic field has dropped to ~490 nT.

would it be strong enough to attract any sort of magnets back to the Earth?

I doubt one could actually create a scenario to test this as all things in space are orbiting at several km/s.  Some spacecraft do use the Earth's magnetic field for orientation/attitude control, but generally these just cause small rotations not radial forces or effective drag forces.

or repel it away if it's facing the similar magnetic pole?

I highly doubt this.

Does that mean a neodymium magnet with the strength of 1.4 tesla and hypothetically the same size of the Earth can protect itself far much better from Solar Wind?

If we had a stronger field and the source region was as large as the Earth, then yes.  If you used something the size of a small refrigerator magnet then no.  You could see this by changing (in Equation 1 above) $R_{E} \rightarrow r_{o} \sim 1 cm$ and $B_{o} \rightarrow b_{o} \sim 1 T$.  The size of the source shrunk by ~8 orders of magnitude while the strength of the field only increased by ~5-6.
The Earth protects us from the solar wind because those particles are charged, thus they respond to a magnetic field.  The Earth's magnetosphere also creates a bow shock upstream of the Earth, which provides additional protection since it slows down any inflowing particles and deflects them (due to gradients in the magnetic field).
I wrote some more details on the effects of the solar wind at https://physics.stackexchange.com/a/214509/59023.

A: If you put your itty bitty magnet with the 1.4 tesla field at the North Magnetic Pole, and another identical one at the South Magnetic Pole, then you would have added 1.4 tesla at each pole. There would be zero effect on the Earth's magnetic field. Like all fields you're likely to encounter, magnetic field strength depends on the distance from the source. The measurement of strength at some undefined distance from the source is not useful information. Industrial magnets use a customary distance to characterize (which I've forgotten). The magnetic field strength ON Earth's surface, has a distance to the poles dependent on latitude. Unfortunately, magnetic fields are more complicated than gravitational fields (gravity is very symmetric), and except very near the Earth, a two-pole magnet is not a good approximation of the actual shape of Earth's field.


text:
Q: Low latency message queue Basically I have one master node that distributes tasks between worker nodes. Number of workers could change, that means that the workers could not be hard coded at the server side. Master submits a task to the queue and one of the workers takes this task, processes it and returns the result back. The most critical aspect is low latency. The typical process time on worker node is about 100-300 ms, this means that messaging system should not add significant delay to the process time.
Currently I'm looking at request-response JMS pattern. This means that master would submit the task to the shared queue, the worker would take the task from the queue and submit the result to another queue which is listened by master node. Master would correlate the response with request.
I'm afraid that JMS may bring latency to the system, which is not acceptable. Probably I should look at other solutions? Such as RabbitMQ, JGroups or ZooKeeper?
If JMS is suitable here, could you recommend the fastest JMS broker? Currently I'm looking at ActiveMQ
One more requirement for the solution is that it should be able to work in the cloud

A: A JMS based solution cannot guarantee low latency because of the inherent message batching technique used by all vendors, be it Rabbit or Hornet or ActiveMQ for high throughput.
Vendors like IBM and Mule have released specific low latency products for the job.
But everything depends on your load and number of tasks produced and number of workers consuming. So with tuning you can get your personalised numbers.
CoralQueue based on LMAX disruptor is definitely worth a look.

A: You should have a look here [1], Rabbitmq has a good performance article and the talks about latency.
A quick resum, I have to say that Rabbitmq can take 400ms lateny value in some stressed circumstances but usually with low sending rate it is most close to 40ms or fewer. Have a look at (sending rate attempted vs latency graphic)
By the way you should take into account your network latency as well. This benchmark shows a localhost performance.
[1] http://www.rabbitmq.com/blog/2012/04/17/rabbitmq-performance-measurements-part-1/

A: I presume you are looking for a Java solution (From JMS)
For hight throughput low, latency in memory queue functionality you could consider Hazelcast  (http://hazelcast.org/)
It might do... It depends on how frequently workers will leave/join the cluster. Very frequent Adding / Removing members of a cluster will make it less efficient.
Also, if you require persisted queues or complex queue management, this might also be troublesome.
Non-java clients will be problematic since you will need to purchase a license.
However if you just want a low latency queue for java - it will do the trick
For quick look to see if it will fit your purpose look here:
http://docs.hazelcast.org/docs/latest/manual/html/queue.html
Make sure you have a good network config as well. 10gig if you can, 1gig will do but make sure you use a reputable switch.


text:
Q: How to customize message and title for notification I have been using react-native-fcm before and had to switch to react-native-push-notification because notifications are not triggered when the app is killed. Here is the Link.
In react-native-push-notification, when a remote notification is received the notification is fired automatically with the message i get from payload. I want to customize the message with more details i get from payload.
I have two ways,

*

*Stop the automatic triggering and use PushNotification.localNotification(details: Object) when the remote notification is received.

*Edit the message which is automatically triggered. (preferred)
I want the 2nd option to implement because the notification is triggered when the app is killed.
Can anyone help me with this problem.
I did tried to go into react-native-push-notification folder in node_modules and change it but it resulted in app crash. I might changed the wrong code.


text:
Q: Concerns about tight coupling between ODP.NET and Oracle Client causing deployment issues on webservers with large numbers of applications Just deployed an application using the "Oracle Data Provider for .NET" and received the error "Exception: The provider is not compatible with the version of Oracle client"
Unless I am mistaken, it appears that the version of ODP.NET that one uses in their code must exactly match the oracle client deployed to the server.
I've always worked with the System.Data.Oracle provider which is independent of the oracle client version, and before that ADODB.. and ADO (DAO anyone?). With all of these technologies, they would work with most any Oracle client, and this was very important, both for organization-wide deployment of client applications and for deployment of web-based applications to servers used by many developers.
Does Oracle seriously expect us to deploy ONE SINGLE oracle client version across our entire enterprise? Under this scenario, how would we upgrade that version later, without re-compiling and re-deploying our entire application suite?
Am I missing something fundamental here, or is there truly a tight coupling between Oracle's ODP.NET and the specific oracle client? If so, how could this ever work in a production environment?


text:
Q: Homotopy equivalence of spaces versus existence of homotopy For now I have seen homotopy being defined as follows.

*

*If $\phi,\psi:\Omega\to Z$ are continuous maps, we say that they are homotopic if there exists a continuous $F:\Omega \times [0,1]\to Z$ such that $F(\cdot, 0) = \phi(\cdot)$ and $F(\cdot, 1) = \psi(\cdot)$.

*Two topological spaces $X$ and $Y$ are homotopy equivalent if there exist $f:X\to Y$ and $g:Y\to X$ such that $f\circ g$ is homotopic to $\mathrm{id}_Y$ and $g\circ f$ is homotopic to $\mathrm{id}_X$. In particular, homeomorphic spaces are homotopy equivalent.
This way it seemed to me that homeomorphism is a stronger relation than homotopy, but here comes a problem with my understanding of the latter concept. Let $\Bbb S^1 \subseteq\Bbb R^3$ and let $K\subseteq \Bbb R^3$ be treefoil knot. Am I correct in assuming that $\Bbb S^1$ and $K$ are homeomorphic but there does not exist a homotopy between them in $\Bbb R^3$? I mean that if $\phi:\Bbb S^1\to \Bbb R^3$ and $\psi:\Bbb S^1 \to \Bbb R^3$ are embeddings of $\Bbb S^1$ and $K$, then there does not exist a homotopy $F:\Bbb S^1\times[0,1]\to \Bbb R^3$ that connects them? Then how should the intuition "homeomorphism is stronger than homotopy" be understood?

A: I think the intuition should say "homeomorphism is stronger than homotopy equivalence".
Perhaps the confusion arises from the following: being homeomorphic to something is a property intrinsic to the space, whereas being homotopic refers to a map $f: X \to Y$, so from that point of view we could say that there is an "ambient" space $Y$ where the deformation takes place. Being homotopy equivalent to something is also an intrinsic property of the space.
I should add that any two maps parametrising the unknot and the trefoil respectively will be homotopic (actually any two maps to $\mathbb{R}^3$ will be) but not isotopic. An isotopy between embeddings $f_0,f_1: X \hookrightarrow Y$ is a map $F: X \times [0,1] \to Y$ such that $F(-,i)=f_i$, $i=0,1$ and the map $F(-,t): X \to Y$ is an embedding for all $t \in [0,1]$.  This is because any attempt to unknot the trefoil will lead you to cross two strands. While this is allowed for a homotopy, it is not for isotopy, as one of the $F(-,t)$ will fail to be injective (when the strands cross each other).
To be more precise about why unknotting the trefoil through isotopies is not possible, one has to look at invariants of (say smooth) embeddings $S^1 \hookrightarrow \mathbb{R}^3$, that is knots. A very simple knot invariant that will distinguish the unknot and the trefoil is tricolourability.


text:
Q: Javascript Object Model REST/AJAX: does callback/resulting function have access to the id of newly created item so if I use rest like method to create a list item in javascript, can I get the id of the newly created item in the callback/result function?
function createNewRecord(url, body, callback)
{
    $.ajax({
         type: 'POST',
         url: url,
         contentType: 'application/json',
         processData: false,
         data: body,
         success: function () {  callback(); }
    });
}

function createAnItem() {

  newItem = {};
  newItem.Title = 'Hello World';
  var body = Sys.Serialization.JavaScriptSerializer.serialize(newItem);
createNewRecord(urlVariable, body, onNewItemCallback);

}

function onNewItemCallback() {
     //is the id of the created item available here?
}

thanks! like response, response.get_responseData() from a GET request...or something like that?

A: The response from the POST message contains a JSON object representing the item that was just created. A reference to this object is passed as part of the first parameter to the success callback.
function createItem() {
    var due = new Date();
    due.setDate(due.getDate() + 7); // seven days from today

    jQuery.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Tasks')/Items",
        type: "POST",
        data: JSON.stringify({
            "__metadata": { type: "SP.Data.TasksListItem" },
            Title: "Sample Task",
            AssignedToId: _spPageContextInfo.userId,
            DueDate: due
        }),
        headers: {
            Accept: "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },
        success: function (data, textStatus, jqXHR) {
            var itemId = data.d.Id;  // Id of new item

            var message = jQuery("#message");
            message.text("Item added. Id = " + itemId);
        }
    });
}


text:
Q: Can not find cakephp model I am having extreme issues trying to get cakephp to find a model. i been working on this project for 4 months now and created ton's of models but for some reason, cake can not find this model. This is how it is set up at minimum
app/controllers/arbitrations_controller.php
<?php
class ArbitrationsController extends AppController {
    var $name = 'Arbitrations';
}

app/models/arbitration.php
<?php
class Arbitration extends AppModel {
    var $name = 'Arbitration';
}

database name: arbitrations
Error Message

Controller::paginate() - can't find model Arbitration in controller
  ArbitrationsController [CORE\cake\libs\controller\controller.php, line
  1102]

I've tried clearing tmp/cache/models and tmp/cache/persistent

A: I got it to work. I just deleted my arbitrations_controller.php file and recreated and it worked. Must be some type of glitch or something. I think it may have had something to do with even going about deleting the tmp files and recreating the files again.
Dont know what it was, but it wasted 3 hours of my life.

A: I just set this up using CakePHP v1.3.x and it worked out of the box using scaffolding. A couple of things you can try:

*

*Double check the spelling on everything. Arbitration can be easily
misspelled.

*Add the var $uses = array('Arbitration') to the top of the
controller and see if that changes anything.

*Double check the model spellings in the controller
$this->Arbitration->recursive = -1;
If all of those things are set and working as expected it should work. Another thing to try is to load it in a clean app to see if it works in a stand alone environment.


text:
Q: Android record screen and stream it I am working on a personal project in which I want to record the screen of my phone and stream it. It doesn't have to record the whole, it can be just my app. I am trying to use ffmpeg, but I see that is not possible to read from /dev/graphics/fb0 as it requires root.
I am trying to check what other options do I have. I know it must be possible, as there are other apps that do the same without the need of having a rooted device.
I have just found this class https://developer.android.com/reference/android/media/projection/MediaProjection.html, that might be useful, but it is only available in API 21.
Could you give me any tips of tools, or how could I achieve this?
Thanks.

A: This github project is very simple and is using MediaProjection to achieve screen recording. I hope it will help with recording part.


text:
Q: Create Eth / IP packets in Java I need to create an Ethernet packet with existing UDP payload. I need to put in the ports / checksum for UDP, IP's/checksum for IP layer etc. Is there any library for that?
Thanks!


text:
Q: Reading files in android. how to fix bad path I am trying to read a file in android.
I am used to doing this in java but here I am getting a open failed enoent (no such file or directory) error.
I am not sure how to import the file. Should I put it in the same directory as my application? right now its on my desktop.
here is my code
package com.androidplot.fun;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    private String path;
    public ReadFile(String file_path){
        path = file_path;
    }
    public String[] OpenFile() throws IOException{
        FileReader fr = new FileReader(path);
        BufferedReader textReader = new BufferedReader(fr);
        int numberOfLines = 3;
        String[ ] textData = new String[numberOfLines];
        int i;
        for (i=0; i < numberOfLines; i++) {
            textData[ i ] = textReader.readLine();
        }
        textReader.close( );
        return textData;
    }
    int readLines() throws IOException{
        FileReader file_to_read = new FileReader(path);
        BufferedReader bf = new BufferedReader(file_to_read);

        String aLine;
        int numberOfLines = 0;
        while (( aLine = bf.readLine()) != null){
            numberOfLines++;
        }
        bf.close();
        return numberOfLines;
    }

}

This is the class I've been using. And this is what I am using in my main program
try{
    ReadFile file = new ReadFile("/Users/jonathon/Desktop/data.txt");
    String[] aryLines = file.OpenFile();
    int x;
    for ( x=0; x < aryLines.length; i++ ) {
      System.out.println( aryLines[ i ] ) ;
    }
 }
 catch ( IOException e ) {
   System.out.println( e.getMessage() );
 }

A: Is this file going to be bundled with your application? If so, you should include it as a resource. Here's a link with some general information on how to accomplish that.
Edit: I just took a look at your file path. The code running on an android emulator is not going to have access to your Windows desktop. Start the emulator, transfer the data to it, and then have the application attempt to read it from the "phone."

A: That path won't be valid.  If you want to store it on the SD card, start with:
Environment.getExternalStorageDirectory().getAbsolutePath();
That should return the root of the SD card, and you can put files directly in there or create your own structure under it.  (Also, personally, I don't bother with the emulator unless I want to test on something my phone can't do, like a different version of Android.  I plug the phone in and test strictly on that.  From how clunky the emulator is, I suspect the Google developers do this too...)


text:
Q: How can I vertically and horizontally center a div within a larger div? How to horizontally center a
 in another
? I managed to center horizontally using styling from the accepted answer. How can I also center it vertically? The inner div is of an unknown height.

A: From: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

  <title>Universal vertical center with CSS</title>

        any text

        any height

        any content, for example generated from DB

        everything is vertically centered

A: Here's a cool technique for centering a box both vertically and horizontally :
The outher container

*

*should have display: table;
The inner container

*

*should have display: table-cell;

*should have vertical-align: middle;

*should have text-align: center;
The content box

*

*should have display: inline-block;

*should re-adjust the horizontal text-alignment to eg. text-align: left; or text-align: right;, unless you want text to be centered

The elegance of this technique, is that you can add your content to the content box without worrying about its height or width!
Just add your content to the content box.
Demo

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}

You can put anything here

Yes, really anything!

See also this Fiddle!


text:
Q: MKMapView framwork hasn't the relief google-map type in MKMapType declaration, but it works i was trying to use a MKMapView, and i wanted to show/change the kind of map which google offers.
We all know that on web sites we can use normal-roads type, hybrid type, satellite/photo type and, more recently, also the relief type.
this last is the one i'd like to use. I had no problem to insert it in a UIWebView + HTML + standard google API,
but for many reasons now i'd prefer use it with a MKMapView.
But... surprise:
"it seems" we couldn't use tat type of map...
reading in Apple MKMapView Class Reference:
MKMapType
The type of map to display.
enum {
   MKMapTypeStandard,
   MKMapTypeSatellite,
   MKMapTypeHybrid
};

where 0 is for MKMapTypeStandard
1 is MKMapTypeSatellite
and of course 2 is MKMapTypeHybrid...
so we are officially allowed to use just those 3 kind of maps, not the relief type, it seems it doesen't exist at all in the apple framwork...
but i'm curious and so i tried this:
myMKMapView.mapType = 3; // a number not officially declared

and it works perfectly, the apple framweork asks to google the right type of map and then it shows it in my view, both in simulator and iPhone device.
so, that's my question:
Do you think I could use it anyway even if it's not "officially" declared in apple documents?
Would Apple reject my app to use it's framework this way?
thanks in advance,
luca

A: I'm sure Apple would reject your app if they knew you were doing it as they are quite clear that you can only use documented features. I know they have tools which detect calls to undocumented methods and use of private frameworks but whether that extends to checking the value of a property when it's set, I'm not sure.
What I am sure though is that this creates fragile code. If Google introduces other map types and Apple decides to support them all in a future SDK update there's no guarantee that the relief type will remain as 3. Also what if Apple adds a check to this property so that in a future iOS release setting it to 3 will throw an exception? Your app will break for anyone that upgrades their OS and you will be forced to use another map type which may upset your users as the functionality is changing. That's just two examples of changes out of your control that could break this for your users.
In summary, could you use this: Yes, but Apple may reject your app and the only way to find out if they will or not is to do it. You'll also have to stay on your toes to ensure future iOS updates don't break your code.


text:
Q: I am using bootstrap to create a navbar but it isn't working,however other classes of bootstrap are working fine I am not able to create a navbar,I tried other classes of bootstrap and they are working fine.
Please suggest something?

<!DOCTYPE html>

<meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description"
         content="">
    <meta name="keywords"
          content="">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="stylesheet.css?v=<?php echo time(); ?>">

Home

A: Double check the classes.  I was able to get it to work following the documentation here:
https://getbootstrap.com/docs/4.0/components/navbar/
Your classes are off because I was able to use everything else in your code just fine.

    <!DOCTYPE html>

    <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description"
             content="">
        <meta name="keywords"
              content="">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="stylesheet.css?v=<?php echo time(); ?>">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

A: You are using the wrong code for Bootstrap 4.x. Your code works on bootstrap 3.x
If you want to use the latest bootstrap version's navbar, then use this.

       Home

For more info check Bootstrap Navbar


text:
Q: Import leaflet in single component svelte I'm using in a single component leaflets plugin, for the moment I put the js and css in public/index.html but i need to find a way to import only the js and css in the single component. Also i tryed with svelte::head but it didn't work. Also this project is going to be used like a node_modules, so i need to find a way to not put the js and css files in folder public. Any suggestions? I tryed to import leaflet installing leaflet with npm and import like
import from 'leaflet'
import * as L from 'leaflet'

but it didn't work.

A: You can import the styles using rollup-plugin-css-only.  To avoid the ugly css import with a relative path to node_modules you may want to use postcss instead: https://medium.com/@bekzatsmov/how-to-import-css-from-node-modules-in-svelte-app-2a38b50924ff
This is based on the standard Svelte template: https://github.com/sveltejs/template
App.svelte
<script>
    import * as L from 'leaflet';
    import '../node_modules/leaflet/dist/leaflet.css'; // It might be better to use postcss.
    import { onMount } from 'svelte';

    let div = null;

    onMount(() => {
        let map = L.map(div, {
            center: [17.385044, 78.486671],
            zoom: 10
        });

        L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
    });
</script>

<div bind:this={div} style="height: 100vh; width: 100%;"></div>

main.js
import App from './App.svelte';

const app = new App({
    target: document.body
});

rollup.config.js
import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';

const production = !process.env.ROLLUP_WATCH;

export default {
    input: 'src/main.js',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
    },
    plugins: [
        svelte({
            // enable run-time checks when not in production
            dev: !production,
            // we'll extract any component CSS out into
            // a separate file - better for performance
            css: false,
            emitCss: true
        }),
        css({ output: 'public/build/bundle.css' }),

        // If you have external dependencies installed from
        // npm, you'll most likely need these plugins. In
        // some cases you'll need additional configuration -
        // consult the documentation for details:
        // https://github.com/rollup/plugins/tree/master/packages/commonjs
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs(),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

function serve() {
    let started = false;

    return {
        writeBundle() {
            if (!started) {
                started = true;

                require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
                    stdio: ['ignore', 'inherit', 'inherit'],
                    shell: true
                });
            }
        }
    };
}

export default app;

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>

    <title>Svelte app</title>

    <link rel='icon' type='image/png' href='/favicon.png'>
    <link rel='stylesheet' href='/global.css'>
    <link rel='stylesheet' href='/build/bundle.css'>
    <script defer src='/build/bundle.js'></script>
</head>

<body>
</body>
</html>