text:
Q: Get last word from URL after a slash in PHP I need to get the very last word from an URL. So for example I have the following URL:
http://www.mydomainname.com/m/groups/view/test
I need to get with PHP only "test", nothing else. I tried to use something like this:
$words = explode(' ', $_SERVER['REQUEST_URI']);
$showword = trim($words[count($words) - 1], '/');
echo $showword;

It does not work for me. Can you help me please?
Thank you so much!!

A: Use basename with parse_url:
echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

A: I used this:
$lastWord = substr($url, strrpos($url, '/') + 1);

Thnx to: https://stackoverflow.com/a/1361752/4189000

A: by using regex:
preg_match("/[^\/]+$/", "http://www.mydomainname.com/m/groups/view/test", $matches);
$last_word = $matches[0]; // test

A: You can use explode but you need to use / as delimiter:
$segments = explode('/', $_SERVER['REQUEST_URI']);

Note that $_SERVER['REQUEST_URI'] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', rtrim($_SERVER['REQUEST_URI_PATH'], '/'));

A: To do that you can use explode on your REQUEST_URI.I've made some simple function:
function getLast()
{
    $requestUri = $_SERVER['REQUEST_URI'];

   # Remove query string
    $requestUri = trim(strstr($requestUri, '?', true), '/');
   # Note that delimeter is '/'
    $arr = explode('/', $requestUri);
    $count = count($arr);

    return $arr[$count - 1];
}

echo getLast();

A: If you don't mind a query string being included when present, then just use basename. You don't need to use parse_url as well.
$url = 'http://www.mydomainname.com/m/groups/view/test';
$showword = basename($url);
echo htmlspecialchars($showword);

When the $url variable is generated from user input or from $_SERVER['REQUEST_URI']; before using echo use htmlspecialchars or htmlentities, otherwise users could add html tags or run JavaScript on the webpage.

A: use preg*
if ( preg_match( "~/(.*?)$~msi", $_SERVER[ "REQUEST_URI" ], $vv ))
 echo $vv[1];
else
 echo "Nothing here";

this was just idea of code. It can be rewriten in function.
PS. Generally i use mod_rewrite to handle this... ans process in php the $_GET variables.
And this is good practice, IMHO

A: ex: $url      = 'http://www.youtube.com/embed/ADU0QnQ4eDs';
$url      = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
// **output**: $basename is "ADU0QnQ4eDs"

complete solution you will get in the below link. i just found to Get last word from URL after a slash in PHP.
Get last parameter of url in php


text:
Q: Redux - Understanding advanced mapStateToProps returning a function I am trying to understand the mechanics of mapStateToProps when it returns a function.
So I can't find much documentation except a short excerpt from the Redux docs that says in advance cases by returning a function, each instance will get its own memoized mapStateToProps and another user saying that this is an optimisation that prevents mapStateToProps being called for any parent prop changes.
So this seems great for list items, where I would't want to re-render large list of items for any changes that doesn't affect an item.
So the part that confuses me is that mapStateToProps won't be called for any parent prop changes, does that mean in order for an individual list 'Item' to be re-rendered it needs to be a smart connected component for it to pick up changes it cares about and re-render? Or does that mean it will never re-render for this particular Item instance?
Update:
Wanted to clarify that I am talking specifically about the factory function version of mapStateProps.
Here is the feature I am talking about, taken from React-Redux docs:
Note: in advanced scenarios where you need more control over the rendering performance, mapStateToProps() can also return a function. In this case, that function will be used as mapStateToProps() for a particular component instance. This allows you to do per-instance memoization. You can refer to #279 and the tests it adds for more details. Most apps never need this.
And paragraph taken from this article:
https://medium.com/@cvetanov/redux-mapstatetoprops-optimization-5880078a8a7a
If redux receives an implementation which returns a function it performs a closure for wrapping the own props of the component and therefore bypasses the invocation of the mapStateToProps every time the component changes it's props received from the parent component. It creates a so called purePropsSelector. How this is done can be seen here.
Update 2:
Right I am investigating the article that mentions the skipping, it seems to be when you wrap the own props in a closure and return a function that only uses the state. So it prevents the mapStateToProps being invoked when the parent props changes for each 'connected' child item.
This is taken from that medium article I read above:
function mapStateToPropsFactory(initialState, ownProps) {
  // a closure for ownProps is created
  // this factory is not invoked everytime the component
  // changes it's props
  return function mapStateToProps(state) {
    return {
      blogs:
        state.blogs.filter(blog => blog.author === ownProps.user)
    };
  };
}
export default connect(mapStateToPropsFactory)(MyBlogs);

A: The second argument of ownProps is the props that were passed to the component that you are wrapping. You mentioned list items so let's call it (ListItem).
So the ListItem component, when its displayed on the screen is passed some library of lists, for example,
const { id, title } = this.props.library;
The ownProps object is exactly equal to this.props inside the component.
So any item you pass into the component will show up in the mapStateToProps as ownProps. By getting access to ownProps inside of this mapStateToProps:
const mapStateToProps = (state, ownProps) => {
  return { selectedLibraryId: state.selectedLibraryId };
};

You can predetermine exactly what props you want to pass down inside your component and this allows you to remove all logic from your component entirely like this:
const mapStateToProps = (state, ownProps) => {
  const selected = state.selectedLibraryId === ownProps.library.id;
  return { selected };
};

The component no longer needs to worry about the meaning of selectedLibraryId, it can just look at the { selected } and decide whether or not to show the details of the selected item from the list.

A: Every mapStateToProps function will always be called if the state changes. There is no mechanism included in redux that prevents mapStateToProps from being called.

From the docs for connect():
mapStateToProps(state, [ownProps]): stateProps] (Function): If this argument is specified, the new component will subscribe to Redux store updates. This means that any time the store is updated, mapStateToProps will be called.

What you want to prevent (usually by using selectors) is that expensive computations happening inside mapStateToProps will be repeated on every state update even if they produce the same result.

Or does that mean it will never re-render for this particular Item
  instance?

It will re-render as usual if any props received by the connected component change. The point is to prevent mapStateToProps from doing expensive calculations. mapStateToProps is dumb. It does its calculations and passes them to the connected component as props. The component then checks if the props differ from the previous ones and decides to re-render based on that.
Consider this mapStateToProps function which uses a selector getVisibleTodos:
const mapStateToProps = state => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

Selectors memorize the result of a call and will simply return that result on subsequent calls as long as the input parameters do not change. The selector in this example only gets its input from the redux state. As long as state.todos and state.visibilityFilter do not change it can use the memorized result from the last call and does not need to recompute something.
Now consider this another example:
const TodoList = ({id, todos}) => (
  <ul id={id}>
    {todos.map(/* ... */)}
  </ul>
);

const mapStateToProps = (state, props) => {
  return {
    todos: getVisibleTodos(state, props)
  }
}

export default connect(mapStateToProps)(TodoList);

This time the selector additionally takes the components own props as input. This is problematic because if we use two instances of the connected TodoList and render it like
<TodoList id="list1" />
<TodoList id="list2" />

this will cause mapStateToProps to be called twice on state updates, one time for each TodoList instance. And both times it will receive different props. One time with {id: 'list1'} and the second time with {id: 'list2'}. But both components share the same selector. This will lead to a re-computation by the selector even if the todos for each individual TodoList did not change. Now the mapStateToProps function that returns a function by itself comes into play:
const makeMapStateToProps = () => {
  const getVisibleTodos = makeGetVisibleTodos() // this creates a new selector function
  const mapStateToProps = (state, props) => {
    return {
      todos: getVisibleTodos(state, props)
    }
  }
  return mapStateToProps
}

This creates an individual mapStateToProps function for each instance of TodoList which has its own selector so that it memorizes the props for each instance individually and will only re-compute if props for the instance it was created for change. This will solve the issue from the previous example.
So tl;dr;: When a selector inside mapStateToProps takes the own props of the connected component as a parameter you need to use the mapStateToProps as a factory to allow for per-instance memorization.
You can find a more detailed explanation with an example under Comuting Derived Data in the redux docs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Obtaining data key/value pair from Materialise CSS autocomplete. How? I was able to change the code below to output what I click to console. As you can see, the sendItem function does that for me.
I am having a hard time accomplishing the following:

*

*User types AP

*autocomplete completes it to Apple

*User clicks on APPLE

*Its corresponding value is sent to console
Basically, materialize has a really awesome function they choose to display pictures with, when it can do a lot more. For example, a whole mySQL search based on:

*

*Load the auto complete data with current pending clients

*Each client is a key/value pair in a json array of clients (array of
arrays)

*autocomplete searches the keys in the data array and upon user
click,

*dispatches a ajax mysql search for its corresponding value which in
this case is a unique client id.

*Finally, we render the results to user.

function sendItem(val) {
    console.log(val);
}

$(function () {
    $('input.autocomplete').autocomplete({
        data: {
            "Apple": null,
            "Microsoft": null,
            "Google": 'http://placehold.it/250x250'
        },
        onAutocomplete: function(txt) {
          sendItem(txt);
        },
        limit: 20, // The max amount of results that can be shown at once. Default: Infinity.
    });

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>

                <input type="text" id="autocomplete-input" class="autocomplete">
                Autocomplete

A: It seems like there is no documentation about this in the plugin. So, one solution would be performing the search yourself based in the selected value (txt parameter of onAutocomplete function).
So, keep a data structure that maps the keys and values, similar to the data option passed to the plugin, and once a value is selected, you use it to find the corresponding value in your data structure and perform the operations you want.
Good luck.
Update
Now they material css providing documentation for the autocomplete but this is available for the version 1.0.0-rc.2 and to view the documentation
click here

A: Well... would you guys say this solution is a.. bit of a hack? Because... for some reason, it just doesn't please the eye for me.
Perhaps I should just wait for their framework to evolve a bit more and just go learn how to create an ajax live search from scratch which shouldn't be hard to find on Google.

function sendItem_OLD(val) {
    console.log(val);
}

function sendItem(ele, e) {
    if (e.isTrigger != undefined) {
        console.log('Key: ' + ele.value + ' | Value: ' + $(ele).nextAll('.dropdown-content').find('img').attr('src'));
    }
}

$(function () {
    $('input.autocomplete').autocomplete({
        data: {
            "Apple": null,
            "John Doe": "465605",
            "Google": "http://placehold.it/250x250"
        },
        limit: 20, // The max amount of results that can be shown at once. Default: Infinity.
    });

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>

                <input type="text" id="autocomplete-input" class="autocomplete" onchange="sendItem(this, event)">
                Autocomplete


text:
Q: android setOnItemLongClickListener conflict with textIsSelectable property set to true hi all Android experts:
I have a listview item layout which uses a TextView, it is set to
android:textIsSelectable="true"
In my activity I setup the list item long click on open the action menu:
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
            // Called when the user long-clicks on someView
            @Override
            public boolean onItemLongClick(AdapterView<?> parent,
                    View view, int position, long id) {
                if (mActionMode != null) {
                    return false;
                }

                selectedLeaveId = position;

                // Start the CAB using the ActionMode.Callback defined above
                mActionMode = MyActivity.this
                        .startActionMode(mActionModeCallback);
                view.setSelected(true);
                return true;
            }
        });

During runtime if I long click on the text of a list item, I get the action menu on top first. Then I long click on the text again I get the the text selection menu on top.
I am thinking of making set textisselectable to false, and add one more actual menu item to open the select text menu, however it sounds a wierd solution...
Is there a way to solve this conflict or this is actually a bad implementation that these 2 behaviors cannot co-exist?
thanks in advance


text:
Q: Java Installing error- Neither command line parameter specified is an existing directory I was installing java from java.com to my machine. It downloaded a 900kb exe and started installing. But when I started installing it gave an error.
Neither command line parameter specified is an existing directory.

after this error it says java could not be updated on your system. Any advise to fix this for successful installation.
Thanks In Advance !!

A: Uninstalling previous version of Java and installing it again fixed the issue.


text:
Q: Minimum to install for a visual web browser in Ubuntu Server I have set up a machine with Ubuntu Server. Some of the server software I want to run on it has web based user interfaces for setting it up et cetera. I know I could connect to it from a different machine which has a graphical user interface, but in this case I would rather do it on the box.
So, from a fresh Ubuntu Server installation, what is the minimum I need to install to be able to launch a web browser I can use for this? For example chromium, firefox or arora.

A: The lightest (and least-functional) browser I can find is links2 .
You can run it in graphics mode with the -g flag, like this:
 links2 -g http://localhost:9090

One of the lighter browsers with modern features I've used is arora .
Here are the listed dependencies from sudo apt-cache show arora :
Depends: libc6 (>= 2.2.5), libgcc1 (>= 1:4.1.1), libqt4-dbus (>= 4:4.5.3), libqt4-network (>= 4:4.5.3), libqt4-script (>= 4:4.5.3), libqt4-sql (>= 4:4.5.3), libqtcore4 (>= 4:4.7.0~beta1), libqtgui4 (>= 4:4.6.1), libqtwebkit4 (>= 2.0~week26), libstdc++6 (>= 4.1.1)
It should work for what I expect would be normal browser-based control panel stuff.
Here's what actually would be installed (taken from my 10.04 server) :
sudo apt-get install --simulate arora
[...]
The following NEW packages will be installed:
  arora libaudio2 libmng1 libphonon4 libqt4-dbus libqt4-designer
  libqt4-network libqt4-script libqt4-sql libqt4-sql-mysql libqt4-webkit
  libqt4-xml libqt4-xmlpatterns libqtcore4 libqtgui4
0 upgraded, 15 newly installed, 0 to remove and 0 not upgraded.
Inst libaudio2 (1.9.2-3 Ubuntu:10.04/lucid)
Inst libmng1 (1.0.9-1ubuntu1 Ubuntu:10.04/lucid)
Inst libqtcore4 (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-xml (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-dbus (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-script (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqtgui4 (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-designer (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libphonon4 (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-network (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-sql (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-sql-mysql (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-xmlpatterns (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst libqt4-webkit (4:4.6.2-0ubuntu5.1 Ubuntu:10.04/lucid-updates)
Inst arora (0.10.2-0ubuntu1 Ubuntu:10.04/lucid)

Other options
Although I have tried very few of these, a nice list (with brief descriptions) of light browsers is here: http://www.helgefjell.de/browser.php
The front page of the site also has this very nice admonition, in line with the idea of light web browsers:

Note: You have activated ECMA-Script
  (JavaScript). This web site does not
  use active contents and encourages you
  to deactivate ECMA-Script. Good web
  design does not require any active
  content [...]

Some of the ones I tried weren't happy with a 64-bit environment.
dillo used to be the way to go for a very light browser, but I had stopped using it do to lack of packaging and general rudimentary functionality.
Fennec is another slightly weirder possibility -- it's the mozilla mobile broswer. Very light, but it expects a tiny screen.  It is in the repos.


text:
Q: Explicitly_shared action not working properly https://graph.facebook.com/me/maxxxotime:uploaded?method=post&photo=http://domain.com/&image[0][url]=http://domain.com/image/photo.jpg&image[0][user_generated]=true&explicitly_shared=true&access_token=ACCESSTOKEN
I am using the above but it is only showing up on my activity feed, how to properly post the data so it appears in newsfeed too?

A: Some of the facebook documentation is incorrect. I believe using fb:explicitly_shared=true should work


text:
Q: shift count overflow when doing 1<<40 I am puzzled on the following code behavior as to left shift: the intent is to define a variable terabytes, TB = 1024*1024*1024*1024, which would be 2**40 or 1<<40. What is it complaining:
warning: shift count >= width of type [-Wshift-count-overflow]
    uint64_t TB = 1<<40;
                   ^ ~~
1 warning generated.

This is compiled on Mac (10.13.1), with clang-900.0.38, -std=c++11.
#include <cstdint>
#include <iostream>

int main(int argc, char** argv) {

    uint64_t TB = 1<<40;
    std::cout << "TB = " << TB << std::endl;
    return 0;
}

A: Try this code :
1ULL << 40
Constants need a qualified type if you want something other than default.


text:
Q: No Sound Through HDMI The problem I have is there is no sound on the HDMI port. I get video, but no sound.
aplay -l
**** List of PLAYBACK Hardware Devices ****
    card 0: HDMI [HDA ATI HDMI], device 3: HDMI 0 [HDMI 0]
      Subdevices: 1/1
      Subdevice #0: subdevice #0
    card 1: Generic [HD-Audio Generic], device 0: ALC887-VD Analog [ALC887-VD Analog]
      Subdevices: 1/1
      Subdevice #0: subdevice #0
    card 1: Generic [HD-Audio Generic], device 1: ALC887-VD Digital [ALC887-VD Digital]
      Subdevices: 1/1
      Subdevice #0: subdevice #0

speaker-test -c 2 -l 1 -D hw:0,3 does NOT produce sound.
pacmd list-cards
2 card(s) available.
index: 0
name: <alsa_card.pci-0000_00_01.1>
driver: <module-alsa-card.c>
owner module: 6
properties:
    alsa.card = "0"
    alsa.card_name = "HDA ATI HDMI"
    alsa.long_card_name = "HDA ATI HDMI at 0xfeb44000 irq 38"
    alsa.driver_name = "snd_hda_intel"
    device.bus_path = "pci-0000:00:01.1"
    sysfs.path = "/devices/pci0000:00/0000:00:01.1/sound/card0"
    device.bus = "pci"
    device.vendor.id = "1002"
    device.vendor.name = "Advanced Micro Devices, Inc. [AMD/ATI]"
    device.product.id = "9902"
    device.product.name = "Trinity HDMI Audio Controller"
    device.form_factor = "internal"
    device.string = "0"
    device.description = "Built-in Audio"
    module-udev-detect.discovered = "1"
    device.icon_name = "audio-card-pci"
profiles:
    output:hdmi-stereo: Digital Stereo (HDMI) Output (priority 5400, available: no)
    output:hdmi-surround: Digital Surround 5.1 (HDMI) Output (priority 300, available: no)
    output:hdmi-surround71: Digital Surround 7.1 (HDMI) Output (priority 300, available: no)
    off: Off (priority 0, available: unknown)
active profile: <off>
ports:
    hdmi-output-0: HDMI / DisplayPort (priority 5900, latency offset 0 usec, available: no)
        properties:
            device.icon_name = "video-display"
index: 1
name: <alsa_card.pci-0000_00_14.2>
driver: <module-alsa-card.c>
owner module: 7
properties:
    alsa.card = "1"
    alsa.card_name = "HD-Audio Generic"
    alsa.long_card_name = "HD-Audio Generic at 0xfeb40000 irq 16"
    alsa.driver_name = "snd_hda_intel"
    device.bus_path = "pci-0000:00:14.2"
    sysfs.path = "/devices/pci0000:00/0000:00:14.2/sound/card1"
    device.bus = "pci"
    device.vendor.id = "1022"
    device.vendor.name = "Advanced Micro Devices, Inc. [AMD]"
    device.product.id = "780d"
    device.product.name = "FCH Azalia Controller"
    device.form_factor = "internal"
    device.string = "1"
    device.description = "Built-in Audio"
    module-udev-detect.discovered = "1"
    device.icon_name = "audio-card-pci"
profiles:
    input:analog-stereo: Analog Stereo Input (priority 60, available: no)
    output:analog-stereo: Analog Stereo Output (priority 6000, available: no)
    output:analog-stereo+input:analog-stereo: Analog Stereo Duplex (priority 6060, available: no)
    output:iec958-stereo: Digital Stereo (IEC958) Output (priority 5500, available: unknown)
    output:iec958-stereo+input:analog-stereo: Digital Stereo (IEC958) Output + Analog Stereo Input (priority 5560, available: unknown)
    off: Off (priority 0, available: unknown)
active profile: <output:iec958-stereo+input:analog-stereo>
sinks:
    alsa_output.pci-0000_00_14.2.iec958-stereo/#0: Built-in Audio Digital Stereo (IEC958)
sources:
    alsa_output.pci-0000_00_14.2.iec958-stereo.monitor/#0: Monitor of Built-in Audio Digital Stereo (IEC958)
    alsa_input.pci-0000_00_14.2.analog-stereo/#1: Built-in Audio Analog Stereo
ports:
    analog-input-front-mic: Front Microphone (priority 8500, latency offset 0 usec, available: no)
        properties:
            device.icon_name = "audio-input-microphone"
    analog-input-rear-mic: Rear Microphone (priority 8200, latency offset 0 usec, available: no)
        properties:
            device.icon_name = "audio-input-microphone"
    analog-input-linein: Line In (priority 8100, latency offset 0 usec, available: no)
        properties:

    analog-output-lineout: Line Out (priority 9900, latency offset 0 usec, available: no)
        properties:

    analog-output-headphones: Headphones (priority 9000, latency offset 0 usec, available: no)
        properties:
            device.icon_name = "audio-headphones"
    iec958-stereo-output: Digital Output (S/PDIF) (priority 0, latency offset 0 usec, available: unknown)
        properties:

Relevant part of lspci -v
00:01.1 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] Trinity HDMI Audio Controller
    Subsystem: ASUSTeK Computer Inc. Trinity HDMI Audio Controller
    Flags: bus master, fast devsel, latency 0, IRQ 38
    Memory at feb44000 (32-bit, non-prefetchable) [size=16K]
    Capabilities: <access denied>
    Kernel driver in use: snd_hda_intel
    Kernel modules: snd_hda_intel

A: This works for me when, after wake up, all HDMI sound outputs / sinks are either "unplugged", "unavailable" or just gone :
xrandr --output HDMI-1 --auto --set "audio" on

Note : Everything else failed, including

*

*Log out and back in

*Delete ~/.config/pulseaudio/*

*pulseaudio -k

*pulseaudio --start

*pulseaudio -D

*Any combination of the above points

The only thing I did / will not try is to run pulseaudio in system-wide mode.


text:
Q: Why is onDestroy always called when returning to parent activity? I have a very simple app based on the Building Your First App tutorial.  There are two activities: MainActivity invokes DisplayMessageActivity through startActivity().
When entering DisplayMessageActivity, I see:
MainActivity.onStop()

as expected, but when I press the back button to return to the parent MainActivity, I get:
MainActivity.onDestroy()
MainActivity.onCreate(null)
MainActivity.onStart()

The activity always gets destroyed for this very simple application.  But according to the documentation (second bullet point), the typical behavior is for the activity to be stopped and restarted in such cases.
Also, onDestroy() does not happen when first starting the child activity, but only once back button is clicked.
Two questions:

*

*Is there a way to prevent parent from being destroyed in the common case?

*Why is null being passed to onCreate() here?  This prevents me from preserving state through onSaveInstanceState().

Note that I've verified that Settings -> Developer Options -> Apps -> Don't keep activities is unchecked.
Edit:
Here is how the child activity is linked to parent:
    <activity
        android:name="com.example.helloworld.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.helloworld.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.helloworld.MainActivity" />
    </activity>

Tracing through DisplayMessageActivity.onOptionsItemSelected(), I can see that it's calling Activity.onNavigateUp().

A: Thanks to Greg Giacovelli's comments, I found the answer here.  The solution was to set android:launchMode="singleTop" to the parent activity.
I still can't understand why such basic information is so unknown and hard to find!

A: Adding launchMode in Manifest changes launch mode every time, even it is not launched by child activity.  There are other ways to launch existed instance.
1.override onOptionsItemSelected(item: MenuItem)
override fun onOptionsItemSelected(item: MenuItem): Boolean {
   return when (item.itemId) {
        android.R.id.home -> {
            // Respond to the action bar's Up/Home button
            val upIntent: Intent? = NavUtils.getParentActivityIntent(this)
            when {
                upIntent == null -> throw IllegalStateException("No Parent Activity Intent")
                else -> {
                    //add launch flag here
                    upIntent.flags=Intent.FLAG_ACTIVITY_CLEAR_TOP
                    NavUtils.navigateUpTo(this, upIntent)
                }
            }
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

*2nd solution looks like a bug. Set "android:parentActivityName" to activity which is not existed in current task stack.  Android will behavior like "BACK" button. It launches the top instance instead of launching parent activity.  Document mentions "NavUtils.shouldUpRecreateTask" can recognize if parent activity existed in current task. But it doesn't work in my test. Navigate up with a new back stack


text:
Q: How to make hr longer between cols? I am using bootstrap for my column structure and want to draw a horizontal line between the columns:

mycomp account number
2000299999940

mycomp account number:

2000299999940

css:
.line {
    width: 200px;
    height: 3px;
    background-color: #dadada;
    margin-right:40px;
  }

Because of the bootstrap columnstructure there are margins involved, but how can I make the line without all the space ie make it wider? Codepen here

A: well in case you want to ignore the default padding and margin in bootstrap make a class in css file as
.no-padding-margin
{
padding:0px;
margin: 0px;
}

and then apply this class to your bootstrap columns as

mycomp account number
2000299999940

mycomp account number:

2000299999940

A: well as i understand you just want your line to be longer .
so why don't you remove the paddings from the col the line is in. and also add width:100% on the .line if you want.
code :
.line {
  width: 100%;
  height: 3px;
  background-color: #dadada;
}
.col-md-1 {
  padding-left:0;
  padding-right:0;
}


text:
Q: Azure cli: clone pipeline Looking at az pipelines documentation it seems it's not possible to clone a pipeline using cli.
I've looked at getting the yaml (az pipelines show -name=x > x_orig.yaml) and then trying to change json and create pipeline from modified yaml, but that feels like a lot of work that could break after next update.
Is there a way to clone a pipline without going the the Web UI?

A: Currently, there indeed is not available Azure CLI that can clone or export/import a pipeline to create a new pipeline.
I also searched and tried the Azure DevOps REST API for Pipelines, but did not find the available API.
Ideally, the Azure CLI "az pipelines create" can provide an input parameter that allows users specify an existing pipeline as a starting point for the new pipeline.
If your projects really need this feature, I recommend that you can directly report a feature request on the "Azure/azure-cli" repository to ask adding the parameter like as above mentioned. That will allow you directly interact with the appropriate engineering team, and make it more convenient for the engineering team to collect and categorize your suggestions.

A: As a workaround, we could clone the build definition via power shell script to call REST API.
Note: We need to change the original build definition name.
REST API
Get build definition:
GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0

Create build definition
POST https://dev.azure.com/{organization}/{project}/_apis/build/definitions?api-version=6.0

Power shell script
$connectionToken="{pat}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$BuildDefinitionInfoURL = "https://dev.azure.com/{org name}/{project name}/_apis/build/definitions/386"
$BuildDefinitionInfo = Invoke-RestMethod -Uri $BuildDefinitionInfoURL -Headers @{authorization = "Basic $base64AuthInfo"} -Method Get
Write-Host $BuildDefinitionInfo.name

$BuildDefinitionInfo.name = $BuildDefinitionInfo.name +" clone"

Write-Host $BuildDefinitionInfo.name

$body = $BuildDefinitionInfo | ConvertTo-Json -Depth 99
$createBuildDefinitionURL = "https://dev.azure.com/{org name}/{project name}/_apis/build/definitions?api-version=6.0"
$response = Invoke-RestMethod -Uri $createBuildDefinitionURL -ContentType "application/json" -Body $body -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST

Write-Host $response.id

Result:


text:
Q: How to name my averaging technique? Suppose, I have a list of values {4, 10, 3, 6, 7, 15, 11}. The average of this number list is avg=8. Now I will select only those elements > avg, which are {10, 11, 15}. Now I am doing average again and selecting the elements bigger than their average. I believe this a helpful technique to get the top rated values from a list, I am not sure about the naming of this averaging technique. Can anybody help me with some name of this method?
Thanks in advance

A: How about using Averoveraging?

A: I'm not sure what your code looks like, but I'd imagine on one pass you are returning elements higher than the average? So I would name that method ElementsGreaterThanAverage.
If you're only always doing two passes, you could call it TopQuarterByAveraging or something.

A: You're computing the mean, then showing everything over it. Hence OverMean.


text:
Q: ngrok not working with mamp I am using MAMP Pro as development environment. I have used ngrok with MAMP before. however in this particular situation it redirects from the ngrok url to my local url and https is not available .
my local server is e-kyc.dev and im using ngrok http -host-header=e-kyc.dev 80 to run ngrok.

however when im using https:/a95118d9.ngrok.io it loads the welcome page(wihtout ssl) and once I click on a link it will redirect to a local url like e-kyc.dev/login instead of https:/a95118d9.ngrok.io/login
NOTE: my server works as expected locally, also functioning properly while using xip.io(for Lan) and selfsigned SSL.

A: for me the option --host-header=rewrite did work out:
./ngrok http --host-header=rewrite myname.test:80

A: Two ways to fix this:
First, the free way:

*

*In MAMP, go to your hosts and turn off the built in SSL.

*In MAMP, for that host, change the port for that host to something other than 80 (I used 8080).

*Open your terminal and navigate to the public directory for the web app. Run ngrok http 8080 from inside the public directory.

*Grab the https path provided by ngrok and you should have success.

Next, the paid way:

*

*Upgrate ngrok to the pro or business plan

*Use tls ngrok tls -subdomain=encrypted 443
... I'm assuming that the OP wants to go the free route. Hope this helps!


text:
Q: Contact form 7 not reading input values This is the first time i face this strange issue .. i have contact form and i receive an email from it but input variable like [fullname] are not replaced with input value inserted by the user.

Here is my form code in admin panel

[text* fullname id:name class:form-control placeholder"Please enter your name"]

[email* email id:email class:form-control placeholder"Please enter your Email Address"]

[text* phone id:phone class:form-control placeholder"Please enter your phone number"]

[text* subject id:subject class:form-control placeholder"Please enter message subject"]

    [textarea* message id:message rows:4 class:form-control placeholder"We are in love with details, feel free to share as much details as you would love to. We respond to messages in 12 hours or lesser time - for quick response, please leave your phone number so that we can call you back."]

[submit class:default-btn class:btn-block "Send"]


text:
Q: How do I toggle the display of a scrollbar? I would like to toggle the display of a scrollbar on a DIV container based on whether the mouse is over the container or not. So, only show the scrollbar when the mouse is over the DIV container (and the DIV is overflowing with content, of course).
I have tried to change the overflow from hidden to auto and vice-versa with CSS like the following:
div.container {
    overflow: hidden;
}

div.container:hover {
    overflow: auto;
}

This does toggle the display of the scrollbar, but when the scroll bar is shown again, it is reset to the top. I need to keep the position of the scrollbar at its last state.
What is the easiest way to toggle the display of a scrollbar? I am trying to stay with a pure CSS solution, but minimal JavaScript would probably be OK.

A: This is arguably a WebKit bug. Consider reporting it.
Edit: There's already at least one existing bug report. Though that one is somewhat unloved.

For now, here's a silly workaround:
$('.container').hover(function(){
    var scrollTop = $(this).scrollTop();
    $(this).scrollTop(0).scrollTop(scrollTop);
});

See: http://jsfiddle.net/C5vmK/
This can easily be written without jQuery if you're not already using it.


text:
Q: Range TextVisibleOnScreen always return -1 I am using the following code to find some strings in my document:
Application application = Addin.Application;
Document document = application.ActiveDocument;
Range rng = document.Content;

rng.Find.ClearFormatting();
rng.Find.Forward = true;
rng.Find.Text = findText;

while (rng.Find.Execute() && rng.Find.Found)
{
    // here this is always rng.TextVisibleOnScreen == -1
}

According to the documentation:

The TextVisibleOnScreen property returns 1 if all text in the range is
  visible; it returns 0 if no text in the range is visible; and it
  returns -1 if some text in the range is visible and some is not. Text
  that is not visible could be, for example, text that is in a collapsed
  heading.

However the property is always -1 even when the text is not on the screen at all or when all the text is on the screen... Is this a known issue? Am I doing something wrong?


text:
Q: Football Matches - build temp standings table for each Gameweek I have the following data in a sql database and i need that for each game in the table to add new columns with the Rank in Table, Number of Points and Goals Scored at home, for each Gameweek (the trickiest part).
Basically what i need is that after each gameweek (order ascending) to create a standings table and then bring Kpis from the standings table to each team for each match in the gamesweek.
The goal of all this is to build a Data Model with KPIs on how the team performed in the standings before each game and try to make some predictions afterwards  ps: if anyone interested, after the model will be ready please get in touch and will gladly share
Here is the table
Div DataMeciului HomeTeam       AwayTeam    FTHG    FTAG    Gameweek
E0  2018-08-10  Man United      Leicester     2      1         1
E0  2018-08-11  Bournemouth     Cardiff       2      0         1
E0  2018-08-11  Fulham          Crystal Palace0      2         1
E0  2018-08-11  Huddersfield    Chelsea       0      3         1
E0  2018-08-11  Newcastle       Tottenham     1      2         1
E0  2018-08-11  Watford         Brighton.     2      0         1
E0  2018-08-11  Wolves          Everton       2      2         1
E0  2018-08-12  Arsenal         Man City      0      2         1
E0  2018-08-12  Liverpool       West Ham      4      0         1
E0  2018-08-12  Southampton     Burnley       0      0         1
E0  2018-08-18  Cardiff         Newcastle     0      0         2
E0  2018-08-18  Chelsea         Arsenal       3      2         2
E0  2018-08-18  Everton         Southampton   2      1         2
E0  2018-08-18  Leicester       Wolves        2      0         2
E0  2018-08-18  Tottenham       Fulham        3      1         2
E0  2018-08-18  West Ham        Bournemouth   1      2         2
E0  2018-08-19  Brighton        Man United    3      2         2
E0  2018-08-19  Burnley         Watford       1      3         2
E0  2018-08-19  Man City        Huddersfield  6      1         2
E0  2018-08-20  Crystal Palace  Liverpool     0      2         2
E0  2018-08-25  Arsenal         West Ham      3      1         3
E0  2018-08-25  Bournemouth     Everton       2      2         3
E0  2018-08-25  Huddersfield    Cardiff       0      0         3
E0  2018-08-25  Liverpool       Brighton      1      0         3
E0  2018-08-25  Southampton     Leicester     1      2         3
E0  2018-08-25  Wolves          Man City      1      1         3
E0  2018-08-26  Fulham          Burnley       4      2         3
E0  2018-08-26  Newcastle       Chelsea       1      2         3
E0  2018-08-26  Watford       Crystal Palace  2      1         3
E0  2018-08-27  Man United      Tottenham     0      3         3
E0  2018-09-01  Brighton        Fulham        2      2         4
E0  2018-09-01  Chelsea         Bournemouth   2      0         4
E0  2018-09-01  Crystal Palace  Southampton   0      2         4
E0  2018-09-01  Everton         Huddersfield  1      1         4
E0  2018-09-01  Leicester       Liverpool     1      2         4
E0  2018-09-01  Man City        Newcastle     2      1         4
E0  2018-09-01  West Ham        Wolves        0      1         4
E0  2018-09-02  Burnley         Man United    0      2         4
E0  2018-09-02  Cardiff         Arsenal       2      3         4
E0  2018-09-02  Watford         Tottenham     2      1         4

Desired outcome
HTPts HTPos HomeTeam   AwayTeam   ATPos   ATPts
  3     1   Man United Leicester    15      0
  3     3   Bournemouth Cardiff     16      0
  0     13  Fulham     Crystal Palace 6     3

Sorting the temptables to define position should be done one order by PTS, SUM(FTHG - FTAG)


text:
Q: Which is formal; "In this paper I argue" or "This paper argues"?
In this paper I argue that small incentives can lead to greater participation in surveys.

OR

This paper argues that small incentives can lead to greater participation in surveys.

According to Unit 1: An approach to Academic Writing (Page: 22), the first one is informal and should be avoided in the academic writings; I'd agree to it too. However, the second one seems to be odd as the inanimate subject of it (This paper) is followed by an action verb (argues).
Can action verbs be sometimes used with inanimate subjects/topics? Because, otherwise, the second sentence would not be formal either.

A: Academic style varies somewhat from journal to journal and from institute to institute. However, many large academic publishing houses (IEE, IOP, Elsevier) do not express preference on the usage or not of personal pronouns. Often research attempts to express objective truth, where personal pronouns would be misplaced. However it is unavoidably true that someone or a group of people wrote the paper, so these singular (I) or collective (we) pronouns would be fine, since they permit you to use the active voice.
If you feel that "I" is too informal, you could refer to yourself in the third person, by saying "the author".

A: Generally, in a formal paper the proper etiquette is to avoid first person words/point of view (I, me, we, my, our).
"This paper outlines..."
"This paper argues..."
"This paper demonstrates.."
The above are all valid for formal academic writing.


text:
Q: Discord.js music bot does not respond to first music request I've been coding an all purpose bot recently for my discord server, and have been running into some problems with music requests. there is currently no queue system, and i'm not sure if I plan to implement one, so at the moment, if a song is playing and a new one is requested, the current one is skipped and the new one starts playing. my problem however is that when a song is playing and a new one is requested, it just plays the last requested song, AKA the current one. this essentially means that the songs are always one request behind. my code for the music part is as follows
var channel;
var dispatcher;
var contentID;
var playing = false;
var queue = [] bot.on("message", message => {
    let args = message.content.substring(musicPrefix.length).split(" ");
    //GOOGLE API AREA!

    channel = message.member.voice.channel
    if (!message.guild && args[0] === "play") return message.reply('Please send music requests in a Sleepybot© supported server!');
    switch (args[0].toLowerCase()) {
        case ("play"):
            google.youtube("v3").search.list({
                    key: youtubeToken,
                    part: "snippet",
                    q: message.content.slice(6),
                    maxResults: 1,
            }).then((response) => {
                const { data } = response data.items.forEach((item) => {
                    console.log(item.id.videoId);
                    contentID = item.id.videoId;
                });
            }).catch((err) => console.log(err)); //if (message.member.voice.channel) {

            if (!channel) {
                message.reply("you must be in a voice channel to play music!");
                return;
            } else if (!args[1]) return message.reply("please specify a song title or link");

            channel.join().then(connection => {
                var sound = "https://www.youtube.com/watch?v=" + contentID; // const stream = ytdl(sound, { filter: 'audioonly' })
                //  if(playing===false){
                const stream = ytdl(sound, { filter: 'audioonly' });
                dispatcher = connection.play(stream);
                console.log('playing something');
                playing = true;
                return;
            });
            break;
        case ("disconnect"):
            message.reply("disconnecting...") dispatcher.end();
            if (!channel) {
                message.reply("there was an error leaving the channel");
            } else {
                channel.leave() message.reply("disconnected");
            }
            playing = false; //you may not just "leave all channels" you need to leave a specific one, so make sure you're leaving the one it's in
            break;
        case ("pause"):
            dispatcher.pause() message.reply("Paused"); console.log("paused");
            break;
        case ("resume"):
            dispatcher.resume() message.reply("resumed!"); console.log("resumed");
            break;
        }
    }
);

A: When using promises in javascript, anything that depends on the result of a promise needs to be within the lambda function provided to .then(). Example
promise.then((response) => {
  // after the promise calls the lambda function provided
});
// code runs immediately right after the promise is **created**, not when done running

In your situation, you are running code outside of the lambda. This means it will run that "outside" code instantly after creating the promise, whether or not it called .then()... To fix this: move the part that plays the audio
if (!channel) {
    //.........
channel.join().then(connection => {
    //........
    return;
});

into here
google.youtube("v3").search.list({
        key: youtubeToken,
        part: "snippet",
        q: message.content.slice(6),
        maxResults: 1,
}).then((response) => { // START OF LAMBDA FUNCTION
    const { data } = response data.items.forEach((item) => {
        console.log(item.id.videoId);
        contentID = item.id.videoId;
    });
    // ----------------
    // INSERT CODE HERE
    // ----------------
    // END OF LAMBDA FUNCTION
}).catch((err) => console.log(err));

Hopefully that fixes your problem. :)


text:
Q: Image compression with minimal loss of quality It is worth to clarify that with the programming language Swift and with all its components, I have known for three days!
Three days I try to solve this problem, I have not found a single solution, I have rummaged through a lot of sites! I need to make sure that images when uploading to the server are fun no more than 150 kb, but at the same time, so that the quality is good.
During the search, I found an algorithm, on sites and on GitHub they wrote that it was a copy of the WhatsApp messenger image compression, but on the iphone 8 it does not compress the image very well. If you give an example, the compression of the photographed image on the iphone 8 when transferring to the messenger WhatsApp is compressed to 100 kb., While the image quality is very good, and the length and width is more than 1000px. And if you use this algorithm, then at a length of: 800px and a width of: 600px and a compression ratio of 0.01 the image weighs more than 200 kb. and the quality is terrible.
Here is the algorithm:
extension UIImage {
func compressImage() -> UIImage? {
    // Reducing file size to a 10th
    var actualHeight: CGFloat = self.size.height
    var actualWidth: CGFloat = self.size.width
    let maxHeight: CGFloat = 800.0
    let maxWidth: CGFloat = 600.0
    var imgRatio: CGFloat = actualWidth/actualHeight
    let maxRatio: CGFloat = maxWidth/maxHeight
    var compressionQuality: CGFloat = 0.01

    if actualHeight > maxHeight || actualWidth > maxWidth {
        if imgRatio < maxRatio {
            //adjust width according to maxHeight
            imgRatio = maxHeight / actualHeight
            actualWidth = imgRatio * actualWidth
            actualHeight = maxHeight
        } else if imgRatio > maxRatio {
            //adjust height according to maxWidth
            imgRatio = maxWidth / actualWidth
            actualHeight = imgRatio * actualHeight
            actualWidth = maxWidth
        } else {
            actualHeight = maxHeight
            actualWidth = maxWidth
            //compressionQuality = 1
        }
    }
    let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
    UIGraphicsBeginImageContext(rect.size)
    self.draw(in: rect)
    guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
        return nil
    }
    UIGraphicsEndImageContext()
    guard let imageData = UIImageJPEGRepresentation(img, compressionQuality) else {
        return nil
    }
    return UIImage(data: imageData)
}

}
As it did not work with this algorithm, I started looking for an image compression library for Swift, but unfortunately I did not find anything! Then I tried to use the LZFSE compression algorithm, but as I understood, without a decompressor on another device (assuming with Android OS), the image will not be displayed, besides, he complained about nil-data in one of the lines of code.
Here's the code:
 public enum CompressionAlgorithm {
  case lz4   // speed is critical
  case lz4a  // space is critical
  case zlib  // reasonable speed and space
  case lzfse // better speed and space
}

private enum CompressionOperation {
  case compression, decompression
}

private func perform(_ operation: CompressionOperation,
                     on input: Data,
                     using algorithm: CompressionAlgorithm,
                     workingBufferSize: Int = 2000) -> Data?  {
  var output = Data()

  // set the algorithm
  let streamAlgorithm: compression_algorithm
  switch algorithm {
    case .lz4:   streamAlgorithm = COMPRESSION_LZ4
    case .lz4a:  streamAlgorithm = COMPRESSION_LZMA
    case .zlib:  streamAlgorithm = COMPRESSION_ZLIB
    case .lzfse: streamAlgorithm = COMPRESSION_LZFSE
  }

  // set the stream operation, and flags
  let streamOperation: compression_stream_operation
  let flags: Int32
  switch operation {
    case .compression:
      streamOperation = COMPRESSION_STREAM_ENCODE
      flags = Int32(COMPRESSION_STREAM_FINALIZE.rawValue)
    case .decompression:
      streamOperation = COMPRESSION_STREAM_DECODE
      flags = 0
  }

  // create a stream
  var streamPointer = UnsafeMutablePointer<compression_stream>
    .allocate(capacity: 1)
  defer {
    streamPointer.deallocate(capacity: 1)
  }

  // initialize the stream
  var stream = streamPointer.pointee
  var status = compression_stream_init(&stream, streamOperation, streamAlgorithm)
  guard status != COMPRESSION_STATUS_ERROR else {
    return nil
  }
  defer {
    compression_stream_destroy(&stream)
  }

  // set up a destination buffer
  let dstSize = workingBufferSize
  let dstPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: dstSize)
  defer {
    dstPointer.deallocate(capacity: dstSize)
  }

  // process the input
  return input.withUnsafeBytes { (srcPointer: UnsafePointer<UInt8>) in

    stream.src_ptr = srcPointer
    stream.src_size = input.count
    stream.dst_ptr = dstPointer
    stream.dst_size = dstSize

    while status == COMPRESSION_STATUS_OK {
      // process the stream
      status = compression_stream_process(&stream, flags)

      // collect bytes from the stream and reset
      switch status {

      case COMPRESSION_STATUS_OK:
        output.append(dstPointer, count: dstSize)
        stream.dst_ptr = dstPointer
        stream.dst_size = dstSize

      case COMPRESSION_STATUS_ERROR:
        return nil

      case COMPRESSION_STATUS_END:
        output.append(dstPointer, count: stream.dst_ptr - dstPointer)

      default:
        fatalError()
      }
    }
    return output
  }
}

// Compressed keeps the compressed data and the algorithm
// together as one unit, so you never forget how the data was
// compressed.
public struct Compressed {
  public let data: Data
  public let algorithm: CompressionAlgorithm

  public init(data: Data, algorithm: CompressionAlgorithm) {
    self.data = data
    self.algorithm = algorithm
  }

  // Compress the input with the specified algorithm. Returns nil if it fails.
  public static func compress(input: Data,
                              with algorithm: CompressionAlgorithm) -> Compressed? {
    guard let data = perform(.compression, on: input, using: algorithm) else {
      return nil
    }
    return Compressed(data: data, algorithm: algorithm)
  }

  // Factory method to return uncompressed data. Returns nil if it cannot be decompressed.
  public func makeDecompressed() -> Data? {
    return perform(.decompression, on: data, using: algorithm)
  }
}

// For discoverability, add a compressed method to Data
extension Data {
  // Factory method to make compressed data or nil if it fails.
  public func makeCompressed(with algorithm: CompressionAlgorithm) -> Compressed? {
    return Compressed.compress(input: self, with: algorithm)
  }
}

Here in this line, after applying this algorithm:
UIImage(data: imageCompressData)//к переменной imageCompressData был применен код сверху!

Next, I accidentally stumbled upon this code:
func resizeImageUsingVImage(image:UIImage, size:CGSize) -> UIImage? {
    let cgImage = image.cgImage!
    var format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.first.rawValue), version: 0, decode: nil, renderingIntent: CGColorRenderingIntent.defaultIntent)
    var sourceBuffer = vImage_Buffer()
    defer {
        free(sourceBuffer.data)
    }
    var error = vImageBuffer_InitWithCGImage(&sourceBuffer, &format, nil, cgImage, numericCast(kvImageNoFlags))
    guard error == kvImageNoError else { return nil }
    // create a destination buffer
    let scale = image.scale
    let destWidth = Int(size.width)
    let destHeight = Int(size.height)
    let bytesPerPixel = image.cgImage!.bitsPerPixel/8
    let destBytesPerRow = destWidth * bytesPerPixel
    let destData = UnsafeMutablePointer<UInt8>.allocate(capacity: destHeight * destBytesPerRow)
    defer {
        destData.deallocate(capacity: destHeight * destBytesPerRow)
    }
    var destBuffer = vImage_Buffer(data: destData, height: vImagePixelCount(destHeight), width: vImagePixelCount(destWidth), rowBytes: destBytesPerRow)
    // scale the image
    error = vImageScale_ARGB8888(&sourceBuffer, &destBuffer, nil, numericCast(kvImageHighQualityResampling))
    guard error == kvImageNoError else { return nil }
    // create a CGImage from vImage_Buffer
    var destCGImage = vImageCreateCGImageFromBuffer(&destBuffer, &format, nil, nil, numericCast(kvImageNoFlags), &error)?.takeRetainedValue()
    guard error == kvImageNoError else { return nil }
    // create a UIImage
    let resizedImage = destCGImage.flatMap { UIImage(cgImage: $0, scale: 0.0, orientation: image.imageOrientation) }
    destCGImage = nil
    return resizedImage
}

A bit more detailed look at the code and having studied the documentation for vImage, and Accelerate library, I realized that this very powerful image processing library, if I had enough knowledge, maybe I could create a good image compressor, but my knowledge is not enough, so all the hope for You.

A: In the first sample, 0.01 compression quality means the quality will be 1% of the original image.
Try changing the value to 0.8 for 80% quality and see if it gets better.

A: Since what you're really looking to do is insure that you have the highest quality image uploaded with a maximum image size (800x600) and data byte size (150k) I'd split it up into two separate steps:
// size down the image to fit in 800x600
let sizedImage = image.aspectFit(toSize:CGSize(width:800, height:600))

// get the jpeg image with a max size of 150k bytes
let imageData = sizedImage.getJPEGData(withMaxSize:150_000)

Of course, all that really doesn't help without definitions for UIImage.aspectFit:
func *(lhs:CGSize, rhs:CGFloat) -> CGSize {
    return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
}

extension CGSize {
    func aspectFit(toSize:CGSize) -> CGSize {
        return self * min(toSize.width / width, toSize.height / height, 1.0)
    }
}

extension UIImage {
    func aspectFit(toSize:CGSize) -> UIImage? {
        let newSize = size.aspectFit(toSize:toSize)

        UIGraphicsBeginImageContext(newSize)
        defer {
            UIGraphicsEndImageContext()
        }

        draw(in: CGRect(origin: CGPoint.zero, size: newSize))

        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

and UIImage.getJPEGData:
extension UIImage {
    func getJPEGData(withMaxSize max:Int) -> Data? {
        for quality in stride(from: 1.0 as CGFloat, to: 0.05, by: 0.05) {
            if let data = UIImageJPEGRepresentation(self, quality), data.count < max {
                return data
            }
        }

        return nil
    }
}

This is a little bit "smarter" approach that performs a binary search to get the best image quality that's under 150k, but it's really probably overkill for most purposes:
func binarySearch<Type:Comparable, Result>(lhs:Type, rhs:Type, next:(Type, Type)->Type, predicate:(Type)->Result?) -> (Type, Result)? {
    let middle = next(lhs, rhs)

    if(middle == lhs) {
        return predicate(lhs).map { ( middle, $0) }
    }

    if(predicate(middle) != nil) {
        return binarySearch(lhs: middle, rhs: rhs, next: next, predicate: predicate)
    }
    else {
        return binarySearch(lhs: lhs, rhs: middle, next: next, predicate: predicate)
    }
}

extension UIImage {
    func jpegData(withMaxSize max:Int) -> Data? {
        if let data = UIImageJPEGRepresentation(self, 1.00), data.count < max {
            return data
        }

        guard let (quality, data) = binarySearch(lhs: 1, rhs: 100, next: { ($0 + $1) / 2 }, predicate: { (quality:Int)->Data? in
            guard let data = UIImageJPEGRepresentation(self, CGFloat(quality)/100) else {
                return nil
            }

            return data.count <= max ? data : nil
        }) else {
            return nil
        }

        print("quality = \(quality)")

        return data
    }
}


text:
Q: PrePended Button Does Not Appear to be firing Added
 $('#'+course.code).append('<button class="collapsible">'+course.title+'</button>');

To add a button to each div with an ID of course code. The works fine. When I click the button it won't fire the code below. If I copy and paste this exact code it works fine. Does generating a button list of buttons with prepend effect its functionality?
var coll = document.getElementsByClassName("collapsible");
var i;

    for (i = 0; i < coll.length; i++) {
      coll[i].addEventListener("click", function() {
          alert('sup');
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.display === "block") {
          content.style.display = "none";
        } else {
          content.style.display = "block";
        }
      });
    }

Here is the final generated code

<button class="collapsible">AP Calculus BC</button>

Course Title: AP Calculus BC

Course Code: 472101A

Level: AP

Credit(s): 1

Semester(s): 2

Course Fee: N/A

Description:

Suggested Skills: Basic understanding of function behavior, such as polynomials, rationals, rational exponent, trigonometric functions and other transcendental functions. Should be able to solve, graph, evaluate and analyze those functions. Should be able to apply those functions to model real world phenomena.  Class covers BOTH Calculus 1 and 2. Accelerated Pace. Students should be able to process and apply information at a very fast pace.

Prerequisite Classes & Grades:

Honors PreCalculus: Students must earn an A,B both semesters and pass a proficiency exam in May
OR
Regular PreCalculus: Students must earn an A both semesters and pass a proficiency exam in May
OR
ATP: Students must earn an A,B both semesters and pass a proficiency exam in May

Typical Grade Level:

11-12

Level of Challenge (1-5) 5 is extremely challenging:

5

Typical Homework Commitment:

4-6

Interests / Career Aspirations:

Engineering, Computer Science, Business

Other:

Suggested Skills: Basic understanding of function behavior, such as polynomials, rationals, rational exponent, trigonometric functions and other transcendental functions. Should be able to solve, graph, evaluate and analyze those functions. Should be able to apply those functions to model real world phenomena.  Class covers BOTH Calculus 1 and 2. Accelerated Pace. Students should be able to process and apply information at a very fast pace.

*All AP Courses are expected to have a $100 fee ($25 class fee and $75 exam fee).

The exact exam fee for testing in May 2016 will be released by the CollegeBoard in October 2015. This exam fee determines the total price that students will owe for each AP Course/exam. The AP exam fee may be fully or partially reduced for students with free/reduced lunch, per funding by district and state grants. The exact fee will be provided as soon as the district and state release their funding statement.

A: It sounds like you are setting the event listener before the element is created. Make sure you run your for loop after the jQuery append statement.
Just to make sure the elements exist when you are setting the listener you could run console.log(coll[i]) to tell you for certain if the element exists yet at that point in execution.
Another option is to use jQuery's on function. So in your case you could use something like this:
$('body').on('click', '.collapsible', function() {
    // do something
})

This gives you the benefit that it will trigger even if you append elements to the page after running this function. This will also work for any .collapsible element, and doesn't have to be applied to each one individually.


text:
Q: jQuery datepicker hover output date I am using jQuery datepicker and I want to display out the date that the user is currently hovering over. I have the code below (you can also try the code with JSFiddle, http://jsfiddle.net/JGM85/):
$(function() {
    $("#datepicker").datepicker();
    $(".ui-state-default").live("mouseenter", function() {
        $("h1").text($(this).text());
    });
});

Currently when hovering over a date, the number of the date (ie. 23) is outputed to the h1 tags. I want to change this so that it outputs the whole date and stores it in a variable.
Any help with this would be appreciated.

A: It's not the best way I did it, because I found nothing in the jQuery UI Datepicker documentation for getting the actual Date, but here you go:
$(function() {
    $("#datepicker").datepicker();
    $(".ui-state-default").on("mouseenter", function() {
        $("h1").text($(this).text()+"."+$(".ui-datepicker-month",$(this).parents()).text()+"."+$(".ui-datepicker-year",$(this).parents()).text());
    });
});

http://jsfiddle.net/JGM85/1/
The second version with saving the actual Date + alerting it afterwards:
$(function() {
    $("#datepicker").datepicker();
    $(".ui-state-default").on("mouseenter", function() {
        $("h1").text($(this).text()+"."+$(".ui-datepicker-month",$(this).parents()).text()+"."+$(".ui-datepicker-year",$(this).parents()).text());
    var actualDate=$('h1').text();
        alert(actualDate);
    });
});

http://jsfiddle.net/JGM85/2/
UPDATE: I previously had .live as an event handler but .live is no deprecated and .on() is the method to go.


text:
Q: Swift - Animate Constraints in Custom UIView I am trying to animate constraints in a custom UIView. The ending layout is correct, but I cannot get UIView.animate to work correctly, and I have seen that everyone is calling self.view.layoutIfNeeded() from a view controller, so perhaps that is my problem. I am calling self.layoutIfNeeded() on the custom view itself. In case the hierarchy matters, I have as follows: ViewController > TableView > Cell > View > AnimationView.
class AnimationView: UIView {

    // MARK: - Properties
    let ratioMultiplier: CGFloat = 0.28
    var listLeadingConstraint: NSLayoutConstraint!
    var listTrailingConstraint: NSLayoutConstraint!
    var checkmarkLeadingConstraint: NSLayoutConstraint!
    var checkmarkTrailingConstraint: NSLayoutConstraint!

    // MARK: - UI Components
    lazy var listImageView: UIImageView = {
        let image = UIImage(named: "list.small")
        let result = UIImageView(image: image)
        return result
    }()

    lazy var checkmarkImageView: UIImageView = {
        let image = UIImage(named: "checkmark.small")
        let result = UIImageView(image: image)
        return result
    }()

    // MARK: - Inits
    init() {
        super.init(frame: .zero)
        setupView()
    }

    required init?(coder: NSCoder) {
        return nil
    }

    // MARK: - Methods
    func playAnimation() {
        // 1. change constraints
        listLeadingConstraint.constant += (listImageView.frame.size.width * ratioMultiplier)
        listTrailingConstraint.constant += (listImageView.frame.size.width * ratioMultiplier)
        checkmarkLeadingConstraint.constant += (checkmarkImageView.frame.size.width * ratioMultiplier)
        checkmarkTrailingConstraint.constant += (checkmarkImageView.frame.size.width * ratioMultiplier)
        self.layoutIfNeeded()

        // 2. animate constraints
        UIView.animate(withDuration: 3.0) {
            self.layoutIfNeeded()
        }
    }

    func setupView() {
        // 1. add subviews
        addSubview(listImageView)
        addSubview(checkmarkImageView)

        // 2. add constraints
        ConstraintHelper.anchor(view: checkmarkImageView, options: [.top, .bottom])
        checkmarkLeadingConstraint = checkmarkImageView.leadingAnchor.constraint(equalTo: leadingAnchor)
        checkmarkTrailingConstraint = checkmarkImageView.trailingAnchor.constraint(equalTo: trailingAnchor)
        checkmarkLeadingConstraint.constant -= checkmarkImageView.frame.size.width * ratioMultiplier
        checkmarkTrailingConstraint.constant -= checkmarkImageView.frame.size.width * ratioMultiplier
        NSLayoutConstraint.activate([checkmarkLeadingConstraint, checkmarkTrailingConstraint])

        ConstraintHelper.anchor(view: listImageView, options: [.top, .bottom])
        listLeadingConstraint = listImageView.leadingAnchor.constraint(equalTo: leadingAnchor)
        listTrailingConstraint = listImageView.trailingAnchor.constraint(equalTo: trailingAnchor)
        NSLayoutConstraint.activate([listLeadingConstraint, listTrailingConstraint])
    }
}

Additional info: playAnimation() is called from cellForRow on the table view and I also tried using self.superview?.layoutIfNeeded() calls to no success. The ConstraintHelper calls translatesAutoresizingMaskIntoConstraints and the constraints are working correctly, so don't worry about that. Any help would be great.

A: The reason why your initial post is not working is that you called your first layoutIfNeeded() after the constraint changes. When your animation block is executed, there's no changes to be animated at all.
It does not matter whether you change the constraints in or out of the animation block.
The common steps are:

*

*Call layoutIfNeeded() on the rootest view that your constraints may affect. In your case, self is ok because all the involving constraints are for the subviews. In some cases, you might change a constraint for the self view, then you need to call layoutIfNeeded on its superview.

*Make your constraint changes: modify constant property, activate/deactivate constraints, etc.

*Call layoutIfNeeded() in a animation block on the same view as you did in the first step.

Please try the following alternative:
func playAnimation() {
    // Request a layout to clean pending changes for the view if there's any.
    self.layoutIfNeeded()

    // Make your constraint changes.
    listLeadingConstraint.constant += (listImageView.frame.size.width * ratioMultiplier)
    listTrailingConstraint.constant += (listImageView.frame.size.width * ratioMultiplier)
    checkmarkLeadingConstraint.constant += (checkmarkImageView.frame.size.width * ratioMultiplier)
    checkmarkTrailingConstraint.constant += (checkmarkImageView.frame.size.width * ratioMultiplier)

    UIView.animate(withDuration: 3.0) {
        // Let your constraint changes update right now.
        self.layoutIfNeeded()
    }
}

A: Got it working. Moving the constraint changes to the animation block fixed it, though this is in contrast to most of the posts out there, which say to make constraint changes before the animation block, call layoutIfNeeded() once in preparation, and then a second layoutIfNeeded() in the animation block to force the update and animation. Why this behavior is different in my code, I'm still not sure...
func playAnimation() {

    // update constraints & animate
    UIView.animate(withDuration: 3.0) {
        listLeadingConstraint.constant += (listImageView.frame.size.width * ratioMultiplier)
        listTrailingConstraint.constant += (listImageView.frame.size.width * ratioMultiplier)
        checkmarkLeadingConstraint.constant += (checkmarkImageView.frame.size.width * ratioMultiplier)
        checkmarkTrailingConstraint.constant += (checkmarkImageView.frame.size.width * ratioMultiplier)
        self.layoutIfNeeded()
    }
}


text:
Q: Does it make sense to use TFS purely as a project management tool? Does it make sense to use the project management features of Team Foundation Server without using the Source Control and Automatic Build features? We're doing agile in an non-.net environment and would use TFS to manage the project but keep using the currently used source control and build software.
Thanks in advance,

A: One of TFS' primary strengths is that the work item tracking and source control are so closely linked.  Another of its primary strengths is the integration into the Visual Studio IDE.  It sounds like you wouldn't be using either of those features, so that starts to drive you away from using TFS as a solution.
Another factor that is an unknown here is how much you would need to pay for TFS licensing.  If you already have that covered under existing MSDN licenses, then it probably isn't a factor.
That being said, the agile process template in TFS 2010 is a very nice agile-in-a-box solution, giving you the work items and management reports that you need to work in an agile environment.  Additionally, you can modify the process template as needed to meet your particular flavor of agile.


text:
Q: Flutter Column bottom overflowed by pixels I'm trying to show an item in a Gridview with the format:
Price text -> item image -> title text
Im using a column to achieve it and it seems like the tile in GridView has a fixed height, so when the image gets too big it will lead to bottom overflow.
So my question is, is there a way to keep the Price and title text and only squeeze the middle image? Something similar to android/iOS layout constraints? Thanks guys.
[Update] I have pasted the code snippet as well.
There is one more thing I have tried is to set the image with fixed height and width and it works, but that requires me to carefully find a suitable extent which is not really flexible to me. And GridTile also does not really give me the layout that I want. Is there really no way that I can just squeeze the middle view(image in this case here) with Column?

@override
Widget build(BuildContext context) {
  final imageUrl = doc['main_image']['downloadURL'];
  Widget image;
  if (imageUrl != null) {
    image =  Image.network(
          imageUrl,
          fit: BoxFit.scaleDown,
        );
  } else {
    image = Container(
      color: Colors.grey,
    );
  }

  String price = '\$' + doc[FIREBASE_COL_PRICE].toString();
  return Card(
      child: Column(
    children: <Widget>[
      Align(
        alignment: Alignment.centerRight,
        child: Text(
          price,
          maxLines: 1,
        ),
      ),
      Container(
        padding: const EdgeInsets.symmetric(horizontal: 8.0),
        child: image,
      ),
      Align(
        alignment: Alignment.centerLeft,
        child: Text(
          doc[FIREBASE_COL_NAME],
          maxLines: 1,
        ))
    ],
  ));
}

A: Have you considered using Expanded widgets? It should distribute the size of widgets inside the Card.
GridView builder I used to test
GridView.count(
  primary: false,
  padding: const EdgeInsets.all(20),
  crossAxisSpacing: 10,
  mainAxisSpacing: 10,
  crossAxisCount: 2,
  children: List.generate(
    20, (index) {
      return gridCard(index);
    },
  ),
),

Cards for the GridView. I've modified the snippet you've provided.
gridCard(int index) {
  final imageUrl = "URL";
  Widget image;
  if (imageUrl != null) {
    image = Image.network(
      imageUrl,
      fit: BoxFit.scaleDown,
    );
  }
  else {
    image = Container(
      color: Colors.grey,
    );
  }

  String price = '\$1234';
  return Card(
    child: Container(
      padding: const EdgeInsets.symmetric(horizontal: 12.0),
      child: Column(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Align(
              alignment: Alignment.centerRight,
              child: Text(
                price,
                maxLines: 1,
              ),
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: image,
            ),
          ),
          Expanded(
            flex: 1,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Some Text $index',
                maxLines: 1,
              ),
            ),
          ),
        ],
      ),
    ),
  );
}

Demo


text:
Q: Why is it necessary for the block to not move only when the wedge accelerates?
Angel of inclination = $37^{\circ}$
Here , there a wedge of mass 5m and a constant force is being applied on the wedge . Now , it says in book that for the mass m (block) to not move , the wedge must accelerate. I don't understand why must the block accelerate so that the block m does not move and why not let the wedge move with a certain constant velocity.
I know one reason is constant force but if it moves with a certain constant velocity at some point. Then ?

A: The block of mass $m$ is experiencing the force of gravity in downward direction (call it $y$ axis).
.
So we can break it in two components, one along the inclined surface of wedge and one perpendicular to the previous one.
So the component of gravity tangential to inclined to surface or wedge should be counter, or else there will be a external unbalanced force, that means it will move.
So, to make it at rest in $y$ axis, there should be force and that comes from our acceleration of wedge and we call there is a pseudo force on mass $m$ when observing in the wedge's reference frame.

A: All velocity is relative. If an object is moving at a constant velocity, the numerical value and direction of that velocity can be anything you choose depending on your reference frame. You can choose to view the block and wedge as being at rest, moving at a constant 0 m/s. Or, you could hop in a car and drive away from the block and wedge and a constant 10 m/s, and view the block and wedge as moving away from you at 10 m/s. Whatever velocity you choose to assign to the block and wedge certainly cannot change its physical behavior - whether I choose to say that the block is a rest or moving at a constant 10 m/s depends entirely on my point of view, and changes nothing whatsoever about what the block and wedge are actually doing.
Basically, being at rest and moving at a constant velocity are fundamentally the same, since it depends entirely on your personal choice of how you view the problem. Anything that occurs at rest will also occur when moving at a constant velocity. It's quite intuitive that while at rest, the block will simply slide down the wedge, since there's nothing holding it in place. That will also occur in the exact same way if you drive away from the apparatus and view it as moving at a constant velocity. Since the block slides down the wedge while at rest, it also slides down the wedge while moving at a constant velocity.


text:
Q: Which is the synthesized digital circuit for this [verilog] mux with an uncompleted sensibility list? Which is the synthesized not optimized digital circuit for the following code:
a, b and c are 1 bit long.
sel has 2 bits.
always@(a, b, sel)
case(sel)
    begin
    2'b00: a;
    2'b01: b;
    2'b10: c;
    default: 0;
    end
endcase

If i am not mistaken we would have a mux with three inputs and two selection bits.
As selection bits we have sel[0] and sel[1].
As inputs we have a, b and a latch.
The latch will have as input c and something else. I dont know what else has to enter the latch.
This question is just educational.

A: This does not synthesize into digital logic. The enable signal for the latch on c would have to be "when any of the 4 bits {a,b,sel} change, and then close it before c changes again".

A: Most synthesizers do not consider the sensitivity list unless it is for synchronous logic. The latching behavior you would see in simulation will not happen post-synthesis. The major reason @* was added in IEEE1364-2001 prevent accidental omissions from sensitivity list.
If you truly want to output a latched version of c, then you need to create the latch before the mux:
always @*
  if (lat_en) c_latch <= c;
always @*
  case(sel)
    2'b00: a;
    2'b01: b;
    2'b10: c_latch;
    default: 0;
  endcase

Level-sensitive latches are not common on FPGAs. The are used sparingly on ASICs due to timing concerns. Edge-sensitive flip-flops are generally preferred:
always @(posedge clk)
  if (update) c_ff <= c;
always @*
  case(sel)
    2'b00: a;
    2'b01: b;
    2'b10: c_ff;
    default: 0;
  endcase


text:
Q: how to render different layout & json data in one action of conroller in rails? I am new to Rails.
I want to render layout(.html.erb file) as well as json data from action of controller.
How can I perform it?
Can I render both of them in single action? how?

A: This is exactly what respond_to is for. From the Rails Action Controller guide:
class UsersController < ApplicationController
  def index
    @users = User.all
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render xml: @users}
      format.json { render json: @users}
    end
  end
end


text:
Q: I want to make webview in android, but back button function not work? i am making webview in android, i am begineer in android. Below my code and i am facing following problems.

*

*Back button not work , when i visiting different pages of my application and press back button then its not work and give error application has been stoped and take back me on home screen of my mobile.

*2nd i want when any user open this application then if internet not connected or not working then its give the alert some like "This application required internet connection" and in background by default my given background show wihotu internet connection. If internet connection found then this app work fine.
I am new in android. In advance i am very thankful for this help. and please in your answere write the code for fix the below issues. Thanks in advance
package com.example.edarabia;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.annotation.SuppressLint;
import android.view.KeyEvent;

@SuppressLint("SetJavaScriptEnabled")

public class MainActivity extends Activity {
WebView mywebview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView mywebview = (WebView) findViewById(R.id.webview);
        mywebview.loadUrl("http://www.grafdom.com/operations/projects/ma/edarabiaapp/");
    WebSettings webSettings = mywebview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setBuiltInZoomControls(true);
    mywebview.setWebViewClient(new WebViewClient());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // Check if the key event was the Back button and if there's history
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
        mywebview.goBack();
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

}

A: *

*You should remove
@Override
public void onBackPressed (){
    if(webView.canGoBack()) webView.goBack();
    else super.onBackPressed();
}

to avoid NullPointerException. Why do you use such implementation?
2. You can use such function for your purpose:
    public boolean isOnline() {
       boolean res = false;
       ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
       NetworkInfo netInfo = cm.getActiveNetworkInfo();
       if (netInfo != null && netInfo.isConnectedOrConnecting()) {
           res= true;
       }
       else
       {
           Toast.makeText(context, "You've lost internet connection. Please check it and try again", Toast.LENGTH_LONG).show();
           res = false;
        }
       return res;
   }

and in the Activity:
boolean isOnline = isOnline();
if (isOnline)
 {
      //What you want to do if there's a connection..
  }

A: You can do something like the following,
1.Override the back button functionality
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

2.For checking internet connection at app startup put the following code inside onCreate()
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null) {
            if (!info.isConnected()) {

                Toast.makeText(this,
                        "Please check your wireless connection and try again.",
                        Toast.LENGTH_LONG).show();

            }

            // if positive, fetch the articles in background
            else
                // Do your task...
        } else {
            Toast.makeText(this,
                    "Please check your wireless connection and try again.",
                    Toast.LENGTH_SHORT).show();
        }

A: You have not initalized the main WebView webView; and you are referring that in your onBackPressed() method thats why its giving you error.
Just change as below in your file:

public class MainActivity extends Activity {
    WebView mywebview;   <<--- instead of webview use mywebview which you have declared in your onCreate.
   @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     mywebview = (WebView) findViewById(R.id.webView1);
     mywebview.loadUrl("http://www.grafdom.com/operations/projects/ma/edarabiaapp/");
     WebSettings webSettings = mywebview.getSettings();
     webSettings.setJavaScriptEnabled(true);
     webSettings.setBuiltInZoomControls(true);
     mywebview.setWebViewClient(new WebViewClient());
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.activity_main, menu);
     return true;
 }
 @Override
 public void onBackPressed (){
 if(mywebview.canGoBack()) mywebview.goBack();
    else super.onBackPressed();
 }
 }

For your second query:
You can check your internet connection using the below method:

 public static boolean IsNetConnected()
{
    boolean m_netConnected = false;
    try
    {
        ConnectivityManager m_connectivity = (ConnectivityManager) AppConstants.m_context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (m_connectivity == null)
        {
            Log.w(TAG, "couldn't get connectivity manager");
            m_netConnected = false;
        }
        else
        {
            NetworkInfo[] m_info = m_connectivity.getAllNetworkInfo();
            if (m_info != null)
            {
                for (int i = 0; i < m_info.length; i++)
                {
                    if (m_info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        m_netConnected = true;
                    }
                }
            }
        }
    }
    catch (Throwable e)
    {
        ErrorReporter.getInstance().handleException(e);
        if (AppConstants.DEBUG)
        {
            Log.e(TAG, "IsNetConnected Error" + e.toString(), e);
            }
        m_netConnected = false;
    }
    return m_netConnected;
}

You can use the above method as below :

  if(!IsNetConnected())
    {
   showDialog(MainActivity.this,"This application required internet connection");
     //set your default background as per your requirements.
   }

A: override the functionality of onBackPressed()
@Override
  public void onBackPressed() {
      finish();
  }

hope this will help you.


text:
Q: Performance degradation after migrating application from .net 5.0 to .net 6.0 I have upgraded my payment application from .Net 5.0 to .Net 6.0 without any single line of code changes. I performed stress test using jmeter on both pre migration and post migration releases.
The stress results of post migration are showing degradation in 2 respects, when users were 100-200 and duration was 5 mins:

*

*lower TPS (Transaction per second)

*High CPU usage

Am I missing something? Do i need to do some server level configurations to make my application give best results with .net6.0?

UPDATES:
The high CPU usage issue is resolved, which was due to a costly database call in one of the application. But still I cannot see any difference in  the TPS, infact TPS is a bit dropped in .net 6.0.
I have set the below variables:
set DOTNET_ReadyToRun=0
set DOTNET_TieredPGO=1
set DOTNET_TC_QuickJitForLoops=1

Still no difference in performance can be seen. Pls. suggest.

A: It shouldn't be the case, looking at Performance Improvements in .NET 6 article your app should work faster.
If you're absolutely sure that the lower TPS is caused by higher CPU usage you need to use a profiler tool like YourKit or an APM tool to see what exactly causes the CPU usage or slowdown.
You also can try setting the following options:
set DOTNET_ReadyToRun=0
set DOTNET_TieredPGO=1
set DOTNET_TC_QuickJitForLoops=1


text:
Q: .NET Async/Await - when return task and when await I am in the process of converting synchronous code to async code. I have a windows form application in VB.net which shows the representation of physical devices which are part of a registrationpost being managed by a postmanager.
So the PostManager class is used to manipulate RegistrationPost objects. These registrationpost, contain multiple devices which need to be connected to with Socket communication in one way or another. These devices conform to a IDevice interface by implementing a "connect" sub/function.
Below a condensed version of the code to get an idea of what I'm trying to do:
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        ...
        Dim pm As New PostManager
        pm.ConnectAndStartPosts
        ...
    Catch ex As Exception
        ...
    End Try
End Sub

Then inside the PostManager Class:
Friend Sub ConnectAndStartPosts()
    ' The global variable "Posts" is a List of RegistrationPost objects
    Parallel.ForEach(Of RegistrationPost)(Posts, Sub(x) x.ConnectAndStartReading())
End Sub

Then inside the RegistrationPost Class:
Public Sub ConnectAndStartReading()
    Parallel.ForEach(Of IDevice)(AllDevices, Sub(x)
                                                 x.Connect()
                                                 ...
                                             End Sub)
End Sub

Then inside an IDevice:
Public Sub Connect() Implements IDevice.Connect
    ' socket is a global variable of the type Socket(SocketType.Stream, ProtocolType.Tcp)
    socket.Connect(IP, Port)
    ... more code gets executed (if connected, log a message)

    NotifyPropertyChanged("Connected")
End Sub

Ok this is all working but of course I'd like to use async/await to get all the benefits of connecting to an external socket asynchronously. But I'm having trouble understanding how far to "bubble up" the async/await keywords? I'm afraid to get into performance problems because every time you use the async/await keyword, a state machine gets created, so probably it isn't needed to go all the way up?
Would it also be better to drop the Parallel.Foreach and go for a regular ForEach? Or even another approach? See below how this would impact the code example:
' Async/await here as well?
Private async Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        ...
        Dim pm As New PostManager
        await pm.ConnectAndStartPosts
        ...
    Catch ex As Exception
        ...
    End Try
End Sub

Then inside the PostManager Class:
' Leave this a regular 'Sub' or transform to async Function as Task?
Friend Sub ConnectAndStartPosts()
    ' The global variable "Posts" is a List of RegistrationPost objects
    Parallel.ForEach(Of RegistrationPost)(Posts, async Sub(x) await x.ConnectAndStartReading())
End Sub

Then inside the RegistrationPost Class:
' Leave this a regular 'Sub' or transform to async Function as Task?
Public async Function ConnectAndStartReading() as Task
    Parallel.ForEach(Of IDevice)(AllDevices, async Sub(x)
                                                 await x.Connect()
                                                 ... more code, start reading, etc...
                                             End Sub)
End Function

Then inside an IDevice:
Public async Function Connect() as Task Implements IDevice.Connect
    ' socket is a global variable of the type Socket(SocketType.Stream, ProtocolType.Tcp)
    await socket.ConnectAsync(IP, Port)
    ... more code gets executed (if connected, log a message)

    NotifyPropertyChanged("Connected")
End Function

A:
I'm having trouble understanding how far to "bubble up" the async/await keywords? I'm afraid to get into performance problems because every time you use the async/await keyword, a state machine gets created, so probably it isn't needed to go all the way up?

You should go async all the way. The overhead of async/await, while not zero, is completely lost in the noise as soon as you have real I/O going on.

Would it also be better to drop the Parallel.Foreach and go for a regular ForEach? Or even another approach?

Yes. Parallel is intended for CPU-bound code. For asynchronous concurrency, use Task.WhenAll. I.e., call your new ConnectAsync method for each device (e.g., using LINQ's Select) and then do an Await Task.WhenAll on the resulting tasks. You can do the same thing for registration posts.

A: I changed my code to reflect the suggestions in the selected answer. I'm not sure if I should make a new question or not, but I'm now here:

*

*Async Form_load runs "await postManager.ConnectAndStartPostsAsync".

*postManager.ConnectAndStartPostsAsync:
Dim tasks As IEnumerable(Of Task) = From post In Posts Select post.ConnectAndStartReadingAsync
Await Task.WhenAll(tasks.ToArray)

*Now in the registrationpost I need to run two things synchronously in one unit of work (task):
a) await connect
b) await startreading
But this needs to be done asynchronously for a collection of registrationposts. I'm not sure how to get a collection of registrationposts to synchronously connect and start reading, while asynchronously running the task itself.
So in step 3 I'm looking for a way to: await Task.WhenAll(collectionOfTasks) where each individual task does two awaits inside the task.


text: Q: Showing an autohidden panel only when the mouse is in a corner I recently installed xubuntu and I'm trying to get one of my panel that I have on autohide to only show when my mouse is in the bottom left corner instead of whenever my mouse is on the left side. Is this possible to do?


text:
Q: Wordpress Get Password after Admin changes it I am passing the unhashed password to a different system when user clicks forgot password and changes it. I also want to do the same when the Admin changes the user password from the dashboard and click update. Is there any hook that when admin edits user details i can get the user id and their edited information so i can insert it in anther table. I have tried using
 add_action( 'password_reset', 'my_password_reset', 10, 2 );

But it only works for forgot password?
Any suggestions will be highly appreciated

A: Hello try this code.
//is run when you edit YOUR profile, and save it
add_action( 'personal_options_update', 'getDataFunction' );
//is run when you edit ANY OTHER profile and save it
add_action( 'edit_user_profile_update', 'getDataFunction' );
function getDataFunction($userId){
 echo '<pre>'; print_r($_REQUEST);
 echo $userId;
 die();
}

you will get all the data. Let me know if you find any query on answer.


text:
Q: Parse json and search for property c# I have to log every request in our ASP.Net Web API project. When I log every request, I need to search for a property/token (PersonId) in the payload and persist it in the log table. The issue is the payload (or viewmodel) changes for every request, so I need to search for property for different payload. I am thinking of using SelectToken and pass the path to PersonId on every call. Is there any better way to get the value for different viewmodels/payload?

A: Are you trying to determine if PersonId exists or get the value of it regardless where it is in the JSON?
JObject myObj = JsonConvert.DeserializeObject<dynamic>(myJsonReq);
var isPersonIdPresent = myObj[0].Children<JProperty>().Any(p => p.Name == "PersonId");

I wonder if it might be easier to just to search the string for "PersonId" or "PersonId":.
If you wan the value of the element with PersonId as key:
var jsonObj = (JObject)JsonConvert.DeserializeObject(myJsonReqAsString);
string personIdValue = data["PersonId"].Value<string>();

Take a look at this example using Newtonsoft.JSON.


text:
Q: Email Id from Address Book I'm getting all the contacts from the addressbook into my application, i just need to get  email address from the selected contact, here's my code
shouldContinueAfterSelectingPerson
- (BOOL)peoplePickerNavigationController:

(ABPeoplePickerNavigationController *)peoplePicker

      shouldContinueAfterSelectingPerson:(ABRecordRef)person {

    // Select phone number

    ABMultiValueRef emailProperty = ABRecordCopyValue(person, kABPersonEmailProperty);

    NSString *email = (__bridge NSString *)(emailProperty);

    [self dismissModalViewControllerAnimated:YES];

    self.view.frame = CGRectMake(0, 44, 320, 370);

    return NO;

}

Please help me out of this guys, Thanks in advance
Am printing it in the log given below
email string is ABMultiValueRef 0x1eb2ddb0 with 0 value(s)

A: CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
    value = ABMultiValueCopyValueAtIndex(multi, 0);
    emailid = (NSString*) value;
    NSLog(@"self.emailID   %@",emailid);
    CFRelease(value);
}
else
{
    for (CFIndex i = 0; i < count; i++)
    {
        label = ABMultiValueCopyLabelAtIndex(multi, i);
        value = ABMultiValueCopyValueAtIndex(multi, i);

        // check for Work e-mail label
        if (CFStringCompare(label, kABWorkLabel, 0) == 0)
        {
            emailid = (NSString*) value;
            NSLog(@"self.emailID   %@",emailid);
        }
        else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
        {
            emailid = (NSString*) value;
            NSLog(@"self.emailID   %@",emailid);
        }

        CFRelease(label);
        CFRelease(value);
    }
}
CFRelease(multi);

A: You can add below code to acces email form contacts..
-(IBAction)Contact
{
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
        [self presentModalViewController:picker animated:YES];
    [picker release];}
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [self dismissModalViewControllerAnimated:YES];
 }

- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    ABMultiValueRef emailMultiValue = ABRecordCopyValue(person, kABPersonEmailProperty);
    NSArray *email = [(NSArray *)ABMultiValueCopyArrayOfAllValues(emailMultiValue) autorelease];
    CFRelease(emailMultiValue);
   [self dismissModalViewControllerAnimated:YES];}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    return NO;
}