text:
Q: Convert string to int in PHP Following is my piece of code in which I am assigning my screen width to variable $width. But when I convert it to integer and echo it, 0 is returned.
$width = '<script> document.write(window.screen.width); </script>';
//if i echo $width it shows 1366 which is width of my screen
$height = '<script> document.write(window.screen.height); </script>';
echo "The height is = $height"."<br>The width is = ".$width;
$a = (int)($width);
echo $a;

I am asking for guidenance to make this conversion perfect.

A: You aren't actually getting the screen dimensions at that time. That runs on the client. You will have to make an ajax call to the server to set it.

A: You cannot use javascript to echo out a PHP variable. The javascript isn't executed until the PHP is LONG finsihed doing what it does. The best you can do with javascript is to ajax the data back, but that could only be used in a fresh PHP script - and not the current page.
You certainly can't expect data to come back before the script has finished executing.

A: It would be intval but what you are doing isn't possible because you cannot pass client data from the browser through to a php script without $_POST, $_GET, or the similar.

A: You don't need parantheses. Try $a = (int) $width; or $a = intval($width);.
Also, there is no sense in the code you are running.
$width = '<script> document.write(window.screen.width); </script>';

This will just set $width to be the string containing the HTML code (with the JavaScript inside). You can't fetch the return value of the JavaScript code that easily into a PHP variable, mainly because the JS part is executed way after the PHP is done (PHP is handled by the server, the generated HTML (with JS inside) is sent to the browser and the browser takes care of executing JS). To do that, you will need AJAX.


text:
Q: Changing menu icon in shiny dashboard The following css style corresponds to the menu icon in a shiny dashboard. I want to change it. I tried with tags$head(tags$style.. in the body, but it didn't work. Any ideas?
.main-header .sidebar-toggle:before {
    content: "\f0c9";
}

A: You need to escape the \:
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    tags$head(tags$style(HTML('
      .main-header .sidebar-toggle:before {
        content: "\\f0c7";}')))
    )
)

server <- function(input, output) { }

shinyApp(ui, server)

I also generally wrap the CSS in HTML to prevent escaping of other HTML characters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why duplicate key for hash in ruby language not return Error? A. Duplicate key with String as a key
irb(main):001:0> myHash = {'a' => 'a', 'a' => 'a'}
(irb):1: warning: key "a" is duplicated and overwritten on line 1

B. Duplicate key with Array as a key
irb(main):001:0> myHash = {[1,2,3] => [1,2,3], [1,2,3] => [4,5,6]}
=> {[1, 2, 3]=>[4, 5, 6]}

A: For duplicate string as key, error is not thrown, rather it s a warning.
In both cases, the duplicate key is overwritten into one, as the returned values here are {"a"=>"a"} and {[1, 2, 3]=>[4, 5, 6]}.


text:
Q: Classified geologic maps in QGIS (3.12.2) I'm really new to QGIS and trying to understand how to import and classify a geologic map. For example, here is a map from the AZ geological survey: http://repository.azgs.az.gov/uri_gin/azgs/dlio/1737
I've downloaded the GDB for the map and I can add the polygons etc, but they are all imported as a single category. Is there some way to get QGIS to create the symbology to look like the finished PDF? Please don't tell me that I need to pick each color by hand.

A: I've faced the same issue with geological maps. By far the best approach is to go back to the source and ask them to provide you with a style file (.sld or .qml format) or at least the RGB (red green blue) color definitions for each of the lithologies. You can then load this style file as described in many posts for example here: https://digimap.edina.ac.uk/webhelp/digimapgis/qgis/standard_qgis_functions/applying_style_files.htm
Picking by hand is the only option I have found if the definitions are unavailable but it is surprisingly fast to do. If you have to use this approach then symbolize your lithology in grey-scales first because this makes it easiest to see which ones are still to match.


text:
Q: pageref to label in last page in resume.cls I am using the class resume.cls for writing my curriculum.
I would like to use as page numbers the text "page k out of n", but I seem not to be able to get a reference to the last page.

*

*If I add a simple label 'lastone' at the end of the resume and use \pageref{lastone} the reference stays undefined no matter how many times I compile the source.

*If I use the package 'lastpage' I get an error related to a missing curly brace (which disappears as soon as I do not include that package).

*If I use the package 'zref-lastpage' and refer to the last one with \zpageref{LastPage}, I get an error related to an undefined macro.

Is there any way I can have a reference to the last page in order to insert its page number?
This is an example (you need to download the .cls file because I could not find a way to attach files).
\documentclass[margin,line]{resume}

\usepackage{zref-lastpage}
\usepackage{fancybox}

\makeatletter \renewcommand{\@evenfoot}%
{\normalsize\slshape CV di Tizio \hfil \upshape pag. {\thepage} di \zpageref{LastPage}} % \pageref{ultima}} % \zpageref{LastPage}}
\renewcommand{\@oddfoot}{\@evenfoot} \makeatother

\begin{document}
\name{\Large Tizio -- \it Curriculum Vitae et Studiorum}

\begin{resume}
\pagenumbering{arabic}

\section{\mysidestyle Informazioni\\ personali}\vspace{2mm}\label{informazioni-personali}
This is me

% ENDING
bye

\label{ultima}\end{resume}
\end{document}

A: \label uses a deferred writing, when the page is shipped out. At this time the page number is known for sure. Because of the asynchronous output routine this is not guaranteed otherwise. However, deferred writing is void after the last page is shipped out, because there is no page for the writing to take place.
Therefore the packages uses \immediate\write for the last label, e.g. package lastpage:
\documentclass{article}
\usepackage{lastpage}
\begin{document}
First page.
Last page is \pageref{LastPage}.
\newpage
Last page
\end{document}

The same example with package zref-lastpage. Note: \zpageref is provided by package zref-user:
\documentclass{article}
\usepackage{zref-lastpage,zref-user}
\begin{document}
First page.
Last page is \zpageref{LastPage}.
\newpage
Last page
\end{document}

The total number of pages can be different from the page number of the last page, because the numbering might change (title page, front matter, ...).
zref provides package zref-totpages for this purpose:
\documentclass{article}
\usepackage{zref-totpages}
\begin{document}
First page.
Number of pages is \ztotpages.
\newpage
Last page
\end{document}

Also \ztotpages uses the reference system, because the number of pages is known after the last page.
Class resume
The class resume from the question sabotages the reference system by using \nofiles. Then auxiliary files are not written, including references, thus labels remain unknown regardless of the number of LaTeX runs.
Workaround:
\let\nofiles\relax
\documentclass{resume} % http://linux.dsplabs.com.au/files/p54-resume/resume.cls


text:
Q: How in Android do I centre text that changes per second? I've got some Android code that works fine to make a piece of text count down...
final TextView mTextField = new TextView(this);

            mTextField.setTextColor(Color.RED);
            mTextField.setTextSize(25);
            mTextField.setTypeface(tf);
            final Handler handler = new Handler();
            final Runnable r = new Runnable() {
                public void run() {

                    mTextField.setText("Days : " + getTimes()[0] + " Hours : "
                            + getTimes()[1] + " Minutes : " + getTimes()[2]
                            + " Seconds : " + getTimes()[3]);

                    handler.postDelayed(this, 1000);

                }
            };

            handler.postDelayed(r, 1000);
            setContentView(mTextField);

The problem I have is, I can't format this text in anyway, I want it to be like exact centre of the screen, but as the text is actually in Java rather than XML, how would I go about say embedding this inside a relativeLayout so I can control the location of where the text is printed to the screen?
Thanks,

A: You can define a parent that is a FrameLayout and set gravity for center and then add that TextView:
FrameLayout frame = new FrameLayout(this);

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,FrameLayout.LayoutParams.FILL_PARENT,Gravity.CENTRAL)
frame.setLayoutParams(params);

 final TextView mTextField = new TextView(this);

 mTextField.setTextColor(Color.RED);
 mTextField.setTextSize(25);
 mTextField.setTypeface(tf);
 final Handler handler = new Handler();
      final Runnable r = new Runnable() {
            public void run() {
               mTextField.setText("Days : " + getTimes()[0] + " Hours : "
                        + getTimes()[1] + " Minutes : " + getTimes()[2]
                        + " Seconds : " + getTimes()[3]);

                handler.postDelayed(this, 1000);

            }
        };

        handler.postDelayed(r, 1000);

frame.addView(mTextField);
setContentView(frame);

UPDATE 1: Fixed the FrameLayout.LayoutParams.

A: if you want to center your text programatically. here is a method, use setGravity() , see this link for argument options..


text:
Q: UIAlertView in iPad What is the standard size of UIAlertView for ipad application?
it's same as iPhone?
if anybody has some idea please let me know.

A: They are identical in terms of pixels. However, they differ in physical size because of the difference in screen resolution between the two devices. The iPad version appears about 20% larger in terms of area. In both cases, the alert is about 275px wide.

A: More precisely, the width of an alert view's frame is 284 points and the height is 141 points.


text:
Q: my iOS App crash very often with [UIGestureRecognizer _delegateShouldReceiveTouch:] of pan gesture My iOS App crash very often at [UIGestureRecognizer _delegateShouldReceiveTouch:] with pan gesture. I am using pan gestures for the resizing and moving of a view. The view has multiple instances during the running of my App. Though crash happens very often, it can't be reproduced reliably. Here is the main part of the crash log.
Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000000
Crashed Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libobjc.A.dylib                 0x39de65b6 objc_msgSend + 22
1   UIKit                           0x33e4193e -[UIGestureRecognizer _delegateShouldReceiveTouch:] + 114
2   UIKit                           0x33d6f8b2 -[UITouchesEvent _addGestureRecognizersForView:toTouch:currentTouchMap:newTouchMap:] + 782
3   UIKit                           0x33d6f394 -[UITouchesEvent _addTouch:forDelayedDelivery:] + 212
4   UIKit                           0x33d6f2ac _AddTouchToEvent + 184
5   UIKit                           0x33d5d026 _UIApplicationHandleEvent + 5910
6   GraphicsServices                0x35a515a0 _PurpleEventCallback + 588
7   GraphicsServices                0x35a511ce PurpleEventCallback + 30
8   CoreFoundation                  0x31f2a170 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32
9   CoreFoundation                  0x31f2a112 __CFRunLoopDoSource1 + 134
10  CoreFoundation                  0x31f28f94 __CFRunLoopRun + 1380
11  CoreFoundation                  0x31e9beb8 CFRunLoopRunSpecific + 352
12  CoreFoundation                  0x31e9bd44 CFRunLoopRunInMode + 100
13  GraphicsServices                0x35a502e6 GSEventRunModal + 70
14  UIKit                           0x33db12fc UIApplicationMain + 1116
15  TestApp                             0x0008adb4 0x1c000 + 454068
16  TestApp                             0x0001e40c 0x1c000 + 9228

Does any one has a similiar experience of crashing at [UIGestureRecognizer _delegateShouldReceiveTouch:]?
Any hint, theory on how it would happen is appreciated.

A: It looks like the delegate that you assigned to the UIGestureRecognizer instance got deallocated. Hence the gesture recognizer will call a delegate method on an object that does not exist any more.
Make sure to set the delegate of the gesture recognizer to nil, when the object that is assigned as the delegate gets released. E.g. in the dealloc method.


text:
Q: English term for what translates as "conjugated imaginary points/lines" for a conic I am trying to find a reference for a certain concept that arises in my native language as, directly translated, "conjugated imaginary points".
The problem is this direct translation does not give me any results online because it must be named something else in English. I have seen this in the contents of a book called Descriptive Geometry written in my native language, but I have no access to this book so I am searching for other references of this concept.
I will try to provide context where this appears so maybe someone can tell me where I can read more about it. As I said it is contained in the topic of descriptive geometry and in context(of conic sections) it is used as:

Every line has two common points with a conic. If these points are real and different, we say that the line is a secant of the conic. If these two points coincide we say that the line is a tangent and if these points are conjugated imaginary then this line is a pasant(?) of a conic.

Here is also a figure for this text:

Obviously this last case of a line is one that does not even touch the conic, but I am more interested in this concept of conjugated imaginary points. I will gladly give more context if required.

A: When there are no intersections with the conic, the coordinates of the two imaginary intersections will be complex conjugates. That is, corresponding coordinates of the two points will be of the form $a\pm bi$. For example, the unit circle $x^2+y^2=1$ intersects the line $y=2$ at the imaginary points $(\pm\sqrt3i,2)$; the intersections of the line $x+y=2$ with this circle are $\left(1\pm\frac1{\sqrt2}i,1\mp\frac1{\sqrt2}i\right)$  .
This is a consequence of the fact that these coordinates are solutions of quadratic equations with real coefficients, complex roots of which always come in conjugate pairs.


text:
Q: How to render data in table Anguar? I got the following JSON response:
let rows = [[{"key":"undetected","value":"","indexrow":0,"columnindex":0},{"key":"fullname","value":"Robert servel","indexrow":0,"columnindex":1},{"key":"num","value":"5137999","indexrow":0,"columnindex":2},{"key":"mmyy","value":"09\/24","indexrow":0,"columnindex":3},{"key":"country","value":"MASTERCARD FRANCE S.A.S.","indexrow":0,"columnindex":5},{"key":"name","value":"servel","indexrow":0,"columnindex":6},{"key":"name","value":"roselyne","indexrow":0,"columnindex":7},{"key":"undetected","value":"20\/05\/1962","indexrow":0,"columnindex":8},{"key":"email","value":"ro@laposte.net","indexrow":0,"columnindex":9},{"key":"address","value":"10, route d'arlanc","indexrow":0,"columnindex":10},{"key":"address","value":"Craponne sur arzon","indexrow":0,"columnindex":11},{"key":"zip","value":"43500","indexrow":0,"columnindex":12},{"key":"phone","value":"08888","indexrow":0,"columnindex":13}]];

It is array of  rows with array of columns where column is like:
{"key":"zip","value":"43500","indexrow":0,"columnindex":12}

I try to render  this object in table form:

    <ng-container *ngFor="let row of rows">

                {{column.value || '-'}}

    </ng-container>

Hwo to display each column the same contect type? For exmaple for all rows in first column must be zip type etc.
Yes, I can sort array of columns in sequance what I need by keys: "zip", "num", "fullname"

A: I would advise you to do some data transformation before you display it in a html table...
your data has the row and column index as well as the name of the data points and its values:
{"key":"undetected","value":"","indexrow":0,"columnindex":0}

{"key":"fullname","value":"Robert servel","indexrow":0,"columnindex":1}

*

*I suggest you transform it into something that looks like this:

rows = [
 { "undetected": "", "fullname": "Robert servel", ...}
 ...
]

*once the transformation is done building the table columns with the desired order becomes considerably easier:

      Undetected
      Full name
      ...

    <ng-container *ngFor="let row of rows">

             {{row.undetected || '-'}}
             {{row.fullname || '-'}}
            ...

    </ng-container>


text:
Q: Is writing dvd's at a lower speed better for reliability? I've written quite a few DVD's.  At 16x, I've gotten occasional errors (using the same brand of media all the while) - about 1 in 25 fails to write.  I recently started writing at 4x, I'm finding I've gotten no errors and no unreadable disks.  I'm starting to think I should write all my important dvd's at this low speed.
I've also written dvd's only to have them pass the initial "verification", then about a month later, try to use them only to find that parts of them have become unreadable.
(None of the dvd's are scratched or physically damaged)
Does writing at a lower speed increase reliability of dvd's ?

A: It help a little, but I would also be aware that disk rotating at much lower speed is getting burned much more that designed and that can cause problems also. Higher speed DVDs have also more sensitive layer.
Best bet would be to leave it on auto since most (if not all) DVD writters test their burn intensity anyhow.
I assume that big part of you problem here is not writting speed but batch of bad DVD media.

A: Generally if you run your burning software on "Auto" it'll burn at the fastest speed it can with the drive and media ok. Normally if I keep getting bad burns it's because the DVD's I purchased aren't very good, or if you haven't used the drive yet maybe the drive is defective.
The risk of buffer under runs and such were much more common in the early days of CD burners, but today it really isn't much of an issue. Todays burning software and hardware is much better at preventing burn issues.


text:
Q: Angular, which event can be fired before browser refresh stateChangeStart is not fired when refresh page.
        this.scope.$on('$stateChangeStart', (event, next, current) => {
            if(!confirm("Are you sure you want to refresh this page?")) {
                event.preventDefault();
            }
        });

stateChangeSuccess is only fired when the page refresh is already done.
which event would be fired before the refresh?

UPDATE:
tried window.onbeforeunload not working in my case
this is part of my code, is that right?
export default class TableController {
    constructor($scope,$state, $location) {
        //some initialization here
        window.onbeforeunload = function() {
            console.log('onbeforeunload');
            debugger;
            return null;
        }
    }
    //other coll functions
    ...
}

A: Handling the page refresh is not part of angular state's job.
Use window.onbeforeunload.
window.onbeforeunload = function(){
   return "are your sure?";
}

NOTE:
This function bound to window.onbeforeunload will not be removed when angular's state changes. you need to manually set it to null when you don't need it any more.
window.onbeforeunload = undefined

A: State change events are done at root scope. Probably that might be the reason as it is not working. Please refer the documentation on how to call the state change events.
https://github.com/angular-ui/ui-router/wiki#state-change-events


text:
Q: C: For loop acting REALLY strangely with scanf So I've got the following code:
int q, x, y;
char l;
for (q = 0; q<10; q+=1) {
    printf("%d\n", q);
    if (3 == scanf("%c %d %d", &l, &x, &y)) {
        printf("%d\n", q);
    }
}

I would expect this to run "scanf" 10 times. Each time it will print 'q' before I enter anything, and once again after. So the expected output should be this (correct me if I'm wrong):
0
> a 1 1
0
1
> b 2 2
1
2
> c 3 3
2
...and so on.

But I actually get this.
0
> a 1 1
1
1
2
> a 2 2
3
3
4
> a 3 3
5
5
6
> a 4 4
7
7
8
> a 5 5
9
9

If I take out the scanf function, it counts from 0-9 as expected. What's happening with the scanf function to make the for loop act so weirdly? I've got some experience in Java/Python, but I'm totally new to C.
Editing the code based on your comments to this (apologies for weird formatting):
for (q = 0; q<10; q+=1) {
        printf("%d: ", q);
        if (3 == scanf("%c %d %d ", &c, &x, &y)) printf("%d\n", q);
        else { printf("WTF %d\n", q); }
    }

half solves the problem. It works for all of the iterations EXCEPT for the first one. As so:
0: a 0 0
WTF 0
1: b 1 1
1
2: c 2 2
2

What's going on there? There is other outputted code above that first line, from another part of the program. Could that be causing this?

A: you have unconsumed "\n", getchar() will consume it:
if (3 == scanf("%c %d %d", &l, &x, &y)) {
    getchar();
    printf("%d\n", q);
}

A: Unlike %s, %d, %f, and most other conversion specifiers, the %c conversion specifier doesn't skip over any leading whitespace, so it's picking up the newline from the previous entry.
After you type a 1 1 <Enter>, the contents of the input stream are {'a', '1', '1', '\n'}.  The first scanf consumes the a, 1, and 1, leaving the trailing \n in the input stream.  scanf returns 3 and you print the value of q.
The second time through the loop, scanf picks up the leftover \n and assigns it to l, but since there's nothing else in the input stream it doesn't assign x or y, so it returns a value of 1 and your branch isn't taken.  Then the loop starts over again.
The easiest way around this problem is to put a leading space in the format string before the %c conversion specifier:
if (3 == scanf(" %c %d %d", &l, &x, &y))
  printf("%d\n", q);

That leading space in the format will cause scanf to skip over any leading whitespace in the input stream, so you won't accidentally pick up the trailing newline from the previous entry.  Of course, if you want to pick up any whitespace characters, you'll have to do something different.

A: Why don't you try adding an else statement and printf to your vars to debug this?
It seems that for every time (3 == ..) is true, there is another time that it is false.
scanf might be running twice for the newline character when you hit enter...

A: scanf function is returning different values instead of 3(three inputs). I don't know exact reason but I feel because of spaces in scanf("%c space %d",&c,&i); function it is returning different values.


text:
Q: Codeigniter Framework How can I pass values through form action field in CodeIgniter framework?
First, I tried to add PHP variable direct to the form action field, that I  am attaching below
<form class="col s12" action="<?php echo base_url('index.php/Welcome/forgotpass/').$res; ?>" method="post">

$res is an array. That is defined below
$res=array('id'=>$h['id'],'username'=>$h['username'],'usertype'=>$h['usertype']);

$h is defined in the controller
$res['h'] = $this->forgotpassword->forgotpassword();

$this->load->view('forgotpassword1',$res);
the h is read in the view array $res and I want to pass this array through form action and that would be read in the controller.

A: You can do a few things:
Turn the variables into a string $str where $str = 'id=this&username=that' and in your action <?php echo base_url('index.php/Welcome/forgotpass/') . '?' . $str; ?> and fetch the individual variables via $this->input->get('username') .etc.
OR
Turn each into a hidden input:
$this->load->helper('form');
foreach ($res as $field_name => $field_value) {
    echo form_hidden($field_name, $field_value);
}

and fetch the individual variables via $this->input->post('username')
OR
Send the user a recovery key:
Have the user enter a unique identifier such as their username or name and post that to the forgotten password controller which will then get the user's email in a fashion like:
$this->db->select('email')->where('username', $this->input->post('username'))->get('users')->row()->email;
and store a hashed long value in your database in the users row (let's call it recovery_key) which you send to the user using the email you just got from the unique identifier. When the user gets the email it contains a link like somewebsite.com/pass_recovery/some_recovery_key and with that they can reset their password as only they have the unique hash.
On the recovery page simply see if a hashed value like that exists in the database, if it does, it exists to a single user - the user that is trying to recover their password.
Check out Ion_Auth, they do this well.


text:
Q: creating a data and pushing in to array and showing them in a map is not working correctly? Problem:
I am creating react native app with Google map integration. This is how I have done It.
import React, { Component } from "react";
import { View, Text, StyleSheet, Dimensions } from "react-native";

import { MapView } from "expo";
import Marker from "./Marker";
class Parking extends Component {
  static navigationOptions = {
    title: "Parking",
    headerStyle: {
      backgroundColor: "#06153b"
    },
    headerTintColor: "#fff",
    headerTitleStyle: {
      color: "#ffff"
    }
  };
  constructor(props) {
    super(props);
    this.state = {
      focusedLocation: {
        latitude: 0,
        longitude: 0,
        latitudeDelta: 0.0122,
        longitudeDelta:
          (Dimensions.get("window").width / Dimensions.get("window").height) *
          0.0122
      },
      locationChosen: false,
      placesList: []
    };
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      pos => {
        const coordsEvent = {
          nativeEvent: {
            coordinate: {
              latitude: pos.coords.latitude,
              longitude: pos.coords.longitude
            }
          }
        };

        this.pickLocationHandler(coordsEvent);
      },
      err => {
        console.log(err);
        alert("Fetching the Position failed");
      }
    );
  }

  pickLocationHandler = event => {
    const coords = event.nativeEvent.coordinate;
    let placesList = [];
    let places = [];
    this.map.animateToRegion({
      ...this.state.focusedLocation,
      latitude: coords.latitude,
      longitude: coords.longitude
    });
    const apikey = "My API key";
    fetch(
      "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
        coords.latitude +
        "," +
        coords.longitude +
        "&radius=500" +
        "&type=parking" +
        "&key=" +
        apikey
    )
      .then(response => response.json())
      .then(responseJson => {
        if (responseJson) {
          placesList = responseJson.results;
          console.log(placesList);
          placesList.map((el, index) => {
            const place = {
              title: el.name,
              coordinates: {
                latitude: el.geometry.location.lat,
                longitude: el.geometry.location.lng
              }
            };
            places[index] = place;
          });
        }
      });

    if (places) {
      this.setState({ placesList: places });
      console.log(places);
    }
    this.setState({ locationChosen: true });
  };

  render() {
    let marker = null;
    if (this.state.locationChosen) {
      marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
    }
    const places = this.state.placesList;
    return (
      <View style={styles.container}>
        <MapView
          initialRegion={this.state.focusedLocation}
          showsUserLocation={true}
          style={styles.map}
          onPress={this.pickLocationHandler}
          ref={ref => (this.map = ref)}
        >
          {places.map((place, index) => {
            <MapView.Marker
              coordinate={place.coordinates}
              title={place.title}
            />;
          })}
          {marker}
        </MapView>
      </View>
    );
  }
}

export default Parking;

const styles = StyleSheet.create({
  container: {
    width: "100%",
    alignItems: "center",
    paddingBottom: 10,
    paddingLeft: 10,
    paddingRight: 10,
    paddingTop: 10
    // backgroundColor:"#192f6a"
  },
  map: {
    height: "100%",
    width: "100%"
  },
  button: {
    margin: 8
  }
});

But It is showing Nothing On the Map. When I console log the places Like this.
if (places) {
          this.setState({ placesList: places });
          console.log(places);
        }

It shows an Empty array. If I console log the placesList inside the fetch it shows the results. Can Someone help me to solve this problem and To modify My code in order to show the markers for the places that I have got from the fetch result from google API in the map?. Thank You very Much!!.

A: I'm fairly new to all this but I would say a couple of things:
1 - You're declaring 'place' as a const const place = ... but you're also trying to update it within the map loop, so I'm guessing that won't work. Use var place = ... instead?
2 - Instead of places[index] = place, does places.push(place) work?


text:
Q: Prevent text highlight when click I have a input field with plus minus sign to raise/lower the number in it. Looks like this:
-
<input type="text" text-input">
+

How can I disable/prevent the select/highlight of the +/- text when I click to raise the numbers?
I'm looking for a solution that works cross browser. Thanks

A: Depending of what versions of browsers you have to support, you can try using css property user-select to none. Here you have an example of such implementation http://css-tricks.com/almanac/properties/u/user-select/

A: you can use css ::selection
::selection {
  background: none;
}
::-moz-selection {
  background: none;
}
::-webkit-selection {
  background: none;
}

A: The best practice is to have <button> doing that.
Then both your highlight problem is solved and you write code in a better way.
(you can also change buttons with CSS so they look like you want)

A: <!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

    <button onclick="less()">-</button>
    <input type="text">
    <button onclick="more()">+</button>

    OR<br

    -
    <input type="text">
    +

Quick plnkr: http://plnkr.co/edit/u7dKekjLg6DpyUjz1a06?p=preview


text:
Q: Interview Q - Design File System - Review All,
I was recently asked in one of the technical interviews to write a high level design for a File Sysem. My answer to the question was as follows. I would request everyone to please review and let me know if there are suggestions/improvement:
  interface BaseFileSystem
{
    /*Basic file/folder attributes are:
      1. File/Folder Size
      2. File/Folder Date created
      3. File/Folder Date Modified
      4. File/Folder permissions - Read, write and execute
      5. File/Folder Owner - Owner of the file who defines permissions for other users
      6. File/Folder Visibility - Hidden or Visible
      7. File/Folder Name

      Hence each one of the above attributes would have public <return type> get() and public void set<AttributeName>(<variable datatype>) */
}

public class File implements BaseFileSystem
{
       /*The `File` class should implement all of the methods from interface `BaseFilesystem`.
         In addition, it must also implement following specific methods that can only be associated with physical files*/

        public String getFileExtension(){….}

        public void setFileExtension(String value) {….}

        public String[] getAssociatedPrograms(){ …..}

        public void executable(){ …. };
}

public class Folder implements BaseFileSystem
{

      /*The `Folder` class should implement all of the methods from interface `BaseFileSystem`. In addition, it must also implement following specific methods that can only be associated with the physical 'folders'*/

        public BaseFileSystem[] getSubFoldersAndFiles(){ …. }

        public void addSubFolderAndFiles(BaseFileSystem fileObj) { …. }

        public void executable(){throw new UnsupportedOperationException();}
}

Additionally, any general pointers to such design questions would be greatly appreciated.

A: There are three essential operations, that are missing:

*

*reading the contents of a file

*writing the contents of a file

*testing whether a BaseFileSystem is a File or a Folder
On the other hand, there are some operations that I do not consider essential for a file system:

*

*the file extension does not have any significance in all operating systems. Then why should a method exists for setting and retrieving it?

*the associated programs only have a meaning in a single computer/os combination. In a general purpose file system, the programms might exists only temporarily (because a different os is booted or the device is moved). It should IMHO not be stored as part of the meta information of a file, because of separation of concerns.

*public void executable() seems out of place. But this is only a guess, because I do not know what this method is supposed to do. If this executes an executable file: that should be done by the operating system manually. Also, it has no business being defined in class Folder.

Furthermore, the attributes that you defined in BaseFileSystem make some assumptions about the requirements of the file system. Maybe your simple permissions system is not sufficient or the purpose of the file system and ACLs are needed. Maybe visibility is determined by the name of the file (like in UNIX). You should clarify that beforehand.

A: From what i know about interview questions, you need to make sure you ask clarifying questions about the file system. The hidden part of a question like that is to make sure you're someone who can identify ambiguity. Also figure out who your users might be, since they might not care about "Date Modified"
When i read this question, i was thinking something *nix-based and would use the command lines! Good luck!

A: I don't think it makes sense to just give an API. If you follow POSIX, the API is already given to you. Wouldn't it make more sense to describe the data model for the file system? For example, how do you link the data, track used/free blocks, handle modifications, etc...
I didn't like this either:

Hence each one of the above attributes would have public  get() and public void set() */

I really detest getters/setters. If I was going to design a file system, I would push any file metadata outside of the file system. Instead provide a generic interface for arbitrary metadata. For example, permissions might be irrelevant on an embedded system, so why make it part of the file system?
Good luck!


text:
Q: Is there a vector 2-norm function in Pydrake? I have defined the following function to compute the pairwise distances between positions of different agents:
def compute_pairwise_distance(X, x_dims):
    """Compute the distance between each pair of agents"""
    assert len(set(x_dims)) == 1
    m = sym if X.dtype == object else np

    n_agents = len(x_dims)
    n_states = x_dims[0]

    pair_inds = np.array(list(itertools.combinations(range(n_agents), 2)))
    X_agent = X.reshape(-1, n_agents, n_states).swapaxes(0, 2)
    dX = X_agent[:2, pair_inds[:, 0]] - X_agent[:2, pair_inds[:, 1]]

    return m.linalg.norm(dX, axis=0)

where X is a 2-dimensional array, and x_dim refers to the dimension of the state vector of each agent as a list, such as [4,4,4], which means there are 3 agents each with 4 state vectors. However, since I'd like to include this pairwise distance metric into a collision-avoidance cost function in symbolic form, the following error occurred:
def cost_avoidance(x,x_dim):
    #`x` here is a 1-dimensional vector
    m = sym if x.dtype == object else np
    if len(x_dim) == 1:

        return 0

    threshold = 0.5 #threshold distance below which cost avoidance is activated

    distances = compute_pairwise_distance(x,x_dim)

    cost_avoid = np.sum((distances[distances<threshold]-threshold)**2)*1000

    return cost_avoid

<ipython-input-46-eeef96aeac91> in cost_avoidance(x, x_dim)
      7     threshold = 0.5 #threshold distance below which cost avoidance is activated
      8
----> 9     distances = compute_pairwise_distance(x,x_dim)
     10
     11     cost_avoid = np.sum((distances[distances<threshold]-threshold)**2)*1000

<ipython-input-45-8b13423fbdb8> in compute_pairwise_distance(X, x_dims)
     14     #     return torch.linalg.norm(dX, dim=0)
     15
---> 16     return m.linalg.norm(dX, axis=0)

AttributeError: module 'pydrake.symbolic' has no attribute 'linalg'

It seems like I must use a symbolic version of vector 2-norm. However, I can't find one according to the documentation. Is there a symbolic vector 2-norm function in Pydrake at all?
https://drake.mit.edu/pydrake/index.html

A: If you do want the 2-norm in symbolic form, then np.sqrt(x.dot(x)) will do the trick:
import numpy as np
from pydrake.all import MakeVectorVariable

x = MakeVectorVariable(2, 'x')
print(np.sqrt(x.dot(x)))

But if your goal is collision avoidance, you might want to take a look at Drake's implementation of MinimumDistanceConstraint.  There are a lot of details in there that make things work well -- like smoothing potential discontinuities at zero distance and/or when the closest body changes to a different collision pair.


text:
Q: Passing string to Angular expression from app.js I've got this function which redirects to the login page when certain conditions are met. This part is working fine, but I want a message on the login page saying why they were redirected.
Currently I have this function within my app.js
app.run(function ($rootScope, $window) {
    $rootScope.$on('$routeChangeStart', function (event) {
        //stuff to evaluate
        if (stuff = true) {
            $rootScope.$evalAsync(function () {
                $scope.message = "test";
                $window.location.assign('#/login');
            });
        }
    });
});

And I also have a page, login.html, with a div where I want my message.
        <div ng-hide="message == ''" class="alert alert-danger">
            {{message}}
        </div>

I have tried adding $scope to the function, and accessing $scope.message, but I don't think I'm in the correct scope. The function never hits when I include this, but it does without. Is there any way I can access the scope of this login.html page? The login page does have it's own controller, but I need to be able to redirect to there from this app.js page.
Any help is appreciated!

A: $scope gets re instantiated (recreated) once you navigate to the new state login, instead of using $scope, you should user service/root$scope/localStorage to pass the value to the next page.
Change it using $rootScope as,
 $rootScope.$evalAsync(function () {
         $rootScope.message = "test";
         $window.location.assign('#/login');
 });


text:
Q: Snowflake - Java Script UDF calling Snowflake External function We have an External function defined in Snowflake. I want to call that function in my JavaScript UDF function. Is it possible to do so?
Thanks

A: Currently, you can't call any other UDF including external functions from a JavaScript UDF. You can call them from SQL UDFs and JavaScript stored procedures by executing them in a SQL statement.
You can also nest UDF calls, like select function_1(function_2(my_value));


text:
Q: MySQL Insert requires specifying all fields? When I execute a pdo that specifies some but not all fields in a table, it inserts fine on one server, but fails to insert on the other server.
FOR EXAMPLE, ON THE PROBLEM SERVER...
With table that has three fields id, time, and intervention...
If I run this statement, it inserts as expected.
$query = "INSERT INTO data_agreements (`id`, `time`, `intervention`) VALUES (?, ?, ?)";
$q = $pdo->prepare($query);
$q->execute(array("x", "y", "z"));

But if I run the following statement, it fails to insert.
$query = "INSERT INTO data_agreements (`id`, `time`) VALUES (?, ?)";
$q = $pdo->prepare($query);
$q->execute(array("x", "y"));

The problem server is an IIS with MySql 5, PHP 5.2.6. On a different server Apache with MySql 5, PHP 5.2.6, both statements insert as expected. So I am wondering if there is some MySQL install/setting that I need to set on the problem server to tell it to accept statements that specify only a subset of fields in a table. ?
Thanks!

A: There is nothing syntactically wrong with your SQL statement. There is no specific "setting" in the MySQL server that controls this behavior, but there are some settings that can influence whether a particular INSERT statement will succeed or not, for example, the setting that allows for invalid dates (i.e. non-existent dates such as June 31), and the setting that allows for zero dates ('0000-00-00') to be stored. (This behavior has changed across versions, where the "old" (e.g. V3.23)  default was to allow invalid dates, and the "newer" (e.g. v5.1) default is to disallow invalid dates.)
If the values supplied for the bind parameters are valid, then the most likely explanation for the behavior you observe is that there is a CONSTRAINT that is (or would be) violated.
This could be primary key constraint, a unique key constraint, a foreign key constraint, a NOT NULL constraint, or it could even be a trigger that is throwing an exception.
For example, the column intervention may be defined as NOT NULL and not have a default value specified.
The MySQL error information might be useful for debugging this.
Another possibility is that this statement is actually succeeding, but is being executed in the context of a transaction that is subsequently being rolled back rather than committed.)
There's not enough information in your question to tell.
I would suggest that you compare the table definitions on the two databases. Easiest way (for me) would be to grab the output from a SHOW CREATE TABLE intervention statement from each database, and look for differences. It's also possible that one of the databases has a BEFORE INSERT FOR EACH ROW trigger which is missing on the other.

A: I bet column intervention do not allow null values.
try to alter the table and see if it works:
ALTER table data_agreements Modify intervention varchar(50) null DEFAULT '';

and try to execute again the query. I assumed that intervention is string but, of course, you can modify it that fits your needs.
Thanks.

A: INSERT INTO data_agreements
  (id, time)
VALUES
  (?, ?) ;

will run fine, if the other fields, intervention in this case, have been defined with a DEFAULT attribute or with AUTO_INCREMENT when the table was created. If not, you have to explicitly provide a value to the INSERT statement.
Check with SHOW CREATE TABLE data_agreements in the 2 installations, how the tables have been defined.
The TIMESTAMP columns of a table have a non-obvious functionality. Only one of them can have a DEFAULT CURRENT_TIMESTAMP attribute (and if you don't state that, only the first one of them in a table gets this default).
The issue you have may have been caused if you had defined one table with more than one timestamp columns and then dropped the first one.


text:
Q: How to change column delimiter in the exported .csv file of the Concurrency Visualizer Thread View, in Visual Studio 2012? I need to change the column delimiter character of the .csv exported file of the Concurrency Visualizer Thread View. I'm using C#, in Visual Studio 2012, on Windows 7 Ultimate.
The problem is that the CSV file uses the comma , character, to separate the columns, and also in the numbers. This brings confusion to the statistics software, including Microsoft Excel. With this symbol you cannot tell if 2000,22 is a float number or two columns (the first with the 2000 value, and the second with the 22 value). I tried to open these files with Microsoft Excel and SPSS v19, using comma (,) or space as columns delimiter, but I do not get the same table exported from the Concurrency Visualizer.
I'm doing an investigation that requires measuring code block in milliseconds, that is why I'm using the span of the Concurrency Visualizer. I need to statistically process the duration of all the spans, to be sure my code is getting the right results. That is why I am using the CSV export feature, in the Concurrency Visualizer Thread View.
The semicolon character ; could be a nice column delimiter, because it eliminates the ambiguity.
The CSV file exported by the Concurrency Visualizer Thread View can be a great tool for software investigation, once we solve this.


text:
Q: How to Get Selected Cell Value InTextBox I have a textbox and a GridView. I have made a column in gridview as a linkbutton. I want that when I click a linkbutton I get that link button text value in my textbox.
My gridview is shown below-

I want When I click test5 my textbox1.text = test5 and so on..
How can I do this ?

A: Please add commandname in gridview link column as below
<asp:LinkButton runat="server" id="lnklink" CommandName="displayLink" />

And add the "RowCommand" event on gridview like below
<asp:GridView ID="gvDemo" runat="server
onrowcommand="gvDemo_RowCommand" />

protected void gvDemo_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "displayLink")
    {
       textbox1.text=((LinkButton)e.CommandSource).Text;
    }
}

A: You can do this both in asp as well as using client side technologies like JQUERY javascript etc, I will suggest you to use jquery since keeping such things in client side will help you improve the performance
Now when u create a grid /repeater etc ultimately .net renders it into simple html controls, and jquery or client side technologies just work over this html , here is a small example with simple html
> HTML
My data : <input type="Text" id="TxtBox"/> //in .net id u have to take care by using .clientid property

            <input type="checkbox"/>

            SOmething

            LINK1

            <input type="checkbox"/>

            SOmething2

            LINK2   //class name is important since thats what we  are going deal with

            <input type="checkbox"/>

            SOmething3

            LINK3

JQUERY
    $(".someName").on("click","",function(){
       $("#TxtBox").val($(this).text());
    });

FIDDLE
http://jsfiddle.net/AmarnathRShenoy/Hw4UG/

A: create RowCommand event for grid and then do the following code
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.ToLower() == "test")
    {
        textbox1.Text = e.CommandArgument.ToString();
    }
}

and for aspx page do the following in your linkbutton
                <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="linkbtn" runat="server" Text="test5" CommandArgument="test5" CommandName="test" />
                </ItemTemplate>
            </asp:TemplateField>

or if you are binding your database table column to your linkbutton then do the following
                <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="linkbtn" runat="server" Text='<% yourcolumname %>' CommandArgument='<% yourcolumname %>' CommandName="test" />
                </ItemTemplate>
            </asp:TemplateField>


text:
Q: Counting changes made to a file in Perl I have a file named "boot.log". I'm pattern matching this file, making changes to certain keywords, and then writing them to a file named "bootlog.out". I'm not sure how I can count the number of changes made and print them to "bootlog.out". I'm pretty sure I need to use a foreeach loop and a counter, but I'm not sure where. And how to print those changes made. Here's what I have so far...
open (BOOTLOG, "boot.log") || die "Can't open file named boot.log: $!";
open (LOGOUT, ">bootlog.txt") || die "Can't create file named bootlog.out: $!\n";

while ($_ = <BOOTLOG>)
{
    print $_;
    s/weblog/backupweblog/gi;
    s/bootlog/backupbootlog/gi;
    s/dblog/DBLOG/g;
    print LOGOUT $_;
}

close (LOGOUT) || die "Can't close file named bootlog.txt: $!\n";
close (BOOTLOG) || die "Can't close the file named boot.log: $!";

A: The substitution regex returns the number of substitutions made. Here is an updated copy of your code as an example:
open (my $bootlog, '<', "boot.log")   || die "Can't open file named boot.log: $!";
open (my $logout, '>', "bootlog.txt") || die "Can't create file named bootlog.out: $!\n";

my $count = 0;
while (<$bootlog>)
{
    print $_;
    $count += s/weblog/backupweblog/gi;
    $count += s/bootlog/backupbootlog/gi;
    $count += s/dblog/DBLOG/g;
    print {$logout} $_;
}

close ($logout)  || die "Can't close file named bootlog.txt: $!\n";
close ($bootlog) || die "Can't close the file named boot.log: $!";
print "Total items changed: $count\n";


text:
Q: Html.BeginForm - HTTP POST method - VB.NET 2012 MVC 4 Visual Studio The focus is on the "controllerName As String" - part - of the Html.BeginForm function.
The HTML:
root/Views/Home/Therequestform.vbhtml

Therequestform

@Html.BeginForm("Therequest", "Home", method:= FormMethod.Post)

    <fieldset>
        <input type="text" name="ColorName" />
        <input type="submit" name="ColorName_SubmitButton" />
    </fieldset>

The Controller:
root/Controllers/HomeController.vb
Function Therequestform() As ActionResult

    Return View()

End Function

    <HttpPost()>
    Function Therequest() As ActionResult

        Response.Write("The color you have submitted: " & Request.Form("ColorName"))

        Return View()
    End Function

End Class

The Question:
EDIT: The call to the View is done above the request call to the HTTP POST method with the function "Therequest" - in the Controller.
The reference to the ControllerName has been done in the second part of the Html.BeginForm, whereas in the first part of Html.BeginForm the reference to the function to call a request to the HTTP POST method is done.
The problem I am having is, that after pressing the submit button, the call to the function (in the controller) is not done in the set location. Where the following error message comes up, after the ´submit button´ is pressed:

Server Error in Application.
  The view 'Therequest' or its master was not found or no view engine supports the searched locations. The following locations were searched:
Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The view
  'Therequest' or its master was not found or no view engine supports
  the searched locations. The following locations were searched:
~/Views/Home/Therequest.aspx

~/Views/Home/Therequest.ascx

~/Views/Shared/Therequest.aspx

~/Views/Shared/Therequest.ascx

~/Views/Home/Therequest.cshtml

~/Views/Home/Therequest.vbhtml

~/Views/Shared/Therequest.cshtml

~/Views/Shared/Therequest.vbhtml

Source Error: An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

The "search", or also the "call" is not done in the set location. Where by the parameter array of the Html.BeginForm, the to be executed function name is set, and also, the controllerName is set - which is set to (root/Controllers/HomeController.vb) - and in the third part the method is set to POST.
The question is, what is causing it to not do the call in the set location?

The Tools Used: VB.NET 2012, MVC 4, Visual Studio 2012, Microsoft SQL Server 2012

A: it is trying to render View named Therequest.vbhtml whereas you have your view named Therequestform.vbhtml
Either change the view name to Therequest.vbhtml or change the controller name to Therequestform and all the places where it is referenced


text:
Q: Can we pass the argument in SQL query while working with pandas dataframe, python I have to program for calculating the 'Date Anomalies' for number of contacts per client, number of contracts varies per client. With the following 3 steps I am calculating the Date Anomalies correctly for each contact and at last appending all dataframes and writing it into excel file with sheet wise(as per contract) and one consolidated sheet of all contracts.
Here is the code:
Step1:  # Connecting to Database
import pandas as pd
import numpy  as np
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=XXXXXXXX;'
                      'Database=XXXXXXX;'
                      'Trusted_Connection=yes;')

Step 2: sql_query = pd.read_sql_query("Select DISTINCT  ContractName , clientcode, TypeOfFile (CASE WHEN SentToBBDate > BBLoadedDate then 'ERROR - SENT DATE GREATER THAN LOAD DATE' WHEN ReceivedDate > SentToBBDate then 'ERROR - RECEIVED DATE GREATER THAN SENT DATE'  WHEN ReceivedDate is NULL then 'ERROR - FILE NOT RECEIVED' ELSE 'NORMAL' END) AS Error_Message from DataDashboard Where  **ContractName like '%***%**' AND  ClientCode LIKE '%AAA%' Order by TypeOfFile", conn)
first = sql_query.to_csv("firstDashboard.csv")

Step 3:
first= pd.read_csv("C:\\Users\\pd\\Desktop\\firstDashboard.csv")
first = Cigna.iloc[: , 1:]
first.drop(first[(first['ERROR_MESSAGE'] == 'NORMAL')].index, inplace=True)
first.to_excel("first_DateReport.xlsx", index=False)

Step 2& 3 I repeat for each contract in same Notebook(Jupyter). And append all the dataframes and writing the result into excel file contract wise in different sheets in one excel file.
Here is the Code
writer = pd.ExcelWriter("C:\\Users\\pd\\Desktop\\Consolidated_DateReport.xlsx")
sheets_in_writer=['Conso_DateReport', 'First_DateReport','Second_DateReport']
data_frame_for_writer=[Appenddf,First, Second]

for i,j in zip(data_frame_for_writer,sheets_in_writer):
    i.to_excel(writer,j,index=False)

### Assign WorkBook
workbook=writer.book
# Add a header format
header_format = workbook.add_format({'bold': True, 'size':11,
                                                      'valign': 'top','fg_color': '#c7e7ff','border': 1})

for worksheet in writer.sheets.values():
            row_count = len(df.index)
            column_count = len(df.columns)

### Apply same format on each sheet being saved
for i,j in zip(data_frame_for_writer,sheets_in_writer):
    for col_num, value in enumerate(i.columns.values):
        writer.sheets[j].write(0, col_num, value, header_format)
        writer.sheets[j].freeze_panes(1,0)
        writer.sheets[j].autofilter(0, 0, row_count-1, column_count-2)
        writer.sheets[j].set_column(0, 7 - 1, 25)

writer.save()

How do I use the loop/function to pass on the values in Step2 and 3 and avoid writing same code number of times(11 times). In step2 ContractName should get change in SQL query(Where ContractNmae like '%AAA%) And in step3 it should get change such as second then third upto 11.
Any help will be appreciated.


text:
Q: Referring to "Stack Overflow" as "Stack Exchange", and vice versa When writing generally about Stack Exchange, I often find myself either:

*

*Saying "Stack Overflow" instead since it is more well-known.

*Saying something like "Stack Overflow/Exchange".

That's a bit like saying "Google Search/Mail" when talking about Gmail. Search came first but Gmail isn't exactly a subset of "Google Search", but in fact just "Google".
Although it's a bit of a chicken-before-the-egg situation, Stack Overflow is now a subset of Stack Exchange since it runs on the SE network, correct? However, the following links don't redirect:

*

*overflow.stackexchange.com

*stackoverflow.stackexchange.com
In any case, what should one call it all?
(This is more a question of branding really... so "Stack" would be good, but that domain is taken.)

A: I would call Stack Overflow "Stack Overflow", just like I would refer to other specific sites by their names (Super User, Arqade, Programmers, etc.).
It really depends on what you're writing about, I think. You could say "Stack Overflow, which is a part of a larger Stack Exchange network of Q&A sites" or something along those lines.
Stack Exchange is also the name of the company, so if you're talking about that... call it that.
If you're writing about the network in general but want to inject a familiar name, something like "The Stack Exchange network that includes sites like Stack Overflow and Server Fault..." could work.
You get the idea.
There's also the section on proper use of our name in the Trademark Guidelines:

Stack Exchange Inc. is the official name of the company.
Stack Overflow is a programmer Q&A site on the Stack Exchange Network. As a name, Stack Overflow, is always written "Stack Overflow"
(two words, capital letters). The website domain name is always
written stackoverflow.com (no CamelCase, single word
capitalization rules apply). Currently, all Stack Exchange Network
sites follow this convention: Server Fault (serverfault.com), Super
User (superuser.com), etc.
A Stack Exchange site is a Q&A
website built on the technology of Stack Exchange Inc. The phrase
"Stack Exchange" is generally used as an adjective, not a noun. One
would say "Propose a Stack Exchange site on Area 51" (correct), not
"Propose a Stack Exchange on Area 51" (wrong).
The Stack Exchange
Network refers to the collection of Stack Exchange sites and
services.
Area 51 (two words) is the site used to propose new Stack Exchange sites for the Stack Exchange Network.
The Stack Exchange API
allows users to write applications based on the Stack Exchange engine.
The API is always referred to as "Stack Exchange API", even if the
application is written for a specific site (i.e. never Stack Overflow
API, Server Fault API, etc.).
The Stack Exchange Blog is the
company blog which talks about everything we're doing on all our sites
and what the company itself is doing.

(If these guidelines change and this answer isn't updated, ignore what's here and go with the official version on the page linked above.)


text:
Q: How to send a post request to Azure IoT Hub using postman I am trying, in order to simulate a device, to send a message to an existing IoT-Hub following this procedure: https://www.codeproject.com/Articles/1113447/Azure-IOT-Hub-REST-API
I am able to successfully create my shared access signature using the Device Explorer.
In postman, I send a post request to:
https://myHubName.azure-devices.net/devices/myDeviceId/messages/events?api-version=2016-02-03
(my real hub name isn't myHubName)
With the Authorization header with the shared access signature and with the content type header,
With this JSON: {deviceId: "myDeviceId", temperature: "80"}
But I have no response whatsoever from the endpoint (Timeout).
I feel like the server should at least respond with an unauthorized request. Am I missing something here?

EDIT:
As discussed with Rita, I was missing the s in https when I was trying to send the request. The IoT-Hub now responds appropriately.


text:
Q: Dynamic columns with Datatables javascript js in order to display a json file. I extract the name of my columns and build an array like this one :
columns = ["Date", "C2R", "CM", "Total"]

My sTitle and mData have the same name so I try to do that but fail.
    jQuery('#result_example').dataTable( {
        "data": result_table,
        "columns": [
            jQuery.each(columns, function(i, value){
                //console.log(value); which give ["Date", "C2R", "CM", "Total"]
                { "sTitle": + value + , "mData": + value + },
            })
        ],

        paging: true,
        searching: false,
        "bInfo" : false
    } );

The objective is to have a result like this :
    jQuery('#result_example').dataTable( {
        "data": result_table,
        "columns": [
                { "sTitle": "Date" , "mData": "Date" },
                { "sTitle": "C2R" , "mData": "C2R" },
                { "sTitle": "CM" , "mData": "CM" },
                { "sTitle": "Total" , "mData": "Total" }
        ],

        paging: true,
        searching: false,
        "bInfo" : false
    } );

A: You can build an object outside and then use it inside dataTable
var clmns = [];
jQuery.each(columns, function(i, value) {
    clmns.push({ "sTitle": value, "mData": value}); // push it in
});
jQuery('#result_example').dataTable({
    "data": result_table,
    "columns": clmns, // use it here
    paging: true,
    searching: false,
    "bInfo": false
});

A: Issue:
When you execute your datatable code it does not get the columns name because you are extracting it later but at that moment datatable code has been executed, so what you can do is this with jQuery.map() is to create an array filled with objects of each iteration of your columns array:
var colData = $.map(columns, function(colName) { // creates an array
   return { "sTitle": colName, "mData": colName};// fills with js objects
});

jQuery('#result_example').dataTable( {
     "data": result_table,
     "columns":colData, //<---------you can pass it here.
     // other code as is
});


text:
Q: Overlay smaller image in a larger image in OpenCV C# I have already searched the answer in python.
But I don't know how to convert it into C#
Python code:  (copy from [overlay a smaller image on a larger image python OpenCv)
import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0],x_offset:x_offset+s_img.shape[1]] = s_img

//alpha channel
s_img = cv2.imread("smaller_image.png", -1)
for c in range(0,3):
l_img[y_offset:y_offset+s_img.shape[0],
x_offset:x_offset+s_img.shape[1], c] =  s_img[:,:,c] * (s_img[:,:,3]/255.0) +  l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1], c] * (1.0 - s_img[:,:,3]/255.0)


text:
Q: How to add password to website using Ngrok I'm using ngrok to expose my website to Internet, and I have a question is it possible using ngrok to add password to website, so before someone see the website has to enter password ?

A: You can use basic ngrok authentication using bellow command to start exposing your server
ngrok http {port_which_you_want_to_expose} -auth="{username}:
{password}"

A: I used
ngrok http 8000 --basic-auth 'ngrok:issecure' --basic-auth="username:password"

You need the issecure flag, and also the --basic-auth= should be wrote like this not like -auth= only


text:
Q: How to transfer data from all table in database to azure data lake destination? I have two tables tbl1 and tbl2. I want to create a package which will read the data from tbl1 and tbl2 and transfer the data to Azure data lake as two files tbl1.txt and tbl2.txt.
What I have done is created Execute SQL task with query
select name from sys.tables ,which will return table names and loop through that result and store into store variable. But Oledb Source doesn't accept query like
select * from @[user::tablName] (a variable which has a table name)

A: Frame the entire query in the variable
select * from <variablename>

And then use select query from variable  option to fetch the data.


text:
Q: Stylesheet not loading I'm doing a web development project using flask and I'm using CSS and JS template for the frontend of my homepage. I need help because, the stylesheets are not loading. This is the file structure:
.
├── __pycache__
│  └── app.cpython-310.pyc
├── app.py
├── README.md
├── requirements.txt
└── website
   ├── __init__.py
   ├── __pycache__
   │  ├── __init__.cpython-310.pyc
   │  ├── auth.cpython-310.pyc
   │  ├── models.cpython-310.pyc
   │  ├── types.cpython-310.pyc
   │  ├── validator.cpython-310.pyc
   │  └── views.cpython-310.pyc
   ├── models.py
   ├── templates
   │  ├── assets
   │  ├── base.html
   │  ├── home.html
   │  ├── index.html
   │  ├── Readme.txt
   │  ├── sign-up.html
   │  └── test.html
   └── views.py

The code below is from a base template called base.html and I used jinja to import the contents in the base template to my home.html.
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>{% block title %}Home{% endblock %}</title>

  <link
    href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Jost:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i"
    rel="stylesheet">

  <link href="assets/vendor/aos/aos.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet">
  <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet">

  <link href="assets/css/style.css" rel="stylesheet">

{% block navbar %} nav bar will be here {% endblock %}

{% block content %}Stuff here ...{% endblock %}

I tried checking the link of the stylesheets and they are all fine but still couldn't load the css and js files.


text:
Q: How to I resize fluid image from "gatsby-image" on my index.js page in gatsby? I have been trying to resize the image on my index.js page in my Gatsby project. I have it loaded through the "gatsby-image" import, and all my code as it should be, but I cant figure out how to resize on both that js file, or the scss file I made for styling.
I have tried to change the maxWidth size, but all that seems to do is change the actual image quality, and not the size. I have also tried to change it in the scss file, but that doesnt seem to work either.
<Img fluid={props.data.imageOne.childImageSharp.fluid} />

export const fluidImage = graphql`
  fragment fluidImage on File {
   childImageSharp {
    fluid(maxWidth: 1000) {
  ...GatsbyImageSharpFluid
     }
   }
  }
`;

export const pageQuery = graphql`
 query {
  imageOne: file(relativePath: { eq: "me.jpg" }) {
  ...fluidImage
   }
 }
`

I am expecting the image to be smaller, but the only output I have had at the moment is a lower quality image, or parts of the image being chopped off.

A: Unfortunately, you cannot change the maxWidth: 1000 directly in the query via a variable because GraphQL runs once at build time and then never again. No hot reloading possible.
export const fluidImage = graphql`
  fragment fluidImage on File {
   childImageSharp {
    fluid(maxWidth: 1000) {
  ...GatsbyImageSharpFluid
     }
   }
  }
`;

GraphQL delivers the image to you in the quality you specify. You can then resize the image via CSS. I remember having the same problem as you. I wrapped the image component in a div that has a defined with or min-width / max-width. Not the most elegant solution but it works.
import GatsbyImage from "gatsby-image";
// ...
<ImageWrapper className="imageWrapper">
  <GatsbyImage fluid={fluid} />
</ImageWrapper>

In your CSS file:
.imageWrapper {
   /*   min-width: 11rem; */
   /*   max-width: 20rem; */
   width: 280px;
}


text:
Q: Java map replace one-ot-one For example, I have a String "PARAMS @ FOO @ BAR @" and String array {"one", "two", "three"}.
How would you map the array values one-to-one to the string (replace the markers), so that in the end I would get: "PARAMS one, FOO two, BAR three".
Thank you

A: You could just do
String str =  "PARAMS @ FOO @ BAR @";
String[] arr = {"one", "two", "three"};

for (String s : arr)
    str = str.replaceFirst("@", s);

After this, str would hold "PARAMS one FOO two BAR three". Of course, to include the commas you could just replace with s + ",".

A: You can also do it this way: -
    String str = "PARAMS @ FOO @ BAR @";
    String[] array = new String[]{"one", "two", "three"};
    String[] original = str.split("@");

    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < array.length; i++) {
        builder.append(original[i]).append(array[i]);
    }
    System.out.println(builder.toString());

A: Note - very useful method  in class String: String.format. It helps to solve your problem very laconically:
String str = "PARAMS @ FOO @ BAR @";
String repl = str.replaceAll( "@", "%s" ); // "PARAMS %s FOO %s BAR %s"
String result = String.format( repl, new Object[]{ "one", "two", "three" });
// result is "PARAMS one FOO two BAR three"


text:
Q: Question from Number Theory Through Inquiry I am having trouble proving the following theorem from the book Number Theory Through Inquiry:
Let $p$ be a prime, $b$ an nonzero integer, and k a natural number. Then the number of $k$-th roots of $b$ modulo $p$ is either $0$ or $\gcd(k, p − 1)$.
Thoughts: I see that the question can be simplified to restricting $k$ to be a divisor of $p-1$, but I haven't been able to make further progress.

A: It suffices to consider the case where $k$ is a divisor of $p-1$. Now let $q$ be a primitive root of $G=(\mathbb{Z}/p\mathbb{Z})^*$. Using Will Jagy's hint in the comments, we consider the subgroup $$H=\{q^{vk}\ |\ 1\le v\le p-1\}\subseteq G$$ Note that $q^{v_1k},q^{v_2k}\in H$ are equivalent if and only if $p-1\ |\ k(v_1-v_2)$. Thus $|H|=(p-1)/k$, where each element of $H$ is repeated $k$ times in the sequence $q^{k},q^{2k},\dots,q^{(p-1)k}$.


text:
Q: Openpyxl to check for keywords, then modify next to cells to contain those keywords and total found I'm using python 3.x and openpyxl to parse an excel .xlsx file.
For each row, I check a column (C) to see if any of those keywords match.
If so, I add them to a separate list variable and also determine how many keywords were matched.
I then want to add the actual keywords into the next cell, and the total of keywords into the cell after. This is where I am having trouble, actually writing the results.
contents of the keywords.txt and results.xlsx file
here
import openpyxl

# Here I read a keywords.txt file and input them into a keywords variable
# I throwaway the first line to prevent a mismatch due to the unicode BOM
with open("keywords.txt") as f:
    f.readline()
    keywords = [line.rstrip("\n") for line in f]

# Load the workbook
wb = openpyxl.load_workbook("results.xlsx")
ws = wb.get_sheet_by_name("Sheet")

# Iterate through every row, only looking in column C for the keyword match.
for row in ws.iter_rows("C{}:E{}".format(ws.min_row, ws.max_row)):
    # if there's a match, add to the keywords_found list
    keywords_found = [key for key in keywords if key in row[0].value]
    # if any keywords found, enter the keywords in column D
    # and how many keywords into column E
    if len(keywords_found):
        row[1].value = keywords_found
        row[2].value = len(keywords_found)

Now, I understand where I'm going wrong, in that ws.iter_rows(..) returns a tuple, which can't be modified. I figure I could two for loops, one for each row, and another for the columns in each row, but this test is a small example of a real-world scenario, where the amount of rows are in the tens of thousands.
I'm not quite sure which is the best way to go about this. Thankyou in advance for any help that you can provide.

A: Use the ws['C'] and then the offset() method of the relevant cell.

A: Thanks Charlie for the offset() tip. I modified the code slightly and now it works a treat.
for row in ws.iter_rows("C{}:C{}"...)
    for cell in row:
    ....
    if len(keywords_found):
        cell.offset(0,1).value = str(keywords_found)
        cell.offset(0,2).value = str(len(keywords_found))


text:
Q: Import graphml file in mathematica I am trying import a graphml file I created with NodeXL in mathematica in order to create a network.
However when i try to import it I get the error message: "Cannot import data as GraphML format".
Any help is greatly appreciated!
Thank you!!

A: I downloaded graph 57698 from the NodeXL Graph Gallery, changed the suffix from "xml" to "graphml", tried to Import, and got the same error you report.
Now I don't know anything about XML, but I noticed that GraphML files generated by NetworkX have a namespace that NodeXL didn't include: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance. Adding it made the import work ... no clue why.
My modified GraphML file begins with:
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...


text:
Q: Defining and comparing TIMESTAMP variable with jQuery/Javascript ? I have a table with a column using the timestamp variable from a oracle DB. Im uncertain of how to use JQuery to define my var "schedule Time" from the SQL Query and run the condition. Im basically comparing column timestamp to system time and returning a row background color.
ps. my table is within aspx page
// declaring the time

var currentTime = new Date();
var scheduledTime = "not sure how to declare the variable from my dynamic table"

// variables for the table
var rows = document.getElementById('ewGrid').getElementbyTagName('tr');

 // style class
.rowRed {background-color:red; color:white;}
.rowYellow {background-color:red; color white}

$('tr').each(function() {
// if value is a number and less then zero
if (currentTime - scheduledTime) >15mins<=30mins ) {
    tr = $(this).parent();
    tr.addClass("rowRed");
 }

 });

Thank for any help

A: unix timestamp has an accuration of second, so convert to milisecond and pass to Date constructor:
var scheduledTime = new Date(unixtimestamp*1000)
// where unixtimestamp is the timestamp you get from the database


text:
Q: Can't decode XML with golang, always empty struct I'm trying to decode XML with golang, but the following code gives an empty struct
Anyone can help?
When I run the following code, I always get
{{ packet} []}

Attached source code:
package main

import (
    "fmt"
    "encoding/xml"
//    "io/ioutil"
)

type Field struct {
    XMLName xml.Name `xml:"field"`
    name      string `xml:"name,attr"`
    shownameg string `xml:"showname,attr"`
    fields []Field
}

type Proto struct {
    XMLName xml.Name `xml:"proto"`
    name      string `xml:"name,attr"`
    shownameg string `xml:"showname,attr"`
    fields []Field
}

type Packet struct {
    XMLName xml.Name `xml:"packet"`
    protos []Proto   `xml:"proto"`
}

func main () {
    data := []byte(`
<packet>
  <proto name="geninfo" pos="0" showname="General information" size="122">
    <field name="timestamp" pos="0" show="Jul 17, 2008 15:50:25.136434000 CST" showname="Captured Time" value="1216281025.136434000" size="122"/>
  </proto>
</packet>
    `)

    packet := Packet{}

    err := xml.Unmarshal([]byte(data), &packet)
    if err != nil {
        fmt.Println (err)
        return
    }

    fmt.Println (packet)

    for proto, _ := range (packet.protos) {
        fmt.Println (proto)
    }
}

A: You need to export your struct fields as per https://golang.org/pkg/encoding/xml/#Unmarshal

Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields. Unmarshal uses a case-sensitive comparison to match XML element names to tag values and struct field names.

e.g.
type Proto struct {
    XMLName xml.Name `xml:"field"`
    Name      string `xml:"name,attr"`
    Shownameg string `xml:"showname,attr"`
    Fields []Field
}


text:
Q: What is the kernel module responsible for /sys/class/power_supply/BAT0? After twiddling LEDs with /sys/class/leds/, I'm now trying to understand how to control the battery in my computer with linux kernel power supply attributes, specifically CHARGE_CONTROL_LIMIT.  However, no such attribute exists in /sys/class/power_supply/BAT0/.
How I've tried to answer this question:
From what I understand reading man 5 sysfs, sysfs (usually mounted as sys) is an interface between userspace and kernelspace.
Hypothesis:

*

*There exists a kernel module that creates and updates the contents of /sys/class/power_supply/BAT0/

*That kernel module may, but does not seem to implement CHARGE_CONTROL_LIMIT.  It does implement other attributes:
cat /sys/class/power_supply/BAT0/charge_full
2884000
cat /sys/class/power_supply/BAT0/charge_now
2884000
cat /sys/class/power_supply/BAT0/cycle_count
0                                                 <--- this seems broken
cat /sys/class/power_supply/BAT0/capacity
100

To test this hypothesis, I sought the documentation/source of the responsible kernel module.
A hang-up: Trying to find the kernel module that's responsible for /sys/class/power_supply/BAT0/
ArchWiki and this page demonstrate how to look-up a kernel module, given a modalias.
cat /sys/class/power_supply/BAT0/device/modalias
acpi:PNP0C0A:

sudo grep -E 'PNP0C0A' /lib/modules/*/modules.alias
# nothing is found

I see that the battery hardware is of type acpi, however, there's no exact match for its modalias in modules.alias.  (I tried a a few combinations of wildcards to find it, to no avail).
@0andriy suggested checking /drivers/platform/x86, which I did as follows:
find /lib/modules/5.0.0-15-generic/kernel -type f -name '*.ko' | xargs modinfo | grep -E 'alias.*PNP0C0A'
# Nothing

# Trying another query, to check that the query works:
find /lib/modules/5.0.0-15-generic/kernel/drivers -type f -name '*.ko' | xargs modinfo | grep -E 'alias.*TOS'
alias:          acpi*:TOS1900:*
alias:          acpi*:TOS6208:*
alias:          acpi*:TOS6207:*
alias:          acpi*:TOS6200:*

This is an HP laptop with a recent kernel
uname -a
Linux lithium 5.0.0-15-generic #16-Ubuntu SMP Mon May 6 17:41:33 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

A: The problem is that the power source may be from a module already statically linked to the kernel (not visible in lsmod or present in /lib/modules), rather than left as a standalone module. So:
A) check /sys/module first. This is a directory which contains entries for both dynamically linked (i.e. visible by lsmod) and statically linked ones.  Check if you see a (probably lowercase) pnp* entry there.
B) if you do, and it's not in lsmod, you'll need the kernel sources. These can possibly be obtained from HP, but you can start with the stock sources (http://kernel.org) since there's a good chance this is in the mainline kernel.
C) Those /sys entries are created by code calling "power_supply_register". Try a brute force grep over all the modules, to see which matches. You can also do this over the Linux source tree (something like find . -type f | xargs grep power_supply_register, or grep -R, etc).
Whether or not you can mess with the charging limits, etc, is up to the module in question. Good luck finding it.

A: I was looking for the kernel module that drives the battery of my laptop, and mine uses the same modalias as yours: acpi:PNP0C0A:
On my system this is driven by the 'battery' module.
This is the case at least on openSUSE Leap 15.4, with kernel 5.14.21
grep /lib/modules/$(uname -r)/modules.alias -e ":PNP0C0A"
alias acpi*:PNP0C0A:* battery

modinfo confirms this is what I was searching for:
modinfo battery
filename:       /lib/modules/5.14.21-150400.22-default/kernel/drivers/acpi/battery.ko.zst
license:        GPL
description:    ACPI Battery Driver
author:         Alexey Starikovskiy <astarikovskiy@suse.de>
author:         Paul Diefenbaugh
suserelease:    SLE15-SP4
srcversion:     69EB486D2C8DDEBE723A052
alias:          acpi*:PNP0C0A:*
depends:
supported:      yes
retpoline:      Y
intree:         Y
name:           battery
vermagic:       5.14.21-150400.22-default SMP preempt mod_unload modversions

I don't know the answer to why doesnt it show up in your search, but I hope this is helpful.


text: Q: References to study Weak and Strong Topologies and aproximations on function spaces of manifolds I´m studing weak and strong topologies and aproximations on the function space  $C^{\infty}(M,N)$  of two manifolds $M$ and $N$.  I´m using the book  Differential Topology of Morris Hirsch but it is a very hard book for someone with no experience on topology of functions spaces. Can someone tell me a book where this subject is exposed  in a more accesible form?


text:
Q: Maximum number of tabs & color of line under tabs? I have 2 questions on TabHost.

*

*Is there a maximum number of tabs which we can add via tabHost.addTab(spec)? I need up to 10 tabs.

*I have managed to change the color of each tab and tab divider, but I still cannot change the color of grey line under the tabs (under each unselected tab)). What is the name of that line? Can I change its color or even completely remove it?
Thanks!

A: There is no hard limit but Google suggests a maximum of 4 tabs. You always have to keep in mind your tabs need to be large enough to be clickable.
Concerning your second question you can disable it using the android:tabStripEnabled XML attribute.


text:
Q: C# rest api mail gun gives forbiden access status Good day, I am trying now to do email vertification, and followed all instructions but i get response status Unauthorized
private bool SendEmail(string body, string email)
    {
        //create client
        RestClient client = new RestClient("https://api.eu.mailgun.net/v3");

        client.Authenticator =
            new HttpBasicAuthenticator("api",
            "02a4bca7b2e0c72e98841b20beef1585-69210cfc-a7bc0929");

        var request = new RestRequest();

        request.AddParameter("domain", "sandbox4706f89b4150439ebca3c380f3fa96d0.mailgun.org");
        request.Resource = "{domain}/messages";
        request.AddParameter("from", "Ecommerce sandbox Mail<postmaster@sandbox4706f89b4150439ebca3c380f3fa96d0.mailgun.org>");
        request.AddParameter("to", email);
        request.AddParameter("subject", "Email Vertfication Email");
        request.AddParameter("text", body);
        request.Method = Method.Post;

        var response = client.Execute(request);

        return response.IsSuccessful;

    }

Do anyone had the same problem? I am conecting from EU so changed rest Client from  https://api.mailgun.net/v3 to https://api.eu.mailgun.net/v3
If I use  https://api.mailgun.net/v3 I get response status Unauthorized.

A: Seems like Mailgun changed something in API but forgot to change the documentation. If you go to your domain dashboard and select API, you can see that base URL is different from the one in example

So, base URL shouldn't be https://api.mailgun.net/v3/ but https://api.mailgun.net/v3/sandbox....mailgun.org`
Also, make sure that email you're sending to is added to Authorized Recipients for your domain (see how to add it in knowledge base)

Once you have correct base URL and authorized (and verified recipient), you can send your email. So, in your example, it would be like this (look at comments also):
//note the URL with domain
RestClient client = new RestClient("https://api.eu.mailgun.net/v3/sandbox4706f89b4150439ebca3c380f3fa96d0.mailgun.org");

client.Authenticator =
    new HttpBasicAuthenticator("api",
    "02a4bca7b2e0c72e98841b20beef1585-69210cfc-a7bc0929");

var request = new RestRequest();

//request.AddParameter("domain", ... is not needed anymore becasue of base URL
//also, Resource is now without {domain} parameter
request.Resource = "/messages";
request.AddParameter("from", "Ecommerce sandbox Mail<postmaster@sandbox4706f89b4150439ebca3c380f3fa96d0.mailgun.org>");
//this mail should be authorized recipient
request.AddParameter("to", email);
request.AddParameter("subject", "Email Vertfication Email");
request.AddParameter("text", body);
request.Method = Method.Post;

var response = client.Execute(request);

return response.IsSuccessful;

... And that should send the email without Unauthorized error


text:
Q: Jquery inview adding class to last element I'm trying to use the jquery inview plugin to add a class to an element when it's within the viewport. For some reason the plugin in only adding the class to the very last element even though the other elements are clearly visible in the viewport. Below is my code:
html:

jquery:
$(function() {
    $('.entry').bind('inview', function (event, visible) {
        if (visible) {
            $(this).addClass('show-post');
        }
    });
});

A: Put you script inside ready:I'm changing the color to green to show the effect that the class show-post is added.

<!DOCTYPE html>

  <title>jquery.inview - Example</title>
  <meta name="viewport" content="initial-scale=1.0, width=device-width, height=device-height">

hi

sfsdf

sdfsd

sdfds

sdfds

sdfs


text:
Q: Networkx huge amount of node and edges I have about 40.000 nodes and also about 50.000 edges.
Is there a way to get a graph for it?
Its like taking forever when im trying it.
Thanks in advance.
import networkx as nx

g.add_nodes_from(nodes_refactored)
g.add_edges_from(node_edges_refactored)
g.number_of_nodes() --> 44k
g.number_of_edges() --> 47k
nx.draw(g) --> nothing happens...

A: It's probably being super slow because the amount of nodes is incredibly high. A visual is unlikely to be useful in this case anyway as there are so many nodes & edges that it'll basically just display a big black blob on the screen. Perhaps you could map subgraphs instead, or combine nodes into supernodes?


text:
Q: Can my kid use the pen display while I'm working on my PC? I'm planning to buy a a graphic tablet (pen display) to motivate my kids to learn using Photoshop. But I have a concern: if I have to decide all the time if I work on the computer or they use the pen display, I afraid it would kill the project (they draw a lot, and I work a lot).
Is that possible to setup a system which lets them using the pen display with Photoshop while I'm working on the same PC?


text:
Q: Sort Columns from a Single Row by Number I am probably over-thinking this.. but I can't figure this out. I have a database that has five columns. In these columns is a random number 1-6. I am trying to pull this row and then re-sort them either asc or desc- doesn't matter.
Col1 | Col2 | Col3 | Col4 | Col5
---------------------------------
  2  |   1  |   3  |   5  |   4

I would like to sort these to know if the rows either show:
1,2,3,4,5 or 5,4,3,2,1.
Can anyone help me?

A: Would suggest storing your column values into an array and performing a sort($column_value_array, SORT_NUMERIC)
Also have alook at this http://php.net/manual/en/function.sort.php

A: Well if you are only trying to sort an array in PHP there is already a function done for that
sort ($array [, int $sort_flags = SORT_REGULAR ] )

The method will return a boolean relating to the success state of the sort.
Note that the sort_flag is facultative and in your case don't really need to be used.
See http://php.net/manual/en/function.sort.php for more information.
An other way would be to simply add an order by clause to your query when selecting the row.

A: Here is a query. This will make sure in each column(any) any of the 1,2,3,4,5 number exists i.e. 5 columns have a different number in them
select *,
((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '1', ''))) as one,
((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '2', ''))) as two,
((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '3', ''))) as three,
((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '4', ''))) as four,
((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '5', ''))) as five
from tests
having one = 1 AND two = 1 AND three = 1 AND four = 1 AND five = 1

A: I would suggest
SELECT * from table WHERE

Col1 in (1,2,3,4,5) &&
Col2 in (1,2,3,4,5) &&
Col3 in (1,2,3,4,5) &&
Col4 in (1,2,3,4,5) &&
Col5 in (1,2,3,4,5) &&
Col1 != Col2 &&
Col1 != Col3 &&
Col1 != Col4 &&
Col1 != Col5 &&
Col2 != Col3 &&
Col2 != Col4 &&
Col2 != Col5 &&
Col3 != Col4 &&
Col3 != Col5 &&
Col4 != Col5 &&


text:
Q: Eclipse attribute required is not defined annotation XmlElementRef I work with java 1.6. I don't work with maven. In the lib folder I have the jar
jaxb-api-2.2.jar

When I build the project I get the error
attribute required is not defined annotation XmlElementRef

I have other jars
jaxb-api
jaxb-core.jar
jaxb-impl.jar
jaxb-impl-2.2.7-sources.jar
jaxb-jxc.jar
jaxb-xjc.jar
jaxb-xjc-2.2.7.jar

What jaxb version do I have to use with java 1.6?


text:
Q: Adding a custom JavaScript code to functions.php file in WordPress I am trying to add a JavaScript code to functions.php file using wp_head hook. The JavaScript code just adds a DataLayer to the top of Google Tag Manager Container in <head> tag, on the Thank you page.
I have attempted to use the following code:
function addDataLayerToHead(){
  if (is_checkout() && !empty( is_wc_endpoint_url('order-received') ) )  {
     wp_enqueue_script('Custom-JS', 'https://xxxxxx/dataLayer.js', array('jquery'), '',
     false);
  }
}
add_action( 'wp_head', 'addDataLayerToHead', 10 );

When I run my website, the product page will not be available it says error in function "addDataLayerToHead".
Any help?


text:
Q: IntelliJ IDEA 10.5 produces binary different JARs on different machines with seemingly identical setups (scala) I'm building a JAR from a set of scala sources. We have two physically identical win7 64 bit development machines, and recently a difference between the machines in the library jars referenced by the project caused some issues in production, so we've been looking into ways to ensure that we get the exact same build on the two machines.
The scala compiler and all external JARs are now under version control, as are the IntelliJ project files that are stored with the source code (project.iml and .idea*, except .idea\workspace.hml since it keeps track of the editor state and changes all the time). The project files have been updated to reference the now-under-version-control scala compiler (the  "Libraries" and "Facets" under module settings).
We're using the same version of IntelliJ (10.5, built May 16th, 2011), and have the same Java SDK (1.6.0_24, 64 bit).
Despite synchronizing our setups to this extent we get slightly different JARs: 12 out of 1685 class files are different. Most of the differences are "small", ("offsetX$4" in one, vs "offsetX$5" in the other), but some are more substantial.
IntelliJ does store some configuration information in c:\Users[username].IntelliJIdea10, but there's a lot of it and it's not immediately apparent what impact it may have on the build.
The build is repeatable on the individual machines (i.e. rebuild re-generates the same binary), but different between them.
Any thoughts on what I might be missing? Thanks!

A: Using any IDE for production builds is a bad idea.  It's too hard to precisely control the environment.  Use ant or maven or command files or anything else that doesn't have a lot of secret sauce that you're likely to accidentally stir.  Sorry!


text:
Q: Spring Security Ant Matchers Runtime I have database like this:

ROLE1 -> /ui/ui1
ROLE1 -> /ui/ui2
ROLE2 -> /ui/ui2

How can I change ROLE2 -> /ui/ui1 in Runtime?
Because, I storage in database. :(

A: You can use PermissionEvaluator that which will check authorization with custom your implementation, in which you can check database and compare roles in runtime.
More about how to use it: http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#el-permission-evaluator
If you don't want to use annotations on methods, here is how you can add custom method to Web Security Expressions spring security:intercept-url pattern access="#id == 1 . Then you should be able to use it in configuration like:
    http.authorizeRequests()
            .antMatchers("/url1").access("hasPermission(#user,...)");

Other solution is to make use of custom filter in security filter chain that will check Authentication, url and database.


text:
Q: Can Matlab hold a strong-name reference to a .NET assembly? I have a Matlab-generated .exe that needs to reference functionality in a strongly-named, GAC-installed .NET Assembly. From here: Mathworks help site I see the reference would look like this: function Foo()
NET.addAssembly('MyAssembly');
…
end
 But I can't find in their docs any description of how to make the reference strong...anyone could produce a strongly-named assembly with the same name and install it in the GAC to spoof the real assembly. Are these references destined to be insecure?

A: https://www.mathworks.com/matlabcentral/answers/101936-can-matlab-builder-for-net-create-a-strongly-named-net-assembly
As of MATLAB Builder for .NET 2.1 (R2006b), strongly named .NET assemblies can be created though the Builder does not create them by default. The MWArray.dll, however, is strongly named and can be registered in the Global Assembly Cache (GAC).
In order to create a strongly named assembly with MATLAB Builder for .NET, you will need to provide a signature file. This file can be generated with the .NET SDK. You can use the DEPLOYTOOL interface to sign the .NET assemby as follows:
1) Open DEPLOYTOOL and creating a MATLAB Builder for .NET project.
2) Add the appropriate files to the project.
3) Undock the DEPLOYTOOL GUI.
4) Go to "Project->Settings" to open the project settings pane.
5) Ensure that you have selected the correct .NET Framework version.
6) Under "Assembly Type", select "shared"
7) For "Encryption Key File", browse for the key file generated by .NET SDK.
8) Build the project.
The .NET assembly is now strongly named and can be registered in the GAC.


text:
Q: How to word wrap text in the rows and columns of a QTableWidget? I tried:
    QTableWidget *j = new QTableWidget (10000, 5, centralWidget);
    j->setColumnWidth (0, 500);
    j->setColumnWidth (1, 30);
    j->setColumnWidth (2, 30);
    j->setColumnWidth (3, 320);
    j->setColumnWidth (4, 310);

    j->setWordWrap (true);

Also tried resizeColumnsToContents and resizeRowsToContents, but failed.
If the text is longer than the set width, I want the sentence to break down.
Currenty, the lengthy part of the sentence just doesn't get shown.

A: setWordWrap defines the behaviour of the text, without altering column size. If you need to keep column width fixed, call resizeRowsToContents after the insertion of the item to the cell (I assume you're adding text to the table via QTableWidgetItem).
Please notice that if any of the words contained in the item are wider than column size, text will be elided from that point on (by default you will see ellipses: ...). If you want to change such behaviour you need to reimplement item's painting function or stretch your columns.

A: This will adjust the word wrapping automatically every time a column resizes:

connect(
    tableWidget->horizontalHeader(),
    SIGNAL(sectionResized(int, int, int)),
    tableWidget,
    SLOT(resizeRowsToContents()));

A: As mentioned in the question comment, setting the row size explicitly to some value seems to work:
 tableWidget->resizeRowsToContents();
 tableWidget->verticalHeader()->setDefaultSectionSize(50);

I note that for my code, I did not have to explicitly call setWordWrap in order to have cell contents be word wrapped.


text:
Q: Having issues with C++ Function pointers in COM There is one thing that bothers me, C++ function pointers. I'm asking this question because I'm trying to implement callback functions used in my game engine. The issue is, for example:
// Callback function
HRESULT RenderScene(float fps){ HRESULT hr; return S_OK; }

// Set the message
msk->SetMessage(0, SM_RENDERSCENE, (void*) RenderScene);

The problem is COM doesn't allow function pointers in their member functions. Also, doesn't allow for polymorphism. As you can see, I made it a void*. Fine with me because I know what the callback function is. The main issue is that I want something that is type-safe.
Now say if the user doesn't know the callback function declaration. For example,
// Callback function
HRESULT CALLBACK RenderScene() or RenderScene(int fps) or RenderScene(int a, int b)

Is implemented in WndProc as:
...
SM_RENDERSCENE:
((void (_stdcall*)(float fps)) pfn)(1.0f);
break;
...

The first, doesn't have an argument, therefore, he doesn't see fps. The second, loses precision. The third, loses precision and has an unused argument. Do you see where I'm going at? Tried using a union but COM doesn't allow function pointers in the member function.
I tried, and tried again. Nothing works, even the MFC message maps are ugly if they didnt have those macros.
To clarify, I rather have it return an error like E_FAIL or E_INVALIDFUNCTION if the function doesn't match the specification of SM_RENDERSCENE.
Does anyone have a solution to this problem.
Note: I like the COM specification and I'm not going to change, so focus on the issue not about why I'm using COM. Thank you, any help will do.

A: COM is a technology that is supposed to support multiple programming languages, and not all programming languages have support for all kind of features, hence some features like function  pointers and exceptions are not (in general) supported in COM.
In the case of callbacks, usually the way to go is to define a COM interface that includes the method you need to call. You can implement this function in a COM class of your choice, and you can specify this interface as a parameter to any other COM function.
If you are using ATL for your COM implementation, here is a link on how to add an new interface to an ATL project. And you could also take a look on this article at codeproject about COM Event Handling

A: Pass interface pointers instead of function pointers. Also there is no function overloading in COM, so use different function names. Here is a pseudocode:
struct IRenderScene : public IUnknown
{
  HRESULT RenderScene(); // Callback function
  HRESULT RenderSceneFps(float fps); // Callback function
  HRESULT RenderSceneAB(int a, int b); // Callback function
}

IRenderScene *renderScene = ...;
msk->SetRenderScene(renderScene); // Set the callback

You don't need to implement COM Event Handling (Connection Points) if it is superfluous to you.

A: HRESULT RenderScene(float fps){ ...}
HRESULT CALLBACK RenderScene() or ...
Is implemented ... ((void (_stdcall*)(float fps)) pfn)(1.0f);

No, COM definitely supports function pointers.  It is only when you use the subset of COM Automation or need to marshal function calls that you could get in trouble.  Which is not the case here, you don't marshal between processes or threads and don't need automation since you work with only one language.
The simple problem is that you have the issue that you are trying to protect against, the function pointer definition doesn't match the implementation.  Yes, a (void*) cast will stop the compiler from complaining about it, nothing good happens at runtime.
Your first declaration has the wrong calling convention.  Using the STDMETHODIMP macro is wise.
Your second set of declarations have the wrong arguments.
The third snippet is applying an invalid function pointer cast, a cast to a function that returns void instead of HRESULT.  And assumes __stdcall even though your RenderScene() function didn't use STDMETHODIMP or CALLBACK.  Which is why you don't see a proper value for the argument.
Solve function pointer problems by declaring an alias for the pointer type:
 typedef HRESULT (__stdcall * RenderSceneCallback)(float fps);

And consistenly use RenderSceneCallback in all your declarations.  Never cast.