Q: How To Add A Back Slash To The TextBox For Date Format This Is My JavaScript:
`
function ValidateDate(txt, keyCode)
        {
            if(keyCode==16)
                isShift = false;
            var val=txt.value;
            var lblmesg = document.getElementById("<%=lblMesg.ClientID%>") ;
            if(val.length == 10)
            {
                var splits = val.split("/");
                var dt = new Date(splits[1] + "/" + splits[0] + "/" + splits[2]);

                //Validation for Dates
                if(dt.getDate()==splits[0] && dt.getMonth()+1==splits[1] && dt.getFullYear()==splits[2])
                {
                    lblmesg.style.color="green";
                    lblmesg.innerHTML = "Valid Date";
                }
                else
                {
                    lblmesg.style.color="red";
                    lblmesg.innerHTML = "InValid Date";
                    return;
                }

                //Range Validation
                if(txt.id.indexOf("txtRange") != -1)
                    RangeValidation(dt);

                //BirthDate Validation
                if(txt.id.indexOf("txtBirthDate") != -1)
                    BirthDateValidation(dt)
            }
            else if(val.length < 10)
            {
                lblmesg.style.color="blue";
                lblmesg.innerHTML = "Required dd/mm/yy format. Slashes will come up automatically.";
            }
        }`

And This Is My TextBox:
> <asp:TextBox ID="txtValidate" runat="server" MaxLength = "10" onkeyup = "ValidateDate(this, event.keyCode)" onkeydown = "return DateFormat(this, event.keyCode)"></asp:TextBox>

I want to include a slash within a TextBox for typing a Date.. I don't want it to generate a slash while typing...it should be static when the page is loaded.... Is it possible to do that without using AjaxToolkit ???

A: I use this simple replace

Date: <input name=x size=10 maxlength=10  onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')">

Try it with jsfiddle

A: I made a simple example for your purpose:
var date = document.getElementById('date');

date.addEventListener('keypress', function (event) {
    var char = String.fromCharCode(event.which),
        offset = date.selectionStart;

    if (/\d/.test(char) && offset < 8) {

        if (offset === 2 || offset === 5) {
            offset += 1;
        }
        date.value = date.value.substr(0, offset) + char + date.value.substr(offset + 1);
        date.selectionStart = date.selectionEnd = offset + 1;
    }

    if (!event.keyCode) {
        event.preventDefault();
    }
});

Here is a fiddle

A: Here is a shorter version:
    $("#txtDate").keyup(function(){
      if ($(this).val().length == 2 || $(this).val().length == 5){
         $(this).val($(this).val() + "/");
      }
   });


Q: Scale image in CVImageBuffer I have a task - to scale down an image which I got from the camera. I need it in order to do heavy-lifting operations on smaller version of the image which will help me to save some processing power.
I decided to go with vImage_Buffer from Accelerate. Here's my code with few comments just to give clear understanding what is what there:
        guard let imgBuffer = CMSampleBufferGetImageBuffer(buffer) else {
            return
        }

        CVPixelBufferLockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0))

        // create vImage_Buffer out of CVImageBuffer
        var inBuff: vImage_Buffer = vImage_Buffer()
        inBuff.width = UInt(CVPixelBufferGetWidth(imgBuffer))
        inBuff.height = UInt(CVPixelBufferGetHeight(imgBuffer))
        inBuff.rowBytes = CVPixelBufferGetBytesPerRow(imgBuffer)
        inBuff.data = CVPixelBufferGetBaseAddress(imgBuffer)

        // bring down the size at half
        let new_width: UInt = inBuff.width/2
        let new_height: UInt = inBuff.height/2

        // create output buffer where scaled image is supposed to be
        var outBuff: vImage_Buffer = vImage_Buffer()
        outBuff.data = UnsafeMutableRawPointer.allocate(byteCount: Int(new_width * new_height * 4), alignment: MemoryLayout<UInt>.size)
        outBuff.width = new_width
        outBuff.height = new_height
        outBuff.rowBytes = Int(new_width * 4)

        // perform scale
        let err = vImageScale_ARGB8888(&inBuff, &outBuff, nil, 0)
        if err != kvImageNoError {
            print("Wrong!")
        }

        // I guess I need to unlock buffer at this point, right?
        CVPixelBufferUnlockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0))

        // create CVImageBuffer
        let options = [kCVPixelBufferCGImageCompatibilityKey: true,
                       kCVPixelBufferCGBitmapContextCompatibilityKey: true,
                       kCVPixelBufferWidthKey: new_width,
                       kCVPixelBufferHeightKey: new_height] as CFDictionary

        var newPixelBuffer: CVImageBuffer?
        let status = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
                                                  Int(new_width), Int(new_height),
                                                  kCVPixelFormatType_32BGRA, &outBuff, Int(new_width * 4),
                                                  nil, nil, options, &newPixelBuffer)

        if status == kCVReturnError {
            print("Wrong again!")
        }

        // create CIImage from CVImageBuffer and UIImage from CIImage just to see how scale went
        let ciImg = CIImage(cvImageBuffer: newPixelBuffer!)
        let img = UIImage(ciImage: ciImg)
        delegate?.testSmallImage(img)

It seems like all operations are performed without any errors and I want to check how scale went so I'm trying to create new UIImage out of scaled buffer. But when I try to show an image with UIImageView, I have EXC_BAD_ACCESS error. And when I try to save brand-new UIImage, everything goes without errors, but no file appears in Documents directory. Can you point me out what exactly am I doing wrong here? Thanks!

A: Here's the code snippet on Swift which resizes CMSampleBuffer:
    private func scale(_ sampleBuffer: CMSampleBuffer) -> CVImageBuffer?
    {
        guard let imgBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
            return nil
        }

        CVPixelBufferLockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0))

        // create vImage_Buffer out of CVImageBuffer
        var inBuff: vImage_Buffer = vImage_Buffer()
        inBuff.width = UInt(CVPixelBufferGetWidth(imgBuffer))
        inBuff.height = UInt(CVPixelBufferGetHeight(imgBuffer))
        inBuff.rowBytes = CVPixelBufferGetBytesPerRow(imgBuffer)
        inBuff.data = CVPixelBufferGetBaseAddress(imgBuffer)

        // perform scale
        var err = vImageScale_ARGB8888(&inBuff, &scaleBuffer, nil, 0)
        if err != kvImageNoError {
            print("Can't scale a buffer")
            return nil
        }
        CVPixelBufferUnlockBaseAddress(imgBuffer, CVPixelBufferLockFlags(rawValue: 0))

        var newBuffer: CVPixelBuffer?
        let attributes : [NSObject:AnyObject] = [
            kCVPixelBufferCGImageCompatibilityKey : true as AnyObject,
            kCVPixelBufferCGBitmapContextCompatibilityKey : true as AnyObject
        ]

        let status = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
                                                  Int(scaleBuffer.width), Int(scaleBuffer.height),
                                                  kCVPixelFormatType_32BGRA, scaleBuffer.data,
                                                  Int(scaleBuffer.width) * 4,
                                                  nil, nil,
                                                  attributes as CFDictionary?, &newBuffer)

        guard status == kCVReturnSuccess, let b = newBuffer else {
            print("Can't create new CVPixelBuffer")
            return nil
        }

        return b
    }

And here's a definition of scaleBuffer which acts as a destination in scale operation. I do not need to create it each scale so I do it only once:
        scaleBuffer.data = UnsafeMutableRawPointer.allocate(byteCount: Int(new_width * new_height * 4), alignment: MemoryLayout<UInt>.size)
        scaleBuffer.width = vImagePixelCount(new_width)
        scaleBuffer.height = vImagePixelCount(new_height)
        scaleBuffer.rowBytes = Int(new_width * 4)


Q: paint on a container being added to jcomponent i have a jrame on which i add some JComponent objects.
Each JComponent has a list of containers i add by using JComponent.add( Component).
Now in my main JComponent class, called MyComponent, i override the protected method paintComponent where i can paint things, which works pretty fine.
But i dont want to paint on the main JComponent, i only want to paint on the containers i have added to my main JComponent.
So in MyComponent in paintComponent i do the following.
protected void paintComponent( Graphics g) {
  super.paintComponent( g);

  Graphics page_g = this.getPage( "main").getGraphics();

  page_g.setColor( Color.RED);
  page_g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20);
  page_g.setColor( Color.BLUE);
  page_g.drawString( "HELLO WORLD", this.getWidth() / 2, this.getHeight() / 2);
}

The line this.getPage( "main").getGraphics(); takes the Graphics object from one of my containers added to the MyComponents list of containers and of course to the main component list using JComponents add method. The container is set to visible by calling the setVisible( true); method.
But nothing happens. The screen is empty. When i replace page_g with g, then painting works, because its painting on my JComponent (MyComponent), but i want to paint on the container which is a children of MyComponent in this case.
I often heard "Never use getGraphics()". But how else can ONLY draw on sub components of a parent component when the parents paintComponent method gets called?

A: Really the best bet is to have the classes that are actually doing the custom painting override their own paintComponent() method.  Let the AWT worry about the graphics contexts.


Q: Parameterized Async function returning Promise { "_40": 0, "_55": "English", "_65": 1, "_72": null, } [CLOSED]
How to get the 'English' out of the promise object which is unneccesary

Async Functions -> parameterized

const getLanguageNamefromCode = async (lng_code) => {
  let response, langData, lang;
  try {
    response = await fetch(
      `https://restcountries.eu/rest/v2/lang/${lng_code}?fields=languages`
    );
    langData = await response.json();
    // console.log(langData[0].languages[0]);
    if (langData[0].languages[0].iso639_1 === lng_code) {
      lang = langData[0].languages[0].name;
      console.log(lang);
    }
    return lang;
  } catch (err) {
    throw new Error(err);
  }
};

calling it from inside a for loop and sending in a parameter

      const loadedTrendingMovies = [];
      const loadedTrendingMoviesLength = trendingMovies.results.length;

      for (let i = 0; i < 6; i++) {
        // let credits;
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) =>
            userMovie.id === trendingMovies.results[i].id.toString()
        );

        loadedTrendingMovies.push(
          new Movie(
            trendingMovies.results[i].id.toString(),
            trendingMovies.results[i].media_type === "movie"
              ? trendingMovies.results[i].title
              : trendingMovies.results[i].name,
            posterBaseUrl + trendingMovies.results[i].poster_path,
            trendingMovies.results[i].media_type === "movie"
              ? trendingMovies.results[i].release_date
              : trendingMovies.results[i].first_air_date,
            [],
            trendingMovies.results[i].overview,
            trendingMovies.results[i].vote_average,
            getLanguageNamefromCode(trendingMovies.results[i].original_language),
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }

How to get the value from the promise returned by the getLanguagefromCode Async Method.

This is my MoviesScreen functional component , i am using redux

import React, { useEffect, useCallback, useState, useRef } from "react";
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  ScrollView,
  StatusBar,
  TouchableWithoutFeedback,
  RefreshControl,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import MovieItem from "../components/MovieItem";
import { useSelector, useDispatch } from "react-redux";
import * as MoviesAction from "../store/actions/MoviesAction";
import * as UserActions from "../store/actions/UserActions";
import Colors from "../constants/Colors";

import { useScrollToTop } from "@react-navigation/native";

import SkeletonContent from "react-native-skeleton-content";
import { createSelector } from "reselect";

const stories = createSelector(
  (state) => state.Movies.movies,
  (movies) => movies
);
const newReleases = createSelector(
  (state) => state.Movies.new_releases,
  (new_releases) => new_releases
);
const newTVShows = createSelector(
  (state) => state.Movies.new_tv_shows,
  (new_tv_shows) => new_tv_shows
);
const Anime = createSelector(
  (state) => state.Movies.anime,
  (anime) => anime
);
const MoviesScreen = (props) => {
  const Stories = useSelector(stories);
  const new_releases = useSelector(newReleases);
  console.log(" movie screen rendered", new_releases);
  const new_tv_shows = useSelector(newTVShows);
  const anime = useSelector(Anime);

  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const dispatch = useDispatch();
  const scrollRef = useRef(null);

  useScrollToTop(scrollRef);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    loadScreen().then(() => setRefreshing(false));
  }, [setRefreshing, loadScreen]);

  const loadScreen = useCallback(async () => {
    try {
      dispatch(MoviesAction.loadAll());
    } catch (err) {
      console.log(err);
    }
  }, []);

  useEffect(() => {
    setLoading(true);
    loadScreen().then(() => setLoading(false));
  }, []);

  const renderTrendingMoviesItem = ({ item }) => (
    <SkeletonContent
      boneColor="#303030"
      highlightColor="#252525"
      containerStyle={styles.new_releases}
      isLoading={loading || refreshing}
      layout={[styles.cinemaSkeleton]}
    >
      <MovieItem
        style={styles.new_releases}
        id={item.id}
        movieTitle={item.title}
        posterUrl={item.posterUrl}
        year={item.year}
        onPress={() => {
          props.navigation.navigate({
            name: "MoviesDetailScreen",
            params: {
              movieId: item.id,
              movieTitle: item.title,
              moviesType: "Movies",
            },
          });
        }}
      />
    </SkeletonContent>
  );

  const renderStoriesItem = ({ item }) => (
    <SkeletonContent
      boneColor="#303030"
      highlightColor="#252525"
      containerStyle={{
        ...styles.storyItem,
        marginHorizontal: 10,
        marginVertical: 7.5,
      }}
      isLoading={loading || refreshing}
      layout={[
        {
          key: "story",
          width: 80,
          height: 80,
          borderRadius: 40,
          marginHorizontal: 10,
          marginVertical: 7.5,
        },
      ]}
    >
      <MovieItem
        style={styles.storyItem}
        footerStyle={{ opacity: 0 }}
        imageStyle={styles.storyImage}
        id={item.id}
        posterUrl={item.posterUrl}
        onPress={() => {
          props.navigation.navigate({
            name: "NewReleasesModalScreen",
            params: {
              movieTitle: item.title,
              posterUrl: item.posterUrl,
              movieId: item.id,
            },
          });
        }}
      />
    </SkeletonContent>
  );

  const renderTrendingTVItem = ({ item }) => (
    <SkeletonContent
      boneColor="#303030"
      highlightColor="#252525"
      containerStyle={styles.new_releases}
      isLoading={loading || refreshing}
      layout={[styles.cinemaSkeleton]}
    >
      <MovieItem
        style={styles.new_releases}
        id={item.id}
        movieTitle={item.title}
        posterUrl={item.posterUrl}
        year={item.year}
        onPress={() => {
          props.navigation.navigate({
            name: "MoviesDetailScreen",
            params: {
              movieId: item.id,
              movieTitle: item.title,
              moviesType: "TV",
            },
          });
        }}
      />
    </SkeletonContent>
  );

  const renderAnimeItem = ({ item }) => (
    <SkeletonContent
      boneColor="#303030"
      highlightColor="#252525"
      containerStyle={styles.new_releases}
      isLoading={loading || refreshing}
      layout={[styles.cinemaSkeleton]}
    >
      <MovieItem
        style={styles.new_releases}
        id={item.id}
        movieTitle={item.title}
        posterUrl={item.posterUrl}
        year={item.year}
        onPress={() => {
          props.navigation.navigate({
            name: "MoviesDetailScreen",
            params: {
              movieId: item.id,
              movieTitle: item.title,
              moviesType: "anime",
              goToAnime: true,
            },
          });
        }}
      />
    </SkeletonContent>
  );

  return (
    <ScrollView
      ref={scrollRef}
      style={styles.screen}
      showsVerticalScrollIndicator={false}
      refreshControl={
        <RefreshControl
          refreshing={refreshing}
          onRefresh={onRefresh}
          tintColor={Colors.lightblue}
        />
      }
    >
      {/* new releases stories */}
      <StatusBar barStyle="light-content" />
      <SkeletonContent
        boneColor="#303030"
        highlightColor="#252525"
        containerStyle={styles.headerCont}
        isLoading={loading || refreshing}
        layout={[styles.headerTextSkeleton]}
      >
        <View style={styles.headerCont}>
          <Text style={styles.headerText}> New Releases </Text>
        </View>
      </SkeletonContent>
      <View>
        <FlatList
          keyExtractor={(item) => item.id}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          data={Stories}
          renderItem={renderStoriesItem}
        />
      </View>

      {/* new releases stories */}
      {/*...

      TOP MOVIE THAT WEEK

      ...
      */}

      <View>
        <SkeletonContent
          boneColor="#303030"
          containerStyle={styles.headerCont}
          highlightColor="#252525"
          containerStyle={styles.headerCont}
          isLoading={loading || refreshing}
          layout={[styles.headerTextSkeleton]}
        >
          <View style={styles.headerCont}>
            <TouchableWithoutFeedback
              onPress={() => {
                props.navigation.navigate({
                  name: "SeeAllScreen",
                  params: {
                    new_releases: true,
                    headerTitle: "Trending Movies",
                  },
                });
              }}
            >
              <View style={{ flexDirection: "row" }}>
                <Text style={styles.headerText}> Movies </Text>
                <Ionicons
                  style={{ marginStart: 5 }}
                  name="ios-arrow-forward"
                  size={22}
                  color={Colors.lightblue}
                />
              </View>
            </TouchableWithoutFeedback>
          </View>
        </SkeletonContent>
        <FlatList
          keyExtractor={(item) => item.id}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          data={new_releases}
          renderItem={renderTrendingMoviesItem}
        />
      </View>

      {/* TV SHOWS */}

      <View>
        <SkeletonContent
          boneColor="#303030"
          containerStyle={styles.headerCont}
          highlightColor="#252525"
          containerStyle={styles.headerCont}
          isLoading={loading || refreshing}
          layout={[styles.headerTextSkeleton]}
        >
          <View style={styles.headerCont}>
            <TouchableWithoutFeedback
              onPress={() => {
                props.navigation.navigate({
                  name: "SeeAllScreen",
                  params: {
                    new_tv_shows: true,
                    headerTitle: "Trending TV Shows",
                  },
                });
              }}
            >
              <View style={{ flexDirection: "row" }}>
                <Text style={styles.headerText}> TV Shows </Text>
                <Ionicons
                  style={{ marginStart: 5 }}
                  name="ios-arrow-forward"
                  size={22}
                  color={Colors.lightblue}
                />
              </View>
            </TouchableWithoutFeedback>
          </View>
        </SkeletonContent>
        <FlatList
          keyExtractor={(item) => item.id}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          data={new_tv_shows}
          renderItem={renderTrendingTVItem}
        />
      </View>

      {/* Anime */}

      <View>
        <SkeletonContent
          boneColor="#303030"
          containerStyle={styles.headerCont}
          highlightColor="#252525"
          containerStyle={styles.headerCont}
          isLoading={loading || refreshing}
          layout={[styles.headerTextSkeleton]}
        >
          <View style={styles.headerCont}>
            <TouchableWithoutFeedback
              onPress={() => {
                props.navigation.navigate({
                  name: "SeeAllScreen",
                  params: {
                    moviesType: "anime",
                    goToAnime: true,
                    headerTitle: "Trending Anime",
                  },
                });
              }}
            >
              <View style={{ flexDirection: "row" }}>
                <Text style={styles.headerText}> Anime </Text>
                <Ionicons
                  style={{ marginStart: 5 }}
                  name="ios-arrow-forward"
                  size={22}
                  color={Colors.lightblue}
                />
              </View>
            </TouchableWithoutFeedback>
          </View>
        </SkeletonContent>
        <FlatList
          keyExtractor={(item) => item.id}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          data={anime}
          renderItem={renderAnimeItem}
        />
      </View>
    </ScrollView>
  );
};

This is the actions file

import React, { useState } from "react";

export const SEARCH_MOVIES = "SEARCH_MOVIES";
export const LOAD_MOVIES_WITH_GENRES = "LOAD_MOVIES_WITH_GENRES";
export const CLEAR_SEARCH_LIST = "CLEAR_SEARCH_LIST";
export const CLEAR_GENRE_SCREEN = "CLEAR_GENRE_SCREEN";
export const LOAD_ALL = "LOAD_ALL";

import Movie from "../../models/Movie";

import config from "../../config";
import Cast from "../../models/CastMember";

const getCredits = async (index) => {
  let response, creditsData;
  try {
    response = await fetch(
      `https://api.themoviedb.org/3/tv/${resData.results[index].id}?api_key=${config.TMDB_API_KEY}&language=en-US&append_to_response=credits`
    );
    creditsData = await response.json();
    // console.log("credits", creditsData);
  } catch (err) {
    throw new Error(err);
  }

  const castMembers = [];
  const length =
    creditsData.credits.cast.length > 10 ? 10 : creditsData.credits.cast.length;

  for (let i = 0; i < 6; i++) {
    castMembers.push(
      new Cast(
        creditsData.credits.cast[i].id,
        creditsData.credits.cast[i].character,
        creditsData.credits.cast[i].name,
        posterBaseUrl + creditsData.credits.cast[i].profile_path
      )
    );
  }

  console.log(castMembers);

  return { cast: castMembers };
};

const getLanguageNamefromCode = async (lng_code) => {
  let response, langData, lang;
  try {
    response = await fetch(
      `https://restcountries.eu/rest/v2/lang/${lng_code}?fields=languages`
    );
    langData = await response.json();
    // console.log(langData[0].languages[0]);
    if (langData[0].languages[0].iso639_1 === lng_code) {
      lang = langData[0].languages[0].name;
      console.log(lang);
    }
    return lang;
  } catch (err) {
    throw new Error(err);
  }
};

export const clearSearchList = () => {
  return { type: CLEAR_SEARCH_LIST };
};

export const clearGenreScreen = () => {
  return {
    type: CLEAR_GENRE_SCREEN,
  };
};

export const loadAll = () => {
  const posterBaseUrl = "http://image.tmdb.org/t/p/w185";
  let hasUserSaved;
  const loadedStories = [];
  return async (dispatch, getState) => {
    try {
      //stories response
      const moviesResponse = await fetch(
        `https://www.omdbapi.com/?apikey=${config.OMDB_API_KEY}&s=tokyo`
      );
      // trending movies
      const TrendingMoviesResponse = await fetch(
        `https://api.themoviedb.org/3/trending/all/day?api_key=${config.TMDB_API_KEY}`
      );
      // trending TV
      const trendingTVResponse = await fetch(
        `https://api.themoviedb.org/3/discover/tv?api_key=${config.TMDB_API_KEY}&language=en-US&sort_by=popularity.desc&first_air_date_year=2020&page=1&with_original_language=en`
      );
      // trending Anime
      const trendingAnimeResponse = await fetch(
        `https://kitsu.io/api/edge/trending/anime`,
        {
          method: "GET",
        }
      );

      if (
        !moviesResponse.ok ||
        !TrendingMoviesResponse.ok ||
        !trendingTVResponse.ok ||
        !trendingAnimeResponse.ok
      ) {
        throw new Error("failed response");
      }

      const movies = await moviesResponse.json();
      const trendingMovies = await TrendingMoviesResponse.json();
      const trendingTV = await trendingTVResponse.json();
      const trendingAnime = await trendingAnimeResponse.json();
      // console.log('Trending Movies',resData);
      // console.log("NEW RELEASES", resData);

      //stories array

      const loadedMoviesLength = movies.Search.length;

      for (let i = 0; i < 6; i++) {
        loadedStories.push(
          new Movie(
            movies.Search[i].imdbID,
            movies.Search[i].Title,
            movies.Search[i].Poster,
            movies.Search[i].Year
          )
        );
      }

      //trending movies array

      // console.log("loadedTrendingMovies", loadedTrendingMovies);
      let loadedTrendingMovies=[];

      const loadedTrendingMoviesLength = trendingMovies.results.length;

      // loadedTrendingMovies =
      Promise.all(
        trendingMovies.results
          .slice(0, 5) // use slice instead of a loop
          .map((
            trendingMovie // map movie to [language,movie]
          ) =>
            getLanguageNamefromCode(
              // get async language
              trendingMovie.original_language
              // resolve to [language,movie]
            ).then((language) => [language, trendingMovie])
          ) // sorry, forgot to return here
      )
        .then((
          results // results is [[language,movie],[language,movie]]
        ) =>
          results.map(([language, trendingMovie]) => {
            const hasUserSaved = getState().UserMovies.userMovies.find(
              (userMovie) => userMovie.id === trendingMovie.id.toString()
              // snippet does not have conditional chaining
            );
            return new Movie( // create new Movie
              trendingMovie.id.toString(),
              trendingMovie.media_type === "movie"
                ? trendingMovie.title
                : trendingMovie.name,
              posterBaseUrl + trendingMovie.poster_path,
              trendingMovie.media_type === "movie"
                ? trendingMovie.release_date
                : trendingMovie.first_air_date,
              [],
              trendingMovie.overview,
              trendingMovie.vote_average,
              language,
              hasUserSaved ? hasUserSaved.location : ""
            );
          })
        )
        .then((movies) => {
          // loadedTrendingMovies.push(movies);
          loadedTrendingMovies = [...loadedTrendingMovies, ...movies];
          console.log("loadedTrendingMovies", loadedTrendingMovies);
        })
        .catch((err) => console.log(err));

      // trending TV Shows
      const loadedNewTVShows = [];
      const TVShowsLength = trendingTV.results.length;

      for (let i = 0; i < 6; i++) {
        // let credits;
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) => userMovie.id === trendingTV.results[i].id.toString()
        );
        // let cast = getCredits(i).then((cast) => cast);
        // console.log("CAST", cast);
        loadedNewTVShows.push(
          new Movie(
            trendingTV.results[i].id.toString(),
            trendingTV.results[i].name,
            posterBaseUrl + trendingTV.results[i].poster_path,
            trendingTV.results[i].first_air_date.toString().substr(0, 5),
            // getCredits(i).then((cast) => cast),
            // getCredits(i)
            //   .then((results) => {
            //     console.log("success", results.cast);
            //     return results.cast;
            //   })
            //   .catch((err) => console.log("cast error", err)),
            [],
            trendingTV.results[i].overview,
            trendingTV.results[i].vote_average,
            // getLanguageNamefromCode(trendingTV.results[i].original_language),
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }

      const loadedAnime = [];
      const AnimeLength = trendingAnime.data.length;

      for (let i = 0; i < 6; i++) {
        // let credits;
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) => userMovie.id === trendingAnime.data[i].id.toString()
        );
        // let cast = getCredits(i).then((cast) => cast);
        // console.log("CAST", cast);
        loadedAnime.push(
          new Movie(
            trendingAnime.data[i].id,
            trendingAnime.data[i].attributes.canonicalTitle,
            trendingAnime.data[i].attributes.posterImage.medium,
            trendingAnime.data[i].attributes.createdAt.toString().substr(0, 4),
            // getCredits(i).then((cast) => cast),
            [],
            trendingAnime.data[i].attributes.synopsis,
            trendingAnime.data[i].attributes.vote_average,
            "Japanese",
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }

      dispatch({
        type: LOAD_ALL,
        movies: loadedStories,
        new_releases: loadedTrendingMovies,
        new_tv_shows: loadedNewTVShows,
        anime: loadedAnime,
      });
    } catch (err) {
      console.log(err);
    }
  };
};

export const searchMovies = (MovieTitle) => {
  let response;
  let hasUserSaved;
  const posterBaseUrl = "http://image.tmdb.org/t/p/w185";
  return async (dispatch, getState) => {
    try {
      response = await fetch(
        `https://api.themoviedb.org/3/search/movie?api_key=${config.TMDB_API_KEY}&query=${MovieTitle}&page=1`
      );

      if (!response.ok) {
        throw new Error("failed response");
      }

      const resData = await response.json();
      console.log("search results: ", resData);

      const searchedMovies = [];
      const length = resData.results.length;

      for (i = 0; i < length; i++) {
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) => userMovie.id === resData.results[i].id
        );
        searchedMovies.push(
          new Movie(
            resData.results[i].id.toString(),
            resData.results[i].title,
            posterBaseUrl + resData.results[i].poster_path,
            resData.results[i].release_date,
            // getCredits(i).then((cast) => cast),
            [],
            resData.results[i].overview,
            resData.results[i].vote_average,
            // getLanguageNamefromCode(resData.results[i].original_language),
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }
      dispatch({
        type: SEARCH_MOVIES,
        searched_movies: searchedMovies,
      });
    } catch (err) {
      console.log(err);
    }
  };
};

export const loadMoviesWithGenres = (genreId) => {
  let response;
  let hasUserSaved;
  const posterBaseUrl = "http://image.tmdb.org/t/p/w185";
  return async (dispatch, getState) => {
    await dispatch(clearGenreScreen());
    try {
      response = await fetch(
        `https://api.themoviedb.org/3/discover/movie?with_genres=${genreId}&api_key=${config.TMDB_API_KEY}`
      );

      if (!response.ok) {
        throw new Error("failed response");
      }

      const resData = await response.json();
      // console.log(resData);

      const loadedMoviesWRTGenre = [];
      const length = resData.results.length;

      for (let i = 0; i < length; i++) {
        hasUserSaved = getState().UserMovies.userMovies.find(
          (userMovie) => userMovie.id === resData.results[i].id.toString()
        );
        // let cast = getCredits(i).then((cast) => cast)
        // console.log("CAST", cast);
        loadedMoviesWRTGenre.push(
          new Movie(
            resData.results[i].id.toString(),
            resData.results[i].title,
            posterBaseUrl + resData.results[i].poster_path,
            resData.results[i].release_date,
            // cast,
            // getCredits(i),
            [],
            resData.results[i].overview,
            resData.results[i].vote_average,
            // getLanguageNamefromCode(resData.results[i].original_language),
            hasUserSaved ? hasUserSaved.location : ""
          )
        );
      }

      console.log("moviesWRTGenre", loadedMoviesWRTGenre);

      dispatch({
        type: LOAD_MOVIES_WITH_GENRES,
        moviesWRTGenre: loadedMoviesWRTGenre,
      });
    } catch (err) {
      console.log(err);
    }
  };
};

when i am logging the array in the actions file, it shows the perfect result , i.e.,

loadedTrendingMovies Array [
  Movie {
    "cast": Array [],
    "id": "385103",
    "language": "English",
    "location": "",
    "plot": "In Scooby-Doo’s greatest adventure yet, see the never-before told story of how lifelong friends Scooby and Shaggy first met and how they joined forces with young detectives Fred, Velma, and Daphne to form the famous Mystery Inc. Now, with hundreds of cases solved, Scooby and the gang face their biggest, toughest mystery ever: an evil plot to unleash the ghost dog Cerberus upon the world. As they race to stop this global “dogpocalypse,” the gang discovers that Scooby has a secret legacy and an epic destiny greater than anyone ever imagined.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/zG2l9Svw4PTldWJAzC171Y3d6G8.jpg",
    "ratings": 8.3,
    "title": "Scoob!",
    "year": "2020-05-15",
  },
  Movie {
    "cast": Array [],
    "id": "79680",
    "language": "English",
    "location": "",
    "plot": "Set more than seven years after the world has become a frozen wasteland, the remnants of humanity inhabit a gigantic, perpetually-moving train that circles the globe as class warfare, social injustice and the politics of survival play out.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/n6UNHZoiYj81abwmG38HbNjflDx.jpg",
    "ratings": 3,
    "title": "Snowpiercer",
    "year": "2020-05-17",
  },
  Movie {
    "cast": Array [],
    "id": "80986",
    "language": "English",
    "location": "",
    "plot": "Courtney Whitmore, a smart, athletic and above all else kind girl, discovers her step-father has a secret; he used to be the sidekick to a superhero. \"Borrowing\" the long-lost hero’s cosmic staff, she becomes the unlikely inspiration for an entirely new generation of superheroes.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/JJxVsQPPiuLcArALotMHsCubeo.jpg",
    "ratings": 9,
    "title": "Stargirl",
    "year": "2020-05-18",
  },
  Movie {
    "cast": Array [],
    "id": "530915",
    "language": "English",
    "location": "",
    "plot": "At the height of the First World War, two young British soldiers must cross enemy territory and deliver a message that will stop a deadly attack on hundreds of soldiers.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/AuGiPiGMYMkSosOJ3BQjDEAiwtO.jpg",
    "ratings": 7.9,
    "title": "1917",
    "year": "2019-12-25",
  },
  Movie {
    "cast": Array [],
    "id": "582596",
    "language": "English",
    "location": "",
    "plot": "A guy meets the woman of his dreams and invites her to his company's corporate retreat, but realizes he sent the invite to the wrong person.",
    "posterUrl": "http://image.tmdb.org/t/p/w185/A2YlIrzypvhS3vTFMcDkG3xLvac.jpg",
    "ratings": 6.1,
    "title": "The Wrong Missy",
    "year": "2020-05-13",
  },
]

so i console log in the beginning of the MovieScreen Components (it is the first screen that loads up when my react native app launches) to see if the array is empty

 movie screen rendered Array []
 movie screen rendered Array []
 movie screen rendered Array []
 movie screen rendered Array []

Also i do not know why did it console logged i.e., re-rendered 4 times ,
  do you have any ideas ?

Here is its github repository if you want to check just npm install with expo

A:
The following should work (please note that this also returns a promise that resolves to an array of movies).

   const loadedTrendingMovies = await Promise.all(
      trendingMovies.results
        .slice(0, 5) // use slice instead of a loop
        .map((trendingMovie) => // map movie to [language,movie]
          getLanguageNamefromCode(// get async language
            trendingMovie.original_language
          // resolve to [language,movie]
          ).then((language) => [language, trendingMovie])
        ) // sorry, forgot to return here
    ).then((results) => // results is [[language,movie],[language,movie]]
      results.map(
        ([language, trendingMovie]) =>
          new Movie( // create new Movie
            trendingMovie.id.toString(),
            trendingMovie.media_type === 'movie'
              ? trendingMovie.title
              : trendingMovie.name,
            posterBaseUrl + trendingMovie.poster_path,
            trendingMovie.media_type === 'movie'
              ? trendingMovie.release_date
              : trendingMovie.first_air_date,
            [],
            trendingMovie.overview,
            trendingMovie.vote_average,
            language,
            getState().UserMovies.userMovies.find(
              (userMovie) =>
                userMovie.id === trendingMovie.id.toString()
            // if you don't have optional chaining you can get location
            //  first the way you did before
            )?.location || ''
          )
      )
    );

Working example

const trendingMovies = {
  results: [
    {
      original_language: 1,
      id: 1,
    },
    {
      original_language: 2,
      id: 2,
    },
  ],
};
const getLanguageNamefromCode = (lang) =>
  Promise.resolve(`language is: ${lang}`);
function Movie(id, language, location) {
  this.id = id;
  this.language = language;
  this.location = location;
}
const getState = () => ({
  UserMovies: {
    userMovies: [{ id: '1', location: 'location 1' }],
  },
});
Promise.all(
  trendingMovies.results
    .slice(0, 5) // use slice instead of a loop
    .map((trendingMovie) =>
      // map movie to [language,movie]
      getLanguageNamefromCode(
        // get async language
        trendingMovie.original_language
        // resolve to [language,movie]
      ).then((language) => [language, trendingMovie])
    )
)
  .then((
    results // results is [[language,movie],[language,movie]]
  ) =>
    results.map(([language, trendingMovie]) => {
      const userMovie = getState().UserMovies.userMovies.find(
        (userMovie) =>
          userMovie.id === trendingMovie.id.toString()
        // snippet does not have conditional chaining
      );
      return new Movie( // create new Movie
        trendingMovie.id.toString(),
        language,
        userMovie ? userMovie.location : ''
      );
    })
  )
  .then((movies) => console.log('movies:', movies));


Q: Validation Summary vertical alignment I have a two column layout page with a Validation Summary (VS) control above the 2 columns. The VS is centered in the container above the columns, which is what I want, but I also want the different bullet points to be vertically aligned, if possible. I have tried several things, including placing the VS inside a div (inside the container div that is center aligned) with text-align:left;, but that moves the entire div to the side of the container. I have also tried making the div text-align:center; and the VS text-align:left;, but that also moves the entire block all the way to the left. I've also tried the same thing with a table, but no luck.
This is in Firefox by the way. I haven't tested in other browsers, but it needs to work in FF.
Here is pic to show the messed up vertical alignment:

And here is the code for my VS control, without my alignment attempts (if more code is needed, let me know):

  <asp:Label ID="lblStatus" runat="server" ForeColor="Red"></asp:Label>
  <asp:ValidationSummary ID="VS1" runat="server" CssClass="validator" ValidationGroup="theform" />

Could somebody help me vertically align those bullet points in the center of the page?

A: Since bullet points are part of the list items I don't think you will be able to align them. Why not try something like having a top column with 3 divs and place your validationsummary control in the middle one. Try this
HTML Code

            <asp:ValidationSummary ID="ValidationSummary1" runat="server" />

            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="input value" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>

            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Need come input for this" ControlToValidate="TextBox2" Text="*"></asp:RequiredFieldValidator>

            <asp:Button ID="Button1" runat="server" Text="Button" />

            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="please input text" ControlToValidate="TextBox3" Text="*"></asp:RequiredFieldValidator>

            <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Where is the text?" ControlToValidate="TextBox4" Text="*"></asp:RequiredFieldValidator>

            <asp:Button ID="Button2" runat="server" Text="Button" />

CSS
.container
{
    display: block;
    width:800px;
    margin:0px;
    padding:0px;
}

.top
{
    display:inline-block;
    width:800px;
}

.bottom
{
    display:inline-block;
}

.topMiddle
{
    display:inline;
    background-color:Yellow;
    float:left;
    width:300px;
}

.topLeft
{
    display:inline;
    float:left;
    width:250px;
}

.topRight
{
    display:inline;
    float:left;
    width:250px;
}

.bottomLeft
{
    display:inline;
    width:400px;
    float:left;
    background-color:Orange;
}

.bottomRight
{
    display:inline;
    width:400px;
    float:left;
    background-color:Lime;
}

A: Try using this one....

Edit
Set padding left or margin left to ul as you want...
.validator ul { padding-left: 100px; }

A: Hey you may define your parent text-align left center right
according to your design


Q: How to export event in a DLL? I have the following two classes:
public class DLLClass {
     public delegate void dllDelegate(Object sender, EventArgs e);
     public event dllDelegate dllEvent;
     .....
}

class AppClass {
     DLLClass dll;

     public AppClass() {
         dll.dllEvent += new DLLClass.dllDelegate(dllEventHandler);
     }

     public void dllEventHandler(Object sender, EventArgs e){
     }
}

Each one is a part of the same solution, but refer to different projects.
The problem is that the compiler says that there is no dllEvent member in the DLLClass.
EDIT:
The error:

error CS1061: 'AppNamespace.DLLClass ' does not contain a definition for 'dllEvent ' and no extension method 'dllEvent ' accepting a first argument of type 'AppNamespace.DLLClass ' could be found (are you missing a using directive or an assembly reference?)
error CS0426: The type name 'dllDelegate' does not exist in the type 'AppNamespace.DLLClass.ParametersPanel'

Also when I try to see the definition of the DLLClass from the code of AppClass, MSVS shows me class definition from metadata with no delegates in it.

A: If your reference is not a Project Reference, but a file reference, you may need to build the first project first. Form the Build menu, select Rebuild All.
If that doesn't help, you may have referenced to the wrong file. Remove the reference to the first project, and add a Project reference to it.

A: Found this one link.
The problem was in the .csproject file.


Q: Python socket chat issue I have client and server sample codes. I can send message from client to server and I cant receive message from server to client. what is the issue ?
Server.py file
#server
import socket;
import time;

HOST = "localhost";
PORT = 5454;
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
s.bind((HOST,PORT));
while True:

  print "Client says: " + s.recv(1024);

  data = raw_input("Enter..... ")  ;
  s.sendto(data,(HOST, PORT));

  if data=="bye" or s.recv(1024)=="bye":
       print "Exiting..................";
       time.sleep(1);
       break;

Client.py file
#client
import socket;
import time;

HOST = "localhost";
PORT = 5454;
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
s.connect((HOST,PORT));
while True:

  data = raw_input("Enter..... ")
  s.sendto(data,(HOST,PORT)) ;

  print "Server says: " + s.recv(1024);

  if data=="bye" or s.recv(1024)=="bye":
       print "Exiting...........";
       time.sleep(1);
       break;

What is the issue of above code....
First time i can send mesage from client to server. can not send message server to clint. have to wait more time.... but no responce. help me

A: You expect to receive twice as much data as you send.
  print "Server says: " + s.recv(1024);

  if data=="bye" or s.recv(1024)=="bye":

Calling receive each time will wait for data on the socket. Store the message received first, then manipulate that message.
  msg = s.recv(1024)
  print "Server says: " + msg
  if data=="bye" or msg=="bye":


Q: Append an elements HTML into newly appended textarea I'm building a website designer and have gotten stuck at a little annoying problem. I made a small example of what I'm trying to accomplish here - http://codepen.io/mikethedj4/pen/KqyaH
The code below grabs the html in my canvas, puts it in a textarea when query is added, and I can see that html when I click on the already added media query.
$(".list-of-media-queries").append("
 <button>"+ $(".cwidth").val() +"px</button>"+ "
"+ "@media all and (max-width:"+ $(".cwidth").val() +"px) { \n\n" + $(".dadammediaquery").val() +" }
" +"
<textarea class='"+ $(".cwidth").val() +"'>"+ $(".canves").html() +"</textarea>");

When a global style is added into div.list-of-css-selectors I append the following tags Textarea, DIV, Anchor, Button, and Pre.
Here's an example of what is appended
<textarea class="custom-css-sheet hide" style="cursor:text!important; width:100%; resize:vertical; border:0; border-radius:0; min-height:200px;" placeholder="Your Custom CSS is added here"></textarea>
 <button>body</button>
body {
  background-color: rgb(0, 224, 97);}

Now this is what I'm trying to backup aka the global/custom styles. I have all that stored in a div.list-of-css-selectors so I updated my code (2nd seen below) to where I wanted that backed up to. Now the code inside of div.list-of-css-selectors is suppose to go into the newly added textbox that has the class of the media queries location upon add. However the code is not encased in the textarea. Here's what I get instead.
<textarea class="custom-css-sheet hide" style="cursor:text!important; width:100%; resize:vertical; border:0; border-radius:0; min-height:200px;" placeholder="Your Custom CSS is added here">

I'm not sure why it's reacting this way. If anybody can help it'd be greatly appreciated.
$(".list-of-media-queries").append("
 <button>"+ $(".cwidth").val() +"px</button>"+ "
"+ "@media all and (max-width:"+ $(".cwidth").val() +"px) { \n\n" + $(".dadammediaquery").val() +" }
" +"
<textarea class='"+ $(".cwidth").val() +"'>"+ $(".list-of-css-selectors").html() +"</textarea>");

A: use val() to set textarea's  value
var string = "your html content";

var textarea=$('<textarea>').val( string).appendTo( containerSelector);


Q: Using FXCop in your project Are there a lot of IT shops utilizing FxCop for writing production code?  If so, what was/is your overall experience implementing it in terms of culture shift, pain points, and tangible benefits?
I am in an environment that is somewhat chaotic and looking for tools to help us standardize our development efforts and get us home at a decent hour.  I want to avoid egg on my face for pushing a static analysis tool only to have it fail because it’s
“not practical”.  <- (Anticipated management response)

A: I'd say there aren't that many places really using FxCop.  We have it turned on, but most of the dev staff ignores the warnings produced.
Also, Dev Management here hasn't been interested in really pushing cleaning up the warnings, in part because FxCop really dislikes the conventions (variable names, etc) that management wants us to follow...
On projects where I've been the lead, I've mandated its use because I think it helps us be better programmers.  But you have to have by in at the top in order to get all the dev's to follow it.

A: Note that FxCop is very customisable with regards to the rules you wish to apply. You may find it works best by incrementally introducing it; only for a certain set of rules for a certain set of files, or even excluding all legacy files initially.
There are bound to be rules that you may never activate because they just do not suit your problem domain. And remember that if a piece of code 'breaks a rule' for a specific purpose, there is an attribute to mark such code as acceptable, although I would instate a rule that all such overrides must use the Justification property on the attribute to indicate why.
Finally, as much as the built-in rules will help a lot with improving code quality, the really big wins are to be had in custom rules that will allow you to check for company conventions. If you do not automate your 'peer review' in this fashion, then you cannot really guarantee compliance.
I use FxCop as an integrated part of the build system at work, and our common libraries currently get released with all rules enabled with minimal attribute overrides, and it has been worthwhile in more than a few places.


Q: How to cast an process instance into it's fitting object maybe my question sounds very strange, but I want to do the following:
I have some instances of the Internet Explorer opened (iexplore.exe).
When I start my program, it should refresh all the instances of iexplore.exe without opening another instance of it.
In the beginning I thought it must be easy to refresh the Internet Explorer with help of a Visual Basic exe. But this thought was wrong.
No I was thinking about it and my thoughts where the following:

*

*At runtime I have to find out all the processes iexplore.exe

*I declare a variable Dim Browsers() as WebBrowser

*Now I have to cast all processes iexplore.exe to the object list named Browsers.

*With help of Browsers.Refresh it is easy to solve the Problem.

I have no idea how to do this and even not if this can work at all.
I appreciate your help.


Q: Gunicorn "error: unrecognized arguments --log-file-" I started a Django project and it was working fine in local computer. I deployed it to Heroku and I getting this error:

2019-07-06T10:32:11.836364+00:00 app[web.1]: gunicorn: error:
  unrecognized argum ents: --log-file-
2019-07-06T10:32:19.185756+00:00 app[web.1]: gunicorn: error:
  unrecognized argum ents: --log-file-

My Procfile contains
web: gunicorn tutorial_two.wsgi

A: Gunicorn doesn't recognize the argument --log-file-. The Procfile you shared with us doesn't contain anything like that, but I'm going to assume that it actually contains something like
web: gunicorn tutorial_two.wsgi --log-file-

since the error message specifically mentions that argument and this is almost a correct Procfile for Gunicorn. The problem is that --log-file should get an argument -. Those things shouldn't be attached together.
Modify your Procfile to add a space, e.g.
web: gunicorn tutorial_two.wsgi --log-file -

A: Well, this is rather implied. The gunicorn program takes the --log-file - argument given in the Procfile. May be something like this is the right solution.
web: gunicorn tutorial_two.wsgi; --log-file -


Q: Error deploying Ruby On Rails over CentOS with Apache2 and Passenger I am new on Ruby on Rails and after i have finished my first project and trying to deploy it i found a bunch of error that I do not understand.
0   /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb  31  in `gem_original_require'
1   /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb  31  in `require'
2   /var/www/fabiolaalvaradoservices.com/public_html/config/application.rb  3
3   /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb  31  in `gem_original_require'
4   /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb  31  in `require'
5   /var/www/fabiolaalvaradoservices.com/public_html/config/environment.rb  2
6   /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb  31  in `gem_original_require'
7   /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb  31  in `require'
8   /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/classic_rails/application_spawner.rb 222 in `preload_application'
9   /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/classic_rails/application_spawner.rb 181 in `initialize_server'
10  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/utils.rb 563 in `report_app_init_status'
11  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/classic_rails/application_spawner.rb 174 in `initialize_server'
12  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb   204 in `start_synchronously'
13  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb   180 in `start'
14  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/classic_rails/application_spawner.rb 149 in `start'
15  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 219 in `spawn_rails_application'
16  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server_collection.rb    132 in `lookup_or_add'
17  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 214 in `spawn_rails_application'
18  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server_collection.rb    82  in `synchronize'
19  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server_collection.rb    79  in `synchronize'
20  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 213 in `spawn_rails_application'
21  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 132 in `spawn_application'
22  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 275 in `handle_spawn_application'
23  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb   357 in `__send__'
24  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb   357 in `server_main_loop'
25  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb   206 in `start_synchronously'
26  /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/helper-scripts/passenger-spawn-server  99

Please, I need some one who can give me a hint what do I need to fix.
By the way I am using CentOS + Apache2 + Passenger.
config/application.rb file
require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)

module Demo
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de
  end
end

Configuration for Development and Production
Development Settings

Ruby version: 1.9.3p392

Rails version: 4.0.0.rc2
Production Settings

Ruby version: 1.9.3p484

Rails version: 4.0.2
Here my gemfile
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0.rc2'

# Use sqlite3 as the database for Active Record
gem 'sqlite3'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0.rc2'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

# Use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]


Q: setting the value of a checkbox programmatically in c# (wpf) I'm working on a small wpf project using c#.  I have 2 windows.  When I go from one window to the next, i need to have some items preselected on the 2nd window.  I have a checkbox that I need to set the value based on information that I pull from the registry.  On the 1st window, i have a reference to the 2nd window.  How can I set the checkbox to checked so that when the other window opens it's already checked?
 private void btnGoToNextWindow_Click(object sender, RoutedEventArgs e)
    {
            Window2 w2 = new Window2();

            //This doesn't work
            w2.Checked = true;

            w2.Show();
            this.Close();
     }

A: You can use the IsChecked property.
I hope this helps.
Damian

A: Using this:
        Window2 w2 = new Window2();

        //This doesn't work
        w2.Checked = true;

You're setting the Checked property of the window not the control.  It should be somehting like this:
        Window2 w2 = new Window2();
        w2.MyCheckBox.IsChecked = true;

A: I'd say that you should move towards pushing the view model into the view via IoC or some other fashion. Tie the value to a property and let the framework make your life easier via binding, instead of having to hard code values all over the place.
http://msdn.microsoft.com/en-us/library/ms752347.aspx


Q: Checking Image size using jQuery validation not working I am uploading an image to the folder but before uploading, I am checking the image extension and size. I am using jQuery validation.
I checked on SO before uploading the question and I found the code. But the issue is when I am uploading an image which is less than 100kb(actual image size is 98kb) then I am getting the error "File size must be less than 5". I tried another image which is 3.8MB but still getting the same error.
Would you help me out what size of the image I have to use here? and what is the filesize: 5?
Can any one help me out in this issue?

$.validator.addMethod('filesize', function(value, element, param) {
  return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');

$(function($) {
  "use strict";
  $('#form').validate({
    rules: {
      image: {
        //required: true,
        extension: "jpg,jpeg,png",
        filesize: 5,
      }
    },
  });
});
<form id="form" method="post" action="">
  <input type="file" name="image" />
  <input type="submit" value="Upload" />
</form>

<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>

A: Your parameter is only set to 5
$('#form').validate({
    rules: {
      image: {
        ....
        filesize: 5,  ...

That is 5 BYTES, so of course you would be getting the error message for any file that is 98 kB or 3.8 MB.  Since these are both larger than 5 bytes, they fail your custom rule, which only allows files smaller than 5 bytes.
Try 5242880 if you want to allow files under 5 MB.
filesize: 5242880 // <- 5 MB

$.validator.addMethod('filesize', function(value, element, param) {
  return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0} bytes');

$(function($) {
  "use strict";
  $('#form').validate({
    rules: {
      image: {
        //required: true,
        extension: "jpg,jpeg,png",
        filesize: 5242880 // <- 5 MB
      }
    },
  });
});
<form id="form" method="post" action="">
  <input type="file" name="image" />
  <input type="submit" value="Upload" />
</form>

<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>

A: Usually in these types, file sizes are specified in bytes. So you have to multiply it by 1024 multipliers accordingly.
For example if you want to check if the file size is less than 5MB, you should use
image: {
  extension: "jpg,jpeg,png",
  filesize: 5*1024*1024,
}


Q: Property 'double' does not exist on type 'MyComponent' in vuex-smart-module I have a vue application with typescript. I also use vuex-smart-module.
In my component I get typescript error:
Property 'double' does not exist on type 'MyComponent'.

In the vuex module I defined a getter:
class MyModuleGetters extends Getters<MyModuleState> {
  // You can declare both getter properties or methods
  get double() {
    // Getters instance has 'state' property
    return this.state.count * 2
  }
}

And I add the getter by:
@Component({
  computed: {
    ...MyModule.mapGetters(['double'])
  }
})
export default class MyComponent extends Vue {
  someFunction() {

    console.log(this.double); // <-- the error is here typescript typo.

If I use Vue.extend({ … }) its solved the problem BUT I need for every component to do Vue.extend so basically I create for 2 components each time. which is seems wrong.
Any idea how to make it work without extend?


Q: Change filename after upload Laravel Stapler I'm using the Stapler Lib to make the image uploads.
The image's filename is generated by image description field.
After the upload, the user can change the image description and after that, I need to update the image filename.
Is there a way to do this using the Stapler Lib?

A: Yes You can do like this
if($request->hasFile('image')) {
        $file = Input::file('image');
        //getting timestamp
        $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());

        $name = $timestamp. '-' .$file->getClientOriginalName();

        $blog->image = $name;

        $file->move(public_path().'/../public_html/img/blog/', $name);

        }


Q: MAC VSCode remote ssh extension failed to connect to Linux server I am trying to use VSCode remote ssh extension to access a folder on my school machine. I think initially the connection was established since it prompted me to enter the password. But then the window is stuck, and here is the output:
  [16:27:58.275] > Warning: no access to tty (Inappropriate ioctl for device).
    > Thus no job control in this shell.
    [16:27:58.340] > ready: 4b31ee9ef295
    [16:27:58.410] > Linux 4.19.0-13-amd64 #1 SMP Debian 4.19.160-2 (2020-11-28)
    [16:27:58.410] Platform: linux
    [16:27:58.552] stderr> bash: line 360: syntax error near unexpected token `('
    [16:27:58.552] stderr> bash: line 360: `echo "* as described in the license (https://go.microsoft.com/fwlink/?linkid=2077057)"'
    [16:27:58.552] stderr> function: Command not found.
    [16:27:58.552] stderr> Bad : modifier in $ '-'.
    [16:27:58.553] > 4b31ee9ef295: running
    > *
    >
    [16:27:58.553] stderr> VSCH_LOGFILE: Undefined variable.
    [16:27:58.553] stderr> LISTENING_ON=: Command not found.
    [16:27:58.554] stderr> VSCH_LOGFILE: Undefined variable.
    [16:27:58.554] stderr> WEBUITOKEN=: Command not found.
    [16:27:58.554] stderr> LISTENING_ON: Undefined variable.

The problem should not be on my school's server side because I used the ssh command in zsh and it successfully connects. So can anyone tell me where the problem is? Thank you in advance!

A: Open command palette, run "Remote-SSH: Settings", then config "Remote.SSH: Remote Server Listen On Socket" to true. This did the trick for me.


Q: is it convenient to urlencode all next parameters? - django While writing code, it is pretty common to request a page with an appended "next" query string argument.
For instance, in the following template code next points back to the page the user is on:
<a href="{%url some_view%}?next={{request.get_full_path}}

Here I am following a convention: if next features something that I'm not in control of, such as search keywords a user has typed, I urlencode it. Otherwise I don't.
<a href="{%url some_view%}?next={{request.get_full_path|urlencode}}

Instead of judging for each next argument whether it would be user provided or not, would it be convenient if I urlencode all next strings? Will there be side effects I don't see at the moment?

A: To the best of my knowledge anything that's inside of a url should always be urlencoded.
The only gotcha is that you need to make sure to reverse the encoding when you read in the arguments.  It's very possible that django already does this for you.  I'd need to consult the documentation and/or code to confirm though.


Q: spring boot use file path both in eclipse and after build I'm developing spring boot program using json input.
when I build spring boot from build.gradle file, I copy resources from src/main/resources to deploy/config.
Now, I want to use my json file in Eclipse and after build, but file path is different.
In eclipse, file path is src/main/resources/input/a.json and After build, file path is deploy/config/input/a.json
this is my build.gradle
task deploy() {
    doLast{
        delete ('deploy')
        copy {
            from "src/main/resources"
            into "deploy/config"
            include "*/"
        }
        copy {
            from "build/libs/${rootProject.name}-${version}.jar"
            into "deploy/"
        }
    }
}

And my java source code is like this.
String path1="config/input/"+fileName;
String path2="src/main/resources/input"+fileName;

How can I write file path just one way? I can't modify all the time when I build.
Thank you! :D


Q: asmx WebMethod caching on POST request in asp.net I am using jQuery to get back some JSON data from the server. I am using a POST verb, but even after setting the WebMethod CacheDuration attribute, the JSON doesn't get cached.
I checked the response headers with firebug and the Cache-Control is still set to no-cache.
How can i cache these request on the client and avoid the server to be hit every time.
UPDATE
After reading this post from scottGu I thought it would have been safe to go on to use a POST request. Does his post not apply to the kind of operation i would be trying to do ? (getting data from the server without modifying it). In fact after changing the verb to GET, i am not even getting to the web service ...

A: You should be using a get request. Post does not cache by default. You can try to get a post to cache by using .ajax() and setting cache to true and type to post. I cannot say that this will work as typically you would not expect a post to cache. I suggest using get.
E.g
$.ajax( { url: '/bla',
          type : 'post',
          data : dataObj,
          cache : true } );

A: Use the GET keyword instead if you want to use caching. There is a similar question on SO.

A: I've noticed differences in the way ASP.NET caches responses depending upon whether the caching parameters are query string parameters or (in my case with ASP.NET MVC) route parameters.
I never completely figured out exactly what the conditions were, but this may help someone.


Q: How to redirect an asp page to 2 other pages? I have a web page with checkbox list to choose multiple crystal reports to view. I want to open these reports in new tabs or windows.
I tried this :
This is the show report button:
<asp:Button ID="Button2" runat="server" Text="Show Report" OnClick="ButtonShowReport_Click"
                        CssClass="button" OnClientClick="aspnetForm.target ='_blank';"/>

And this is my gridview control:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
       RowStyle-HorizontalAlign="Center" AutoGenerateColumns="False"
       DataKeyNames="AccountID">
       <RowStyle BackColor="#>
       <Columns>
           <asp:TemplateField HeaderText="Choose Client's Accounts">
               <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server"/>
               </ItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField Visible="false">
               <ItemTemplate>
                    <asp:Label id="lblAccountId" runat ="server" text='<%# Eval("AccountID")%>'>
                    </asp:Label>
               </ItemTemplate>
           </asp:TemplateField>
           <asp:BoundField DataField="AccountID" HeaderText="AccountID" Visible="false"/>
           <asp:BoundField DataField="AccountName" HeaderText="Account Name" />
           <asp:BoundField DataField="Name" HeaderText="Client Name" />
       </Columns>
       <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
       <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
       <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
       <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
       <EditRowStyle BackColor="#2461BF" />
       <AlternatingRowStyle BackColor="White" />
</asp:GridView>

My c# code looks like:
protected void ButtonShowReport_Click(object sender, EventArgs e)
    {
        string accountID;
        int Rows = GridView1.Rows.Count;
        for (int i = 0; i < Rows; i++)
        {
            //CheckBoxField cb = ((CheckBoxField)gvASH.Rows[i].Cells[1]).;
            CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
            if (cb.Checked == true)
            {
                accountID = ((Label)GridView1.Rows[i].FindControl("lblAccountID")).Text;//GridView1.DataKeys[i].Value.ToString();//GridView1.Rows[i].Cells[1].Text;
                //Button2.Enabled = true;
                openReport(accountID);
            }
        }
    }

    protected void openReport(string accountID)
    {
        //some code for setting parameters of the crystal report
        //and for creating report key

        Response.Redirect(string.Format("~/Report.aspx?ReportKey={0}",
            ReportKey.ToString()),false);
    }

So if the user checked 2 reports and clicked on the ShowReport button, it'll do the loop but opens only one new tab with the last report chosen ...
Any Suggestions please ??

A: Add this to the control which triggers the redirect.  I know this works for Buttons/LinkButtons, not sure if it will work on a checkbox though.
OnClientClick="aspnetForm.target ='_blank';"

A: One method you might consider:
Instead of doing the Redirect to each report inside the code behind - dynamically generate some JavaScript that has uses window.open for each report.  The javascript would look similar to this:
<script type="text/javascript">
window.open("<report1URL>", "_blank");
window.open("<report2URL>", "_blank");
...
window.open("<reportNURL>", "_blank");
</script>

Then, instead of doing a Response.Redirect, you should be able to do a Respone.Write() to get the browser to execute the code.
string myJavaScript= <dynamicallyGenerateJavascript>;
Response.Write(myJavaScript);


Q: How can I store recorded data from the NEST simulator in a binary format? I am trying to write spikedetector data into .gdf files in binary format, but I cannot.
I am setting the binary param of the spikedetector to True (I checked it using nest.GetStatus) but files are written in ASCII:
neurons = nest.Create('iaf_psc_alpha', 5)
sr = nest.Create('spike_recorder')
nest.Connect(neurons, sr)
sr.SetStatus({'binary': True})

I am using NEST 2.18

A: The documentation for NEST 2.18 and 2.20 is misleading in this respect. The binary option has no effect (it sets the ios::binary flag when opening the file, but that has no significant consequences).
If you want to write spikes in binary format, you need to switch to NEST 3.0 and use the sionlib recording backend by setting the recorder's record_to property:
neurons = nest.Create('iaf_psc_alpha', 5)
sr = nest.Create('spike_recorder')
nest.Connect(neurons, sr)
sr.SetStatus({'record_to': 'sionlib'})

A guide for recording from simulations is available in the docs.


Q: Failed pushing Python Flask App to Heroku New to Flask and deploying on Heroku, trying to push to Heroku and I get this error when installing dependencies:
The pipenv version looks funny not sure if that is correct or how to correct it if that is the error
Enumerating objects: 38, done.
Counting objects: 100% (38/38), done.
Delta compression using up to 8 threads
Compressing objects: 100% (30/30), done.
Writing objects: 100% (38/38), 83.94 KiB | 10.49 MiB/s, done.
Total 38 (delta 8), reused 0 (delta 0), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing python-3.8.5
remote: -----> Installing pip
remote: -----> Installing dependencies with Pipenv 2018.5.18ÔÇª
remote:        Traceback (most recent call last):
remote:          File "/tmp/build_9fedd330/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/elements/abstracttable.py", line 27, in _enumerate_items
remote:            yield next(non_metadata), next(non_metadata)
remote:        StopIteration
remote:
remote:            return toml.loads(contents)
remote:          File "/tmp/build_9fedd330/.heroku/python/lib/python3.8/site-packages/pipenv/vendor/toml.py", line 307, in loads
remote:            raise TomlDecodeError("Key group not on a line by itself.")
remote:        toml.TomlDecodeError: Key group not on a line by itself.
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:

Not sure what the error is! Any help would be appreciated. I have removed some of the error list due to asking me for more details as to much code

A: If you have not yet done it, create a file with dependencies for your code and specify versions explicitly (example):
Flask==0.8
Jinja2==2.6
Werkzeug==0.8.3
certifi==0.0.8
chardet==1.0.1
distribute==0.6.24
gunicorn==0.14.2
requests==0.11.1

Then (if you didn't create it yet), set up a new virtual environment, install all the requirements and check that your code is running by using the python from this environment.

*

*Install virtualenv:
python3 -m pip install --user virtualenv

*Create a virtual environment: python3 -m venv env

*Activate the virtual environment source env/bin/activate

*Install all the requirements pip install -r requirements.txt

*Run your application in the same console where you activated the virtual environment.
The Heroku uses the following command for installing dependencies pip install -r requirements.txt. So if it gives you error on your local machine you would know what's the problem.


Q: How to make babel compile null coalescing operator? A dependency of mine uses the null coalescing operator. Babel can't handle it. Is there any way to make Babel work here?
babel.config.js
module.exports = {
    presets: ['@babel/preset-env', '@babel/preset-react'],
    plugins: [
        '@babel/transform-runtime',
        '@babel/plugin-proposal-nullish-coalescing-operator'
    ],
};

Compile error:
./node_modules/test/dist/test.js 26:10
Module parse failed: Unexpected token (26:10)
File was processed with these loaders:
 * ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| export class Test {
|   constructor() {
>     null ?? 0;
|   }
|


Q: .attachClickHandler() does not work on page refresh/redirect I'm trying to implement a custom google login button in index.html which works perfectly on page load but does not when the page is reloaded or redirected from another page. On page load, console statements 1,2 and 3 are printed sequentially automatically and 4 is printed on sign-in. When redirected from another page or refreshed the console only prints 1 and 2 and the button is not clickable. The script to include     gapi is included by
<script src="https://apis.google.com/js/api:client.js"></script>

in index.html. I'm using AngularJS if that has something to do with this.

  var googleUser = {};
  var startApp = function() {
  console.log("1");
gapi.load('auth2', function(){
  // Retrieve the singleton for the GoogleAuth library and set up the client.
  console.log("2");
  auth2 = gapi.auth2.init({
    client_id: '*************.apps.googleusercontent.com',
    cookiepolicy: 'single_host_origin',
    // Request scopes in addition to 'profile' and 'email'
    scope: 'profile email'
  });
  setTimeout(function(){
  attachSignin(document.getElementById('g_login'));
}, 1000);
  // attachSignin(document.getElementById('g_login'));
});
  };

function attachSignin(element) {
console.log("3");
auth2.attachClickHandler(element, {},
    function(googleUser) {
      console.log("4");
      document.getElementById('name').innerText = "Signed in: " +
          googleUser.getBasicProfile().getName();
      angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
    }, function(error) {
      alert(JSON.stringify(error, undefined, 2));
    });
  }
startApp();
</script>

A: Solved.
Global variable 'auth2' is automatically initialised each time the page is loaded and can be used to sign users in.
The script is called as:
<script src="https://apis.google.com/js/api:client.js?onload=onLoadCallback" async defer></script>

<script>
var auth2;
var googleUser = {};
var auth3;

window.onLoadCallback = function(){
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
    client_id: '**********.apps.googleusercontent.com',
    cookiepolicy: 'single_host_origin',
    // Request scopes in addition to 'profile' and 'email'
    scope: 'profile email'
  });

auth3 = true;
startApp();
})

}

var startApp = function() {

  element = document.getElementById('g_login');
  auth2.attachClickHandler(element, {},
function(googleUser) {
    console.log("4");
  document.getElementById('name').innerText = "Signed in: " +
      googleUser.getBasicProfile().getName();
  angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
}, function(error) {
    console.log("5");
  alert(JSON.stringify(error, undefined, 2));
});
};

if (auth3)
 startApp();

</script>


Q: Remove Paste option from MenuItems in iOS 16 I have a custom menu options written in
override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool { }

in iOS 16 I see now a Paste option in the context option. I tried to hide it via
if action.description == "paste:" { return false } //FAILED

return action != #selector(UIResponderStandardEditActions.paste(_:)) // FAILED

but did not help. I see Paste option now everywhere.
How to get rid of it ?

A: To remove the paste option from the default context menu, use this:
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
    if action != #selector(UIResponderStandardEditActions.paste(_:)) {
        return true
    }
    return false
}


Q: Javascript Mapping Nested Arrays I have an array of objects ("array"), each containing other arrays of objects.
[
  {
     name: "Object 1",
     question: [{value: "This", type: "text"}, {value: "is", type: "text"},  {value: "1", type: "number".]
     answer: [{value: "Answer", type: "text"}, {value: "is", type: "text"},  {value: "1", type: "number".]
  },
  {
     name: "Object 2",
     question: [{value: "This", type: "text"}, {value: "is", type: "text"},  {value: "2", type: "number".]
     answer: [{value: "Answer", type: "text"}, {value: "is", type: "text"},  {value: "2", type: "number".]
  },
]

In React, I'd like to render out the below:
<Typography>This</Typography><Typography>is</Typography><Number>1</Number>
<Typography>Answer</Typography><Typography>is</Typography><Number>1</Number
<Typography>This</Typography><Typography>is</Typography><Number>2</Number>
<Typography>Answer</Typography><Typography>is</Typography><Number>2</Number

I have tried the below, but can't work out why some of it won't map correctly.
array.map(snippet => {
 snippet.question.map(question => {
  return something here;
})

EDITED AS FORGOT A LEVEL OF OBJECTS

A: Try some thing like this.
array.map(snippet => (
  <>
    {snippet.question.map(que => {
      if (que.type === "text") {
        return <Typography>{que.value}</Typography>;
      } else if (que.type === "number") {
        return <Number>{que.value}</Number>;
      }
      return null;
    })}
    {snippet.answer.map(ans => {
      if (ans.type === "text") {
        return <Typography>{ans.value}</Typography>;
      } else if (ans.type === "number") {
        return <Number>{ans.value}</Number>;
      }
      return null;
    })}
  </>
));


Q: issue with adding a method in object I have this object:
var Point = {
    step: function () {
        alert("hello");
    }
};

This works:Point.step();.
How to make it work with the [ ] notation? Meaning Point["property_name"].

A: It is Point["step"]();. Here is the snippet:

var Point = {
    step: function () {
        alert("hello");
    }
};

Point["step"]();


Q: JQuery UI - .resizable not working I have looked around and although I have found similar questions to this one, none of them had any solutions that worked for me.
Here is a link to another question similar.
Draggable and resizable in JqueryUI for an image is not working?

This is just a very basic example but when I run this the image is movable but is not resizable. Although as far as I can tell, it should definitely work.
In the link above at the bottom of the question there is a link to a working example.
http://jsfiddle.net/8VY52/
The example is using jfiddle with this exact same HTML and javascript.
Is there something I am missing about Jquery UI, why does this work through Jfiddle but does not seem to work within the code above.
Thanks.

A: You are missing the jquery-ui CSS file in your code
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"/>

Demo: Plunker

A: Complete working code would be.

A: This will work for you.

A: As the resizable property only works on right side and bottom side so find the image borders find that by selecting a image in css and border to it then see the output it will work perfectly


Q: Flutter How to make two columns in Container? There is a Container, inside you need to make two columns. In one column there will be icons with texts, and in another there will be one icon in the center.
More details on the photo
enter image description here

A: I made an example of what you are trying to achieve:
class SO extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
            height: 200,
            width: 300,
            decoration: BoxDecoration(
              color: Colors.orange,
              borderRadius: BorderRadius.circular(10),
            ),
            padding: EdgeInsets.only(left: 25),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Icon(
                          Icons.mail_outline,
                          color: Colors.white,
                          size: 30,
                        ),
                        Text('title'),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Icon(
                          Icons.mail_outline,
                          color: Colors.white,
                          size: 30,
                        ),
                        Text('title'),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Icon(
                          Icons.mail_outline,
                          color: Colors.white,
                          size: 30,
                        ),
                        Text('title'),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Icon(
                          Icons.mail_outline,
                          color: Colors.white,
                          size: 30,
                        ),
                        Text('title'),
                      ],
                    ),
                  ],
                ),
                Spacer(),
                Container(
                  height: 60,
                  width: 60,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: Colors.white,
                      width: 2,
                    ),
                  ),
                  child: Center(
                    child: Text('Photo'),
                  ),
                ),
                Spacer(),
              ],
            )),
      ),
    );
  }
}

OUTPUT :

A: This is the code, which will help you attain what you want to achieve. Also, I have replaced the photo with the real image, to give you a feel about how the image works. However, it is NetworkImage(), it uses web images, if you want to use the local image, then do use AssetImage()
       Container(
          height: 200.0,
          width: 350.0,
          padding: EdgeInsets.all(20.0),
          decoration: BoxDecoration(
            color: Colors.orange,
            borderRadius: BorderRadius.circular(10.0)
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    children: <Widget>[
                      Icon(
                        Icons.mail_outline,
                        color: Colors.white,
                        size: 30,
                      ),
                      SizedBox(width: 10.0),
                      Text('title', style: TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold)),
                    ]
                  ),
                  Row(
                    children: <Widget>[
                      Icon(
                        Icons.mail_outline,
                        color: Colors.white,
                        size: 30,
                      ),
                      SizedBox(width: 10.0),
                      Text('title', style: TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold)),
                    ]
                  ),
                  Row(
                    children: <Widget>[
                      Icon(
                        Icons.mail_outline,
                        color: Colors.white,
                        size: 30,
                      ),
                      SizedBox(width: 10.0),
                      Text('title', style: TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold)),
                    ]
                  )
                ]
              ),
              Expanded(
                flex: 1,
                child: Align(
                  alignment: Alignment.center,
                  child: Container(
                    height: 80.0,
                    width: 80.0,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.white, width: 3.0),
                      borderRadius: BorderRadius.all(Radius.circular(40.0)),
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        image: NetworkImage('https://image.shutterstock.com/image-photo/beautiful-pink-flower-anemones-fresh-260nw-1028135845.jpg')
                      )
                    )
                  )
                )
              )
            ]
          )
        )

RESULT


Q: kickme discord.js command, kicks before can dm Im having some issues getting the command to wait for the bot to dm the user before it kicks them, ive put in a wait 5 second function but it kicks well before 5 seconds is up Below is my code and error.
its saying 'wait' isnt defined but ive looked here and used one of those, with a slight modification.
also i have another not so important question, how would i make it so whoever runs the !kickme command gets logged into a .txt file or something similar?
Edit: i figured id clarify. Yes im trying to kick the user who sent the !kickme command. its meant to be a completely useless command for people to mess around with. it should send them a dm with the server invite(so they can rejoin) and then kick them.
as of now it isnt sending the dm to them, its just kicking them
const Discord = require('discord.js')

module.exports.run = async (bot, message, args) => {

    const user = message.author
    const member = message.guild.member(user);

    message.author.send(`Here is an invite so you can join back! https://discord.gg/FBXSduget2 `)

    const timew = async (bot, message, args) => {
        wait(5000);
        console.log("Waited 5s");

        wait(5000);
        console.log("Waited an additional 5s");
      };

      timew();

    if (member) {
        member
          .kick('User was kicked')
          .then(() => {
            console.log(`${user.tag} Kicked themself`);
            message.channel.send(`${user.tag} kicked themself`)
          })
          .catch(err => {
            message.reply('Unable');
            console.error(err);
          });
        }
    }

  module.exports.help = {
    name: "kickme"
  }

(node:13216) UnhandledPromiseRejectionWarning: ReferenceError: wait is not defined
    at timew (C:\Users\8fwbu\Desktop\CodeTProj\-Tux V2\commands\kickme.js:12:9)
    at Object.module.exports.run (C:\Users\8fwbu\Desktop\CodeTProj\-Tux V2\commands\kickme.js:19:7)
    at Client.<anonymous> (C:\Users\8fwbu\Desktop\CodeTProj\-Tux V2\main.js:42:31)
    at Client.emit (events.js:315:20)
    at MessageCreateAction.handle (C:\Users\8fwbu\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (C:\Users\8fwbu\node_modules\ws\lib\event-target.js:132:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13216) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled
with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13216) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13216) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user
    at RequestHandler.execute (C:\Users\8fwbu\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async RequestHandler.push (C:\Users\8fwbu\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
(node:13216) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled
with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Unicorn-Barf#9255 Kicked themself

A: Your error comes from using wait(5000); as this is not defined.
You can use await when sending messages to ensure they are sent.
await message.author.send(`Here is an invite`)
message.member.kick('they kicked themself')


Q: Spring MVC: Testing particular annotated method gets invoked In Spring MVC 3.0, how do I test that a particular method gets invoked?
For example, I have this controller method:
public class myController {
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create(ModelMap map) {
            map.put("category", new Category());
            return new ModelAndView("views/someView", map);
        }
}

How do I test that this create() method gets called when somebody requests http://example.com/create url.

A: In Unit Tests, you should only test your controller's Java code, without using any Servlet technology.
In integration tests you can do one of several things:
Use the org.springframework.mock.web package in the spring-test artifact, which contains Mock Objects for request, response, servletContext to fire fake requests at your controllers and read the data from the fake responses.
Or use a web testing framework like Selenium that works against a deployed webapp.

A:
How do I test that this create() method gets called when somebody requests http://example.com/create url.

Looks really like a integration test. Sean Patrick Floyd already mentioned some ways how to test that, but to my understanding none of this options really tests that a request to an url really invokes the method. -- The mocking way simulates the request and the selenium test tests only the return value, but not the Invocation. -- Don't get my wrong, I believe that this two other tests are in most cases better (easyer to test and even more valid test results), but if you really want to test the invokation I would come up with this solution.
Use a web testing framework like Selenium (or Selenium 2/Webdriver) or only a simple one that only generates HTTP requests. -- To do that tests you will need of curse the deployed application. -- so it is realy an integration test.
To check that the method is invoked. I would recommend to use a logging tool (Log4J). Then use a Tool like AspectJ or Spring AOP Support to add logging statements to your controller method. The logging should be written to some logger that writes to an other destination then the other loggers you use.
At the end the last step is, that you need to verify that the expected logging statement is is the logfile after the test sends the http request. (Pay attention to the fact, that the logging may is asynchronous.)