text:
Q: How to display video from path_provider in flutter? FLutter:
How to display video in video_player from the location of path_provider ?

A: you can copy paste run full code below
In demo, I use getApplicationDocumentsDirectory. you can print full path to check
make sure you have a file located in
/data/user/0/your_proejct_name/app_flutter/Movies/2019-11-08.mp4
code snippet
Future<String> load_path_video() async {
    loading = true;
    final Directory extDir = await getApplicationDocumentsDirectory();

    setState(() {
      dirPath = '${extDir.path}/Movies/2019-11-08.mp4';
      print(dirPath);
      loading = false;
      // if I print ($dirPath) I have /data/user/0/com.XXXXX.flutter_video_test/app_flutter/Movies/2019-11-08.mp4
    });
  }

Container(
            padding: const EdgeInsets.all(20),
            child: loading
                ? CircularProgressIndicator()
                : NetworkPlayerLifeCycle(
                    '$dirPath', // with the String dirPath I have error but if I use the same path but write like this  /data/user/0/com.XXXXX.flutter_video_test/app_flutter/Movies/2019-11-08.mp4 it's ok ... why ?
                    (BuildContext context, VideoPlayerController controller) =>
                        AspectRatioVideo(controller)),
          ),

working demo

full code
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:video_player/video_player.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String dirPath;
  bool loading = false;

  Future<String> load_path_video() async {
    loading = true;
    final Directory extDir = await getApplicationDocumentsDirectory();

    setState(() {
      dirPath = '${extDir.path}/Movies/2019-11-08.mp4';
      print(dirPath);
      loading = false;
      // if I print ($dirPath) I have /data/user/0/com.XXXXX.flutter_video_test/app_flutter/Movies/2019-11-08.mp4
    });
  }

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    load_path_video();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      body: ListView(
        children: <Widget>[
          Container(
            padding: const EdgeInsets.all(20),
            child: loading
                ? CircularProgressIndicator()
                : NetworkPlayerLifeCycle(
                    '$dirPath', // with the String dirPath I have error but if I use the same path but write like this  /data/user/0/com.XXXXX.flutter_video_test/app_flutter/Movies/2019-11-08.mp4 it's ok ... why ?
                    (BuildContext context, VideoPlayerController controller) =>
                        AspectRatioVideo(controller)),
          ),
        ],
      ),
    );
  }
}

class VideoPlayPause extends StatefulWidget {
  VideoPlayPause(this.controller);

  final VideoPlayerController controller;

  @override
  State createState() {
    return _VideoPlayPauseState();
  }
}

class _VideoPlayPauseState extends State<VideoPlayPause> {
  _VideoPlayPauseState() {
    listener = () {
      setState(() {});
    };
  }

  FadeAnimation imageFadeAnim =
      FadeAnimation(child: const Icon(Icons.play_arrow, size: 100.0));
  VoidCallback listener;

  VideoPlayerController get controller => widget.controller;

  @override
  void initState() {
    super.initState();
    controller.addListener(listener);
    controller.setVolume(1.0);
    controller.play();
  }

  @override
  void deactivate() {
    controller.setVolume(0.0);
    controller.removeListener(listener);
    super.deactivate();
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> children = <Widget>[
      GestureDetector(
        child: VideoPlayer(controller),
        onTap: () {
          if (!controller.value.initialized) {
            return;
          }
          if (controller.value.isPlaying) {
            imageFadeAnim =
                FadeAnimation(child: const Icon(Icons.pause, size: 100.0));
            controller.pause();
          } else {
            imageFadeAnim =
                FadeAnimation(child: const Icon(Icons.play_arrow, size: 100.0));
            controller.play();
          }
        },
      ),
      Align(
        alignment: Alignment.bottomCenter,
        child: VideoProgressIndicator(
          controller,
          allowScrubbing: true,
        ),
      ),
      Center(child: imageFadeAnim),
      Center(
          child: controller.value.isBuffering
              ? const CircularProgressIndicator()
              : null),
    ];

    return Stack(
      fit: StackFit.passthrough,
      children: children,
    );
  }
}

class FadeAnimation extends StatefulWidget {
  FadeAnimation(
      {this.child, this.duration = const Duration(milliseconds: 500)});

  final Widget child;
  final Duration duration;

  @override
  _FadeAnimationState createState() => _FadeAnimationState();
}

class _FadeAnimationState extends State<FadeAnimation>
    with SingleTickerProviderStateMixin {
  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController =
        AnimationController(duration: widget.duration, vsync: this);
    animationController.addListener(() {
      if (mounted) {
        setState(() {});
      }
    });
    animationController.forward(from: 0.0);
  }

  @override
  void deactivate() {
    animationController.stop();
    super.deactivate();
  }

  @override
  void didUpdateWidget(FadeAnimation oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.child != widget.child) {
      animationController.forward(from: 0.0);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return animationController.isAnimating
        ? Opacity(
            opacity: 1.0 - animationController.value,
            child: widget.child,
          )
        : Container();
  }
}

typedef Widget VideoWidgetBuilder(
    BuildContext context, VideoPlayerController controller);

abstract class PlayerLifeCycle extends StatefulWidget {
  PlayerLifeCycle(this.dataSource, this.childBuilder);

  final VideoWidgetBuilder childBuilder;
  final String dataSource;
}

/// A widget connecting its life cycle to a [VideoPlayerController] using
/// a data source from the network.
class NetworkPlayerLifeCycle extends PlayerLifeCycle {
  NetworkPlayerLifeCycle(String dataSource, VideoWidgetBuilder childBuilder)
      : super(dataSource, childBuilder);

  @override
  _NetworkPlayerLifeCycleState createState() => _NetworkPlayerLifeCycleState();
}

/// A widget connecting its life cycle to a [VideoPlayerController] using
/// an asset as data source
class AssetPlayerLifeCycle extends PlayerLifeCycle {
  AssetPlayerLifeCycle(String dataSource, VideoWidgetBuilder childBuilder)
      : super(dataSource, childBuilder);

  @override
  _AssetPlayerLifeCycleState createState() => _AssetPlayerLifeCycleState();
}

abstract class _PlayerLifeCycleState extends State<PlayerLifeCycle> {
  VideoPlayerController controller;

  @override

  /// Subclasses should implement [createVideoPlayerController], which is used
  /// by this method.
  void initState() {
    super.initState();
    controller = createVideoPlayerController();
    controller.addListener(() {
      if (controller.value.hasError) {
        print(controller.value.errorDescription);
      }
    });
    controller.initialize();
    controller.setLooping(true);
    controller.play();
  }

  @override
  void deactivate() {
    super.deactivate();
  }

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

  @override
  Widget build(BuildContext context) {
    return widget.childBuilder(context, controller);
  }

  VideoPlayerController createVideoPlayerController();
}

class _NetworkPlayerLifeCycleState extends _PlayerLifeCycleState {
  @override
  VideoPlayerController createVideoPlayerController() {
    return VideoPlayerController.network(widget.dataSource);
  }
}

class _AssetPlayerLifeCycleState extends _PlayerLifeCycleState {
  @override
  VideoPlayerController createVideoPlayerController() {
    return VideoPlayerController.asset(widget.dataSource);
  }
}

/// A filler card to show the video in a list of scrolling contents.
Widget buildCard(String title) {
  return Card(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        ListTile(
          leading: const Icon(Icons.airline_seat_flat_angled),
          title: Text(title),
        ),
        // TODO(jackson): Remove when deprecation is on stable branch
        // ignore: deprecated_member_use
        ButtonTheme.bar(
          child: ButtonBar(
            children: <Widget>[
              FlatButton(
                child: const Text('BUY TICKETS'),
                onPressed: () {
                  /* ... */
                },
              ),
              FlatButton(
                child: const Text('SELL TICKETS'),
                onPressed: () {
                  /* ... */
                },
              ),
            ],
          ),
        ),
      ],
    ),
  );
}

class VideoInListOfCards extends StatelessWidget {
  VideoInListOfCards(this.controller);

  final VideoPlayerController controller;

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        buildCard("Item a"),
        buildCard("Item b"),
        buildCard("Item c"),
        buildCard("Item d"),
        buildCard("Item e"),
        buildCard("Item f"),
        buildCard("Item g"),
        Card(
            child: Column(children: <Widget>[
          Column(
            children: <Widget>[
              const ListTile(
                leading: Icon(Icons.cake),
                title: Text("Video video"),
              ),
              Stack(
                  alignment: FractionalOffset.bottomRight +
                      const FractionalOffset(-0.1, -0.1),
                  children: <Widget>[
                    AspectRatioVideo(controller),
                    Image.asset('assets/flutter-mark-square-64.png'),
                  ]),
            ],
          ),
        ])),
        buildCard("Item h"),
        buildCard("Item i"),
        buildCard("Item j"),
        buildCard("Item k"),
        buildCard("Item l"),
      ],
    );
  }
}

class AspectRatioVideo extends StatefulWidget {
  AspectRatioVideo(this.controller);

  final VideoPlayerController controller;

  @override
  AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController get controller => widget.controller;
  bool initialized = false;

  VoidCallback listener;

  @override
  void initState() {
    super.initState();
    listener = () {
      if (!mounted) {
        return;
      }
      if (initialized != controller.value.initialized) {
        initialized = controller.value.initialized;
        setState(() {});
      }
    };
    controller.addListener(listener);
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller.value.aspectRatio,
          child: VideoPlayPause(controller),
        ),
      );
    } else {
      return Container();
    }
  }
}


text:
Q: Perf($\mathscr{A}$) and perfect chain complexes Suppose $\mathscr{A}$ is a dg category and $ \mathcal{D} (\mathscr{A})$ its associated derived category. For an object in $ a \in \mathscr{A}$ there is associated (right )dg $ \mathscr{A}$ module,  $ \hat{a} := \mathscr{A} (?, a)$. One can define the subcategory $ \text{Perf}(\mathscr{A})$ of $ \mathcal{D} ( \mathscr{A})$  as the smallest thick subcategory ( i.e. strict, triangulated and closed under taking direct summands) containing the set of objects $\{ \hat{a}| a \in \mathscr{A} \}$.
Suppose we take our dg category is  $ \mathscr{A}:= k$ i.e. the category with one object whose endomorphism space is some commutative ring $k$. Then $\mathcal{D}( k)$ is just the derived category category of chain complexes over $k$.
Question: How does one see that an object in Perf($k$), as defined above, is a perfect chain complex in the usual sense of homological algebra, i.e. quasi-isomorphic to a bounded complex of finitely generated projectives without using the fact that these are just the compact objects? ( or is this even possible?)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loading Property file only when it is changed Guys  i have created a properties file outside the jboss classpath
(I kept outside because i can change during runtime and the values will be reflected).
I am loading this property file (like System.getProperty("jboss.base.dir.home")) everytime to do rmi lookup .I think that everytime loading the same file, eventhough it is not changed is pain.
I want ideas , how to detect the change in properties file and load only when there is a change.i thought of having the timestamp of lastmodified .kindly let me know your suggestions.

A: You could reuse Apache commons to read the property file :
http://commons.apache.org/configuration/userguide/howto_filebased.html#Automatic_Reloading
OR
You could do it programatillcay yourself. This would reimplementing the apache commons code - probably with far less testing and more error prone. If you insist on this approach here is that I think you can do :

*

*Use a wrapper class on a Properties instance.

*This wrapper class should (when initialized) load the properties file from the predefined location (probably configurable)

*The wrapper, post init, should start a thread that would run forever and do this :

*

*record the modified timestamp of the properties file recently read (see methods in File class)

*sleep for a configurable time period

*wake up and check the modified timestamp of the properties file

*if there is a difference in the timestamps - reload the properties file into the Properties instance. Remember this must be done in isolation (i.e change the object when no ones accessing it).

HTH

A: Perhaps you could do this with a naming convention. For example, if there are no changes the file would be named (whatever you name it now) for example:
foo.properties

But, on the other hand, if you wish to change it, you could name it something like:
foo.properties-changed

You could then programmatically look for the '-changed' file, load it, and then strip off the suffix.

A: This solution was inspired by javamonkey79's answer and by the way hot deployment is handled in JBoss EAP 6.1.0. Instead of renaming the foo.properties file whenever I change it, I created an additional foo.updated file in the same directory. Whenever I change the settings in the foo.properties file, I rename foo.updated to foo.doUpdate.
In the singleton bean that loads the settings from the foo.properties file on startup, before I try to get a certain value from the bean, I first check if there is a foo.doUpdate file in the configuration directory. If so, I read the settings from the foo.properties file, and then delete foo.doUpdate and create a new file named foo.updated.


text:
Q: Nodes creation error in Ns2 I have implemented a new routing protocol named TRLR in ns-2.34. I am using fedora 13. I have modified ns-lib.tcl, ns-packet.tcl, priqueue.cc, packet.h, cmu-trace.{cc,h}. Then make clean, make and make install have completed successfully. Then I have tried to run this protocol using trlr_2.tcl and I got this strange error. I have no idea how to fix this error neither have I found an acceptable answer to this question anywhere. Please help me out. Any help would be appreciated. Thanks in advance!!!
[root@Care Desktop]# ns trlr_5.tcl
num_nodes is set 5
warning: Please use -channel as shown in tcl/ex/wireless-mitf.tcl
INITIALIZE THE LIST xListHead

(_o17 cmd line 1)
    invoked from within
"_o17 cmd tracetarget _o31"
    invoked from within
"catch "$self cmd $args" ret"
    invoked from within
"if [catch "$self cmd $args" ret] {
set cls [$self info class]
global errorInfo
set savedInfo $errorInfo
error "error when calling class $cls: $args" $..."
    (procedure "_o17" line 2)
    (SplitObject unknown line 2)
    invoked from within
"$ragent tracetarget $T"
   (procedure "_o14" line 14)
   (Node/MobileNode agenttrace line 14)
    invoked from within
"$node agenttrace $tracefd"
   (procedure "_o3" line 106)
   (Simulator create-wireless-node line 106)
    invoked from within
"_o3 create-wireless-node"
    ("eval" body line 1)
    invoked from within
"eval $self create-wireless-node $args"
    (procedure "_o3" line 23)
    (Simulator node line 23)
    invoked from within
"$ns_ node"
    ("for" body line 2)
    invoked from within
"for {set i 0} {$i < $val(nn) } {incr i} {
    set node_($i) [$ns_ node]
    $node_($i) random-motion 0      ;# disable random motion
}"
(file "trlr_5.tcl" line 97)

Well after some googling around, I think this error is caused by my command() function in my trlr.h and trlr.cc files. So, I am attaching chunks of command function in those files here too.
<<< trlr.h >>>
#include <cmu-trace.h>
#include <agent.h>
#include <classifier/classifier-port.h>

class TRLR: public Agent
{
private:
    routingTable rTable;
public:
    TRLR(nsaddr_t id);
    int  command(int, const char *const *);
protected:
    PortClassifier* dmux_;
    Trace* logtarget_;
    PriQueue* ifqueue;
};

<<< trlr.cc >>>
int TRLR::command(int argc, const char*const* argv) {
if(argc == 2) {
 Tcl& tcl = Tcl::instance();

if(strncasecmp(argv[1], "id", 2) == 0) {
  tcl.resultf("%d", index);
  return TCL_OK;
}

if(strncasecmp(argv[1], "start", 2) == 0) {
  rtimer.resched(0.0);
  return TCL_OK;
 }
}
else if(argc == 3) {
if(strcmp(argv[1], "index") == 0) {
  index = atoi(argv[2]);
  return TCL_OK;
}

else if (strcmp(argv[1], "port-dmux") == 0) {
    dmux_ = (PortClassifier *)TclObject::lookup(argv[2]);
if (dmux_ == 0) {
    fprintf (stderr, "%s: %s lookup of %s failed\n", __FILE__,
    argv[1], argv[2]);
    return TCL_ERROR;
}
return TCL_OK;
}

else if(strcmp(argv[1], "if-queue") == 0) {
ifqueue = (PriQueue*) TclObject::lookup(argv[2]);
  if(ifqueue == 0)
return TCL_ERROR;
  return TCL_OK;
}

else if (strcmp(argv[1], "log-target") == 0 || strcmp(argv[1], "tracetarget") == 0) {
    logtarget_ = (Trace*)TclObject::lookup(argv[2]);
if (logtarget_ == 0)
    return TCL_ERROR;
    return TCL_OK;
}
  }
return Agent::command(argc, argv);
}

Thanks in advance.


text:
Q: How to add child to the parent in firebase sequentially? I don't know if the title makes sense or not, so I will try to elaborate my problem here.
{
"rsvp":[
{"event": "event1","name": "name1","rsvp": "going"},
{"event": "event2","name": "name2","rsvp": "going"}
]
}

I would like to store the data in the above mentioned format where if the item comes from the same user it should overwrite but what I am getting now is
{ "rsvp": {"event": "event_here","name": "name_here","rsvp": "going"}}

and every time the value is getting updated irrespective of the user.
Here is my code implementation
    final Firebase firebase = new Firebase(Constant.FIREBASE_URL).child("rsvp");
    final HashMap<String, String> map1 = new HashMap<>();
    map1.put("rsvp", "going");
    map1.put("name", mUserName);
    map1.put("event", title);
    firebase.setValue(map1);

Please let me know where I am doing wrong. Thank you.
Update 1
I'm aware of the push() but while retrieving the data it will be a problem to extract the elements the push() gives the unique tag. Moreover the push()creates instance of each call hence lets say one user performs all three operations it will have three instances of it instead of one.
My Solution
Assuming firebase doesn't support what I am looking for here..
Here we have known UID as well as the event for which I planned on adding the rsvp.
So I have planned on making the data structure the following way,
{"rsvp":{"uid1":{"event1":{"status":"going","email":"someemail@email.com"},"event2":
{"status":"maybe","email":"someemail@email.com"}},
"uid1":{"event1":{"status":"going","email":"someemail@email.com"},"event2":
{"status":"maybe","email":"someemail@email.com"}}}}

But again this solution has restrictions where I won't be able to fetch other user's data from the another. Where I need to know who all member are going for the event.

A: Firebase has an unusual of dealing with arrays. That's because arrays are inherently hard to scale in a distributed multi-user system, such as Firebase. If you'd like to learn more, read this section of the Firebase documentation on arrays and lists.
Instead of storing the data in an array (which has numeric, sequential keys), I recommend storing it in a Firebase list. A Firebase list uses alpha-numeric keys. They are still always incrementing though, so just like array indices, they are great for storing sequential data.
final Firebase firebase = new Firebase(Constant.FIREBASE_URL).child("rsvp");
final HashMap<String, String> map1 = new HashMap<>();
map1.put("rsvp", "going");
map1.put("name", mUserName);
map1.put("event", title);
firebase.push().setValue(map1);

The only difference here is that the last line uses push() to generate a new child. The key will be a string (currently starting with -K) known as a push id. If you'd like to learn more about those, read this blog post on push ids - the 2^120 ways to ensure unique identifiers.
If you keep using push().setValue(...) to add your events to the list, they will show up in the order you added them. Just like with array indices, but now with an approach that will also work when many users are adding events at the same time.
Update
To read all responses for event1:
Query query = firebase.orderByChild("event").equalTo("event1");
query.addListenerForSingleValueEvent(new ValueEventListener() {
  public void onDataChange(DataSnapshot rsvpSnapshot) {
    for (DataSnapshot snapshot: rsvpSnapshot.getChildren()) {
      String name = snapshot.child("name").getValue(String.class);
      String rsvp = snapshot.child("rsvp").getValue(String.class);
      System.out.println(name+": "+rsvp);
    }
  }
});

A: { "rsvp": {"id"="id","event": "event_here","name": "name_here","rsvp": "going"}}
Change your json just check with id and if id is store then update data of particular id  otherwise store all data

A:     FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef;
    myRef=database.getReference().push().child("Email");
    myRef.setValue(nameValue);
    String key=myRef.getParent().getKey();
    myRef=database.getReference(key).child("Password");
    myRef.setValue(passwordValue);


text:
Q: items doesnt stick to bottom react nativr im trying to make a to-do list in react native and im trying to make the input and plus bar stick to the bottom and make it go up when i open the keyboard. when i use padding the bar sticks to bottom but i want to use flexbox to make it compatible with all phones. can someone help make stick it to bottom and make it go up with keyboard
task.js
    import React from 'react';
import {View, Text, SafeAreaView, StyleSheet, TextInput,KeyboardAvoidingView, TouchableWithoutFeedback, TouchableOpacity} from 'react-native';

const AddTask = () => {
    const handleAddTask = () => {
        Keyboard.dismiss();
        setTaskItems([...taskItems, task])
        setTask(null);
      }

  return (
        <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style ={styles.inputbuttons}
    >
        <TextInput style={styles.input} placeholder={'Write a task'}  />
        <TouchableOpacity onPress={() => handleAddTask()}>
        <View style = {styles.plus}>
            <Text>+</Text>
        </View>
        </TouchableOpacity>
        </KeyboardAvoidingView>
      );
};

const styles = StyleSheet.create({
  input: {
    height: 60,
    width:320,
    margin: 12,
    borderWidth: 1,
    padding: 10,
    borderRadius:20,

  },
  inputbuttons:{

    flexDirection:'row',
    alignItems:'center',
    justifyContent:'flex-end'
},
 plus:{
    width:60,
    height:60,
    borderWidth:1,
    borderColor:'black',
    textAlign:'right',
    borderRadius:'15',
    textAlign: 'center',
    justifyContent: 'center',
    fontSize:30
 }
});

export default AddTask;

app.js
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View,Button, Alert,Input } from 'react-native';
import Task from './components/Task';
import AddTask from './components/AddTask';

export default function App() {
  return (
    <View style={styles.container}>

      <View style = {styles.taskWrapper}>
        <Text style={styles.header}>Today's Tasks</Text>

      </View>

      <View style={styles.tasks}>
        <Task></Task>
        <Task></Task>

      </View>

      <View>
        <AddTask></AddTask>
      </View>
    </View>

  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#E8EAED',

  },
  taskWrapper:{
      paddingTop:80,
      paddingHorizontal:20
  },
  header:{
    fontSize:24,
    fontWeight:'bold'
  },
  tasks:{

  },
});

A: You should use KeyboardAvoidingView in your app component so that whenever keyboard gets activated then the component of App gets pushed.


text:
Q: Making a Legit Countdown Timer in SWIFT I'm trying to get a label to countdown when a button is pressed, showing the countdown in a (hr,min,sec) way. I've kind of tried to connect two different codes I found. Here's what I have:
*updated code (some psuedo code)*

var timer = NSTimer()

func timerResults() {
    let theDate = NSDate()
    var endTime = theDate //+ 6 hours
    let timeLeft = endTime - theDate
    timeLeftLabel.text = "\(timeLeft)"
}

@IBOutlet weak var timeLeftLabel: UILabel!

@IBAction func IBbtnUpdateTap(sender: UIButton){

        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerResults"), userInfo: nil, repeats: true)

    }

Also, how do I make this counting down actively happen even when the app isn't running? Essentially, I'm creating a reward system if the user comes back in 6 hours.

A: I can't give a long answer right now but the easiest way is as follows:
When the user starts the timer with some amount of seconds, calculate the exact date when the timer should end (end time = now + amount of seconds). Now you can update the label every display refresh with the calculated time remaining (time left = end time - now).
This way it's guaranteed to keep the time on app relaunches (of course you need to save the ending date with NSUserDefaults or something) and it also guarantees no fluctuations in timer speed (NSTimer wouldn't guarantee that)

A: The items you are missing or need correction are written below:
var startTime: NSDate = NSDate()
var endTime: NSDate?

func viewDidLoad() {
    let clock = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countdown", userInfo: nil, repeats: true)
    endTime = startTime.dateByAddingTimeInterval(21600)
}

func countdown() {
    printSecondsToHoursMinutesSeconds(Int(timeLeft()))
}

func timeLeft() -> Double {
    return endTime!.timeIntervalSinceNow
}

To measure the time when the app is not running requires saving the time when the app goes into the background and then comparing the saved time when the app is opened again. The time can be saved as an NSDate. A comparison between two NSDates can give you an NSTimeInterval, the number of elapsed seconds between the two dates. For example:
let remainingTime = savedTime.timeIntervalSinceNow

See applicationDidBecomeActive: and applicationDidEnterBackground: in your app delegate for the place to compare and save the date into NSUserDefaults.


text:
Q: How can I make a file generated on a web page available to the user as a download? This question is related to one I asked here on "How can I prompt the user for a save location from a Sharepoint page?"
What I need to do is, after generating a PDF thus:
        private void GeneratePDF(List<ListColumns> listOfListItems)
        {
            . . .
            //Create a stream that we can write to, in this case a MemoryStream
            StringBuilder sb = new StringBuilder();
            using (var ms = new MemoryStream())
            {
                using (var doc = new Document(PageSize.A4, 25, 25, 10, 10))
                {
                    //Create a writer that's bound to our PDF abstraction and our stream
                    using (var writer = PdfWriter.GetInstance(doc, ms))
                    {

                        //Open the document for writing
                        doc.Open();

                        Paragraph docTitle = new Paragraph("UCSC - Direct Payment Form", timesBold16UCSCBlue);
                        doc.Add(docTitle);

                        Paragraph subTitle = new Paragraph("(Not to be used for reimbursement of services)", timesRoman9Font);
                        subTitle.IndentationLeft = 20;
                        doc.Add(subTitle);

                        . . . // tons of iTextSharp PDF-generation code elided for brevity

                        String htmlToRenderAsPDF = sb.ToString();

                        //XMLWorker also reads from a TextReader and not directly from a string
                        using (var srHtml = new StringReader(htmlToRenderAsPDF))
                        {
                            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                        }

                        doc.Close();
                    }
                }
                try
                {
                    var bytes = ms.ToArray();
                    // This is currently saved to a location on the server such as C:\Users\TEMP.SP.005\Desktop\iTextSharpTest.pdf (but the number (such as
"005" irregularly increments))
                    String pdfFileID = GetYYYYMMDDAndUserNameAndAmount();
                    String pdfFileName = String.Format("DirectPayDynamic_{0}.pdf", pdfFileID);
                    String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);
                    String fileLinkBase = "Generated PDF: {1}";
                    String filelink = String.Format(fileLinkBase, fileFullpath, pdfFileName);
                    File.WriteAllBytes(fileFullpath, bytes);

                    var pdflink = new Label
                    {
                        CssClass = "finaff-webform-field-label",
                        Text = filelink
                    };
                    this.Controls.Add(pdflink);
                }
                catch (DocumentException dex)
                {
                    throw (dex);
                }
                catch (IOException ioex)
                {
                    throw (ioex);
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
        } // GeneratePDF

...afford the user the opportunity to save that file to their local machine (currently, it is being saved on the server).
IOW, what I basically want to do is replace this line:
String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);

...with something like:
String fileFullpath = "Hey, bloke (or blokette), where do you want to save this?"

This is obviously possible, and even somewhat common, as many websites will generate files for you and then allow you to save those
generated files to either a location you select or a default location, such as your downloads folder.
Either a server-side (C#) or a client-side (jQuery) solution is acceptable, although I prefer server-side, as that is where the PDF is being generated.

A: When I had to force an Excel spreadsheet to download to the client, I used this code, which may point you to where you are wanting to get:
Control xxx of type 'LinkButton' must be placed inside a form tag with runat=server
protected void ExportExcelFile(object Sender, EventArgs e) { //export to excel
        var grdResults = new DataGrid(); // REF: https://stackoverflow.com/q/28155089/153923
        if (periodCriteria.SelectedValue == "year") {
            grdResults = RollupDG;
        } else {
            grdResults = QuarterDG;
        }
        var response = HttpContext.Current.Response;
        response.Clear();
        response.Charset = String.Empty;
        response.ContentType = "application/vnd.ms-excel";
        response.AddHeader("Content-Disposition", "attachment; filename=GlBudgetReport.xls");
        using (var sw = new StringWriter()) {
            using (var htw = new HtmlTextWriter(sw)) {
                grdResults.RenderControl(htw);
                response.Write(sw.ToString());
                response.End();
            }
        }
}


text:
Q: OpenOffice inserted xml not visible for reading (but visible in xml source) I have problem with generating and inserting xml in existing document.
 <table:table table:template-name="default">
                <table:table-column />
                <table:table-column />
                <table:table-column />
                <table:table-row>
                  <table:table-cell>
                    <text:p>1</text:p>
                  </table:table-cell>
                  <table:table-cell>
                    <text:p>2</text:p>
                  </table:table-cell>
                  <table:table-cell>
                    <text:p>3</text:p>
                  </table:table-cell>
                </table:table-row>
</table:table>

This code i successfully inserted in document (and it visible in document xml) but not visible for reading. Bottom line: Inserted xml exists in source, but not visible.
xml table example taken from: http://user.services.openoffice.org/en/forum/viewtopic.php?f=10&t=28229
Note: Generated document xml is valid - no tag mismatch here.
And im using OpenOffice template document (.ott)

A: Sorry, my bad :)
I also was using <table:list> and should first close these tags:
</text:list-item></text:list>


text:
Q: SQL WHERE if field is serialized I've got a problem which needs to be solved...
I have table where one of the fields is serialized (field: s_field).
It's just an array of id's.
But now I need to get all data entries WHERE s_field = 5..
So I have entries where s_field is serialized(array(4, 5, 6)); and there are tons of these entries... so how do I get - using sql - all entries where one of the s_field id's are id == 5;
Hope you understand what I mean
And I don't think that getting all entries and each of them unserialize and check is not the best thing to do, because there are LOTS of them

A: You can try adding the zerofill attribute to the ID field so you will have, say, 0000005 rather than 5, then using LIKE to match the for 0000005

A: Assuming your entry really looks like serialized(array(4, 5, 6)); you could find a '5' with this query:
a:3:{i:0;i:4;i:1;i:5;i:2;i:6;}
SELECT some_field WHERE s_field LIKE '%, 5,%'

However the better solution would be to unserialize all that data and put it in relational tables.
EDIT:
As @kyra pointed, this won't work for the first and last item of the array.
So if you get no result with the first query you could then try:
SELECT some_field WHERE s_field LIKE '%(5,%'

And then finally:
SELECT some_field WHERE s_field LIKE '%, 5)%'

If you have mostly fields with only one element you should start with the second query.
EDIT:
Of course if the serialized data actually looks like this: a:3:{i:0;i:4;i:1;i:5;i:2;i:6;} you can locate the '5' like this:
SELECT some_field WHERE s_field LIKE '%i:5;%'

And this way it should work even for the fisrt and last items.


text:
Q: How can get data to multiple related models and post the data to a controller in asp.net mvc I have two models in my asp.net MVC application, "Booking" and "BookedEquipments", so when a users submits the booking form I want users to also selected the equipment (they can select multiple) along with the booking details on a single view.
These are the models,
   public class Booking
    {
        public int Id { get; set; }
        //....//
        public string PackageTitle { get; set; }
        public decimal PackagePrice { get; set; }
        public virtual ICollection<BookedEquipment> BookedEquipments { get; set; }
    }

The other Model
 public class BookedEquipment
    {
        public int Id { get; set; }
        [Required]
        public string Title { get; set; }
        public decimal Price { get; set; }
        public int BookingId { get; set; }
        public virtual Booking Booking { get; set; }
    }

How can i get the data from users for both the models at the same time and post the data to a controller?


text:
Q: Evaluate triangle by its side My question is about using Javascript to do triangle evaluation by its sides. The following code is very initial version even it works. I'd like to know whether it could be more simplifying or there is other way to achieve the same result.
Thanks!
let a = Number(prompt('Please input the the first side (a)'))
let b = Number(prompt('Please input the the second side (b)'))
let c = Number(prompt('Please input the the third side (c)'))

if (a + b <= c || b + c <= a || c + a <= b || Number.isNaN(a) || Number.isNaN(b) || Number.isNaN(c) || a == "" || b == "" || c == ""){
  console.log("invalid")
}
else if ((a > 0 && b >0 && c >0 ) && (a == b && b == c && c == a)){
  console.log("equilateral triangle")
}
else if ((a > 0 && b >0 && c >0 ) && (a == b || b == c || c == a)){
  console.log("isosceles triangle")
}
else {
  console.log("scalene triangle")
}

A: Another way could be to explicitly convert the lengths to a number (0 for NaN) and sort them first. And a ternary operator can be useful here also:
let [d, e, f] = [a, b, c].map(a => +a || 0).sort((a, b) => a-b);
let result = d + e <= f     ? "invalid"
           : d === f        ? "equilateral"
           : d < e && e < f ? "scalene"
                            : "isosceles";
console.log(result);

This will not be the fastest when doing many thousands of them, but I like the look of it.
Explanation
[a, b, c] turns the three values into an array.
.map is a method available for arrays. For each original value in [a, b, c] the following (arrow) function is executed,
a => +a || 0

map creates a new array consisting of the results of calling that function on each separate value (so first with a, then with b and finally with c)
+a uses the unary plus as a short way of turning a value into a number, which means that you could omit the Number() calls you did in the first three lines of your code. When the result of this is NaN or 0, then || 0 will kick in: instead of NaN or 0, 0 will be taken instead (|| is a logical OR operator and 0 will only be used when the left side is considered "falsy"). This practically means that NaN is replaced by 0.
So up to now the code has roughly done something similar to the following:
let newarray = [];
newarray[0] = +a;
if (Number.isNaN(newarray[0])) newarray[0] = 0;
newarray[1] = +b;
if (Number.isNaN(newarray[1])) newarray[1] = 0;
newarray[2] = +c;
if (Number.isNaN(newarray[2])) newarray[2] = 0;

Then another array method is called on that array returned by .map(): the method .sort(). That method will use the provided callback function (a, b) => a-b to make comparisons in the array and sort it based on the values returned by such calls. It is up to the sort method to decide for which pairs this function is called. When the returned value is negative, it means the compared values are already in increasing order. When positive, they should be rearranged. When zero, they should be considered equal to the sort algorithm.
So... we now have an array that consists of numbers which are guaranteed to no longer have a NaN, and which are sorted in ascending order.
Then that array is assigned using so-called destructuring:
let [d, e, f] =

This means that the individual values of the sorted array are assigned one by one to three new variables. So this is roughly short for:
let d = new_sorted_array[0];
let e = new_sorted_array[1];
let f = new_sorted_array[2];

Because these values are now ordered, we can use them for much simpler comparisons to decide on the shape of the triangle. What follows is an expression using a chain of ternary operators which much resemble an if (...) ... else if ... chain. So:
let result = d + e <= f     ? "invalid"
           : d === f        ? "equilateral"
           : d < e && e < f ? "scalene"
                            : "isosceles";

... is short for this:
let result;
if (d + e <= f) result ="invalid"
else if (d === f) result = "equilateral"
else if (d < e && e < f) result = "scalene"
else result = "isosceles";

A: You can reduce alot of bulk and change the implementation:

*

*You can make the user input a function call

*You can place the input into an array

*You can use every to make sure every value is greater than 0

*You can use a new Set to remove duplicates, if the size is 1, then all sides are the same, if it's 2, then 2 sides are the same, if it's 3, all sides are different

const getSide = l => Number(prompt(`Please input the the second side (${l})`))
const sides = [getSide('a'), getSide('b'), getSide('c')]

if (sides.every(el => el > 0)) {
  const size = new Set(sides).size
  if (size === 1) console.log("equilateral triangle")
  else if (size === 2) console.log("isosceles triangle")
  else console.log("scalene triangle")
} else {
  console.log("invalid")
}

Test cases:

const test = sides => {
  if (sides.every(el => el > 0)) {
    const size = new Set(sides).size
    if (size === 1) console.log("equilateral triangle")
    else if (size === 2) console.log("isosceles triangle")
    else console.log("scalene triangle")
  } else {
    console.log("invalid")
  }
}

test([0,1,2]) // invalid
test([NaN,NaN,NaN]) // invalid
test(['',1,2]) // invalid
test([3,3,3]) // eq
test([2,2,3]) // iso
test([1,2,3]) // sca


text:
Q: ubuntu 14.10 multiple Simultaneous independent remote (desktop like ) connections Can anyone please suggest a free server (that works just like terminal server which allows multiple rdp-like independent sessions) that is compatible for ubuntu 14.10?
I have tried: Simultaneous remote connections
I googled FreeNX but most of the tutorials available are not working for ubuntu 14.10 and also NOMACHINE does not allow multiple sessions.. NOMACHINE works great but restricted to only one session.. when I connect from second account it get disconnected..
https://www.nomachine.com/AR10K00703 "NoMachine (free) allows one connection. Hence it is for individual use."
And also I have tried http://www.xrdp.org using this tutorial https://www.youtube.com/watch?v=gFdBSyy4xcM
It's also not working.. stuck in a blank rdp screen..
VNC is not what I'm looking for since it cant offer independent sessions..
Most of the tutorials are for old Ubuntu versions and not working for me
Any help would be greatly appreciated!! Any basic current tutorial 14.10 or anything which shade light please!
PS
What worked ultimately was VNC

A: As an alternative to VNC, you might want to install XRDP which uses the Microsoft RDP protocol.
I've found it to be much easier to install and use, and the protocol is said to be much more efficient. However, it requires the use of Microsoft Remote Desktop client (available for Windows and Mac) or another Microsoft RDP compatible client.
This the link that was originally almost all in this answer:
http://c-nergy.be/blog/?p=5305  It's for LTS, but it should work with 14.10 as well.
However, I found it so useful, so I added some more info.  Just in case the above link gets outdated, here's how to install in short:
Install XRDP
sudo apt-get install xrdp

Install the xfce4 Desktop environment
sudo apt-get install xfce4

Configure xrdp to use xfce desktop
echo xfce4-session >~/.xsession

Restart the xrdp service
sudo service xrdp restart

Now you can test your RDP connection. In your client machine, start remote Desktop client and enter the ip address/name of your ubuntu machine. You will be asked to login, and then you should see the Linux desktop.

A: Oh, btw, VNC can offer multiple independent sessions, it's just a pain to setup.  You basically run multiple copies of Xvnc on different ports.  The issue is that there is no automatic "bounce me to the next unused desktop" option, so you need to give each user that is going to be using the system remotely their own port.

A: Here are the things worked for me.. (success using this tute  http://www.howtoforge.com/how-to-install-vnc-server-on-ubuntu-14.04 and kudose for Charles Tassell for right directions and advice)
What I did is as follows,
(1) run sudo apt-get update && sudo apt-get upgrade
(2)run sudo apt-get install gnome-core xfce4 vnc4server
(3)then add users (vncserver/unix)
sudo adduser test1

(you will have to fill details afterwards for the user, I have added 3 users (test1, test2, test3 etc for vnc server)
(4)Then you have to switch users one by one and run vncserver and add password for vncuser login (I have three vnc users, so that i had to repeat this for all three user test 1, test2, test3)
su - test1

then run
vncserver

out put will be like this prompting for a vnc password..
You will require a password to access your desktops.

Password:
Verify:

xauth:  file /home/test1/.Xauthority does not exist
New 'server1:1 (test1)' desktop is server1:1
Creating default startup script /home/test1/.vnc/xstartup
Starting applications specified in /home/test1/.vnc/xstartup
Log file is /home/test1/.vnc/server1:1.log

(5) Important : you will have to replace /home/test1/.vnc/xstartup content with below (Else you will not get the desktop, instead you will stuck with blank screen without user interfaces or menus )
vim /home/test1/.vnc/xstartup

and add
#!/bin/sh
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
startxfce4 &

[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &

(6) startup script for the vncserver was created using "Further I will make the startup script for the vncserver like this" section of this tute
sudo vim /etc/init.d/vncserver

and add below content..
#!/bin/bash

unset VNCSERVERARGS
VNCSERVERS=""
[ -f /etc/vncserver/vncservers.conf ] && . /etc/vncserver/vncservers.conf
prog=$"VNC server"
start() {
 . /lib/lsb/init-functions
 REQ_USER=$2
 echo -n $"Starting $prog: "
 ulimit -S -c 0 >/dev/null 2>&1
 RETVAL=0
 for display in ${VNCSERVERS}
 do
 export USER="${display##*:}"
 if test -z "${REQ_USER}" -o "${REQ_USER}" == ${USER} ; then
 echo -n "${display} "
 unset BASH_ENV ENV
 DISP="${display%%:*}"
 export VNCUSERARGS="${VNCSERVERARGS[${DISP}]}"
 su ${USER} -c "cd ~${USER} && [ -f .vnc/passwd ] && vncserver :${DISP} ${VNCUSERARGS}"
 fi
 done
}
stop() {
 . /lib/lsb/init-functions
 REQ_USER=$2
 echo -n $"Shutting down VNCServer: "
 for display in ${VNCSERVERS}
 do
 export USER="${display##*:}"
 if test -z "${REQ_USER}" -o "${REQ_USER}" == ${USER} ; then
 echo -n "${display} "
 unset BASH_ENV ENV
 export USER="${display##*:}"
 su ${USER} -c "vncserver -kill :${display%%:*}" >/dev/null 2>&1
 fi
 done
 echo -e "\n"
 echo "VNCServer Stopped"
}
case "$1" in
start)
start $@
;;
stop)
stop $@
;;
restart|reload)
stop $@
sleep 3
start $@
;;
condrestart)
if [ -f /var/lock/subsys/vncserver ]; then
stop $@
sleep 3
start $@
fi
;;
status)
status Xvnc
;;
*)
echo $"Usage: $0 {start|stop|restart|condrestart|status}"
exit 1
esac

to make it an executable run the following..
chmod +x /etc/init.d/vncserver

(7) To make vnc desktop sessions allocated for users at start up automatically, create following script in /etc/vncserver
sudo mkdir -p /etc/vncserver
sudo vim /etc/vncserver/vncservers.conf

add this in vncservers.conf (this is because i have my users as test1, test2, test3 change it according to )
VNCSERVERS="3:test3 2:test2 1:test1"
VNCSERVERARGS[1]="-geometry 1024x768"
VNCSERVERARGS[2]="-geometry 1024x768"
VNCSERVERARGS[3]="-geometry 1024x768"

(8) Then run
sudo `update-rc.d vncserver defaults 99`

(9) reboot server (you are almost done by now) step 10 and the rest is how to login part
(10)download http://www.realvnc.com/download/viewer/
enter servername/ipaddress and session id
for example my server is 172.16.70.17 and if i use 172.16.70.17:2 it will login to test2 user desktop.. and 172.16.70.17:3 will login to test3 user desktop like wise
make sure encryption to be selected "Prefer off"

Then you can access your desktop and applications in this manner..


text:
Q: Binary Search Tree searching a string by letter Hi I am a novice programmer trying to figure out how to search for a string in a binary search tree using only the first letter it starts with, for example if a just search for the letter 'L' it should bring up all names starting with that letter. Below is the method on how we search for the full name so far.
public void searchByName() throws IOException//My pride and joy
    {

        String exit=null;//to exit the inner while loop
        Boolean end=false;// exit the outer while loop

        while(end!=true) //search author by first name loop
        {

            @SuppressWarnings("resource")
            Scanner keyboard = new Scanner(System.in);

            System.out.printf("Please enter the Author's Last and First:(please enter in this format(Johnson, Cevion)\n");
                String name = keyboard.nextLine();

                System.out.println("This is what we found!!\n");

                System.out.println(findFullName(name));

                System.out.printf("Do you want to search again?? Yes or No\n");//search again loop
                exit = keyboard.nextLine();

                while(!exit.equalsIgnoreCase("yes")&&!exit.equalsIgnoreCase("no"))//yes or no only loop
                {
                    System.out.printf("Invaild choice please enter: Yes or No\n");
                    exit = keyboard.nextLine();
                }

                if(exit.equalsIgnoreCase("yes"))
                    end=false;
                if(exit.equalsIgnoreCase("no"))
                    end=true;
        }

    }

A: Binary tries aren't meant for that kind of search, you better use a hashmap: string -> array
if you would like to implement that kind of behaviour in a tree you will need to  modify (or create) the search method, once it found the first node that match the criteria, in your case string starts with "L", it need to return that node and traverse the tree originate form that node,
you can do it with a simple in-out order traverse and etc... and check all subsequent nodes for that criteria, it can't stop till got to the leaf thus makes this find complexity as O(N) basically traverse all the (sub)tree..


text:
Q: Mvc Javascript Not Working In Mvc Javascript Is Not Working Button Click Event
I Want To Raise Button Click Event.
<input type="button" id="btn_click" value="Click" />
<script type="text/javascript">
    function pageLoad() {
        $('#btn_click').click(function () {
            alert('You Clicked Button');
        });
    }
</script>

Please Help me

A: This actually has nothing to do with ASP.NET, C# or Razor. This is pure HTML and JavaScript.
You have wrapped the click function in pageLoad which is not being called.
So you simply have to remove it.

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
</head>

<body>
    <input type="button" id="btn_click" value="Click" />
    <script type="text/javascript">
      $('#btn_click').click(function() {
        alert('You Clicked Button');
      });
    </script>
</body>

</html>

A: For button
<input type="button" id="btn_click" value="Click" />

Use javascript as-
function showalert(){
     alert('You Clicked Button');
}
document.getElementById("btn_click").onclick = showalert;

A: pageLoad function is never called hence event-listener is never attached!
Either invoke it or just Place your <script> as last-child of <body>(Just before closing body tag(</body>))

$('#btn_click').click(function() {
  alert('You Clicked Button');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="button" id="btn_click" value="Click" />

A: pageLoad function not call, but if you want to call it after pageload you can use $(function(){}) like that
$(function(){
    $('#btn_click').click(function () {
        alert('You Clicked Button');
    });
});

A: You have wra the click event in a function , but button click does not call that function.
You can call this function onClick event of button
<input type="button" id="btn_click" value="Click" onClick="pageLoad()" />

function pageLoad() {
  alert('You Clicked Button');
}

JSFIDDLE

A: Put your Javascript code in document ready.

$(document).ready(function () {
        $('#btn_click').click(function () {
            alert('You Clicked Button');
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btn_click" value="Click" />

A:

function btnclick() {
  alert('You Clicked Button');
};
  <input type="button" id="btn_click" value="Click" onclick="btnclick();" />


text:
Q: How to fix [Errno 2] No such file or directory im try to make restart program using button tkinter python. but when i run it and press the button, it said [Errno 2] No such file or directory. Here my error = C:\Program: can't open file 'C:\Users\ROG FLOW\Desktop\Untuk SIDANG TA\Untuk Upload Ke google drive\Files\Python310\python.exe': [Errno 2] No such file or directory
Can anyone help me with that ? i appreciate every help
import sys`
import os
from tkinter import Tk, Label, Button

def restart_me():
   pth = sys.executable
   os.execl(pth, pth, *sys.argv)

root = Tk()
Label(root, text="hi there!").pack()

Label(root, text="hi there!").pack()
Button(root, text="Restart", command=restart_me).pack()

root.mainloop()

A: It looks like os.execl() cannot handle file path with spaces inside properly.  It works fine when there is no space inside the file path.
I would suggest to use subprocess.Popen() instead and you need to destroy current main window before calling it:
...
import subprocess
import sys
...

def restart_me():
    root.destroy()
    subprocess.Popen([sys.executable, *sys.argv])

...

Note that subprocess.Popen() will not replace current process so that is why the current main window need to be destroyed.


text:
Q: Simulate serial port I am writing a C program in Linux which will read/write to/from a serial port. I know the data that needs to be read and written on the port but I don't have a serial port to currently test this with.
Is there any way to simulate a serial port? Would reading/writing to a file be sufficient? I can have one process write to the file while another process reads that data and writes back other data to the file. Or are there others tools that can be used to simulate a port?
Thanks

A: Serial ports on Linux are terminal devices.  A close simulation is to create a pseudo-terminal pair; the program that normally talks to the serial port is instead told to open the slave side of the pseudo-terminal, and the simulator writes and reads from the master side.
The pty(7) man page has more information.

A: Despite being an old topic, and my answer is not exactly something the OP was looking for, I decided to share my experience, as someone else might come across it like I did. Instead of straightforward simulation, I used the software called Serial to Ethernet Connector to gain access to the specific device I needed to test the app with. Worked nicely for me.

A: A character device, even something as simple as normal stdin and stdout should work if you don't care about attributes specific to port devices.


text:
Q: Why am I getting an error on this simple Scala code? Here's my code:
object Triple {
  object Num extends Enumeration {
    type Num = Value
    val one, two, three, four, five, six, seven, eight, nine = Value
  }
  val triples = for {
    first <- Num.values
    second <- Num.values
    third <- Num.values
    if (first != second)
    if (first != third)
    if (second != third)
  } yield Set(first, second, third)
}

I get an error on the line with third.  It says:
Multiple markers at this line
    - not enough arguments for method map: (implicit bf:
         scala.collection.generic.CanBuildFrom[sudoku.Triple.Num.ValueSet,scala.collection.immutable.Se    t[sudoku.Triple.Num.Value],That])That. Unspecified
 value parameter bf.
- diverging implicit expansion for type
 scala.collection.generic.CanBuildFrom[sudoku.Triple.Num.ValueSet,scala.collection.immutable.Set[sudoku.Triple.Num.Value],That] starting with
 method newCanBuildFrom in object SortedSet
- not enough arguments for method map: (implicit bf:
 scala.collection.generic.CanBuildFrom[sudoku.Triple.Num.ValueSet,scala.collection.immutable.Set[sudoku.Triple.Num.Value],That])That. Unspecified
 value parameter bf.
- diverging implicit expansion for type
 scala.collection.generic.CanBuildFrom[sudoku.Triple.Num.ValueSet,scala.collection.immutable.Set[sudoku.Triple.Num.Value],That] starting with
 method newCanBuildFrom in object SortedSet

Update:  Aleksey Izmailov gave a great answer.  A slightly better implementation of the function is val triples=Num.values.subset(3).toSet

A: Looks like what you are trying to do is this:
scala> object Num extends Enumeration {
     |     type Num = Value
     |     val one, two, three, four, five, six, seven, eight, nine = Value
     |   }
defined module Num

scala>   val triples = Num.values.toList.combinations(3)
triples: Iterator[List[Num.Value]] = non-empty iterator

scala> triples.toList
res0: List[List[Num.Value]] = List(List(one, two, three), List(one, two, four), List(one, two, five), List(one, two, six), List(one, two, seven), List(one, two, eight), List(one, two, nine), List(one, three, four), List(one, three, five), List(one, three, six), List(one, three, seven), List(one, three, eight), List(one, three, nine), List(one, four, five), List(one, four, six), List(one, four, seven), List(one, four, eight), List(one, four, nine), List(one, five, six), List(one, five, seven), List(one, five, eight), List(one, five, nine), List(one, six, seven), List(one, six, eight), List(one, six, nine), List(one, seven, eight), List(one, seven, nine), List(one, eight, nine), List(two, three, four), List(two, three, five), List(two, three, six), List(two, three, seven), List(two, three...
scala>

If you do something like this then it works:
scala> object Triple {
     |   object Num extends Enumeration {
     |     type Num = Value
     |     val one, two, three, four, five, six, seven, eight, nine = Value
     |   }
     |   val triples = for {
     |     first <- Num.values
     |     second <- Num.values
     |     third <- Num.values
     |     if (first != second)
     |     if (first != third)
     |     if (second != third)
     |   } yield (first, second, third)
     | }
defined module Triple

scala> Triple.triples
res1: scala.collection.immutable.SortedSet[(Triple.Num.Value, Triple.Num.Value, Triple.Num.Value)] = TreeSet((one,two,three), (one,two,four), (one,two,five), (one,two,six), (one,two,seven), (one,two,eight), (one,two,nine), (one,three,two), (one,three,four), (one,three,five), (one,three,six), (one,three,seven), (one,three,eight), (one,three,nine), (one,four,two), (one,four,three), (one,four,five), (one,four,six), (one,four,seven), (one,four,eight), (one,four,nine), (one,five,two), (one,five,three), (one,five,four), (one,five,six), (one,five,seven), (one,five,eight), (one,five,nine), (one,six,two), (one,six,three), (one,six,four), (one,six,five), (one,six,seven), (one,six,eight), (one,six,nine), (one,seven,two), (one,seven,three), (one,seven,four), (one,seven,five), (one,seven,six), (one,...
scala>

Note the result of the produced collection is a SortedSet. That result is defined by Num.values - you can convert for comprehension to map, flatMap and filter to check how the types come about.
The problem is that you can put stuff that can be sorted into SortedSet like this for example:
scala> scala.collection.immutable.SortedSet(1, 2)
res6: scala.collection.immutable.SortedSet[Int] = TreeSet(1, 2)

However, you can't put something that does not have ordering defined into a SortedSet because SortedSet guarantees that the stuff is sorted and should know how sorting is done (via implicit ordering):
scala> scala.collection.immutable.SortedSet(Set(1, 2), Set(3, 4))
<console>:8: error: No implicit Ordering defined for scala.collection.immutable.Set[Int].
              scala.collection.immutable.SortedSet(Set(1, 2), Set(3, 4))

Scala looks for implicit Ordering to be defined in scope and does not find one for the Set that you are using, or for the Set[Int] in my example.
Now let's "fix" it:
scala> implicit val dummyOrdering: Ordering[Set[Int]] = Ordering.by(_.size)
dummyOrdering: Ordering[Set[Int]] = scala.math.Ordering$$anon$9@6f00d9a7

scala> scala.collection.immutable.SortedSet(Set(1, 2), Set(3, 4))
res8: scala.collection.immutable.SortedSet[scala.collection.immutable.Set[Int]] = TreeSet(Set(3, 4))

Obviously, this is a bad fix and the real problem is that in your case types are not well chosen. First of all you don't need to use a Set for each combination since you already comparing things to avoid repetition. Just use a Tuple3. Second, if you insist on using a Set, then convert Num.values to List in the for comprehension:
scala> object Triple {
     |   object Num extends Enumeration {
     |     type Num = Value
     |     val one, two, three, four, five, six, seven, eight, nine = Value
     |   }
     |   val triples = for {
     |     first <- Num.values.toList
     |     second <- Num.values.toList
     |     third <- Num.values.toList
     |     if (first != second)
     |     if (first != third)
     |     if (second != third)
     |   } yield Set(first, second, third)
     | }
defined module Triple

Hope that makes it clear. Basically the problem is in the choice of wrong types.


text:
Q: Multiple insert after post call in PHP I need to update insert into MYSQL DB same data from a post call.
This is the form code:
<form action="salva_debiti.php" method="post">

'; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM rimanenti_mese WHERE Mese = $mese AND Anno = $anno ORDER BY cognome ASC"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo '

        Nome
        Cognome
        Da incassare pezzi
        Da incassare benzina
        Residuo '.$mese_scritto.' '.$anno_pr_div.'

'; while($row = $result->fetch_assoc()) { echo '

            <input type="" name="nome[]" value="'.$nome.'">

            <input type="" name="cognome[]" value="'.$cognome.'">

            <input type="" name="pezzi[]" value="'.$pezzi.'">

            <input type="" name="benzina[]" value="'.$benzina.'">

            <input type="" name="rimanenti[]" value="'.$rimanenti.'"

    ' ; } echo '
    <input type="submit" value="Submit">'; echo '</form>';

And this is the code that I use to insert data:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn - > connect_error) {
die("Connection failed: ".$conn - > connect_error);
}

 foreach($_POST['nome'] as $nome) {

$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$rimanenti_ins = $_POST['rimanenti'];

//$sql = "UPDATE rimanenti_mese SET Rimanenti='$rimanenti_ins' WHERE Nome='$nome' AND Cognome = '$cognome'";

$sql = "INSERT INTO rimanenti_mese (Nome, Cognome, Mese, Anno, Benzina, Pezzi, Rimanenti)
VALUES('$nome', '$cognome', '09', '2015', 'xxxx', 'fdfdfd', '$rimanenti_ins')
";

}

 if ($conn - > query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: ".$sql.
"
".$conn - > error;
}

 $conn - > close();

The problem is that it insert only the last row...
Where I'm wrong?

A: Move $conn - > query($sql) into your foreach loop.
foreach($_POST['nome'] as $nome) {
    $nome = $_POST['nome'];
    $cognome = $_POST['cognome'];
    $rimanenti_ins = $_POST['rimanenti'];
    $sql = ".....";
    if ($conn - > query($sql) === TRUE) {

    } else {

    }
}

Because now you do only one query, and after your foreach loop is over $sql contains query for the last item.
Update:
word Array is a string representation of array value.
When you do $nome = $_POST['nome'], your $_POST['nome'] is array, so adding array to a string results in word Array.
So you should take every item of your array per iteration, for example:
$i = 0;
foreach ($_POST['nome'] as $nome) {
    $nome = $_POST['nome'][$i];
    $cognome = $_POST['cognome'][$i];
    $rimanenti_ins = $_POST['rimanenti'][$i];

    // sql
    // run query

    $i++;
}

A: You're calling the $conn -> query($sql) after the foreach is finished, this means in $sql is only stored the last values from the foreach loop.
Try this:
// Create connection
$conn = new mysqli( $servername, $username, $password, $dbname );
// Check connection
if ( $conn->connect_error) {
    die("Connection failed: ".$conn -> connect_error);
}

foreach ( $_POST['nome'] as $nome ) {

    $nome = $_POST['nome'];
    $cognome = $_POST['cognome'];
    $rimanenti_ins = $_POST['rimanenti'];

//$sql = "UPDATE rimanenti_mese SET Rimanenti='$rimanenti_ins' WHERE Nome='$nome' AND Cognome = '$cognome'";

    $sql = "INSERT INTO rimanenti_mese (Nome, Cognome, Mese, Anno, Benzina, Pezzi, Rimanenti)
VALUES('$nome', '$cognome', '09', '2015', 'xxxx', 'fdfdfd', '$rimanenti_ins')
";

    //put your ->query into the foreach loop
    if ($conn -> query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: ".$sql.
        "
".$conn -> error;
    }
}

$conn -> close();


text:
Q: User card Overflow / Underflow ™ on non-English sites On this question on Stack Overflow en español, the text on the user cards for both the author and the last editor cause an overflow/underflow:

A: We've deployed a fix for this that wraps any dates that are longer than the user cards. The user card on the post you linked now looks like this:


text:
Q: Save images from attached file at couchdb I have an image saved as an attached file in my CouchDB, I need to get the image with a GET Request and save the image locally but can't find a way around it. When I uploaded the image file i got this JSON in return
{
  "_id": "95a51bbb8cfbb2abd07c6d14441f662a",
  "_rev": "3-15b7700d2df8fd896065c77a0c66ff11",
  "_attachments": {
    "chris.jpg": {
      "content_type": "image/jpeg",
      "revpos": 2,
      "digest": "md5-gTXsroZpTQ3qRrIsTKGoxw==",
      "length": 53644,
      "stub": true
    }
  }
}
I do know that if I wanted to display the image in a HTML page I would use the blob format, but can't figure out how to use it for saving in a local directory; please help!!

A: Use the /{db}/{docid}/{attachment} endpoint as documented here. It will return just the attachment you want.
If you're using a CouchDB client library, it probably makes this easier for you.

A: Well in case someone faces this issue again, what I finally did was:
r= requests.get(full_url)
superData = r.json()

to get the JSON from couchdb, next:
for key in superData["_attachments"]:
    nuevaURL = full_url + '/' +key
    response = requests.get(nuevaURL, stream=True)

to get the path to the image and finally to save it locally:
with open('img.jpg', 'wb') as out_file:
        out_file.write(response.content)


text:
Q: Retrieving the serial number of a mapped network drive via FileSystemObject I have a piece of VBA code as shown below
VSN = Hex(Format(CDbl(FSO.Drives(FSO.getDriveName(CurrentProject.path)).SerialNumber)))

This is where I retrieve the users Volume Serial Number. This works great on local hard drives however, it doesn't on mapped network drives where (i'm guessing) there is no drive prefix (e.g. C: or D:) for the function FSO.getDriveName. It's either that or it fails on FSO.Drives() as it has no drive letter available.
Does anyone know how to fix this problem?
By the way, the error produced by the code is as follows: Run-time error '5': Invalid procedure call or arguement.
Thanks in advance for any replies/suggestions.

A: I am unable to recreate your issue under Access 2010. The code ...
Option Compare Database
Option Explicit

Sub DriveSerialNumberTest()
    Dim fso As Object  'FileSystemObject
    Dim VSN As String

    Set fso = CreateObject("Scripting.FileSystemObject")
    Debug.Print fso.GetDriveName(CurrentProject.Path)

    VSN = Hex(Format(CDbl(fso.GetDrive(fso.GetDriveName(CurrentProject.Path)).SerialNumber)))
    Debug.Print VSN

    Set fso = Nothing
End Sub

... returns the following in the Immediate window when the database is opened from a network share via a mapped drive letter ...
Z:
DCF1295E

... and it returns the following when the database is opened from a network share via a UNC path ...
\\Weezer\Public
DCF1295E


text:
Q: I can't type the '%' (percentage) character in my mac terminal Just recently, I notice that while using my mac terminal I can't type in the '%' character.
I can use any other character using the same key, for example '5' and '∞' (option+5), but when I want to use '%' (shift+5) I get the error terminal sound.
If I try to copy and paste text with a '%' included, it will copy all the text except for the '%'. If I connect to a server using ssh, '%' works perfectly.
Any suggestions to fix this?

A: The problem was in the .inputrc file in my home directory.
The first line of this file was like this:
% Cnd down arrows cycle through commands that match the start of a line
I had to changed the '%' at the beginning for a '#'.
Still I don't know why that line had the percentage instead.


text:
Q: Docker - Dont see mongoDB image after docker-compose build I am doing my first steps with docker compose and made a docker-compose.yml file which contains:
version: "3.8"

services:
  web:
    build: ./frontend
    ports:
      - "3000:3000"
  api:
    build: ./backend
    ports:
      - "3001:3001"
    environment:
      DB_URL: mongodb://db/slip
  db:
    image: mongo:4.0-xenial
    ports:
      - "27017:27017"
    volumes:
      - slip:/data/db

volumes:
  slip:

However after running $ docker-compose build
This is my result images in docker:
REPOSITORY   TAG                  IMAGE ID       CREATED              SIZE
slip_api    latest               445199e1e418   43 seconds ago       184MB
slip_web    latest               c1168ad560b8   About a minute ago   299MB
node         14.16.0-alpine3.13   50bfd284aa0d   10 months ago        117MB

I am not sure why I don't see the mongo:4.0-xenial image, and also not sure why I see the node:14.16.0-alpine3.13 which is a base (FROM) in docker file of the slip_api and slip_web and not an image by itself that I built.
Using Ubuntu 20.04.3 LTS
Thanks for the help!

A: docker-compose build does literally that: it builds images. In order for an image to be built, the base image needs to present. That is the reason, why you are seeing the node image present.
You do not see the mongoDB image, because it is not built. Once you attempt to docker-compose up it will pull the latest version of mongo:4.0-xenial


text:
Q: What does the word "row" mean in this context? TheFreedictionary.com says that the word "row" can mean: 3. A line of adjacent seats, as in a theater, auditorium, or classroom. or a. (chiefly Brit) a street, esp a narrow one lined with identical houses
which one is it in this context? (if any)
'His wife a year he fondly loved
His wife a—a year he—fondly loved.'
Or suddenly waking up again:
'Walking along the crowded row
He met the one he used to know.'

It is a translation of Russian, from  Crime and Punishment, chapter 1. The original is "По Подьяческой пошел, // Свою прежнюю нашел."

A: It's a very old word for narrow street/road. Some streets in the UK are still called 'row' though not many. For most English people it would sound very Dickensian.

A: It probably means "narrow street".
The original is from Crime and Punishment, and a drunk man is singing drunkenly. "По Подьяческой пошел": literally something like "To Pod'yacheskoy, begone!".  "Pod'yacheskoy" is a narrow street in central St Petersburg.
Perhaps this is a fragment of a Russian bawdy song.
However the English suggests walking along a narrow but crowded street. A free interpretation in order to find a convenient rhyme.


text:
Q: Persist facebook claims and use from User.Identity I have this working code, which logs into via facebook and returns data such as
faceBookOptions.Fields.Add("picture");
            faceBookOptions.CallbackPath = "/ExternalLoginCallback";
            faceBookOptions.Events = new OAuthEvents
            {
                OnCreatingTicket = (context) =>
                {
                    ClaimsIdentity identity = (ClaimsIdentity)context.Principal.Identity;
                    string profileImg = context.User.GetProperty("picture").GetProperty("data").GetProperty("url").ToString();
                    identity.AddClaim(new Claim(JwtClaimTypes.Picture, profileImg));
                    context.HttpContext.User = context.Principal;
                    return Task.CompletedTask;
                }
            };

I now want to access this claim in my razor view:
@User.Identity.Claims

these claims has no profile picture!
ive searched SO and found many relating posts. but they dont use .net core 3.1, they have actual accountControllers and callback methods. in .net core 3.1 it all happens "behind the scenes"
any help would be much appreciated

A: https://haacked.com/archive/2019/07/16/external-claims/
i found this very detailed guide on why this is so complicated and how to work around it


text:
Q: Identifying a specific website in a chrome extention I would like to make an extension (chrome) that will identify if this is the correct webpage, and then it will load Html/Javascript/Css to that website. Can this be done in a .json file or javascript file? Or other languages to complete this action?
So, if I have it identify Facebook, then it will change some of the html/css/javascript on the website just for me. How can I manage to do this?

A: You can modify your manifest to match which websites your extension will run on:
"content_scripts": [
{
  "matches": ["http://facebook.com/*", "https://twitter.com/*"],
  "js": ["jquery.js", "myscript.js"]
}

The /* in facebook.com/* means that the extension will run on facebook.com and any page that belongs to it (e.g. facebook.com/zuck).
As you can see I included the JavaScript files I wanted to use for logic in my extension.
I downloaded JQuery from the JQuery website and saved it in the folder of my unpacked extension.
From here see the answer to this question to assign the url of the current page to a variable in your JavaScript code, using JQuery.


text:
Q: Почему сбрасывается параметр в плагине polylang? Пытаюсь настроить url так, чтобы в зависимости от текущего языка они формировались подобным образом:

*

*mydomain.com/ru/адрес-1

*mydomain.com/ru/адрес-2

*mydomain.com/ru/

Для этого нужно включить настройку:

The language is set from the directory name in pretty permalinks

Но она постоянно сбрасывается

Кто сталкивался с подобным, и какое решение может быть? Я определённо что - то делаю не так.


text:
Q: App Transport Security blocks http request when it's allowed Hi everyone. I have strange issue with App Transport Security on ios9 on share extension. Our project has 2 targets, ios project (based on phonegap) and native share extension. On both targets we do non https requests and on both target I have added
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

to .plist files, so ATS should be turned off.
On application it works and I can do non https requests without problems, but on share extension it still blocks my requests

Somebody knows how can we fix it?

A: You should allow your specific domain first, like this.
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>api.domainname.com</key>
        <dict>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>dev.domainname.com</key>
        <dict>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>


text:
Q: cannot push object returned from mysql in array I cannot push the object result1 into the array a . The array returns as empty everytime.

  app.get('/freezer', (req, res) => {
  var a = [];
  var sql = `SELECT freezer_id FROM freezer_data`;
  db.query(sql, (err, result) => {
    if (err) throw err;
    result.forEach((rs) => {
      var sql1 = `SELECT * FROM freezer_data JOIN live_records ON freezer_data.freezer_id = live_records.freezer_id WHERE live_records.freezer_id = '${rs.freezer_id}' ORDER BY insert_datetime DESC LIMIT 1`;
      db.query(sql1, (err, result1) => {
        if (result1.length) {
          a.push(result1[0]);
        }
      });
    });
    console.log('arrobj', a);
    res.render('freezer.html', { freezers: a });
  });
});

I maybe making some silly mistake here but i am new to this.

A: Your console.log calles before the array a was updated, since the db.query() is async and have a callback which is called sometime in the future.
If you try to check the array here:
db.query(sql1, (err, result1) => {
        if (result1.length) {
          a.push(result1[0]);
          console.log(a);
        }
      });

It won't be empty

A: That is important to know that query use function as parameter (callback), so you cannot return the value outside the query. Use async/await or promise maybe can help you. For example, i am using util (built-in express module).
const util = require('util');
const mysql = require('mysql');

// in this code, i am using connection pool
const databasePool = mysql.createPool({
  host: 'somehost', // ex. localhost
  port: 'someport', // ex. 3306
  user: 'someuser', // ex. root
  password: 'somepass', // ex. 123456
  database: 'somedbname', // ex. mydatabase
});

// i create variable for querying and use util for async/await
let performQuery = util.promisify(databasePool.query).bind(databasePool); // register databasePool.query and bind databasePool

then in your route :
app.get('/someroute', async (req,res,next) => {
  // declaring empty array
  const myArray = []
  // write query string here and use try to success result and catch the error
  const myQuery = `SELECT freezer_id FROM freezer_data`;
  try {
    // executing the query string and use await
    let getResult = await performQuery(myQuery)
    getResult.forEach((items) => {
      const myDeepQuery = `SELECT * FROM freezer_data JOIN live_records ON freezer_data.freezer_id = live_records.freezer_id WHERE live_records.freezer_id = ${items.freezer_id} ORDER BY insert_datetime DESC LIMIT 1`;
      let getDeepResult = await performQuery(myDeepQuery);
      myArray.push(getDeepResult)
    });
    res.send(myArray)
  } catch (err) {
    res.send('oopss..')
  }
})


text:
Q: Search and extract value using JQ command line processor I have a JSON file very similar to the following:
[
  {
    "uuid": "832390ed-58ed-4338-bf97-eb42f123d9f3",
    "name": "Nacho"
  },
  {
    "uuid": "5b55ea5e-96f4-48d3-a258-75e152d8236a",
    "name": "Taco"
  },
  {
    "uuid": "a68f5249-828c-4265-9317-fc902b0d65b9",
    "name": "Burrito"
  }
]

I am trying to figure out how to use the JQ command line processor to first find the UUID that I input and based on that output the name of the associated item. So for example, if I input UUID a68f5249-828c-4265-9317-fc902b0d65b9 it should search the JSON file, find the matching UUID and then return the name Burrito. I am doing this in Bash. I realize it may require some outside logic in addition to JQ. I will keep thinking about it and put an update here in a bit. I know I could do it in an overly complicated way, but I know there is probably a really simple JQ method of doing this in one or two lines. Please help me.
https://shapeshed.com/jq-json/#how-to-find-a-key-and-value

A: You can use select:
jq -r  --arg query Burrito '.[] | select( .name == $query ) | .uuid ' tst.json


text:
Q: PHP - cURL error 58 - Problem with the local SSL certificate So I am working on a credit card integration project where they needs certificates.
This is my PHP variable that uses the key and the pem
$certificate = array('private_key_path' => '/usr/www/users/2619100.key', 'public_key_path' => '/usr/www/users/2619100.pem', 'password' => '4545xss');

When I ran the whole code it throws an error
cURL error 58 - Problem with the local SSL certificate
Not sure it doesn't describe the actual error, does anyone have any idea. Here is the PHP code
    $params = array('device_fingerprint' => array('ip_address' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT']));
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $api_key, 'Content-Type: application/json', 'gateway-entity-id: ' . $this->gateway_entity_id, 'client-request-id: ' . uniqid()));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    if($this->request_type == 'VALIDATION' || $this->request_type == 'PRODUCTION') {
        curl_setopt($ch, CURLOPT_SSLKEY, $this->certificate['private_key_path']);
        curl_setopt($ch, CURLOPT_SSLCERT, $this->certificate['public_key_path']);
        curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->certificate['password']);
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $data = json_decode(curl_exec($ch), true);
    //print_r($data); exit;
    if($errno = curl_errno($ch)) {
        $error_message = curl_strerror($errno);
        throw new Exception('cURL error ' . $errno . ' - ' . $error_message);
    }
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);


text:
Q: Redirect Loop on Mobile & not on Desktop I'm having a weird redirect loop that only shows up on mobile devices.
I'm using IIS10 & urlrewrite to redirect requests to HTTPS. I've installed an SSL certificate from sectigo and used the same redirect rule that's always worked for me. It's quite weird that it works fine on desktop but not on mobile.
I've tested the issue persists across any mobile-device browser: safari, chrome, firefox and both Android/IOS devices across different networks. I've cleared the cache on the devices manually several times and it does nothing to solve the problem.
On the server side I have 4 bindings total IE:
example.com

www.example.com

https://example.com

https://www.example.com

With server identification turned on and the correct cert file selected for the 2 HTTPS bindings. The URL rewrite rule is:
<rewrite>
            <rules>
                <rule name="Redirect to HTTPS" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
                </rule>
            </rules>
        </rewrite>

A: In the response headers of the website I added a new entry Name=cache-control Value=no-cache,no-store this got the site loading on mobile. Not sure exactly how but I think the site was stuck in a forever 301 permanent loop

A: It is really weird while I tested the redirect rule is no problem. So I suggest you enable fail request tracing so that you can see what happened when you access site through mobile.
No-cache instructs the browser that it must revalidate with the server every time before using a cached version of the URL. No-store instructs the browser and other intermediate caches (like CDNs) to never store any version of the file. But some mobile devices ignore headers like no-cache, no-store, you need to manually set these in the response to allow the browser to get the correct URL information. Because in the process of access, the client and the server are constantly transmitting information back and forth.
There may be other factors, such as when you manually clear the cache and it is not cleaned up. Many browsers have an incognito mode. I suggest you try it in this mode.
Since I don't know your server provider (for your information security, you should not tell me), so there may be such a situation. Although the browser shows HTTPS, the server is treating it like an HTTP request. Thus the server always believes it is receiving an HTTP request.

To reduce costs [many hosting providers install the] SSL certificate
on the Gateway and this gateway is simply rewriting the request to
standard HTTP when passing it to the actual web server. So by the time
the request hits IIS and your web application it is a standard plain
HTTP request. Some people have encountered this situation before, it
is not necessarily the cause of your problem, but you can refer to it.