text:
Q: How to access boolean value of one file in another I am new at flutter and building a project. I have two files naming distractor.dart and layout.dart. In distractor I use images which has a boolean value that keeps changing from true to false back forth for the set run time of the program. what I want to know is when a user presses a button or without a button what I the boolean value of the image used in distractor file. I want to know that value in my layout file. can someone help me resolve or make me understand its working. Thank you.
This is my layout file
import 'package:adhd/distracter.dart';
import 'package:adhd/distracter2.dart';
import 'package:adhd/stimuli.dart';

import 'package:flutter/material.dart';

class Layout extends StatefulWidget {
  const Layout({Key? key}) : super(key: key);

  @override
  State<Layout> createState() => _LayoutState();
}

class _LayoutState extends State<Layout> {
  @override
  Widget build(BuildContext context) {
    final btn = Material(
      elevation: 5,
      borderRadius: BorderRadius.circular(30),
      color: const Color.fromARGB(255, 208, 99, 99),
      child: MaterialButton(
          padding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
          minWidth: MediaQuery.of(context).size.width * 0.3,
          onPressed: () {},
          child: const Text(
            "Go",
            textAlign: TextAlign.center,
            style: TextStyle(
                fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold),
          )),
    );

    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage("assets/images/bg.jpg"), fit: BoxFit.cover),
        ),
        child: Column(children: [
          SizedBox(height: MediaQuery.of(context).size.height * 0.1),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Distracter(showImage: false,),
              const SizedBox(
                height: 110,
              ),
              Distracter2(),
            ],
          ),
          SizedBox(height: MediaQuery.of(context).size.height * 0.1),
          const Stimuli(),
          SizedBox(height: MediaQuery.of(context).size.height * 0.1),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Distracter2(),
              const SizedBox(
                height: 110,
              ),
            ],
          ),
          SizedBox(height: MediaQuery.of(context).size.height * 0.1),
          btn
        ]),
      ),
    );
  }
}`.

this is my distractor file
import 'package:flutter/material.dart';

class Distracter extends StatefulWidget {
  bool showImage = false;
  Distracter({ required this.showImage,
    Key? key,
  }) : super(key: key);

  @override
  State<Distracter> createState() => _DistracterState();
}

class _DistracterState extends State<Distracter>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
      reverseDuration: const Duration(seconds: 4),
    )
      ..addListener(() {
        if (controller.status == AnimationStatus.completed) {
          controller.reverse();
        }
        if (controller.status == AnimationStatus.dismissed) {
          controller.forward();
        }
        setState(() {});
      })
      ..forward();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    showD1() {
      if (controller.status == AnimationStatus.forward) {
        widget.showImage = true;
      }
      if (controller.status == AnimationStatus.reverse) {
        widget.showImage = false;
      }
      if (widget.showImage) {
        return SizedBox(
            height: 110,
            child: Image.asset(
              "assets/images/character_robot_attack0.png",
              fit: BoxFit.contain,
            ));
      } else {
        return const SizedBox(
          height: 110,
        );
      }
    }

    return showD1();
  }
}

A: AFAIK you should pass a Callback to Distracter to get the bool.
Distracter(showImage:false, onChanged: (bool value) { /** use the value **/});

//in Distracter
if (controller.status == AnimationStatus.forward) {
  widget.showImage = true;
  widget.onChanged(true);
}
if (controller.status == AnimationStatus.reverse) {
  widget.showImage = false;
    widget.onChanged(false);
}

A: You can keep track boolean value in parent class (Layout file) and use a callback in your child class to change its value. This is usually called Lifting state up. It's quite simple solution for this problem. The other solutions including state management using different packages available on pub.dev, one of them recommended by Flutter team is provider package. I am mentioning out of the box solution here.
layout.dart
class Layout extends StatefulWidget {
  const Layout({Key? key}) : super(key: key);

  @override
  State<Layout> createState() => _LayoutState();
}

class _LayoutState extends State<Layout> {

// initiate your value here, use `setState` if you wish to rebuild the class.

bool showImage = false;
void setShowImage(bool value) => showImage = value;

  @override
  Widget build(BuildContext context) {
   /// code retracted

Now pass these values into distractor file.
class Distracter extends StatefulWidget {
  final bool showImage;
  final VoidCallback setShowImage;
  Distracter({
required this.showImage,
required this.setShowImage,
    Key? key,
  }) : super(key: key);

  @override
  State<Distracter> createState() => _DistracterState();
}

class _DistracterState extends State<Distracter>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
      reverseDuration: const Duration(seconds: 4),
    )
      ..addListener(() {
        if (controller.status == AnimationStatus.completed) {
          controller.reverse();
        }
        if (controller.status == AnimationStatus.dismissed) {
          controller.forward();
        }
        setState(() {});
      })
      ..forward();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    showD1() {
      if (controller.status == AnimationStatus.forward) {
        widget.setShowImage(true);
      }
      if (controller.status == AnimationStatus.reverse) {
        widget.setshowImage(false);
      }
      if (widget.showImage) {
        return SizedBox(
            height: 110,
            child: Image.asset(
              "assets/images/character_robot_attack0.png",
              fit: BoxFit.contain,
            ));
      } else {
        return const SizedBox(
          height: 110,
        );
      }
    }

    return showD1();
  }
}

A: Create a callback function like
class Distracter extends StatefulWidget {
  final bool showImage;
  final Function(bool) callback;

  const Distracter({
    this.showImage = false,
    required this.callback,
    Key? key,
  }) : super(key: key);

  @override
  State<Distracter> createState() => _DistracterState();
}

And
 controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
      reverseDuration: const Duration(seconds: 4),
    )
      ..addListener(() {
        if (controller.status == AnimationStatus.completed) {
          controller.reverse();
        }
        if (controller.status == AnimationStatus.dismissed) {
          controller.forward();
        }
        setState(() {});
      })
      ..forward();

Use it as
Distracter(callback: (value){

  print(value);
},


text:
Q: React Leaflet Load WMS layer in parallel I am loading multiple WMSTile Layers in React Leaflet. They are displaying correctly, but each layer is waiting for the previous layer to finish loading before starting to load the next layer. I can see this by logging in the event handlers like so:
<LayersControl>
      {dateArray.map((date) => {
        const url =
          `${openWeatherMapLayerBaseUrlPaid}/${op}/{z}/{x}/{y}?appid=${openWeatherMapApiKey}` + `&date=${date}`;
        return (
          <LayersControl.Overlay key={`${op}${date}`} name={`Open Weather - ${op}${date}`} checked={true}>
            <WMSTileLayer
              url={url}
              opacity={activeOverlayDate === date ? 1 : 0}
              eventHandlers={{
                tileload: () => {
                  console.log('TILE LOAD: event for every tile in the layer');
                },
                load: () => {
                  console.log('FINISH LAYER: layer load event once after all tiles are loaded');
                },
              }}
            />
          </LayersControl.Overlay>
        );
      })}
    </LayersControl>

If there were two entries in the dateArray, and there were 5 tiles to be loaded in each layer, the output of the above would be something like:
TILE LOAD: event for every tile in the layer
TILE LOAD: event for every tile in the layer
TILE LOAD: event for every tile in the layer
TILE LOAD: event for every tile in the layer
TILE LOAD: event for every tile in the layer
FINISH LAYER: layer load event once after all tiles are loaded
TILE LOAD: event for every tile in the layer
TILE LOAD: event for every tile in the layer
TILE LOAD: event for every tile in the layer
TILE LOAD: event for every tile in the layer
TILE LOAD: event for every tile in the layer
FINISH LAYER: layer load event once after all tiles are loaded

Is there a way to trigger the loading of all the layers so that they happen in parallel?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Haskell's Either v. Error Learn You a Haskell presents Error:
instance (Error e) => Monad (Either e) where
    return x = Right x
    Right x >>= f = f x
    Left err >>= f = Left err
    fail msg = Left (strMsg msg)

Hackage presents Either:
data Either a b = Left a | Right b

If I understand correctly, then Error is a Monad with Either as it's a type.  Also, it looks like there's a fail to handle exceptions.
But, I also see that there's a Control.Monad.Either too - http://hackage.haskell.org/package/category-extras-0.53.4/docs/Control-Monad-Either.html.
Why would Control.Monad.Error be chosen over Control.Monad.Either, and vice-versa?

A: No, Error is not a monad. Either e is a monad, and Error e was a typeclass prerequisite for the Monad instance for Either e to exist. Basically Error e means that e is a type which you can convert error messages into with strMsg, which was used for Either e's fail method.
However, people found this requirement to have an Error e instance just to be able to use Either e as a monad annoying, so after LYAH was written it was actually removed. Now the instance is just
instance Monad (Either e) where
    return = Right
    Left  l >>= _ = Left l
    Right r >>= k = k r

and fail instead uses the default from the Monad class definition:
fail s      = error s

However, the Error e requirement is still (as of newest Haskell Platform at least) required for the monads and transformers defined in Control.Monad.Error, while Control.Monad.Either leaves out that requirement.


text:
Q: Don't understand certain commands in this bash script I've been tasked to modify this bash script and there are some syntax in this script that I don't quite understand.
I understand the majority after researching and studying some bash. I feel bad about posting the entire script here but I didn't want to hide any information from you that would make it harder to answer my questions.
Basically I have gap in understanding the following bash commands you'll find in the script below.

*

*if [[ ${#} -eq 3 ]]; then - What is the $# here? What are [[]]?

*eval HOSTNAME_PORT=\$$ENV
 eval config_mapping_values=\$$MAPPING - there are 2 $ here? What's up with the slash

*IFS=',' read -a mapping_value_array <<< "$mapping_values_param"

*"${!mapping_value_array[@]}" - What is @ sign here in the beginning of loop?

*type_name=$(echo $map_value_item | cut -d":" -f1)- Why $ sign is used outside and inside of parenthesis?

The full script:
#!/bin/sh

insert_mapping()
{
  mapping_name_param=$1
  mapping_values_param=$2
  echo "Calling insert mapping: name: $mapping_name_param values: $mapping_values_param "

  IFS=',' read -a mapping_value_array <<< "$mapping_values_param"

  for index in "${!mapping_value_array[@]}"
  do
    map_value_item=${mapping_value_array[index]}

    if [[ $index -eq 0 ]];then
            echo "Calling Curl Command: curl -XPUT "$HOSTNAME_PORT/$mapping_name_param" -d @$map_value_item"
        curl -XPUT "$HOSTNAME_PORT/$mapping_name_param" -d @$map_value_item
    else
        type_name=$(echo $map_value_item | cut -d":" -f1)
        type_file=$(echo $map_value_item | cut -d":" -f2)
            echo "Calling Curl Command: curl -XPUT "$HOSTNAME_PORT/$mapping_name_param/$type_name/_mapping" -d @$type_file"
        curl -XPUT "$HOSTNAME_PORT/$mapping_name_param/$type_name/_mapping" -d @$type_file
    fi
  done
}

delete_mapping()
{
  mapping_name_param=$1
  echo "Calling Curl Command: curl -XDELETE "$HOSTNAME_PORT/$mapping_name_param""
  curl -XDELETE "$HOSTNAME_PORT/$mapping_name_param"
}

#
# MAIN METHOD
#
source ./configure_es_mapping_util.cfg

if [[ ${#} -eq 3 ]]; then
     export ENV=$1
     export ACTION=$2
     export MAPPING=$3
     echo "ENV: $ENV ACTION $ACTION MAPPING $MAPPING"

     eval HOSTNAME_PORT=\$$ENV
     eval config_mapping_values=\$$MAPPING

     if [[ "$ACTION" == "insert" || "$ACTION" == "INSERT" ]]; then
       if [[ "$MAPPING" == "all" ]]; then
          IFS=',' read -a all_mappings_array <<< "$all_mappings"
          for i in "${all_mappings_array[@]}"
          do
              eval config_mapping_values=\$$i
              insert_mapping $i $config_mapping_values
          done
       else
         insert_mapping $MAPPING $config_mapping_values
       fi
     elif [[ "$ACTION" == "delete" || "$ACTION" == "DELETE" ]]; then
        echo "Calling delete: $ACTION"
       if [[ "$MAPPING" == "all" ]]; then
          IFS=',' read -a all_mappings_array <<< "$all_mappings"
          for i in "${all_mappings_array[@]}"
          do
              delete_mapping $i
          done
       else
         delete_mapping $MAPPING
       fi
    else
        echo "unknown action"
    fi
else
    echo "Invalid Arguments: Provide Env(ITE, QA, UAT, PROD) Action(INSERT, DELETE) Mapping(icrd_alerts)"
    exit 1
fi

A: if [[ ${#} -eq 3 ]]; then

This statement tests whether the number of position parameters (e.g. the number of command line arguments) is 3.
eval HOSTNAME_PORT=\$$ENV eval config_mapping_values=\$$MAPPING

the arguments to eval are read and concatenated together into a single command. The syntax $$ is an indirect reference. Using eval here causes HOSTNAME_PORT to be set to the value of the variable $(whatever $ENV is). Thus if $ENV contains "host1", HOSTNAME_PORT=$host1. The same applies for config_mapping_values=\$$MAPPING
IFS=',' read -a mapping_value_array <<< "$mapping_values_param"

IFS is the Bash Internal Field Separator (defautl is $' \t\n' (space tab newline)) that controls how word-splitting takes place. It causes the words in "$mapping_values_param" to be split on , and the result read into array mapping_value_array.
"${!mapping_value_array[@]}" in the loop beginning I see this.

The keys of an associative array are accessed using an exclamation point. At the beginning of a loop it simply returns a list of key values to iterate over. However, since the array mapping_value_array is a regular indexed array (See: read -a mapping_value_array above), the result is simply the indexes for each element in the array (e.g. 0 1 2 3...).
type_name=$(echo $map_value_item | cut -d":" -f1)

The variable type_name is assigned the result of the command substitution (e.g. the result of echo $map_value_item | cut -d":" -f1).


text:
Q: How to build a PreferredSizeWidget, not a Widget, from a FutureBuilder or async code? I know how to build a Widget from a FutureBuilder, so this is my future/async function, for example:
Future<Null> myFuture() async
{
    // etc.
}

If I want to build an AppBar title, this works fine:
class MyStuff extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AppBar(
        title: FutureBuilder(
            future: myFuture(),
            builder: (context, snapshot) {
              // etc...
              return Text("blahblah");
            }
        ));
  }
}

Now, I want to build the AppBar's bottom which expects a PreferredSizeWidget, so this works, but is not async:
class MyStuff2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AppBar(
      bottom: PreferredSize(),
    );
  }
}

But how can I use this in a future/async way? this doesn't even compile:
class MyStuff3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AppBar(
      bottom: FutureBuilder(, // is there a FutureBuilder for PreferredSizeWidgets?
        future: myFuture(),
        builder: (context, snapshot) {
          // etc...
          // I want to compute preferred size from async call result
          return PreferredSize(); // pseudo-code ???
        }
    );
  }
}

A: It's not gonna work since the FutureBuilder returns a Widget , so, what you can do is convert your stateless builder to a stateful one and create your own "PreferredSizeFutureBuilder"
import 'package:flutter/material.dart';

class PreferredSizeFutureBuilder extends StatefulWidget {
  @override
  _PreferredSizeFutureBuilderState createState() =>
      _PreferredSizeFutureBuilderState();
}

class _PreferredSizeFutureBuilderState
    extends State<PreferredSizeFutureBuilder> {
  bool isCompleted = false;

  @override
  void initState() {
    super.initState();
    myFuture();
  }

  Future<void> myFuture() async {
    //do something

    setState(() {
      isCompleted = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return AppBar(
        bottom: isCompleted //we check if the future has ended
            ? PreferredSize(
                child: YourComponent(), //your component
                preferredSize: Size.fromHeight(12.0), //the size you want
              )
            : null); //if the future is loading we don't return anything, you can add your loading widget here
  }
}

Of course this means that the snapshot object is not gonna work , instead you use the isCompleted bool to check if your future is done, you can even use the ConnectionState instead of a boolean to have the "snapshot" behaviour

A: You can wrap FutureBuilder into a PreferredSize-Widget.
No need to create an own FutureBuilder-Widget that implements PreferredSize.
    class MyStuff2 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return AppBar(
          bottom: PreferredSize(
             child: FutureBuilder(future: _getData(), builder: (BuildContext context, AsyncSnapshot snapshot) {
               if(snapshot.data != null) {
                 return Text(snapshot.data);
                } else {
                 return Text('Loading...');
                }
            ),
             preferredSize: Size.fromHeight(50.0),
        );
      }
    }


text:
Q: fbjni/fbjni.h file not found react-native fbjni/fbjni.h file not found error in react-native when building the android version of RN app.
App to build successfully.

A: try either :

*

*rm -rf node_modules && yarn install (worked for me)

or
These steps:

*

*Close Android Studio

*Add android.disableAutomaticComponentCreation=true in
android/gradle.properties

*Reopen project and build.


text:
Q: Un valor en un dataframe contiene varios valores separados con punto y coma Mi problema es el siguiente:
Tengo el siguiente dataframe:
import pandas as pd
l = [['x', 'aa', 'aa;bb'],
      ['y', 'bb', 'aa;cc;dd'],
      ['z', 'cc', 'cc'],
      ['w', 'dd', 'aa;bb;cc;dd']]
df = pd.DataFrame(l)
df

Cada valor de la columna 3 contiene varios valores de la columna 2 separados por ";".
Necesito contar los valores de la columna 2 que aparecen en cada valor de la columna 3.
Por ejemplo, el 1er valor de la columna 3 es "aa;bb", entonces mi conteo debe dar 2, el 4to valor de la columna 3 es 'aa;bb;cc;dd', el conteo debe dar 4.
Luego tengo que almacenar todos mis conteos en otra columna.
¿Alguien me puede ayudar?

A: Podemos escribir una función que reciba como parámetro un elemento de la columna 2. Por ejemplo recibiría algo como "aa;bb". Esa función debe retornar como resultado cuántos de esos elementos están en la columna 1.
La siguiente función haría ese trabajo:
def cuantos(lista):
  lista = lista.split(";")
  return sum(1 for elem in lista if elem in df[1].values)

Cómo funciona:

*

*Se separa la cadena recibida por el ";", para obtener una lista como ["aa", "bb"]

*Se escribe una expresión generadora que va generando unos (1) por cada elemento que se encuentre en la primera columna de df.

*Se retorna la suma de esos 1.

Ahora habría que aplicar esta función a cada elemento de la columna 2. Esto lo hace el método .map() de pandas:
df[2].map(cuantos)

El resultado en este ejemplo sale:
0    2
1    3
2    1
3    4
Name: 2, dtype: int64

Puedes asignar esto a otra columna si quieres, por ejemplo:
>>> df["cuantos"] = df[2].map(cuantos)
>>> df
   0   1            2  cuantos
0  x  aa        aa;bb        2
1  y  bb     aa;cc;dd        3
2  z  cc           cc        1
3  w  dd  aa;bb;cc;dd        4

A: Espero esto se lo que buscas:
l = [['x', 'aa', 'aa;bb'],
      ['y', 'bb', 'aa;cc;dd'],
      ['z', 'cc', 'cc'],
      ['w', 'dd', 'aa;bb;cc;dd']]

#Cuanto tiene de ancho y de alto.
eje_x = len(l[0])
eje_y = len(l)

for y in range(eje_y):
    for x in range(eje_x):
        if x == eje_x - 1:
            contador = len(l[y][x].split(";"))
            l[y].append(contador)

for a in l:
    print(a)

salida:
['x', 'aa', 'aa;bb', 2]
['y', 'bb', 'aa;cc;dd', 3]
['z', 'cc', 'cc', 1]
['w', 'dd', 'aa;bb;cc;dd', 4]


text:
Q: `Terminal` vs `system()` in R I tried running the following in R
system("Message=HelloWoRld;echo $(sed 's/R/r/' <(echo ${Message}))")

but it fails, while
Message=HelloWoRld
echo $(sed 's/R/r/' <(echo ${Message}))

works fine when copy pasted in the terminal. The issue seems related to <(..). When I do either which bash or system("which bash"), I get /bin/bash.
Why does the same command via system() or directly on the terminal window does not yield to the same output?

FYI, I am on Mac OS X 10.11.3. Bash is GNU bash, version 3.2.57(1) and R is R version 3.2.3.

A: system is not a terminal emulator, and it's not running Bash. Your terminal runs Bash. To get the same effect with system, run the command inside Bash. E.g.
system('bash -c \'echo $(date)\'')

What's more, your current Bash command is quite convoluted and uses unnecessary command invocations; you can achieve the same via the much simpler
sed s/R/r/ <<< $Message

@chepner makes the excellent point that another solution can be used directly in system without need to pass execution to Bash:
system("Message=HelloWoRld; echo $Message | sed 's/R/r/'")


text:
Q: Login and Oauth in Android Studio and Jax-rs im developing an android app and I connect to services to authenticate the user.....
So do you recomend to use JWT and OAuth for security in my android app, I have the rest services in Java with Jax-rs and jersey.


text:
Q: Please allow downvoting in the LQ review queue There is much talk of late about the need to downvote rather than close or delete certain content.  I see these come through the low quality review queue frequently. To give them the appropriate treatment, I have to make several extra mouse clicks to open up. It would seems that you would want to optimize and encourage the correct behavior of downvoting by allowing downvoting right there in the LQ review framework.

A: I don't think this should be a top priority since many posts that end up in that queue are not an answer posts that are going to end up being deleted anyways. Probably like 40%? Just a guess. Depends on the site.
If a question makes it to the LQRQ chances are it already has -1 score or worse, and a close vote from you is top priority. If you want to help out as much as you can, then do the extra clicks and downvote it too.
The only reason I can think of why they don't have it included already, is that they don't want people to just downvote and pass the review successfully, and then have to click back to go and close vote it too. So some technical thing.


text:
Q: Add GData to Zend Framework2 Okay, so this has proven to be more difficult than I expected and think it should be.
All I want to do is utilize the GData library for some youtube functionality in my site. However, I can't seem to figure out how to add everything in so Zend recognizes the classes.
I've downloaded the latest ZendGdata archive, and added the contents of \library into \vendor\Zend. Next step is to autoload all that into my application right? I've tried searching for how to do it, but nothing has helped. Now I look to you, stackoverflow. Please help me figure this madness out.

A: How about ditching manually installing vendors and using composer which will manage all the autoloading stuff for you?
Download composer.phar into your project's root directory and run init to create a basic configuration:
curl -s https://getcomposer.org/installer | php
php composer.phar init

Follow the prompts, when it comes to searching for required packages, select zendframework/zendgdata and use the version dev-master. (If you decided to use composer for all your dependencies which I recommend, you could also at this point add zendframework/zendframework: 2.*).
Once you've done that a composer.json file will have been created. Next install your dependencies:
php composer.phar install

Once that's all done, there should be a vendor/autoload.php file that you require from your entrypoint to have autoloading of your composer dependencies working.


text:
Q: Solve $y''''-2y'''+2y'-y=e^x.$ My attempt: The characteristic polynomial and the solutions gives the homogenous solutions $$p(r)=r^4-2r^3+2r-1=(r+1)(r-1)^3\Rightarrow y_h=Ae^{-x}+(B+Cx+Dx^2)e^{x}.$$
In order to find the particular solution, let's substitute $y=ze^x,$ where $z=z(x).$ We obtain a new differential equation in terms of $z(x)$, whose characteristic equation is
$$p(r-1)=(r-1)^4-2(r-1)^3+2(r-1)-1=r^4-6r^3+12r^2-8r.$$
This means that we get $z''''-6z'''+23z''-8z'=1,$ after dividing both sides with $e^x>0.$ So the particular solution in terms of $z$ is $z_p=-\frac{x}{8}$ and this gives $y_p=z_pe^x=-\frac{xe^x}{8}.$ Finally we have that
$$y(x)=y_h+y_p=Ae^{-x}+(B+Cx+Dx^2)e^x-\frac{xe^x}{8}.$$
Which is wrong, because the last term should be $+\frac{x^3e^x}{12}.$ Need help sorting this out, but other methods of solving are welcome.

A: made for the particular solution the ansatz $$y_P=Ae^xx^3+Be^xx^2+Ce^xx+De^x$$

A: Let $D$ be a shorthand for the operator $\frac{d}{dx}$. For any constant $a$ and function $f(x)$, we have the identity
$$e^{ax} D(e^{-ax}f(x)) = (D-a) f(x)$$
We will abuse notation and write this sort of relation as
$$e^{ax} D e^{-ax} = D - a$$
The $e^{\pm ax}$ here should be interpreted as an operator on the space of function whose effect on any function is pointwise multiplication by $e^{\pm ax}$.
For any polynomial $P(t)$, we have following identity on operators.
$$e^{ax}P(D)e^{-ax} = P(D-a)$$
Notice $r^4 - 2r^3 + 2r - 1 = \color{red}{(r-1)^3(r+1)}$ instead of what stated in the original version of question. The ODE at hand can be rewritten as
$$(D-1)^3(D+1) y = e^x \iff \left[ e^x D^3(D+2) e^{-x} \right] y = e^x
\iff \left[ D^3(D+2) \right] (e^{-x}y) = 1
$$
It is easy to see $\frac12\frac{x^3}{3!} = \frac{x^3}{12}$ is a solution for
$D^3(D+2) f = 1$. As a consequence, the original equation has $\frac{x^3}{12} e^x$ as a particular solution.


text:
Q: How to increase maxDate in jquery datepicker I have two input boxes in the first input box user select date and in second input box the date that should come for selection must be 2 days from that selected day, here is the snippet of code

$(function() {
  var checkIn = $("#date-1"); var checkOut = $("#date-2");
  var todayDate = new Date();

  checkIn.datepicker({
    dateFormat:"dd-mm-yy",
    changeMonth:true,
    changeYear:false,
    minDate:todayDate

  });

  checkIn.on("change",function() {
    var select = checkIn.datepicker("getDate") ;
    var  checkOutDate = select;
    checkOut.datepicker('option','minDate',checkOutDate);
    checkOut.datepicker('option','maxDate',"+2d");
  });

  checkOut.datepicker({
    dateFormat:"dd-mm-yy",
    changeMonth:false,
    changeYear:false
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>

<form>
  <input type="text" id="date-1" placeholder="Date 1">
  <input type="text" id="date-2" placeholder="Date 2">
</form>

The problem is it doesn't set the date when the month is changed with some different date i have also tried this
 checkOut.datepicker('option','maxDate',checkOutDate);

But it doesn't work either i know i am missing some parameter but what is it ?

A: It's because the "+2d" param calculates the diff from now, not from its current value. So in your example, you order to datepicker to show a range between the selected date and now + 2 days. So you get a negative gap => no range displayed. Here a solution :

$(function() {
  const checkIn = $("#date-1");
  const checkOut = $("#date-2");
  const todayDate = new Date();

  checkIn.datepicker({
    dateFormat: "dd-mm-yy",
    changeMonth: true,
    changeYear: false,
    minDate: todayDate,
  });

  checkOut.datepicker({
    dateFormat: "dd-mm-yy",
    changeMonth: false,
    changeYear: false,
  });

  checkIn.on("change", function() {
    const checkOutDate = checkIn.datepicker("getDate");
    const diffDate = checkOutDate - todayDate
    const fromNow = Math.ceil(diffDate / 1000 / 60 / 60 / 24);

    checkOut.datepicker("option", {
      minDate: fromNow,
      maxDate: fromNow + 2,
    });
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>

<form>
  <input type="text" id="date-1" placeholder="Date 1">
  <input type="text" id="date-2" placeholder="Date 2">
</form>


text:
Q: Visual Studio: Reload Dataset and Datagrid when there's structural change in Database I'm a newbie and I'm trying to create an App with Visual Studio 2013 in .vb
This App works with a local database (books, Cd, Dvd, etc. that I have) made with Ms SQl SERVER EXPRESS, and I wonder if I can find a way to reload my DatagridView and my Dataset through the APP when I add a column to my database with the App. In fact I'm trying to find a way to show this new column in my datagridview and I don't want to go always in VS because I want use my App on a small laptop.
Well, I don't know where to start so I've tried this:
Imports System.Data.SqlClient
...
Private Sub Form8_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim cn As New SqlConnection("Data Source=PC-ME\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True")
    Dim cmd As SqlCommand = cn.CreateCommand()
    cmd.CommandText = "Select * FROM CONSULTE"
    Dim adapter As New SqlDataAdapter()
    Dim ds As New DataSet()
    adapter.SelectCommand = cmd
    cn.Open()
    adapter.Fill(ds, "CONSULTE")
    cn.Close()
    CONSULTEDataGridView.DataSource = ds
    CONSULTEDataGridView.DataMember = "CONSULTE"

End Sub

But It does'nt work.
My windows form where I can ALTER TABLE:
Imports System.Data.SqlClient
Public Class Form7
Dim cn As New SqlConnection("Data Source=PC-ME\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader

Private Sub Form7_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cmd.Connection = cn
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If table.Text <> "" And colonne.Text <> "" And typede.Text <> "" Then
        cn.Open()
        cmd.CommandText = "ALTER TABLE " & table.Text & " ADD " & colonne.Text & " " & typede.Text & ""
        cmd.ExecuteNonQuery()
        cn.Close()
        table.Text = ""
        colonne.Text = ""
        typede.Text = ""
    Else
        MsgBox("Vous devez remplir les trois champs!")
    End If
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    If table.Text <> "" And colonne.Text <> "" Then
        cn.Open()
        cmd.CommandText = "ALTER TABLE " & table.Text & " DROP COLUMN " & colonne.Text & ""
        cmd.ExecuteNonQuery()
        cn.Close()
        table.Text = ""
        colonne.Text = ""
    Else
        MsgBox("Vous devez remplir correctement les deux premiers champs!")
    End If
End Sub
End Class

Thanks for you help!
PS: Sorry for my English, it's not my mother tongue.

A: i am not a pro but want to try it. I have used WithEvents statement.
Please try following code. And i am assuming that, you are writing code in two forms right? Form7  and Form 8
In Form 7,do this
Imports System.Data.SqlClient
Public Class Form7
 ...
 Public Event LoadDataGridView(sender As System.Object)

Private Sub Form7_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cmd.Connection = cn
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If table.Text <> "" And colonne.Text <> "" And typede.Text <> "" Then
      --- Your stuff here. After completion of code, following event will be raised

      RaiseEvent LoadDataGridView(sender)
    Else
        MsgBox("Vous devez remplir les trois champs!")
    End If
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    If table.Text <> "" And colonne.Text <> "" Then
      -- Your stuff here. After completion of code, following event will be raised

      RaiseEvent LoadDataGridView(sender)
    Else
        MsgBox("Vous devez remplir correctement les deux premiers champs!")
    End If
End Sub
End Class

Now ,
In Form 8, do this
Imports System.Data.SqlClient
Public Class Form8
Private WithEvents form7 As New Form7

Private Sub Form8_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    -- You stuff
End Sub

Private Sub form7_LoadDataGridView(sender As Object) Handles form7.LoadDataGridView
 'Call load procedure to reload datagridview
 Form8_Load(Nothing,Nothing)
End Sub
End Class

A: So I've found a way! If somebody wants to know, here is an example:
Datagridview1 is the name of my datagridview on form1
Form 1:
Imports System.Data.SqlClient
Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim cn As New SqlConnection("Data Source=PC-ME\SQLEXPRESS;Initial Catalog=BDD;Integrated Security=True")
    cn.Open()
    Dim cmd As SqlCommand = cn.CreateCommand()
    Dim adapter As New SqlDataAdapter()
    Dim ds As New DataSet()
    Dim sql As String

    sql = "SELECT * FROM CONSULTE"
    adapter.SelectCommand = New SqlCommand(sql, cn)
    adapter.Fill(ds)
    DataGridView1.DataSource = ds.Tables(0)

End Sub
End Class

Form 3, where I can add or delete columns:
Imports System.Data.SqlClient
Public Class Form3
Dim cn As New SqlConnection("Data Source=PC-ME\SQLEXPRESS;Initial Catalog=BDD;Integrated Security=True")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cmd.Connection = cn
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If table.Text <> "" And colonne.Text <> "" And typede.Text <> "" Then
        cn.Open()
        cmd.CommandText = "ALTER TABLE " & table.Text & " ADD " & colonne.Text & " " & typede.Text & ""
        cmd.ExecuteNonQuery()
        cn.Close()
        table.Text = ""
        colonne.Text = ""
        typede.Text = ""
    Else
        MsgBox("Vous devez remplir les trois champs!")
    End If
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    If table.Text <> "" And colonne.Text <> "" Then
        cn.Open()
        cmd.CommandText = "ALTER TABLE " & table.Text & " DROP COLUMN " & colonne.Text & ""
        cmd.ExecuteNonQuery()
        cn.Close()
        table.Text = ""
        colonne.Text = ""
    Else
        MsgBox("Vous devez remplir correctement les deux premiers champs!")
    End If
End Sub
End Class

Where "table" (= Table), "colonne" (= Column) and "typede" (= type) are the name of three textboxes


text:
Q: How to return default value when no rows return from table When the table ERRORMESSAGE contains no rows that satisfy the "WHERE" condition, IFNULL fails and I get null, not the default value provided in the IFNULL clause.
select IFNULL(errorCode , 'NOERRORCODE') as "errorCode",
    IFNULL(errorText , 'NOERROR') as "errorText" from
    (select errorcode,
        IFNULL((select errorText from STATIC_ERRORCODES a
        where a.errorcode = b.errorcode), '') as errorText
     from ERRORMESSAGE b  where b.route_id = 'IPN4'
     order by b.row_index)

When there are no rows in ERRORMESSAGE with route_id = 'IPN4', the output should be:
errorCode = NOERRORCODE
errorText = NOERROR

But I get null/empty values. How can I resolve this?

A: You could use NOT EXISTS and UNION ALL
SELECT errorCode, errorText
FROM ERRORMESSAGE WHERE <condition>
UNION ALL
SELECT 'NOERRORCODE', 'NOERROR'
FROM ERRORMESSAGE
WHERE NOT EXISTS (SELECT * FROM ERRORMESSAGE WHERE <condition>)

You need to replace <condition> with actual criteria. So, when there is are row exists, then SELECT after UNION ALL will get executed, which will show static row.
Please note: I have never used HSQLDB, so I wasn't sure how to show static rows, but I used as explained here


text:
Q: How to fix "The connection was not closed, The connection's current state is open." Whenever I click the delete button on my webpage I always recive the "The connection was not closed. The connection's current state is open.", However I already closed the connection.
 protected void DeleteButton_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand comm = new SqlCommand("DELETE FROM [Table] where [Id] ='"+Id.Text+"'", con);
            comm.ExecuteNonQuery();
            con.Close();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Deleted');", true);

            disp_data();
        }

I even tried to change
con.Close();

to
con.Dispose();

but I ended up with the same error

A: You might think it's expensive to create new connections all the time. It's not, there is connection pooling built-in and the connections will actually be reused. Therefore you should do something like this:
protected void DeleteButton_Click(object sender, EventArgs e)
{
    using (var connection = new SqlConnection(myConnectionString))
    {
        connection.Open();
        using (var command = new SqlCommand("DELETE FROM [Table] where [Id] ='"+Id.Text+"'", connection)
        {
            command.ExecuteNonQuery();
        }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Deleted');", true);
        disp_data();
}

The using pattern takes care of closing and disposing both SqlConnection and SqlCommand.
Next you should get rid of con as a class member and use this pattern althrough your code.


text:
Q: How can I create a div in jQuery that I can scroll left to right in I am creating a movie search engine. So far when I type in a movie into my input I receive a list of movies as shown in the screenshot below.
The way my movies are shown. I have to scroll down to see more
Instead I want my images to be represented similar to how they are in google.
The way google shows its movies. You have to scroll right to see more, but the page remains static, only the movies change as you scroll
Hopefully someone can help. Thanks in advance!

A: You can implement it with css but if the situation require JQuery you can do it like below
$('#search-container').append(
  $('<div/>')
    .attr("id", "movie")
    .addClass("new-movie")
    .css({"width": "1000px", "overflow-x": "auto"})
);

A:

 document.getElementById("content").style.overflowX = "scroll";
document.getElementById("content").style.width = "200px";

Try this in your js.


text:
Q: Get data after request is done In my case, the main problem is that I can't get data after the user registered.
In my windows phone app i used to get data by firing event LoadCompleted.
This code shows how I've done it before:
private void AuthBrowser_LoadCompleted(object sender, NavigationEventArgs e)
    {
        string responceData = e.Uri.OriginalString;
        if (responceData.Contains("access_token"))
        {
            if (settings.Contains("IsRegistered"))
            {
                settings["IsRegistered"] = true;
            }
            else
            {
                settings.Add("IsRegistered", true);
            }
            var parameters = responceData.Split('#')[1].Split('&');
            var accessToken = parameters[0].Substring(parameters[0].IndexOf("=", StringComparison.Ordinal)).Remove(0, 1);
            if (settings.Contains("AccessToken"))
            {
                settings["AccessToken"] = accessToken;
            }
            else
            {
                settings.Add("AccessToken", accessToken);
            }
            var expiresIn = parameters[1].Substring(parameters[1].IndexOf("=", StringComparison.Ordinal)).Remove(0, 1);
            var uID = parameters[2].Substring(parameters[2].IndexOf("=", StringComparison.Ordinal)).Remove(0, 1);
            if (settings.Contains("UserId"))
            {
                settings["UserId"] = uID;
            }
            else
            {
                settings.Add("UserId", uID);
            }
            if (settings.Contains("IsRegistered"))
            {
                settings["IsRegistered"] = true;
            }
            else
            {
                settings.Add("IsRegistered", true);
            }
            NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
        }
    }

But now in my IOS app I don't understand how to do this.
I've used WKWebView.
This is my code sample:
import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?
    var uiWebView: UIWebView?
    override func loadView() {
        super.loadView()
        self.uiWebView = UIWebView()
        self.webView = WKWebView()
        self.view = self.webView!

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var url = NSURL(string:"https://oauth.vk.com/authorize?client_id=4537563&" +
            "redirect_uri=http://api.vk.com/blank.html&display=wap&scope=9999999&response_type=token")
        var req = NSURLRequest(URL:url!)

        self.webView!.loadRequest(req)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Thanks.

A: The delegate protocol for UIWebView gives you a number of methods for tracking the status of the request: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebViewDelegate_Protocol/

A: Try using WKNavigationDelegate
Set delegate in viewDidLoad
class ViewController: UIViewController, WKNavigationDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()
    webView.navigationDelegate = self

    var url = NSURL(string:"https://oauth.vk.com/authorize?client_id=4537563&" +
        "redirect_uri=http://api.vk.com/blank.html&display=wap&scope=9999999&response_type=token")
    var req = NSURLRequest(URL:url!)

    self.webView!.loadRequest(req)
  }
}

Use the following to get data after loading is complete
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
    // your request has been completed, get the data here
}


text:
Q: Typescript: Define object type without defining types for keys to get keyof Here I want to define the type for object value only. In order to get types for keys. Is there any way to get without defining types for each value.
const sizes: Record<string, CSSObject>= {
  md: {
    padding: [10, 24],
    fontSize: 'medium',
  },
  xs: {
    padding: [6, 12],
    fontSize: 'small',
  },
  sm: {
    padding: [8, 16],
    fontSize: 'small',
  },
  lg: {
    padding: [14, 30],
    fontSize: 'large',
  },
} as const;

// Expecting 'md' | 'xs' | 'sm' | 'lg'
type Sizes = keyof typeof sizes;

// But it is string

A: As I understand it, you want to infer the keys 'md' | 'xs' | 'sm' | 'lg' from the object's actual properties, but you also want the type-checker to make sure that the properties' values are of type CSSObject.
The problem is that you would need a type annotation on the object literal to check the values are CSSObject; but if you use a type annotation then keyof ... will get the keys from the annotated type, not the object itself.
The way around this is to use a generic helper function, so that the record's key type is inferred while the value type is specified:
function helper<K extends PropertyKey>(obj: Record<K, CSSObject>): Record<K, CSSObject> {
    return obj;
}

const sizes = helper({
  md: {
    padding: [10, 24],
    fontSize: 'medium',
  },
  // ...
});

type Sizes = keyof typeof sizes;
// 'md' | 'xs' | 'sm' | 'lg'

Playground Link

A: Just wanted to add on to @kaya3's very helpful answer:
The helper function here works specifically with CSSObject. I needed to use this helper on multiple objects with different value types, so I wrote a version that lets you pass in any type:
function constrainValuesAndInferKeys<V>() {
    return function <K extends PropertyKey>(obj: Record<K, V>) {
        return obj;
    }
}

const sizes = constrainValuesAndInferKeys<CSSProperties>()({
  md: {
    padding: [10, 24],
    fontSize: 'medium',
  },
  // ...
});

type Sizes = keyof typeof sizes;
// 'md' | 'xs' | 'sm' | 'lg'

The downside is you have to add that extra () in constrainValuesAndInferKeys<CSSProperties>()({.


text:
Q: Slided down
* automatically toggling up when page is scrolled down in Chrome browser in mobile phones I have a responsive navigation in my website. I used jQuery slideToggle() for toggling the navigation in mobile phones. Everything works properly except one. The error is showing only in Chrome browser for Android (I checked all the other browsers including Chrome in iOS). The problem is, after we toggled down the navigation and while we are scrolling down to see the full navigation the navigation is automatically sliding up. I used the following code for toggling the navigation.
$(document).on('click', '.mobmenu', function(){
    if ($(window).width() <= 991) {
        $('.leftmenu > ul').slideToggle();
    }
});


text:
Q: How can I debug ASP.NET Boilerplate Web API? I am using the ASP.NET Boilerplate framework. I have added my code to web API. I am getting an error "An internal error occurred during your request!", So, I want to debug the API. Can anyone tell me how can I do that? when I call the web API, breakpoint should come in the Service project.

A: Please follow the points below for the solution to your problem.

*

*You can open the browser console and in the network tab you can see
that which API is getting failed and you can also see the HTTP
response code.

*For debugging you can use the solution mentioned here.

*You can also see the full exception details in Logs.txt file on
the Web.Host\App_Data\Logs path. For logging, you can refer this
document.


text:
Q: Construct an object with a mapping of parameters scala Is it possible to create an object from a Map[String, Any] where each pair is a (StringField -> Value) ?
For example,
case class Example(a: String, b: Int)
val obj = new Example( Map('a' -> 'blah', 'b' -> 1) ) //?
val orMaybe = Example( Map('a' -> 'blah', 'b' -> 1 ) //?

A: You can pass a tuple as the parameter list to a function using .tupled:

(Example.apply _).tupled("a" -> 1)

With that, and knowing that myMap.map passes each element of the Map as a Tuple, you could do the following:

Map("a" -> 1).map((Example.apply _).tupled).head

A: Yes, it's possible in several ways. One of them would be to use reflection, another (a simpler one) would be to use json as an intermediate.
E.g. with json4s:
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}

scala> implicit val formats = DefaultFormats
formats: org.json4s.DefaultFormats.type = org.json4s.DefaultFormats$@1f2bf363

case class Example(a: String, b: Int)
scala> val obj = read[Example](write( Map("a" -> "blah", "b" -> 1) ))
obj: Example = Example(blah,1)
scala: val orMaybe = read[Example](write( Map("a" -> "blah", "b" -> 1 )))
orMaybe: Example = Example(blah,1)


text:
Q: How to read a full line of text in C with spaces For an assignment at school I have to make the game rogue.  The way we load the rooms is from a file that looks like this:
10x12 de4 ds6 p9,8 g7,5 h1,1 M8,9
24x12 ds5 ds6 p9,8 g7,5 h1,1 M8,9
9x16 ds3 ds6 p9,8 g7,5 h1,1 M8,9
18x17 dn9 ds6 p9,8 g7,5 h1,1 M8,9
5x5 de4 ds6 p9,8 g7,5 h1,1 M8,9
16x11 dw7 ds6 p9,8 g7,5 h1,1 M8,9

Each room has a size to start then all the elements and their locations after it, separated by a space.  When I read it in, I was unable to get each line (10x12 de4 ds6 p9,8 g7,5 h1,1 M8,9), I only got one element at a time (10x12 then de4 then ds6 and so on).  Is there a way to read up until the end of the line and save that in a
char ** rooms variable?

A: First you have to know that at the end of each line there is a character '\n'.
When you open a file, it create a cursor located at the start of the file.
When you read one character, the cursor move on until it reach the end of the file, represented by the state code 'EOF' (-1 value).
To get one line, the strategy will be to read all character until you reach '\n'. And do it again, and again, until you reach 'EOF'.
(be careful because if there is only one line, you will maybe not have '\n')
How to do it using code now:
Use the following function:
fopen() // To open the file
getline() // To read one line
Luckily for you these two function are enough, because they handle everything ('\n', 'EOF', cursor ...)


text:
Q: Comparar dois atributos datas na base dados com duas TextBox Como posso comparar um intervalo de duas datas?
data_Inicio date
data_Fim date

textbox_inicio
textbox_fim

Poderei fazer isso logo do lado do ASP.NET sendo que o objetivo é que a minha data de início nunca seja inferior a minha data de fim e a minha data de fim nunca seja inferior a minha data de início.

A: Considere usar um componente próprio para datas. Dito isto vou tentar dar uma solução ao que parece ser o que precisa:
DateTime dataInicio;
if (!DateTime.TryParse(textbox_inicio.Text, out dataInicio)) {
    lblErro.Text =  "Formato da data inicial é inválido";
    lblErro.Visible = true;
    return;
}
DateTime dataFim;
if (!DateTime.TryParse(textbox_fim.Text, out dataFim)) {
    lblErro.Text =  "Formato da data final é inválido";
    lblErro.Visible = true;
    return;
}

if (DateTime.Compare(dataInicio.Date > dataFinal.Date) {
    lblErro.Text = "Data inicial não pode ser superior à data final";
    lblErro.Visible = true;
} else {
    lblErro.Text = "";
    lblErro.Visible = false;
}

Coloquei no GitHub para referência futura.
Isto é só uma base, dá para fazer melhor que isto e provavelmente será precisa adaptar ao que você precisa já que você não postou seu código.


text:
Q: gnuplot columnhead labels "at end" and in key Two questions about columnheader in gnuplot:
1) I'm plotting a few data columns with column headers and I want to label the graphs BOTH near the end of each graph line (with "at end") AND in a key. If I use "unset key", I get clean labels at the end of the graphs.
unset key
plot for [col=2:6] file using 1:col with lp ls col title columnhead(col) at end

If I comment out "unset key" and try to draw BOTH the labels near the end of each graph AND in the key, I get some weird artifact to the right of the properly drawn key. Any way to get rid of this artifact?
### unset key
plot for [col=2:6] file using 1:col with lp ls col title columnhead(col), for [col=2:6] file using 1:col with lp ls
col title columnhead(col) at end

2) Sometimes I want a substring of the column header when labeling. I tried "substr" (see below), but I get a "0", instead of the substring. Is there a way to get substring of the column header?
plot for [col=2:6] file using 1:col with lp ls col title substr(columnhead(col),0,1) at end

EDIT: Sample data file:
Date,V,W,D,Y,X
2017-09-03,0,0,0,0,-
2017-09-05,-3.67,-4.71,-2.86,-1.69,-
2017-09-06,-4.19,-6.42,-1.65,-1.86,-
2017-09-07,-2.41,-5.64,1.24,-0.26,0
2017-09-08,4.61,-5.38,1.47,0.45,-2.55

EDIT2: Even this simple script with the data above gives me the artifact (Win7 x64, gnuplot 5.2)
set terminal gif
set output "test.gif"
set datafile separator ","
set timefmt "%Y-%m-%d"
set xdata time
plot for [col=2:6] "test.dat" using 1:col with lp ls  col title columnhead(col) at end

A: Bug in 5.2pl0. It overprints the lines in the legend if the "at end" option is used:
plot for [i=1:5] i+x title "i=".i at end

5.0pl6 doesn't do that. Bug report has been filed on sf.net.

A: (This is really just a comment, but I want to provide an image so post it as an answer instead)
Are you sure it's not something else in your gnuplot script that causes a problem? Using the data you posted,
set datafile separator ","
set timefmt "%Y-%m-%d"
set xdata time
plot for [col=2:6] "test.dat" using 1:col with lp ls  col title columnhead(col) at end

gives

which doesn't show the artifact.


text:
Q: searching for right ip address in an array of strings - java android I'm new to android java programming. I'm trying to rewrite an app.
i had an editText contaning ip prefixes delimited by ",". e.g. "10.15,10.31,10.42"
private void MDConnect() {
String str = getIpAddress();
String [] arrayOfString = editText.getText().toString().split(",");
j = 0

while ( j < arrayOfString.length) {
if (str.substring(0,arrayOfString[j].length()).equals(arrayOfString[j])){
addMessage("Success! Your IP address is " + str);
}else{
j++;}
}
addMessage("Retrying")
// this is where the process will start over. disconnect and then connect to get a fresh new ip address
}

my goal is to connect->getIpAdd->check if it matches the ones on the list->if yes, add success message; if no, disconnect and connect again.
Hope someone could help me. Please. Thanks in advance.
EDIT:the code is just checking the first string in the array. it's not looping or moving to the next string. How could i loop an if-statement and do the process i have said in my post?

A: Your code is very sloppy and is missing semi-colons and closing brackets. And your loop can be simplified a lot, although your method CAN work, you are making it much harder than it should be. try this code:
    String str = getIpAddress();
    String [] arrayOfString = editText.getText().toString().split(",");
    for (int i = 0; i < arrayOfString.length; i++) {
        if (str.substring(0,arrayOfString[i].length()).equals(arrayOfString[i])) {
            addMessage("Success! Your IP address is " + str);
            break;
        } else {
           //not found
           addMessage("Retrying")
        }
    }

A: Move the addMessage("Retrying") and disconnect logic outside of the loop, so that it is not executed until it has tried and failed to match on all of the IPs in the array:
private void MDConnect() {
    String ip = getIpAddress();
    String[] prefixes = editText.getText().toString().split(",");
    for (String prefix : prefixes) {
        if (ip.startsWith(prefix)) {
            addMessage("Success! Your IP address is " + ip);
            return;
        }
    }
    addMessage("Retrying");
    ...
}


text:
Q: WIFI poor signal HP 15-af165sa 02:00.0 Network controller [0280]: Broadcom Corporation BCM43142 802.11b/g/n [14e4:4365] (rev 01)
Subsystem: Hewlett-Packard Company Device [103c:804a]
Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx-
Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
Latency: 0, Cache Line Size: 64 bytes
Interrupt: pin A routed to IRQ 36
Region 0: Memory at f0c00000 (64-bit, non-prefetchable) [size=32K]
Capabilities: <access denied>
Kernel driver in use: wl

Wi-fi signal is really weak  but in the same time my mac signal is really strong . So it made me wonder that there is something wrong with the driver. I'm new here and with Linux in general as I never faced such issue I am really confused now . I had a similar issue with 16.04 and when tried to fix it , I managed to completely screw it up. so I reinstalled OS to 14.04.
I followed step by step here Installing Broadcom Wireless Drivers and the signal has gone weaker than before and it keeps disconnecting even more often now.
Network diagnostics results :
results

A: First, check the settings in the router. WPA2-AES is preferred; not any WPA and WPA2 mixed mode and certainly, absolutely not TKIP. Second, if your router is capable of N speeds, you may have better connectivity with a channel width of 20 MHz in the 2.4 GHz band instead of automatic 20/40 MHz, although it is likely to affect N speeds. I also have better luck with a fixed channel, either 1, 6 or 11, rather than automatic channel selection. Also, be certain the router is not set to use N speeds only; auto B, G and N is preferred. After making these changes, reboot the router.
Next, I recommend that your regulatory domain be set explicitly. Check yours:
sudo iw reg get

If you get 00, that is a one-size-maybe-fits-all setting. Find yours here: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Then set it temporarily:
sudo iw reg set IS

Of course, substitute your country code if not Iceland. Set it permanently:
gksudo gedit /etc/default/crda

Use nano or kate or leafpad if you don't have the text editor gedit.
Change the last line to read:
REGDOMAIN=IS

Proofread carefully, save and close the text editor.
Next, I'd set IPv6 to Ignore in Network Manager: http://docs.fedoraproject.org/en-US/Fedora/18/html/Installation_Guide/images/netconfig/network-connections-ipv6-ignore.png  This example is for ethernet, but you want wireless.
After these things are done, reboot and test. Give us your report. If the issue is not improved, please let us have an updated wireless_script.


text:
Q: Problems with CakePHP project Upgrade I have a CakePHP project, initially built using version 1.3. I had saved the files long before and now wanted to deploy the site on my new machine. My new machine runs on PHP 5.4 and hence there were lots of 'Strict Standard' warnings.
I, then downloaded CakePHP Version 2.0 and replaced it with my old 'cake' folder. After that, I ran the 'Update all' command. I got a succesfully updated message. However, I still had to manually change the names of few folders (from config to Config etc.) and specify a path for the bootstrap.php in the app/webroot/index.php
I have managed to get past all the errors, but one, that says "Fatal error: Class 'Dispatcher' not found in /path/to/app/webroot/index.php" on line 82. Is this some path specific error ?

A: You also need to manually replace the following:

*

*app/index.php

*app/webroot/index.php

*app/webroot/test.php

*Any .htaccess file

*Any other core files in the app folder, like cake.generic.css


text:
Q: ClickOnce-signing on continuous integration server only Context:
We are multiple developers that are working on a single Office addin. Our continuous integration (CI) server creates deployable artifacts.
However, Visual Studio enforces every developer to sign the ClickOnce manifest (disabling the checkbox "Sign the ClickOnce manifests" in the project properties will re-check it on the next build). Thus every developer needs to be in possession of the signing certificate.
Is there a way to disable signing the manifest for the developers?
Note: We do not want to eventually deploy without a signed manifest, but we want to keep the signing certificate on a single machine.

A: We now solved this for us as follows:

*

*We created a "development-only" certificate that is self-signed, expires in many years and is under version-control. All developers share this certificate, but it can't be used to create installers signed by our company.

*The continuous integration server will update the application manifest and create a new deployment manifest using Mage (using the real signing certificate)

While this does not disable signing on the development machines, it avoids the problems associated with sharing the trusted certificate on all development machines.


text:
Q: How to cast date to CDT and make concatenated string using BigQuery? I'm trying the following:
count(distinct concat(x.my_id,cast(date_trunc('day',DATETIME(x.my_datetime,'US/Central')) as string)))

But I get the error:
Found invalid date part argument function call syntax for DATETIME()

When I put DATETIME(x.my_datetime,'US/Central') on its own line, it has no errors. So how can I accomplish getting the day of a datetime cast to cdt and putting it in a concatenated string?

A: Two things:

*

*date_trunc() should have the date/datetime/timestamp first, followed by the date part.

*The date part should be the literal day instead of the string 'day'.

With that in mind, your expression should be
count(distinct concat(x.my_id,cast(date_trunc(DATETIME(x.my_datetime,'US/Central'), day) as string)))


text:
Q: Does having a method that updates and add new record if the record does not exist break SRP? Lets say I have a DatabaseService class that has Update(user) and Add(user).
My question is about having them both in one method. Is it a good practice or not ?
To be more specific does it break the singularity rule (i.e. Single Responsibility)?
For example if i have a mothed like this
public void AddOrUpdateUser(User user)
{
   var userFound = GetUserById(user.Id);
   if (userFound == null)
   {
      AddUser(user);
   }
   else
   {
      UpdateUser(user);
   }
}

Would it be a good idea ? or would it be bad because it breaks the singularity rule so let the consumer class decides what to do?

A: It's common to work this way. If given user it hasn't been already persisted, it'll be created, otherwise, it'll be updated.
BTW, I would change the part of getting a possible user by given Id with something like this:
public interface IPersistable
{
     bool IsNew { get; }
}

public class User : IPersistable
{
    public int Id { get; set; };
    public bool IsNew => Id == 0;
}

And then:
IPersistable persistable = user as IPersistable;
Contract.Assert(persistable != null);

if(persistable.IsNew)
{
    // Create
}
else
{
   // Update
}

OP concerns about single responsibility principle (SRP)
Since we call this method as AddOrUpdate, OP has said in some comment on my answer that this could break single responibility principle.
I really believe that this concern comes from the method identifier rather than of what the method really does.
The whole method takes care of persisting objects and, from the consumer point of view, this is a single responsibility: I want you to take care about persisting my object.
Either if it was already on the underlying store or not, it's still persisting an object. We could rename this method to Persist, Save or whatever, but AddOrUpdate, at least, provides more semantics to the operation and it follows another unofficial (but widely accepted) principle: self-documented code (you can understand what your code does just by reading the code itself).
Thus, it seems like it would break single responsibility principle if it would also delete objects or any other unrelated operation that could be represented by another verb.


text:
Q: How to open React Component based on remaining width on right side of x-axis **Background:**I am creating a custom daterange picker component in React and want it to open right by default and open left if width on right hand side is not sufficient for complete two-month window to show?
**Question:**Is there a way in CSS/SASS/JS to determine remaining width and put a logic based on that?
Happy to provide more info, if needed. Please help.
**Current scenario:**Currently I have hardcoded it open right on certain screens and left on others. But would need a more cleaner, generic approach.
Additional info: The container of calendar has calendar plus some other info-based component arranged using CSS grid.


text:
Q: Magento 2: Updated file not working I want to update the class Select and its getValuesHTML() method which is saved here: module-catalog/Block/Product/View/Options/Type/Select.php
I have made a copy of this file and placed it in my theme here:
VENDOR/THEME/Magento_Catalog/Block/Product/View/Options/Type/Select.php
I've done the following, but my changes still aren't taking effect:
php bin/magento setup:static-content:deploy
php bin/magento indexer:reindex
php bin/magento cache:clean
Have I placed the file in the wrong folder location?

A: You can't overwrite .php files using theme, you have to create new module in app/code/Vendor/Module, and create an etc/di.xml file inside this module.
This should be inside di.xml file:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Block\Product\View\Options\Type\Select" type="Vendor\Module\Block\Product\View\Options\Type\Select" />
</config>

Vendor\Module\Block\Product\View\Options\Type\Select should extend Magento\Catalog\Block\Product\View\Options\Type\Select
or using plugin http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html


text:
Q: Regex, are "[ ]" and "( )" mean the same (space)? I have one a question regarding regex
This is my string...
cook, eat, write, play

In a lot of regex I made before I always refer to space by using ( ) I know I should avoid using \s to refer to space, because it includes carriage return, line feed, etc, But why you refer to space using [ ] in this regex below?
(^)?(?:,[ ])?write(?(1),[ ])

I have try to replace the [ ] with ( ) in it, like this...
(^)?(?:,( ))?write(?(1),( ))

But if I do so, the regex doesn't work anymore, why is that?
Why you can refer to space using ( ) in some regex, and why you can not do it in this regex example above?

A: () by default delineates a capture group. (?: ...) is a non-capturing group. By delineating a space as ( ) you are matching on a space and capturing that space in a capture group.
(?(1), [ ]) is a test for if the first capture group (^) was matched, and if it is, an additional match is performed for the bit in the group.
You don't need to add () or [] around a space to match on it; the literal  character will work fine too!
Your regex still works, FWIW, but I suspect you're relying on capture group indices elsewhere, which is why it's breaking; you've added more capture groups! You can also avoid this kind of dependence on specific group placement by using named capture group:
(?<start>^)?(, )?write(?(<start>), )

In this case, I'm naming the initial capture group <start>, and then later, we can test if <start> was matched by name, rather than by index, so that even if you add or remove capture groups, your test always refers to the same capture.
You could also simplify this quite a bit by just having two variants of the match, to avoid testing captures:
/^write, |, write/

That is, either the string must match the start of the line and the string "write, ", or it must match ", write". The same sentiment is expressed without having to worry about backreference testing.


text:
Q: PHP method signature has no parameters method call has one parameter no warning Hello I am trying to make a simple class that has a method with no parameters. With method call I am putting in one parameter to fail a test but the test passes. And if I run the code in browser everything runs with no warning. I am on a development environment so php should detect such violations.
This is the method signature
    public function getServiceDetail(): ServiceDetail
    {
        ...
    }

This is the call
...

$this->repository->getServiceDetail(1);

...

The result of the above is just fine I get the detail from the logic that is in the method no warnings or errors.
Edit: If I put wrong type into signature of the method I get the proper error since I have strict_types on.

A: PHP doesn't care about that because all php functions are variadic by nature. This is why func_get_args exists. Anything you hand to a php function/method is assumed valid unless otherwise explicitly defined as invalid. In other words, you must define a prototype and the call must then explicitly defy that prototype for it be considered invalid.
For example:
function foo(Array $bar, String $baz) {
    var_dump(func_get_args());
}

foo([1], "quix", new stdclass); // is perfectly legal in php

You get

array(3) {
  [0]=>
  array(1) {
    [0]=>
    int(1)
  }
  [1]=>
  string(4) "quix"
  [2]=>
  object(stdClass)#1 (0) {
  }
}

From the manual:

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.


text:
Q: NSFileManager createDirectoryAtPath:withIntermediateDirectories: Not creating directories or creating errors In my app, when a user makes an in app purchase, the application needs to download and unzip a zip file to the app's documents folder. The zip file downloads and can be unzipped. I'm using Objective Zip to unzip the archive. The problem is that when trying to create the folder paths for each file, the folders are never created, and there is no error.
Here is some sample code for the section where this is happening:
// Create file manager
NSFileManager *fileMgr = [NSFileManager defaultManager];

//Unzip
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
ZipFile *unzipFile = [[ZipFile alloc] initWithFileName:[applicationDocumentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",@"Mid America Oireachtas 2011"]] mode:ZipFileModeUnzip];
NSArray *infos= [unzipFile listFileInZipInfos];
for (FileInZipInfo *info in infos) {
    //NSLog(@"- %@ %@ %d (%d)", info.name, info.date, info.size, info.level);

    // Locate the file in the zip
    [unzipFile locateFileInZip:info.name];

    // Expand the file in memory
    ZipReadStream *read= [unzipFile readCurrentFileInZip];
    NSMutableData *data= [[NSMutableData alloc] initWithLength:info.length];
    int bytesRead = [read readDataWithBuffer:data];
    [read finishedReading];
    NSString *appSupportFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *pathfull = [appSupportFolder stringByAppendingPathComponent:info.name];
    NSString *path = [[pathfull stringByDeletingLastPathComponent] copy];
    NSError *errorw;
    NSRange range = [path rangeOfString:@"__MACOSX"];
    if (range.location == NSNotFound) {
        NSLog(@"last: %@", [path lastPathComponent]);
        if ([fileMgr createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&errorw]) {
            NSLog(@"Create Folder: %@", path);
            NSLog(@"Directory Win: %@", errorw);
            if (![[pathfull pathExtension] isEqualToString:@""] && ![[[pathfull lastPathComponent] substringToIndex:1] isEqualToString:@"." ]) {
                [data writeToFile:pathfull atomically:NO];
            }
        }
        else {
            //NSLog(@"Create Folder: %@", path);
            NSLog(@"Directroy Fail: %@", errorw);
        }
    }
}

[unzipFile close];

//delete zip
// For error information
NSError *error;

if ([fileMgr removeItemAtPath:[applicationDocumentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",@"Mid America Oireachtas 2011"]] error:&error] == YES) {
    NSLog(@"File Deleted");
}

//delete zip
// For error information
NSError *error;

if ([fileMgr removeItemAtPath:[applicationDocumentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",@"My Zip"]] error:&error] == YES) {
    NSLog(@"File Deleted");
}

Here is relevant snippet of output from the log file:
    2012-01-04 17:12:51.509 WhatsMyStageOn[3232:15503] Create Folder: /Users/Brandon/Library/Application Support/iPhone Simulator/5.0/Applications/436C2C49-D79B-4CDA-B0AA-15BB98F6F75E/WhatsMyStageOn.app/
    2012-01-04 17:12:51.510 WhatsMyStageOn[3232:15503] Directory Win: (null)
    2012-01-04 17:12:51.510 WhatsMyStageOn[3232:15503] Create Folder: /Users/Brandon/Library/Application Support/iPhone Simulator/5.0/Applications/436C2C49-D79B-4CDA-B0AA-15BB98F6F75E/WhatsMyStageOn.app/Documents/Mid America Oireachtas 2011
    2012-01-04 17:12:51.510 WhatsMyStageOn[3232:15503] Directory Win: (null)
    2012-01-04 17:12:51.510 WhatsMyStageOn[3232:15503] Create Folder: /Users/Brandon/Library/Application Support/iPhone Simulator/5.0/Applications/436C2C49-D79B-4CDA-B0AA-15BB98F6F75E/WhatsMyStageOn.app/Documents
    2012-01-04 17:12:51.510 WhatsMyStageOn[3232:15503] Directory Win: (null)
    2012-01-04 17:12:51.511 WhatsMyStageOn[3232:15503] Create Folder: /Users/Brandon/Library/Application Support/iPhone Simulator/5.0/Applications/436C2C49-D79B-4CDA-B0AA-15BB98F6F75E/WhatsMyStageOn.app/Documents/__MACOSX
    2012-01-04 17:12:51.511 WhatsMyStageOn[3232:15503] Directory Win: (null)
    2012-01-04 17:12:51.511 WhatsMyStageOn[3232:15503] Create Folder: /Users/Brandon/Library/Application Support/iPhone Simulator/5.0/Applications/436C2C49-D79B-4CDA-B0AA-15BB98F6F75E/WhatsMyStageOn.app/Documents/__MACOSX/Mid America Oireachtas 2011
    2012-01-04 17:12:51.511 WhatsMyStageOn[3232:15503] Directory Win: (null)
    2012-01-04 17:12:51.511 WhatsMyStageOn[3232:15503] Create Folder: /Users/Brandon/Library/Application Support/iPhone Simulator/5.0/Applications/436C2C49-D79B-4CDA-B0AA-15BB98F6F75E/WhatsMyStageOn.app/Documents/Mid America Oireachtas 2011
    2012-01-04 17:12:51.512 WhatsMyStageOn[3232:15503] Directory Win: (null)
    2012-01-04 17:12:51.544 WhatsMyStageOn[3232:15503] Create Folder: /Users/Brandon/Library/Application Support/iPhone Simulator/5.0/Applications/436C2C49-D79B-4CDA-B0AA-15BB98F6F75E/WhatsMyStageOn.app/Documents/Mid America Oireachtas 2011/Attractions
    2012-01-04 17:12:51.544 WhatsMyStageOn[3232:15503] Directory Win: (null)

Reading the NSFileManager documentation, this is what should output in the log, but, No folders are created.
EDIT: Fixed not using documents issue, still have same problem as decried before edit.
EDIT: Updated code to working solution!

A: You shouldn't be writing to the app's bundle itself. Try this:
NSString *appSupportFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [appSupportFolder stringByAppendingPathComponent:info.name];

A: I don't think you're able to create directories directly inside of WhatsMyStageOn.app/, try creating them inside of your Documents directory.
NSMutableString *path = [info.name mutableCopy];
path = [[path stringByDeletingLastPathComponent] mutableCopy];
path = [NSMutableString  stringWithFormat:@"%@/%@", applicationDocumentsDir, path];

You have a line at the bottom that deletes the correct file path inside of Documents, but your original path variable points at the bundle directory, not the Documents directory.


text:
Q: How do I know when kendo treeview has finished loading? I'm trying the Kendo Ui framework. I'm working on a treeview.
I need to know if there is an event that is raised when it is finished loading the complete treeview. I'm using a call json.

A: Loading it or rendering it? It is similar but not the same, first you need to load the data and only then it starts rendering the loaded items.
For loading you might use dataBound in the TreeView


text:
Q: Javascript date validation - year and full stops Checking fields:
checkFields = function() {
  var colCheck = 0;
  var colArray = [];
  var colDupArray = [];
  var iDate = $("check_date").value;
  if(iDate.length > 0) {
    var a = iDate.split("/");
    if(isValidDate(a[0],a[1]-1,a[2]) == false){
      alert("You have entered an invalid date. Please amend!");
      return false;
    }

Validation:
isValidDate = function(day,month,year) {
  var dteDate;
  dteDate=new Date(year,month,day);

  var day = dteDate.getDate();
  var month = dteDate.getMonth() + 1;
  var year = dteDate.getFullYear();

  var formatted =
      (day < 10 ? "0" : "") + day + "/"  +
      (month < 10 ? "0" : "") + month + "/"  +
      year;

  return
+day === dteDate.getDate() &&
+month === dteDate.getMonth() &&
+year === dteDate.getFullYear();
}

The problem is that my code is accepting a date such as "03.06.2012" when I only want it to accept slashes between the numbers.
It also accepts "03/06/12" when I only want a four digit year.
Any ideas?

A: As suggested this let's the user enter a date in a format of choice. The output should be as expected for you.
I've expanded my little demo with a Date.prototype.formatDateField and a library called moment which also seems to be pretty clean. As third option the jQuery-UI $.datepicker.formatDate()
Still this isn't bulletproof and maybe you should look for a datepicker which can handle the format for you. The best solution to your problem imho.
If you want to go custom however this might get you started:
// prototype
Date.prototype.formatDateField = function (options) {
    var i = 0,
        date = [],
        len = date.push(this.getDate(), this.getMonth() + 1, this.getFullYear());

    for (; i < len; i += 1) {
        var chunk = date[i];
        date[i] = chunk < 10 ? options.pad + chunk : chunk;
    }

    return date.join(options.separator);
};

// Setup output
var cfg = {
    fieldDate: "#fieldDate",
    options: {
        pad: "0",
        format: "dd/MM/yyyy",
        separator: "/"
    }
};

// function to call
function reformatInput(){
    $(cfg.date).blur(function(){
        var moment = moment(this.value).calendar(cfg.options2.format),
            prot = new Date(this.value).formatDateField(cfg.options2),
            jqueryui = $.datepicker.formatDate(cfg.options2.format, new Date(this.value));

        $(cfg.fieldDate1).val(moment);
        $(cfg.fieldDate2).val(prot);
        $(cfg.fieldDate3).val(jqueryui);
    });
}

// run on demand
reformatInput();

demo: http://jsfiddle.net/tive/YvdKA/

A: At least for the four-digit-year problem, look at this jfiddle output and the code:
d1 = new Date(1,2,3);
d2 = d1.getFullYear();
d3 = d1.getMonth();
d4 = d1.getDay();
alert(d2);
alert(d3);
alert(d4);

The Date constructor is not strict about four year digits (despite what Mozilla says you should do). In the example above, it's even taking the int 1 as a year! That is reflecting in your program accepting years that aren't 4 characters in length.
Perhaps test the length of the year string?
As for the split, perhaps you can use a regular expression that would both split and make sure that you're only accepting slashes (as suggested here)?

A: You somehow mixed a formatting with a validating function. This is how it should be:
function isValidDate(day,month,year) {
    var dteDate = new Date(year,month,day);

    return +day === dteDate.getDate()
        && +month === dteDate.getMonth()
        && +year === dteDate.getFullYear();
}
function formatDate(dteDate) {
    var day = dteDate.getDate(),
        month = dteDate.getMonth() + 1,
        year = dteDate.getFullYear();

    var formatted = (day < 10 ? "0" : "") + day + "/"
                  + (month < 10 ? "0" : "") + month + "/"
                  + year;
    return formatted;
}


text:
Q: How to associate two tables without association table? It's currently i am using .In that i want to reduces the association table .And attain the same objective.Kindly some one help me to find solution.
 CREATE TABLE sys_student_t (
 student_id MEDIUMINT NOT NULL AUTO_INCREMENT,
 student_name VARCHAR(255),
 PRIMARY KEY (student_id)
);

 CREATE TABLE sys_classrooms_t (
  classroom_id MEDIUMINT NOT NULL AUTO_INCREMENT,
  classroom_name VARCHAR(255),
  PRIMARY KEY (classroom_id)
 );

 CREATE TABLE student_classroom_association_t (
  association_id MEDIUMINT NOT NULL AUTO_INCREMENT,
  classroom_id MEDIUMINT NOT NULL,
  student_id MEDIUMINT NOT NULL,
  FOREIGN KEY (student_id) REFERENCES sys_student_t (student_id),
  FOREIGN KEY (classroom_id) REFERENCES sys_classrooms_t    (classroom_id),
  PRIMARY KEY (association_id)
 );

Here is fiddle link :- http://www.sqlfiddle.com/#!9/ada4fd/2
thanks

A: A "Many-To-Many" relationship will always require an additional table. The only thing you can do is changing the primary key of the association table to the pair student_id and classroom_id.
CREATE TABLE student_classroom_association_t (
  classroom_id MEDIUMINT NOT NULL,
  student_id MEDIUMINT NOT NULL,
  FOREIGN KEY (student_id) REFERENCES sys_student_t (student_id),
  FOREIGN KEY (classroom_id) REFERENCES sys_classrooms_t    (classroom_id),
  PRIMARY KEY (student_id, classroom_id)
 );


text:
Q: Generating Hibernate Mapping Files and POJOs from Database with netbeans I just reinstalled everything on my computer and had to setup Netbeans again.
I've opened a hibernate project and I've just added 3 new tables to the database.
I've attempted to map these files by using "Hibernate Mapping Files and POJOs from Database".
However, Netbeans gives me the following error:
INFO [org.netbeans.modules.hibernate.wizards.HibernateCodeGenWizardDescriptor]: access to hibernate fails.
org.hibernate.HibernateException: could not instantiate QueryTranslatorFactory: org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory
    at org.hibernate.cfg.SettingsFactory.createQueryTranslatorFactory(SettingsFactory.java:391)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:222)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2005)
    at org.hibernate.cfg.JDBCMetaDataConfiguration.readFromJDBC(JDBCMetaDataConfiguration.java:40)
    at org.netbeans.modules.hibernate.wizards.HibernateCodeGenWizardDescriptor.checkConfig(HibernateCodeGenWizardDescriptor.java:282)
    at org.netbeans.modules.hibernate.wizards.HibernateCodeGenWizardDescriptor.isValid(HibernateCodeGenWizardDescriptor.java:177)
    at org.openide.WizardDescriptor.updateStateOpen(WizardDescriptor.java:872)
    at org.openide.WizardDescriptor.updateState(WizardDescriptor.java:820)
    at org.openide.loaders.TemplateWizard.updateState(TemplateWizard.java:754)
    at org.netbeans.modules.project.ui.NewFileWizard.updateState(NewFileWizard.java:124)
    at org.openide.WizardDescriptor._updateState(WizardDescriptor.java:798)
    at org.openide.WizardDescriptor.goToNextStep(WizardDescriptor.java:1070)
    at org.openide.WizardDescriptor.access$1800(WizardDescriptor.java:90)
    at org.openide.WizardDescriptor$Listener$1.run(WizardDescriptor.java:2122)
    at org.openide.WizardDescriptor.lazyValidate(WizardDescriptor.java:1502)
    at org.openide.WizardDescriptor.access$1900(WizardDescriptor.java:90)
    at org.openide.WizardDescriptor$Listener.actionPerformed(WizardDescriptor.java:2141)
    at sun.reflect.GeneratedMethodAccessor231.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.openide.util.WeakListenerImpl$ProxyListener.invoke(WeakListenerImpl.java:457)
    at com.sun.proxy.$Proxy43.actionPerformed(Unknown Source)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:337)
    at org.openide.WizardDescriptor.doNextClick(WizardDescriptor.java:1618)
    at org.netbeans.modules.project.ui.TemplateChooserPanel$1.actionPerformed(TemplateChooserPanel.java:95)
    at org.netbeans.modules.project.ui.TemplateChooserPanelGUI$FileChooserBuilder.actionPerformed(TemplateChooserPanelGUI.java:418)
    at org.openide.explorer.view.ListView.performObjectAt(ListView.java:684)
    at org.openide.explorer.view.ListView$PopupSupport.mouseClicked(ListView.java:1327)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)
    at java.awt.Component.processMouseEvent(Component.java:6300)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
    at java.awt.Component.processEvent(Component.java:6062)
    at java.awt.Container.processEvent(Container.java:2039)
    at java.awt.Component.dispatchEventImpl(Component.java:4660)
    at java.awt.Container.dispatchEventImpl(Container.java:2097)
    at java.awt.Component.dispatchEvent(Component.java:4488)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4245)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166)
    at java.awt.Container.dispatchEventImpl(Container.java:2083)
    at java.awt.Window.dispatchEventImpl(Window.java:2489)
    at java.awt.Component.dispatchEvent(Component.java:4488)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:674)
    at java.awt.EventQueue.access$400(EventQueue.java:81)
    at java.awt.EventQueue$2.run(EventQueue.java:633)
    at java.awt.EventQueue$2.run(EventQueue.java:631)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:647)
    at java.awt.EventQueue$3.run(EventQueue.java:645)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:644)
    at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:159)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178)
    at java.awt.Dialog$1.run(Dialog.java:1052)
    at java.awt.Dialog$3.run(Dialog.java:1104)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Dialog.show(Dialog.java:1102)
    at org.netbeans.core.windows.services.NbPresenter.superShow(NbPresenter.java:1076)
    at org.netbeans.core.windows.services.NbPresenter.doShow(NbPresenter.java:1126)
    at org.netbeans.core.windows.services.NbPresenter.run(NbPresenter.java:1098)
    at org.netbeans.core.windows.services.NbPresenter.run(NbPresenter.java:128)
    at org.openide.util.Mutex.doEventAccess(Mutex.java:1363)
    at org.openide.util.Mutex.readAccess(Mutex.java:273)
    at org.netbeans.core.windows.services.NbPresenter.show(NbPresenter.java:1083)
    at java.awt.Component.show(Component.java:1591)
    at java.awt.Component.setVisible(Component.java:1543)
    at java.awt.Window.setVisible(Window.java:843)
    at java.awt.Dialog.setVisible(Dialog.java:987)
    at org.netbeans.core.windows.services.DialogDisplayerImpl$1AWTQuery.showDialog(DialogDisplayerImpl.java:260)
    at org.netbeans.core.windows.services.DialogDisplayerImpl$1AWTQuery.run(DialogDisplayerImpl.java:186)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:672)
    at java.awt.EventQueue.access$400(EventQueue.java:81)
    at java.awt.EventQueue$2.run(EventQueue.java:633)
    at java.awt.EventQueue$2.run(EventQueue.java:631)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:642)
    at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:159)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.lang.ClassCastException: org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory cannot be cast to org.hibernate.hql.QueryTranslatorFactory
    at org.hibernate.cfg.SettingsFactory.createQueryTranslatorFactory(SettingsFactory.java:388)
    ... 94 more

My hibernate.cfg file looks like the following:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="hibernate.connection.url">jdbc:sqlserver://SERVER:PORT;databaseName=NAME</property>
    <property name="hibernate.connection.username">USER</property>
    <property name="hibernate.connection.password">PASS</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
    <mapping resource="com/bmw/resources/LocationDept.hbm.xml"/>
</session-factory>
</hibernate-configuration>

I'm connecting to SQL Server 2008 database.
I'm using Hibernate 4.2.0 and have the following JARs in my classpath:
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.2.0.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
hibernate-entitymanager-4.2.0.Final.jar
sqljdbc4.jar
log4j-1.2.17.jar

Any ideas?

A: This is what worked for me:
change hibernate.query.factory_class to org.hibernate.hql.classic.ClassicQueryTranslatorFactory and then go for the Hibernate Mapping Files and POJOs from Database step
After you are done with that change it back to org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory


text:
Q: map not loading when integrating google map api iOS I want to show current location in my app using Google Map API.
I have used Google map API in our project I followed all steps  from "here".
I have also given proper API key and bundle identifier but map is not loading only simple blank and last Google button show.
And I have used same API key in demo of "GoogleMaps-iOS-1.9.1" it's in proper worked but not load map on my app.
so, please give any suggestion or source code which is apply in my code.
Thank You.

A: Use following steps:
In AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Put your API key here.
    [GMSServices provideAPIKey:GOOGLE_PRJ_API_KEY];
    return YES;
}

Somewhere in your class say MapsController use following code in will appear:
- (void)setupGoogleMap{
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude zoom:DEFAULT_ZOOM_LEVEL];
    if (!_googleMapView) {
        _googleMapView = [GMSMapView mapWithFrame:self.view.bounds camera:camera];
        [self.view insertSubview:_googleMapView atIndex:0];
        _googleMapView.settings.compassButton = YES;
        _googleMapView.myLocationEnabled = YES;
        [_googleMapView setDelegate:self];
    }
    _googleMapView.camera = camera;
}

Do check with your provided API keys or try regenerating or set of iOS only keys with bundle identifier


text:
Q: Question on the construction of mapping from space of strategy profile into itself in Nash(1951) To appeal to Brouwer fixed point theorem, Nash(1951) constructed a continuous mapping $\operatorname{T}$ from strategy profile space into inself:
For player $i$, the probability of a pure strategy $a_{i} \in A_i$ is
$$\operatorname{T}s_i(a_i) = \frac{s_i(a_i) + \phi_{i, a_i}(s)}{1+\sum_{b_i \in A_i}\phi_{i, b_i}(s)}$$
in which, $A_i$ is the player $i$'s pure strategy space, $s_i$ is a mixed strategy that assigns each pure strategy with its probability.$s$ is a strategy profile, a vector of every player's strategy.
My question is why we need $\phi_{i, a_i}(s) = \max \{0, u_i(a_i, s_{-i})-u_i( s)\}$? Why not to replace $\phi_{i, a_i}(s)$ with $u_i(a_i, s_{-i})-u_i( s)$, which is$$\operatorname{T'}s_i(a_i) = \frac{s_i(a_i) + u_i(a_i, s_{-i})-u_i( s)}{1+\sum_{b_i \in A_i}(u_i(b_i, s_{-i})-u_i( s))}$$
It seems to me, Besides being continuous, $\operatorname{T'}$ statisfies that $\sum_{b_i \in A_i}\operatorname{T'}s_i(b_i)=1$ and that a fixed point of $\operatorname{T'}$  necessarily constitutes a nash equilibrium.

A: To appeal to the Brouwer fixed point theorem, one wants this map to go from a nonempty, compact, and convex to itself. Using the "max", we know the map goes from the compact unit  simplex to itself. Your map would map oints in the unit simplex to points outside the unit simplex.


text:
Q: Accept working copy "as is" in Subversion Is there a simple way to accept the working copy "as is" in Subversion? I would like to have the "unknown" files denoted by ? to be added, missing files to be deleted and changed files commited.

A: a svn commit would commit the modified files, but for:

*

*the deleted files, you need first (before the commit) a command like

    $ svn status | grep '^\!' | sed 's/! *//' | xargs -I% svn rm %

*

*the files added (with spaces in them):

   $ svn status | grep "^\?" | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add

On recent SVN you could just svn add --force * (it is recursive)

A: There isn't a single svn command that does all that at once.
Here is a simple bash script that deletes missing files:
for i in `svn list -R`; do if [ ! -e $i ]; then svn rm $i; fi; done

A: If your on windows use TortiseSVN it will show you a list of all the new/deleted files and you can just select all the changes and commit.