text:
Q: custom filter won't update live results on iPhone UPDATE: Here's a plunkr
I have a basic search field that displays matching names from a JSON array of employee data:
<form>
    Enter name: <input type="text" ng-model="search">
</form>

1">

This works fine, but because it's mobile, I wanted to reduce the size of the JSON download as much as possible. Since the full_name field is created on-the-fly as a concatenation of first_name and last_name, I could strip that field out of the JSON completely if I could search both first and last name instead.
So I created a custom filter:
app.filter('firstAndLastName', function() {
    return function(collection, str) {
        return collection.filter(function(el) { // javascript array.filter()
            return (el.first_name.toLowerCase().indexOf(str) !== -1 || el.last_name.toLowerCase().indexOf(str) !== -1);
        });
    };
});

and updated my view to use it:

This works as expected on my desktop browsers -- results are live-updated as text is typed. But on mobile, it no longer displays any results at all, whether the keyboard is open or not. This happens in both Safari and Chrome (iOS 8.0.2).
I tried making my filter stateful, but that didn't change anything. (I'm currently using AngularJS 1.3.0-rc.4.)
Why does the AngularJS built-in filter update live results, but my custom filter does not? And why does this only happen on mobile?

A: Have you tried to make sure both the input and search string are set to lowercase:
app.filter('firstAndLastName', function() {
    return function(collection, str) {
        var strToLower = str.toLowerCase();
        return collection.filter(function(el) { // javascript array.filter()
            return (el.first_name.toLowerCase().indexOf(strToLower) !== -1 || el.last_name.toLowerCase().indexOf(strToLower) !== -1);
        });
    };
});

I realized that my phone was auto-capitalizing the first letter and was causing the results not to show. If that is not it you might need to put some more information as to how the data is getting in there.


text:
Q: How to use RTK query and redux thunk in same react app? I have requirement where I have to use RTK query for data fetching and Redux-thunk for global state management. For the same I have created 2 separate stores, one for RTK and another for redux. Now I am facing issue as we should not have 2 stores in our application.
store 1:-
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import combineReducer from './combineReducer';

export const configureStore = () : any => {
  const middleWares = [thunk];
  const middlewareEnhancer = applyMiddleware(...middleWares);

  const enhancers = [middlewareEnhancer];
  const composedEnhancers: any = compose(...enhancers);

  const store = createStore(combineReducer, composedEnhancers);

  return store;
};

store 2:-

import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { postApi } from "../services/posts";

export const store = configureStore({
  reducer: {
    [postApi.reducerPath]: postApi.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(postApi.middleware),
});

setupListeners(store.dispatch);

App.tsx:-
const App: React.FC = () => (
  <Provider store={store}>
  <Provider store={rtkStore}>
    <Suspense fallback={
Loading...
}>
      <BrowserRouter>
        <Routes />
      </BrowserRouter>
    </Suspense>
  </Provider>
  </Provider>
);

I am sure, there is something fishy in this. Any solution for requirement would be appreciable.

A: Redux Toolkit comes with thunk per default. You do not need to set it up. RTK Query internally is based on thunks. You cannot have multiple Redux stores in one application.
Just create one store with configureStore, also add your other reducers there and use that for everything.
Generally we recommend in the Redux style guide to use Redux Toolkit for all your Redux logic, as helpers like createSlice massively reduce your boilerplate code and guard against most common bugs.
This is the default recommendation for over two years now.
I would highly recommend you to read the official Redux Essentials tutorial if you haven't already.

redpajama_set_name: RedPajamaStackExchange


text:
Q: help with interfaces and abstract classes I'm recently getting a bit confused with interfaces and abstract classes and I feel I dont fully grasp it like I thought I did. I think I'm using them incorrectly. I'll describe what I'm doing at the moment, the problem I have faced, and then hopefully it be clear what I'm doing wrong if anything.
I wanted to write some classes that do some parsing of xml. I have different user types that have different parsing requirements.
My logic went as follows.
All parsers share a "parse" function in common and must have at least this function so I made an Interface with this function defined named IParse;
I start out with 2 user types, user type A and user type B. User type A & B share some basic functions but user type B has slightly more functions than A so I put the functions to parse what they share in an abstract class that both will extend called "ParseBase".
So now I have
// Interface

    public interface IParser
     {
      function parse(xml:XML):void;
     }

// Base Class

public class ParseBase()

{
  public function getbasicdata():void{}

public function getmorebasicdata():void{}

}

//User type A

public class userTypeA extends ParseBase implement IParse

{
    public function parse(xml:XML):void
{
       getbasicdata()

       getmorebasicdata()

}

}

//user type B

public class userTypeB extends ParseBase implement IParse

{
    public function parse(xml:XML):void
{
       getbasicdata()

       getmorebasicdata()

}

   public function extraFunctionForB():void
{

}

  public function anotherExtraFunctionForB():void
{

}

}

The problem I have come up against now which leads me believe that I'm doing something wrong is as follows.
Lets say I want to add another function UserTypeB. I go and write a new public function in that class. Then In my implementation I use a switch to check what Usertype to create.
Var userParser:IParser

if(a)

{
userParser= new userTypeA();
}else if(b)

{
userParser= new userTypeB();
}

If i then try to access that new function I can't see it in my code hinting. The only function names I see are the functions defined in the interface.
What am I doing wrong?

A: You declare the new function only in userTypeB, not in IParser. Thus it is not visible via IParser's interface. Since userParser is declared as an IParser, you can't directly access userTypeB's functions via it - you need to either downcast it to userTypeB, or add the new function to IParser to achieve that.
Of course, adding a function to IParser only makes sense if that function is meaningful for all parsers, not only for userTypeB. This is a design question, which IMO can't be reasonably answered without knowing a lot more about your app. One thing you can do though, is to unite IParser and BaseParser - IMO you don't need both. You can simply define the public interface and some default implementation in a single abstract class.
Oher than that, this has nothing to do with abstract classes - consider rephrasing the title. Btw in the code you show, ParseBase does not seem to be abstract.

A: In order to access functions for a specific sub-type (UserTypeB, for example) you need the variable to be of that type (requires explicit casting).
The use of interfaces and abstract classes is useful when you only require the methods defined in the interface. If you build the interface correctly, this should be most of the time.

A: As Peter Torok says (+1), the IParser declares just one function parse(xml). When you create a variable userParser of type IParser, you will be allowed to call ony the parse() method. In order to call a function defined in the subtype, you will have to explicitly cast it into that subtype.
In that case IMO your should rethink the way you have designed your parsers, an example would be to put a declaration in your IParser (Good if you make this abstract and have common base functionality in here) that allow subtypes (parsers) to do some customization before and after parsing.
You can also have a separate BaseParser abstract type that implemnts the IParser interface.


text:
Q: Yarn cannot start AM on some nodes after update I've got a problem after updating system to HDP 2.6.5. I have a cluster with three nodes and trying to start a simple application with python:
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext, SparkSession, HiveContext
sc = SparkContext()
print sc.master

with command
/usr/bin/spark-submit \
    --master yarn \
    --deploy-mode cluster \
    --name 'test script' \
    /opt/test/youdmp/test/script.py

It says
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.hadoop.yarn.proto.YarnProtos$ResourceProtoOrBuilder.getMemory()I
    at org.apache.hadoop.yarn.api.records.impl.pb.ResourcePBImpl.getMemory(ResourcePBImpl.java:61)
    at org.apache.spark.deploy.yarn.Client.verifyClusterResources(Client.scala:313)
    at org.apache.spark.deploy.yarn.Client.submitApplication(Client.scala:166)
    at org.apache.spark.deploy.yarn.Client.run(Client.scala:1217)
    at org.apache.spark.deploy.yarn.YarnClusterApplication.start(Client.scala:1585)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:906)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:197)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:227)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:136)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

I can see such situation when application starts on either on one or another node. But the third node works.
And client deploy-mode says:
Traceback (most recent call last):
  File "/opt/test/youdmp/test/script.py", line 3, in <module>
    sc = SparkContext()
  File "/usr/hdp/current/spark2-client/python/lib/pyspark.zip/pyspark/context.py", line 119, in __init__
  File "/usr/hdp/current/spark2-client/python/lib/pyspark.zip/pyspark/context.py", line 181, in _do_init
  File "/usr/hdp/current/spark2-client/python/lib/pyspark.zip/pyspark/context.py", line 279, in _initialize_context
  File "/usr/hdp/current/spark2-client/python/lib/py4j-0.10.6-src.zip/py4j/java_gateway.py", line 1428, in __call__
  File "/usr/hdp/current/spark2-client/python/lib/py4j-0.10.6-src.zip/py4j/protocol.py", line 320, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.NoSuchMethodError: org.apache.hadoop.yarn.proto.YarnProtos$ResourceProtoOrBuilder.getMemory()I
    at org.apache.hadoop.yarn.api.records.impl.pb.ResourcePBImpl.getMemory(ResourcePBImpl.java:61)
    at org.apache.spark.deploy.yarn.Client.verifyClusterResources(Client.scala:313)
    at org.apache.spark.deploy.yarn.Client.submitApplication(Client.scala:166)
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.start(YarnClientSchedulerBackend.scala:57)
    at org.apache.spark.scheduler.TaskSchedulerImpl.start(TaskSchedulerImpl.scala:164)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:500)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:238)
    at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
    at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:745)

What kind of mistake can it be? What should I fix?
Seems like Yarn can't start Application Master on some nodes, because some libs are different on the nodes. But I cannot find out which libs are, both nodes have similar libs

A: There were some library conflicts in my case.
Fixing that we should add option spark.driver.extraClassPath.
In our case
spark.driver.extraClassPath    /usr/hdp/current/hadoop-yarn-client/hadoop-yarn-common.jar:/usr/hdp/current/hadoop-yarn-client/hadoop-yarn-api.jar:/usr/hdp/current/hive-server2-hive2/lib/hive-hcatalog-core.jar


text:
Q: layout views in slide menu in iOS I am using SWRevealViewController as a slide menu in iOS. When I created the rear viewcontroller (the slide menu) a xib file was created with .m and .h files. I do not use autolayout and set the simulated metrics size as None.
The view seems all right when slide in and out on iPhone except that when the view is presented on iPad I want the positions of the menus to also change as the view becomes bigger but it doesn't.
Originally the view is as the image below shows:

In order to move the "settings" menu to the bottom I have made changes to the view settings of "settings image", "settings button" and the extra UIImageView as below:

but I want the settings menu to also locate at the bottom of the view just like it is now on iPhone. How can I do that?

A: I have used "Masonry" library to sort this out.
It is pretty amazing.
Check out Masonry from GitHub


text:
Q: Can't install Window AppMenu Applet I am new to Linux and I've been trying to install the plasma widgets window Appmenu and window buttons. They show up in the widget list but without a icon and cannot be used.
When I run sh install.sh in the directory where I extracted the files, I got the following:
install.sh: 1: [: -a: unexpected operator
mkdir: cannot create directory 'build': File exists
install.sh: 5: install.sh: cmake: not found
make: No targets specified and no makefile found.  Stop.

Then it asks for the password and I get:
make: *** No rule to make target 'install'.  Stop.
Can I get a straightforward guide on how to install correctly?

A: The cmake command is needed to build that code, and you don't have it. This, rather than the [: -a: unexpected operator message, appears to be what is actually keeping your build from continuing. So first install cmake. Some software needs a very new version of cmake to build (which you can install if you need to) but most does not. I recommend you install the cmake package.
While you're at it, it's a good idea to make sure you have the usual toolchain for building programs on your Ubuntu system, too, which the build-essential package will get you.
These commands will install both cmake and those other tools:
sudo apt update
sudo apt install build-essential cmake

This will likely be sufficient to enable you to successfully build the software, or at least to get past the current error you're facing. However, I recommend you delete the build directory and its contents before proceeding:
rm -r build

After further troubleshooting steps that involve installing or removing software or editing files from the source code (or, if you like, even every time you build the source code), I recommend removing the build directory and starting fresh.
The messages you're getting about -a are probably not stopping the build from succeeding. You can probably ignore them. They also would likely go away if you used bash instead of sh, though I don't think that's the best solution. If you want to get rid of them or you suspect they are causing a problem then you can either edit the install.sh script to use the appropriate test (or no test) or you can manually perform the actions that script performs. So if you want to do something about this, see below for the details.

In the source code for both applet-window-buttons and applet-window-appmenu, install.sh currently has this as its complete contents:
if ! [ -a build ] ; then
    mkdir build
fi
cd build
cmake -DCMAKE_INSTALL_PREFIX=/usr .. -Wnodev
make
sudo make install

This is the file you are attempting to run with sh that is producing errors. Its use of the -a test is very strange. -a typically appears between two other expressions, and causes [ to return true when both expressions are true.
In Ubuntu, sh is provided by dash. If you use bash instead of dash, it may work (or appear to work). Perhaps that's what the authors did. However, instead of doing that, I recommend you either fix the script or just manually do what it does.
If you want to fix the script, one way would be to replace -a with -e or -d. The -e test takes a filename operand and checks if it exists; -d checks if it exists and is a directory. Another way to fix the script would just be to remove the if and fi lines entirely; mkdir would fail if the directory exists, but that's no problem.
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX=/usr .. -Wnodev
make
sudo make install

But all this script does is create a build directory if there isn't one, change into it with cd, run cmake with some arguments, run make, and then run sudo make install. You can just do these things yourself. One way to do so is to run those commands in your interactive shell, one after another.
This has advantages. As written, the script doesn't stop just because some step reports failure, but you probably would want to stop. You could make further modifications to the script to achieve that (perhaps ending each line except the first and last with &&) but it's probably easier to just run the commands yourself if you're not planning on compiling the code numerous times.

A: I was also facing some issues. Managed to build it on Kubuntu 21.04.
Following should be kept in mind

*

*Delete the build/ folder in subsequent build attempts

*Install the dependencies. This can be referred.

*Do make sure gcc, cmake etc. are not conflicting

*After the install, the widget appears in the "add widget" option on panel


text:
Q: Как сделать в jquery плавный скролинг к якорю? Есть код, где переход по ссылке  ведет  к якорю ajax-представления. Код, динамически меняющегося контента, скрипта ajax работает. По якорю переходит, но быстро, нужно сделать, чтоб был плавный скроллинг.
Код страницы:
  <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

1

2

3

4

 //якорь

A: Можно вот так
    $("ссылка").click(function(event) {
    event.preventDefault();
    var id = $(this).attr('href'),
        top = $(id).offset().top;
    $('body,html').animate({
        scrollTop: top
    }, 1000);
});


text:
Q: running multiple flask application using apache I have tried with all possible approaches on different websites. But have no luck.
Currently I am following - Run multiple independent Flask apps in Ubuntu
I have two flask application
/var/www/html/myapps/flaskapp2
/var/www/html/myapps/flaskapp

Both having python file and wsgi files.
/var/www/html/myapps/flaskapp2/flaskapp2.py
from flask import Flask
app = Flask(__name__)
@app.route("/newflask")
def hello():
    return "Hello,welcome to flask website!"
if __name__ == "__main__":
    app.run()

/var/www/html/myapps/flaskapp2/flaskapp2.wsgi
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/html/myapps/flaskapp2/")

from flaskapp2 import app as application

and conf file
<VirtualHost *:80>
                ServerName http://IP
                ServerAlias IP
                ServerAdmin admin@mywebsite.com

                WSGIDaemonProcess app1 user=karim group=karim threads=5 python-home=/var/www/html/myapps/flaskapp:/home/k/projects_r/venv_3.7/lib/python3.7/site-packages
                WSGIScriptAlias /app1 /var/www/html/myapps/flaskapp/flaskapp.wsgi
                <Directory /var/www/html/myapps/flaskapp>
                        WSGIApplicationGroup app1
                        WSGIProcessGroup app1
                        Order allow,deny
                        Allow from all
                </Directory>

                WSGIDaemonProcess app2 user=karim group=karim threads=5 python-home=/var/www/html/myapps/flaskapp2:/home/k/projects_r/venv_3.7/lib/python3.7/site-packages
                WSGIScriptAlias /app2 /var/www/html/myapps/flaskapp2/flaskapp2.wsgi
                <Directory /var/www/html/myapps/flaskapp2>
                        WSGIApplicationGroup app2
                        WSGIProcessGroup app2
                        Order allow,deny
                        Allow from all
                </Directory>

                ErrorLog ${APACHE_LOG_DIR}/error.log
                LogLevel warn
                CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

When I try to open
http://IP/myapps/flaskapp/flask
http://IP/myapps/flaskapp2/newflask

It gives me

Not Found The requested URL was not found on the server. If you
  entered the URL manually please check your spelling and try again.

UPDATE 1
only this app.conf  works at IP/flask
<VirtualHost *:80>
                ServerName http://IP
                ServerAlias IP
                ServerAdmin admin@mywebsite.com
                WSGIScriptAlias / /var/www/html/flaskapp/flaskapp.wsgi
                <Directory /var/www/html/flaskapp>
                        Order allow,deny
                        Allow from all
                </Directory>

                ErrorLog ${APACHE_LOG_DIR}/error.log
                LogLevel warn
                CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

A: It looks to me that you are using the wrong URLs. Your WSGIScriptAlias is set to listen on /app1 and /app2 respectively so I would first try accessing:
http://IP/app1
http://IP/app2

and check the WSGIScriptAlias documentation


text:
Q: How to make AngularJS components play nice with Bootstrap style? I'm trying to compartmentalise a large wedge of code.
I want to create an angularjs component for a piece of data that is to be displayed in a bootstrap panel. These panels will be expandable/collapsible.
Here's a plunker
Script.js:
var app = angular.module('app', [])

.controller('kittenController', function () {
  const $ctrl = this;
  $ctrl.click = function () {
    console.log(`You clicked on ${$ctrl.kitten}!`);
  };
})

.component('kittenPanel', {
  templateUrl: 'kitten-panel.template',
  controller: 'kittenController',
  bindings: {
    kitten: '='
  }
});

Index.html:
<!DOCTYPE html>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" />
    <link rel="stylesheet" href="style.css" />

        <kitten-panel kitten="k" ng-repeat="k in kittens"></kitten-panel>

Heading 1

Content 1

Heading 2

Content 2

Heading 3

Content 3

You can see that each panel is butted up against the last because of the way Bootstrap's CSS works.
The second panel group shows what I'd expect to see, with a small gap between each panel in the group.
I need to eliminate the component element that's inserted by angular. But components don't support insertion by attribute.
I'm aware that UI Bootstrap has accordion, but I wanted to get a general solution for how to manage things like this, where angular inserts elements that might break bootstrap.
Any ideas?
Angularjs 1.5.3, Bootstrap 3.3.6

A: This is the bootstrap css that puts the margin:
.panel-group .panel+.panel{
    margin-top: 5px;
}

So you need a .panel inside a .panel-group, that comes after another .panel.
In other words, the .panel elements must be on the same level. If you encapsulate them in other elements, this css rule doesn't apply.

{{k.name}}

{{k.colour}}

EDIT:
to use template:

And using directive instead of component as it can use attribute match instead of only element for kitten-panel


text:
Q: Getting the full file path using a Node + Meteor + Electron file browser dialog This is a tricky one...
I have a Meteor web app that runs locally on a user's machine, either in the browser or packaged within an Electron app.
https:github.com/lacymorrow/cinematic
cinematic.[js|html] are the important files CSS selector #directory-path.
It uses local files on the machine, so technically the server and the client are the same machine, currently I require the user to explicitly know the file path of their Movies directory (ex: /Users/username/Movies), enter it on the client-facing side, and process the files using the fs NodeJS module.
I do as much inferring as possible, setting the default directory to the most likely location, but this just isn't good UI. I need a directory browser dialog.
The Problem
Since the client view is HTML, a doesn't allow full access to the filesystem for security reasons.
<input id="directory-path" type="file" name="files" webkitdirectory mozdirectory directory multiple />
The values returned are a FileList with just the filenames, so I can process the video files, but don't have the full path to "open" them.
Possible Solutions

*

*In Chome/WebKit I'm able to access a temporary URL

(Downfall: while the browser is open). There are no temp URLs in Firefox or Safari but Electron uses the same V8 JS engine in Canary so maybe that's an advantage.

*

*Detecting for Electron, serving an Electron dialog to app users, serving the path input for browser users.

(Downfall: Multi-ui; Requires connection between Electron-Meteor instead of just wrapping the app whole.
Can anyone help me choose a reasonable approach to this?


text:
Q: How can I parse a string into a hash? I am trying to parse a string into a hash.
str = "Notifications[0].Open=1
Notifications[0].Body.Message[0]=3455
Notifications[0].Body.Message[1]=2524
Notifications[0].Body.Message[2]=2544
Notifications[0].Body.Message[3]=2452
Notifications[0].Body.Error[0]=2455
Notifications[0].Body.Currency=EUR
Notifications[0].Published=true"

The result should look similar to this:
pairs = {
 'Open' = 1,
 'Published' => true
 'Body' => {
    'Message' => [3455, 2524, 2544, 2452],
    'Error' => [2455],
    'Currency' => 'EUR',
 }
}

Maybe someone can help on how I can make it. The only way I can think as for now is regexp.

A: something like this with regexp:
require 'pp'

str = "Notifications[0].Open=1
Notifications[0].Body.Message[0]=3455
Notifications[0].Body.Message[1]=2524
Notifications[0].Body.Message[2]=2544
Notifications[0].Body.Message[3]=2452
Notifications[0].Body.Error[0]=2455
Notifications[0].Body.Currency=EUR
Notifications[0].Published=true"

pairs         = {}
pairs['Body'] = {}
values        = []

str.scan(/Body\W+(.+)/).flatten.each do |line|
  key   = line[/\A\w+/]
  value = line[/\w+\z/]

  if line[/\A\w+\[\d+\]/] || key == 'Error'
    values = [] unless pairs['Body'][key]

    values << value
    value = values
  end

  pairs['Body'][key] = value
end

str.scan(/\[0\]\.(?!Body.).*/).each do |line|
  key   = line[/(?!\A)\.(\w+)/, 1]
  value = line[/\w+\z/]

  if line[/\A\w+\[\d+\]/]
    values = [] unless pairs[key]

    values << value
    value = values
  end

  pairs[key] = value
end

PP.pp pairs

-
{"Body"=>
  {"Message"=>["3455", "2524", "2544", "2452"],
   "Error"=>["2455"],
   "Currency"=>"EUR"},
 "Open"=>"1",
 "Published"=>"true"}

A: Here it is. This code should work with any structure.
def parse(path, value, hash)
  key, rest = path.split('.', 2)
  if rest.nil?
    hash[key] = value
  else
    hash[key] ||= {}
    parse(rest, value, hash[key])
  end
end

def conv_to_array(hash)
  if hash.is_a?(Hash)
    hash.each do |key, value|
      hash[key] = if value.is_a?(Hash) && value.keys.all? { |k| k !~ /\D/ }
                    arr = []
                    value.each do |k, v|
                      arr[k.to_i] = conv_to_array(v)
                    end
                    arr
                  else
                    conv_to_array(value)
                  end
    end
    hash
  else
    if hash !~ /\D/
      hash.to_i
    elsif hash == 'true'
      true
    elsif hash == 'false'
      false
    else
      hash
    end
  end
end

str = "Notifications[0].Open=1
Notifications[0].Body.Message[0]=3455
Notifications[0].Body.Message[1]=2524
Notifications[0].Body.Message[2]=2544
Notifications[0].Body.Message[3]=2452
Notifications[0].Body.Error[0]=2455
Notifications[0].Body.Currency=EUR
Notifications[0].Published=true"

str = str.tr('[', '.').tr(']', '')
hash = {}
str.split(' ').each do |chunk|
  path, value = chunk.split('=')
  parse(path.strip, value.strip, hash)
end
hash = conv_to_array(hash)

hash['Notifications'][0]

# => {"Open"=>1, "Body"=>{"Message"=>[3455, 2524, 2544, 2452], "Error"=>[2455], "Currency"=>"EUR"}, "Published"=>true}


text:
Q: F5 IRule,Generate New Alerts I use F5 and I have an issue.
I want to build an Irule that check the following scenario
url=="domain.com" and Content-Length(of the request) > 400
then
alert(response)

Is it possible to create this Irule?

A: I'm not sure what your alert action desire is (simulated here with the # take action block), but the rule is pretty simple:
when HTTP_REQUEST {
  if { ([HTTP::host] eq "domain.com") and ([HTTP::header Content-Length] > 400) } {
     # take action
  }
}

A: Do you possibly mean you want to use alertd to generate an email or SNMP trap? If so, then as long as alertd is looking for the error you put in the log, that would take the alert action.


text:
Q: How to insert an alphabet/digit at specific location of string? I am supposed to write a JavaScript function which inserts the character/s between only two consecutive Hash (#) symbols. For an example: If input string is:
var str = "#TIME##MONEY#";

Then output string must be "#TIME#IS#MONEY#"

A: You can use the replace() method.

var str = "#TIME##MONEY#";
var insert = 'IS'

var newstr = str.replace('##', '#'+insert+'#')
console.log(newstr);

A: Splice the string where you find ## and concat the string

var str = "#TIME##MONEY#";

for (i = 0; i < str.length; i++) {
  if (str[i] == '#' && str[i + 1] == '#') {
    newStr = str.slice(0, i+1) + 'abc'
    +str.slice(i + 1, str.length);
  }
}
console.log(str)
console.log(newStr)

A: Just use replace

// Once
var str = "#TIME##MONEY#";
document.write(str.replace('##','#IS#'));

//more than once
var str2 ="#TIME##MONEY##TIME##MONEY#";
while(str2.indexOf('##') != -1)
{
    str2 = str2.replace('##','#IS#');
}

document.write('<br />'+str2);


text:
Q: How to display a multi-line pattern which has start and end patterns based on a condition within the pattern How can I just print the pattern blocks where I have DFW-YYYY... and ignore the others. My start Pattern is ### My Ending Pattern is ##
Also the line pattern DFW-YYYY can have multi [] brackets. it is not fixed. I need to match the exact/ partial string (which could involve [blah] brackets for the match.
I had seen the article where the whole pattern is brought into a buffer and only printed when end pattern is found. I am looking for an enhancement to that thought process that I print conditionally once I find the start and end pattern block. The article I am talking about is: How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)?
I have a file like:
xxx
xxx
###
xxx
zzz Problem Key: DFW-XXXXX [blah blah][blah blah][blah blah]
yyy
xxx
*##*
yyy
###
 zzz
xxx
yyy
zzz Problem Key: DFW-YYYY [blah blah][blah blah]
*##*
xxx
xxx
zzz
yyy
###
xxx
zzz Problem Key: DFW-XXXXX [blah blah][blah blah][blah blah]
yyy
xxx
*##* ....

The pattern I was trying to enhance was:
awk 'flag{
        if (/*##*/)
           if  (print_flag =1 )
               {printf "%s", buf; flag=0; buf=""} /* only print if print_flag =1 */
           else
               {  flag=0; buf=""} /* ignore pattern */
        else
            buf = buf $0 ORS

            /* peek into $0 and look for conditional pattern.
              conditional pattern may have sq brackets like [] but not limited to one occurrence
              I could avoid spl chars if I could look for multiple small strings within $0.
              Like $0 ~ "x" and $0 ~ "y" and $0 ~ "z", this way spl. char matching can be avoided
              but conditional pattern can still be matched*/

              if ($0 ~ "conditional-pattern1" and $0 ~ "conditional-pattern2" and $0 !~ "conditional-pattern3")
                  print_flag=1
     }
     /###/ {flag=1}' <file-name>

But my if statements of looking into $0 value for condition and assigning/ checking print_flag is failing syntactically.

Any guidance on how this could be achieved.

A: I got it working for me as:
 awk 'flag{
    if (/*##*/)
       {printf "%s", buf ~ "conditional-pattern" ? buf : "" ; flag=0; buf=""}
    else
        buf = buf $0 ORS
 }
  /###/{flag=1} ' file.txt

Multiple conditional pattern matching was achieved with:
{printf "%s", buf ~ "aaaaaa" && buf ~ "xxxxxxx" ? buf : "" ; flag=0; buf=""}

A: with gawk multi-char record separator, something like this should work
$ awk -v RS='\n(*##*|###)' '!(NR%2) && /DFW-YYYY/' file

 zzz
xxx
yyy
zzz Problem Key: DFW-YYYY [blah blah][blah blah]

test with your actual pattern you're looking for.


text:
Q: Set Paper Source of PDF page in ASP.NET Web Form Application I have an ASP.NET Application using Web Forms that I am trying to print a PDF. I currently use DynamicPDF to generate that PDF in a new tab but the Dynamic PDF module that our company has does not deal with printing.
I need to print a two page PDF. The 1st page needs to be for an envelope and then the 2nd page will need to print a regular piece of paper like normal. Anybody have any idea how to set that paper source in code? Ideally I just want to hit print on my web page and the printer knows to print the first page envelope and the 2nd page regular. Having my users change that setting every time they print something is a HUGE draw back. Any ideas or any tools that can accomplish this?
Thanks!!

A: In order to print a PDF to a specific printer, you will need to use the DynamicPDF PrintManager for .NET product. You can specify the paper source for each page during runtime as shown below.
        InputPdf pdf = new InputPdf(@"Path for Input PDF");
        Printer printerObj = new Printer("Printer name");
        PrintJob printJobObj = new PrintJob(printerObj, pdf);

        //Setting paper source for whole print job.
        printJobObj.PrintOptions.PaperSource = printerObj.PaperSources[1];

        //Setting specific tray as paper source for first page in the print job.
        PrintJobPage page1 = printJobObj.Pages[0];
        page1.PrintOptions.Inherit = false;
        page1.PrintOptions.PaperSource = printerObj.PaperSources[2];

       //Setting specific tray as paper source for second page in the print job.
        PrintJobPage page2 = printJobObj.Pages[1];
        page2.PrintOptions.Inherit = false;
        page2.PrintOptions.PaperSource = printerObj.PaperSources[3];

        printJobObj.Print();

Disclaimer: I work for ceTe Software, the company that develops DynamicPDF libraries.


text:
Q: Is it possible to override ONE axis of a CSS background-position using CSS? I am using CSS sprites to build a six-tab-menu. Since the tabs overlap, I decided to use six versions of the image in the sprite, one for each active tab state (one below the other). So I need to change more than one tab for each state because of adjacent overlaps, so I might as well just change the position of all of them.
In the menu each link in the menu has its own CSS background defined from the sprite image. It all fits together nicely.
What I'd like to do is add a class to the body that would change the vertical position of all the link backgrounds without having to define the horizontal so that the horizontal position can be inherited. This way I only need to define six more classes to make it work instead six of them for each state (=36).
Some equivalent of background-position:inherit -94px.
I can do it easily with jQuery, but was hoping for a CSS-only solution.

A: No it can't be done. Mostly because firefox doesn't support background-position-x and background-position-y though understandable because its not part of the specs.
I had this problem myself not long ago but brief investigation told me it was still not possible.
I am going to asume you have a sprite you want to use for multiple states of the menu. In this case you should just split up the sprite in 2, one for state a and one for state b, and when you add the class you simply switch over to image b with background-image.
It's ofcourse one more image but there really isn't a crossbrowser way to just shift one axis.


text:
Q: Autohotkey - Using DOM, trigger javascript function There are some buttons(actually, links) on a web, and I can click on it menually.
but,

wb:=ComObjCreate("InternetExplorer.Application")
wb.document.getElementById("Status").click()

this script don't work. @critsz said because there is no definition about click.
so, I'm trying to trigger the function after defining "click"
the following is a part of the source.

 Basic

 Status

function viewPage(Name,Number){

$("#TabMenu li").removeClass("active");
$("#"+Name).addClass("active");

$("#ViewPage").load(
    Name+".asp",
    {
        Number : Number
    },
    function( response, status, xhr ) {
        if ( status == "error" ) {
            var msg = "an error: ";
            $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
        }
});
}

And I tried this.

wb.document.getElementById("Status").addEventListener("click",viewPage(Status,10000))

but an error occurs : Call to nonexistent function.
Specifically: viewPage(Status,10000)
Does this mean that I need to define the function on my autohotkey script? or Is there any other way to do that?
if i should do, how can I do that?

A: Try wb.navigate("javascript:viewPage('Status','10010');")


text:
Q: What is the relationship between quality of a video and highly composite numbers? The most common resolutions are 240p, 360p, 480p, 720p or 1080p. 3 of these 5 resolutions are highly composite numbers, namely 240, 360 and 720. Is there a reason for that or is it just a coincidence?

A: Consider that most typical videos render at 30 fps. If a monitor renders at 30 fps with 240 pixels to render, than you get nice even pretty calculations that are easy to render and track. Note that each of those numbers share specific compositions. Consider 120 which is shared between them. 30 x 40 which 3x4 is a very common screen designation as wide screen is only a recently common thing. So, common screen size and common fps means that 120 is very easy to work with.


text:
Q: how to fix the pwgui installation error Command 'pwgui' not found, did you mean:
command 'p2wgui' from deb pgn2web (0.4-3build1)
Try: sudo apt install

A: I solved the same issue.
First, to go your PWgui folder installation,
mine
cd PWgui-6.1
then type a command
./pwgui to launch.
Good luck!
ss pwgui


text:
Q: How to delete local directory with ansible I have to make delete some directory and create them on local before copy to the remote. Is there anyway to delete and create locally?
Currently I'm using 'command'
command: rm -r directory

But warning shows as
Consider using file module with state=absent rather than running rm

Is there any options we can use for local folder changes?

A: If you're running this in a playbook, you can use a section of the playbook that uses a local connection to make changes on the command machine, then copies files to the remote:
---
- hosts: 127.0.0.1
  connection: local
  tasks:
    - name: Delete local directory
      file: path=/directory state=absent

- hosts: myhosts
  tasks:
      copy: src=/directory dest=/foo/directory

A: You can use diffrent delegation methods or use the local_action:
- local_action: file path=directory state=absent

A: Update:
Current Ansible (2.10) does not like - local_action: , instead use delegate_to:
- name: Remove directory 'dir1'
  file:
    path: "path/to/dir1"
    state: absent
  delegate_to: localhost


text:
Q: How to set database, server, username and password in Laravel 5.1? I am trying to set the database name, server name, username and password in Laravel via an html form (similar to the way that this can be done in WordPress). Is there any way to do this with Laravel?

A: It is possible to do it in 2 ways in Laravel:
1) Go to <projectname>/config/database.php and search for 'connections' =>
2) Set it in .env file on the root.

A: *

*go to .env file in the root of your project (must enable show hidden file)

*if you are using mySql database find these three line or if not exist add this three line into .env file

*

*DB_DATABASE=your_database_name

*DB_USERNAME=your_database_username

*DB_PASSWORD=your_database_password

for example :

*

*DB_DATABASE=college

*DB_USERNAME=root

*DB_PASSWORD=password

after doing these work, run this command again "php artisan serve"

A: You can write your own AdminPanel where you get all config values from the .env file, put them in a form and write them back to the file. Make sure to delete the AdminPanel after the configuration because it's a big security issue.


text:
Q: PHP/SQL Question regarding updating/deleting in php with a sql database I'm working on a basic database app which uses a sql database to store and retrieve information from as part of the crud operations the creation and reading of data works perfectly fine. However I'm facing issues with updating and deleting the data stored and it never happened before.Is there something I'm doing wrong?
I'm assuming the something that I've done wrong in update may be similar to my issue in delete.
          Here's the code for the update part : [Note this is just for a basic demo and so security features aren't important]
<?php
require "config.php";
require "common.php";
if (isset($_POST['submit'])) {
    try {
        $connection = new PDO($dsn, $username, $password, $options);
        $user =[
                "char_id"    => $_POST['char_id'],
                "char_name"  => $_POST['char_name'],
                "currency"   => $_POST['currency'],
                "server_id"  => $_POST['server_id'],
                "account_id" => $_POST['account_id']
                ];

        $sql = "UPDATE characters
                SET
                  char_name = :char_name,
                  currency = :currency,
                  server_id = :server_id,
                  account_id = :account_id
                WHERE char_id = :char_id";

        $statement = $connection->prepare($sql);
        $statement->execute($user);
    } catch(PDOException $error) {
        echo $sql . "
" . $error->getMessage();
    }
}

if (isset($_GET['char_id'])) {
    try {
        $connection = new PDO($dsn, $username, $password, $options);
        $char_id = $_GET['char_id'];
        $sql = "SELECT * FROM characters WHERE char_id = :char_id";
        $statement = $connection->prepare($sql);
        $statement->bindValue(':char_id', $char_id);
        $statement->execute();
        $user = $statement->fetch(PDO::FETCH_ASSOC);
    } catch(PDOException $error) {
        echo $sql . "
" . $error->getMessage();
    }
} else {
    echo "Something went wrong!"; //this happens
    exit;
}
?>

<?php require "templates/header.php"; ?>

<?php if (isset($_POST['submit']) && $statement) : ?>

<?php echo escape($_POST['char_name']); ?> successfully
updated.

<?php endif; ?>

Edit a character

<form method="post">
    <?php foreach ($user as $key => $value) : ?>
      <label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?>

            <input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>"     <?php echo ($key === 'id' ? 'readonly' : null); ?>>
        <?php endforeach; ?>
        <input type="submit" name="submit" value="Submit">
    </form>
        Back to home
    <?php require "templates/footer.php"; ?>

A: The problem seems to be that your loop of inputs expects an array variable called $user. The $user comes from a DB query, using inputs from your form, but the actual input values comes from the $user variable which isn't set until the DB query is run!
First I would try keeping the $_GET in your code. Your SELECT query expects $_GET['char_id'] to be set in order to execute. Do that by adding ?char_id=SOME NUMBER HERE to your url and go. The number should be a char_id present in your Database.
Now the DB query gets the $_GET['char_id'] that it needs (since the $_GET method fetches parameters from the URL), and you should get some working inputs from your loop, and be able to update entries in your Database.


text:
Q: GCC ICU 57 static linking I am trying to link ICU 57 to my binary file. That does not work even thought (I think at least) I am linking the static lib files.
Here is a blunt example:
gcc -static /usr/lib/libicui18n.a /usr/lib/libicuuc.a /usr/lib/libicudata.a /usr/lib/libicule.a /usr/lib/libiculx.a /usr/lib/libicutu.a /usr/lib/libicuuc.a /usr/lib/libicuio.a obj/ex.o obj/msg.o -o bin/ex

This is the error message that I get:
src/msg.c:5: undefined reference to `u_fopen_57'
src/msg.c:9: undefined reference to `u_fgetfile_57'
src/msg.c:10: undefined reference to `u_fgetfile_57'
src/msg.c:11: undefined reference to `u_frewind_57'
src/msg.c:18: undefined reference to `u_fgetc_57'
src/msg.c:17: undefined reference to `u_feof_57'
src/msg.c:25: undefined reference to `u_fclose_57'

Linking the dynamic libs works fine though.

A: If you can, I'd recommend using pkg-config as I recommended here,
specifically with pkg-config --static … as explained here


text:
Q: iPhoto library was deleted, had me create a new library. Went into Finder & don't have the "Masters" folder. Where are my original photos? I did a little research, & I found numerous websites directing me to go to iPhoto on Finder, right click, & click on "Show Package Contents". When I click on it, I am directed to a folder that says "Contents".
However, when I open that folder, I was promised there would be a folder called "Masters", but I found 8 folders and 4 other items- none with the name "Masters" & none of the folders had my original pictures.
To be more specific, the names of the folders I have are: _CodeSignature, _MASReceipt, Frameworks, MacOS, Library, PlugIns, Resources, and XCPServices.
Are my photos gone forever?

A:
I think ...

That's a bad beginning. You need to know what you did.

I hit create library, and all my photos were deleted and I was redirected to iPhoto's introduction page

When you entered a name, did it ask "___ exists. Replace?"

...go to iPhoto on Finder...  the names of the folders I have are: _CodeSignature, _MASReceipt, Frameworks, MacOS, Library, PlugIns, Resources, and XCPServices.

That's the iPhoto application. Not the iPhoto Library. Look in Home -> Pictures for something like "Theresa's iPhoto Library" and double-click on it.


text:
Q: OpenCV Android, drawing largest contour, something is wrong I am trying to draw a largest contour, I am working in realtime, processing each camera frame.
My input image is going to be hand, I have a few constraints - black background, no specular light.
I expect largest contour to be as close as possible to below image
My code is as below, I have referred many samples available online, and I am almost at a thought that there is nothing wrong in my code.
        mRgba = inputFrame.gray();
        contours = new ArrayList<MatOfPoint>();
        mcontours = new ArrayList<MatOfPoint>();
        List<Mat> hull = new ArrayList<Mat>(contours.size());

        hierarchy = new Mat();
        Imgproc.Canny(inputFrame.gray(), mIntermediateMat, 50, 50);
        Imgproc.findContours(mIntermediateMat, contours, hierarchy,
                Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

        for (int idx = 0; idx != contours.size(); ++idx)
        {
            Mat contour = contours.get(idx);
            double contourarea = Imgproc.contourArea(contour);
            Log.i(TAG, "maxAreaIdx =" + idx + "contourarea = " + contourarea);
            if (contourarea > maxArea)
            {
                maxArea = contourarea;
                maxAreaIdx = idx;
                Log.i(TAG, "maxAreaIdx =" + maxAreaIdx + "MaxArea = " + maxArea);

            }

        }

        if(maxAreaIdx > 0 && maxAreaIdx < contours.size())
            mcontours.add(contours.get(maxAreaIdx));
        else
            break;

        Imgproc.cvtColor(mIntermediateMat, mRgba, Imgproc.COLOR_GRAY2RGBA,
                4);
        hierarchy.release();
        Imgproc.drawContours(mRgba, mcontours, -1, CONTOUR_COLOR, -1);

Now, all I get is a very small fraction of this. My current understanding is that OpenCV itself is not able detect big continuous contour. Please refer to images below.

Not only this, I tested it for other images as well, but I am somehow not able to get large big continuous contour.
Am I wrong in applying Canny first? Is there a better technique? I wish to get outline of the hand contour. In future, I want to compare it with saved similar database of contours. Am I on the right track?

A: Try this one :
List<MatOfPoint> mContours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();

//"tes" is binary image from threshold result
Imgproc.findContours(tes, mContours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0,0));
    Mat overlay = contImg; //this is source image RGB
    for(int i = 0; i < mContours.size(); i++)
    {
            Imgproc.drawContours(overlay, mContours, -1, red, 2); //draw contour
    }
    return overlay;

Hope it will help you


text:
Q: $G=\big$ How can we know $ba^2=a^2b$ $\quad$and $ba^3=a^2ba?$
let $G$ be the dihedral group $D(4)$:
  $$G=\big<a, b: a^4=1=b^2 \quad and\quad ab=ba^{-1}\big>$$
  Let $N$ be the subgroup generated by $a^2,$ so that $N$ consists of the two
  elements $1$ and $a^2.$ Then $N$ is a normal subgroup of G. This may be seen
  in a variety of ways, one way being to enumerate the four left cosets of N
  in G as:
$$1N=\{1,a^2\}, bN=\{b,ba^2\}, aN=\{a,a^3\},
 baN=\{ba,ba^3\}$$

Since $ba^2=a^2b$ $\quad$and $ba^3=a^2ba$$\qquad$, it is easy to see that each of these is a
    right coset:

$1N=N1, bN=Nb, aN=Na, baN=Nba.$

Here I didn't understand the part starting with "since". How did we show $ba^2=a^2b$ $\quad$and $ba^3=a^2ba$$\qquad$ ?And also how did we know N is normal subgroup of G in the first place? How can we check that?

A: From the second relation, multiplying on the left by $b$ gives
$$
bab = a^{-1}
$$
Squaring this, remembering that $b^2 = 1$, gives
$$
ba^2b = a^{-2}
$$
Now $a^2 = a^{-2}$ because $a^4 = 1$, so this can be rewritten
$$
ba^2 b = a^2
$$
Once more right-multiply by $b$ to get
$$
ba^2 = a^2b.
$$
Do similar stuff to get the other relation you're confused by. Practice makes perfect.

A: In the definition of $G$ you have that
$$
a^4=1 \ \text{and} \ ab=ba^{-1}
$$
so
$$
a^3=a^{-1}\Rightarrow a^2=a^{-2}
$$
This means that
$$
a^2b=aab=aba^{-1}=ba^{-2}=ba^2.
$$
Furthermore
$$
ba^3=ba^{2}a=a^2ba.
$$

A: $a^{-1}=a^3$ so $\color{blue}{ab=ba^3}$. And we have
\begin{eqnarray*}
a^2b=a \color{blue}{ab}=a\color{blue}{ba^3}=\color{blue}{ab}a^3=\color{blue}{ba^3}a^3 =ba^2.
\end{eqnarray*}
We cannot conclude that $N$ is normal until we have shown that its cosets are left & right cosets.


text: Q: Is there any list of almost all subspaces of $\ell ^\infty$? Is there any long list of subspaces of $\ell ^\infty$ (The set of real bounded sequences equipped with the supremum norm). This would help to find a great many counterexamples. Moreover, I wonder how much interesting subspaces can it have.


text:
Q: how to create ForeignKey for username (not userid) in django models.py I created the following fieldmodels.py
added_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

and it contained the user Id , but how to make it contain the username instead.

A: ForeightKey key always reference with an id.If you want to display the username you can do something like added_by.username

A: If you're using Django Rest Framework, then here's your solution:
class Your_Model_Serializer(serializers.ModelSerializer):
added_by = serializers.CharField()
class Meta:
    model = Your_Model_Object
    fields = ['added_by']

Notice the added_by =serializers.Charfield()? That will return the ForeignKey as text not ID.


text:
Q: Why can't two TBytes use overlapping data? Consider the following XE6 code.  The intention is that ThingData should be written to the console for both Thing1 & Thing2, but it is not.  Why is that?
program BytesFiddle;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  TThing = class
  private
    FBuf : TBytes;
    FData : TBytes;
    function GetThingData: TBytes;
    function GetThingType: Byte;
  public
    property ThingType : Byte read GetThingType;
    property ThingData : TBytes read GetThingData;

    constructor CreateThing(const AThingType : Byte; const AThingData: TBytes);
  end;

{ TThing1 }

constructor TThing.CreateThing(const AThingType : Byte; const AThingData: TBytes);
begin
  SetLength(FBuf, Length(AThingData) + 1);
  FBuf[0] := AThingType;
  Move(AThingData[0], FBuf[1], Length(AThingData));

  FData := @FBuf[1];
  SetLength(FData, Length(FBuf) - 1);
end;

function TThing.GetThingData: TBytes;
begin
  Result := FData;
end;

function TThing.GetThingType: Byte;
begin
  Result := FBuf[0];
end;

var
  Thing1, Thing2 : TThing;

begin
  try
    Thing1 := TThing.CreateThing(0, TEncoding.UTF8.GetBytes('Sneetch'));
    Thing2 := TThing.CreateThing(1, TEncoding.UTF8.GetBytes('Star Belly Sneetch'));

    Writeln(TEncoding.UTF8.GetString(Thing2.ThingData));
    Writeln(Format('Type %d', [Thing2.ThingType]));

    Writeln(TEncoding.UTF8.GetString(Thing1.ThingData));
    Writeln(Format('Type %d', [Thing1.ThingType]));

    ReadLn;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

A: Dynamic arrays are pointers internally, and assignment-compatible with pointers; but the only correct pointers on the right side of assignment are nil or another dynamic array. FData := @FBuf[1]; is obviously wrong, but interesting that FData := @FBuf[0]; is probably OK, even if $TYPEDADDRESS is enabled.
The following code compiles and works as expected in Delphi XE:
program Project19;

{$APPTYPE CONSOLE}
{$TYPEDADDRESS ON}

uses
  SysUtils;

procedure Test;
var
  A, B: TBytes;

begin
  A:= TBytes.Create(11,22,33);
  B:= @A[0];
  Writeln(B[1]);
end;

begin
  try
    Test;
    readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Seems like the compiler "knows" that @A[0] is a dynamic array, not just a pointer.

A: Let me walk you through the ways in which this code fails and how the compiler allows you to shoot yourself in the foot.
If you step through the code using the debugger you can see what happens.

After the initialization of Thing1 you can see that FData is filled with all zeros.
Strangely enough Thing2 is fine.
Therefore the error is in CreateThing.  Let's investigate further...
In the oddly named constructor CreateThing you have the following line:
FData := @FBuf[1];

This looks like a simple assignment, but is really a call to DynArrayAssign
Project97.dpr.32: FData := @FBuf[1];
0042373A 8B45FC           mov eax,[ebp-$04]
0042373D 83C008           add eax,$08
00423743 8B5204           mov edx,[edx+$04]
00423746 42               inc edx
00423747 8B0DE03C4000     mov ecx,[$00403ce0]
0042374D E8E66DFEFF       call @DynArrayAsg      <<-- lots of stuff happening here.

One of the checks DynArrayAsg performs is to check whether the source dynamic array is empty or not.
DynArrayAsg also does a few other things which you need to be aware about.
Let's first have a look at the structure of a dynamic array; it's not just a simple pointer to an array!
Offset 32/64  |   Contents
--------------+--------------------------------------------------------------
-8/-12        | 32 bit reference count
-4/-8         | 32 or 64 bit length indicator
 0/ 0         | data of the array.

Performing FData = @FBuf[1] you are messing up with the prefix fields of the dynamic array.
The 4 bytes in front of @Fbuf[1] are interpreted as the length.
For Thing1 these are:
          -8 (refcnt)  -4 (len)     0 (data)
FBuf:     01 00 00 00  08 00 00 00  00  'S' 'n' .....
FData:    00 00 00 08  00 00 00 00  .............. //Hey that's a zero length.

Oops, when DynArrayAsg starts investigating it sees that what it thinks is the source for the assign has a length of zero, i.e. it thinks the source is empty and does not assign anything. It leaves FData unchanged!
Does Thing2 work as intended?
It looks like it does, but it actually fails in rather a bad way, let me show you.

You've successfully tricked the runtime into believing @FBuf[1] is a valid reference to a dynamic array.
Because of this the FData pointer has been updated to point to FBuf[1] (so far so good), and the reference count of FData has been increased by 1 (not good), also the runtime has grown the memory block holding the dynamic array to what it thinks is the correct size for FData (bad).
          -8 (refcnt)  -4 (len)     0 (data)
FBuf:     01 01 00 00  13 00 00 00  01  'S' 'n' .....
FData:    01 00 00 13  00 00 00 01  'S' ..............

Oops FData now has a refcount of 318,767,105 and a length of 16,777,216 bytes.
FBuf also has its length increased, but its refcount is now 257.
This is why you need the call to SetLength to undo the massive overallocation of memory. This still does not fix the reference counts though.
The overallocation may cause out of memory errors (esp. on 64-bit) and the wacky refcounts cause a memory leak because your arrays will never get freed.
The solution
As per David's answer: enable typed checked pointers: {$TYPEDADDRESS ON}
You can fix the code by defining FData as a normal PAnsiChar or PByte.
If you make sure to always terminate your assignments to FBuf with a double zero FData will work as expected.
Make FData a TBuffer like so:
TBuffer = record
private
  FData : PByte;
  function GetLength: cardinal;
  function GetType: byte;
public
  class operator implicit(const A: TBytes): TBuffer;
  class operator implicit(const A: TBuffer): PByte;
  property Length: cardinal read GetLength;
  property DataType: byte read GetType;
end;

Rewrite CreateThing like so:
constructor TThing.CreateThing(const AThingType : Byte; const AThingData: TBytes);
begin
  SetLength(FBuf, Length(AThingData) + Sizeof(AThingType) + 2);
  FBuf[0] := AThingType;
  Move(AThingData[0], FBuf[1], Length(AThingData));
  FBuf[Lengh(FBuf)-1]:= 0;
  FBuf[Lengh(FBuf)-2]:= 0;  //trailing zeros for compatibility with pansichar

  FData := FBuf;  //will call the implicit class operator.
end;

class operator TBuffer.implicit(const A: TBytes): TBuffer;
begin
  Result.FData:= PByte(@A[1]);
end;

I don't understand all this mucking about trying to outsmart the compiler.
Why not just declare FData like so:
type
  TMyData = record
    DataType: byte;
    Buffer: Ansistring;
    ....

And work with that.

A: The problem can be seen readily by enabling type-checked pointers. Add this to the top of your code:
{$TYPEDADDRESS ON}

The documentation says:

The $T directive controls the types of pointer values generated by the
  @ operator and the compatibility of pointer types.
In the {$T-} state, the result of the @ operator is always an untyped
  pointer (Pointer) that is compatible with all other pointer types.
  When @ is applied to a variable reference in the {$T+} state, the
  result is a typed pointer that is compatible only with Pointer and
  with other pointers to the type of the variable.
In the {$T-} state, distinct pointer types other than Pointer are
  incompatible (even if they are pointers to the same type). In the
  {$T+} state, pointers to the same type are compatible.

With that change your program fails to compile. This line fails:
FData := @FBuf[1];

The error message is:

E2010 Incompatible types: 'System.TArray<System.Byte>' and 'Pointer'

Now, FData is of type TArray<Byte> but @FBuf[1] is not a dynamic array but rather a pointer to a byte in the middle of a dynamic array. The two are not compatible. By operating in the default mode where pointers are not type-checked, the compiler lets you commit this terrible mistake. Quite why this is the default mode is utterly beyond me.
A dynamic array is more than a pointer to the first element – there is also metadata such as length and reference count. That metadata is stored at an offset from the first element. Hence your entire design is flawed. Store the type code in a separate variable, and not as part of the dynamic array.

A: constructor TThing.CreateThing(const AThingType : Byte; const AThingData: TBytes);
var
  Buffer : array of Byte;
begin
  SetLength(Buffer, Length(AThingData) + Sizeof(AThingType));
  Buffer[0] := AThingType;
  Move(AThingData[0], Buffer[1], Length(AThingData));

  SetLength(FBuf, Length(Buffer));
  Move(Buffer[0], FBuf[0], Length(Buffer));
  SetLength(FData, Length(AThingData));
  Move(Buffer[1], FData[0], Length(AThingData));
end;


text:
Q: Rename a specific url parameter and its value htaccess mod_rewrite I want to replace a specific url parameter and it's value in htaccess per modrewrite:
OLD:
/index.php?id=364&lang=de
/index.php?id=364&lang=en

NEW:
/index.php?id=364&L=0
/index.php?id=364&L=1

Any hints for this?
I tried this, but it's not for the value itself. Sorry, I'm not so fit in mod_rewrite conditions:
RewriteCond %{QUERY_STRING} (?:^|&)lang=(.*)$
RewriteRule ^(.*)$ /$1?L=%1 [L,R]

Thanks and all the best,
Chris

A: With your shown attempts, please try following. Please clear browser cache before testing your URLs.
RewiteEngine ON
##Rule for internal rewrite to index.php for de language.
RewriteCond %{THE_REQUEST} \s/(index\.php)\?id=(\d+)&lang(de)\s [NC]
RewriteRule ^ %1?id=%2&L=0 [L]
####Rule for internal rewrite to index.php for en language.
RewriteCond %{THE_REQUEST} \s/(index\.php)\?id=(\d+)&lang(en)\s [NC]
RewriteRule ^ %1?id=%2&L=1 [L]


text:
Q: Android keyBoard does not popup when tap in EditText I create a popup and add a EditText for it.But when i tap the text field soft keyboard does not show.How can i do it?
thanks..

A: Please check the context you are giving to popup. As i have faced the same problem by simply providing context by  getAppContext() method rather then this.

A: I think there is some problem in your xml. Do the below.
Here is popup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:gravity="bottom"
              xmlns:android="http://schemas.android.com/apk/res/android">
     <EditText android:id="@+id/dialogSearchBox"
               android:inputType="text"
               android:hint="Search"
               android:layout_height="40dip"
               android:layout_width="fill_parent">
     </EditText>
</LinearLayout>

Now you haven't mention that what kind of alert you like to use and whether you like to use any positive or negative button or not.
So, I just inflate this layout to ther alert dialog.
AlertDialog.Builder pop_up = new AlertDialog.Builder(this);
pop_up.setView(this.getLayoutInflater().inflate(R.layout.popup, null));
pop_up.show();

On tapping the edit text soft keyboard is showing. Try it.


text:
Q: new disk in Vm shows as ata2 The admin added a new disk to my VM and it appears as ata2 after I rescanned the scsi controller with:
root@jpax-build07:~# echo "- - -" > /sys/class/scsi_host/host0/scan
root@jpax-build07:~# echo "- - -" > /sys/class/scsi_host/host1/scan
root@jpax-build07:~# echo "- - -" > /sys/class/scsi_host/host2/scan
fdisk -l

but it doesn't show under fdisk -l how can I create a fs and mount it?
# fdisk -l
Disk /dev/sda: 300 GiB, 322122547200 bytes, 629145600 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xa8c4da68
...

/dev/sda is the existing disk
dmesg:
[10600270.932925] ata2: soft resetting link
[10600271.122685] ata2.00: configured for UDMA/33
[10600271.123105] ata2: EH complete
[10600430.666938] ata1: soft resetting link
[10600430.836638] ata1: EH complete
[10600467.936948] ata2: soft resetting link
[10600468.122680] ata2.00: configured for UDMA/33
[10600468.123125] ata2: EH complete

A: ata is for IDE disks. ( Actually a stronger telltale is UDMA/33 )
As such the hotplug SCSI commands that you are using for scanning the SCSI bus for new disks, won't make the kernel show any new disks at all (the new  disk is in an emulated IDE bus after all).
If you want to do new disks hotplug in your VMs, you have to ask your VMWare admin to create new virtual disks as (emulated) SCSI disks instead.
TLDR the Linux kernel does not support hot add of IDE disks. After rebooting that VM, a new disk will appear.


text:
Q: How to access a REST api from a Java application hosted by Elastic Beanstalk that is behind AWS VPC? I created an Elastic Beanstalk environment with a AWS VPC. It is a Java REST application using Spring framework.
When I setup the Elastic Beanstalk environment without a VPC, I'm able to hit the REST endpoint.
http://my-service.us-east-1.elasticbeanstalk.com/swagger-ui.html
However, now with VPC, I'm not able to access it.
What is the proper way to access this REST endpoint now?


text:
Q: What is the python data type for Google Bigquery's TIMESTAMP? I'm loading data into Google's BigQuery using the google-cloud-python library as found here:
http://google-cloud-python.readthedocs.io/en/latest/index.html
Part of it involves checking the data types of the data I'm importing to ensure they match the datatypes in the schema for the target table. To do this I convert a python object type to the GBQ equivalent:
import datetime

def convert_type_to_bigquery(object_type):
    if isinstance(object_type, str):
        return 'STRING'
    elif isinstance(object_type, bytes):
        return 'BYTES'
    elif isinstance(object_type, int):
        return 'INTEGER'
    elif isinstance(object_type, float):
        return 'FLOAT'
    elif isinstance(object_type, bool):
        return 'BOOLEAN'
    elif isinstance(object_type, datetime.date):
        return 'DATE'
    elif isinstance(object_type, datetime.time):
        return 'TIME'
    elif isinstance(object_type, datetime.datetime):
        return 'DATETIME'
    elif isinstance(object_type, ???):
        return 'TIMESTAMP'
    else:
        return None

I can find equivalents for all but the TIMESTAMP type. Is there an equivalent I can use in isinstance()?

A: You can do print(type(object_type)) with the TIMESTAMP object to be sure but, according to this github page, it looks like it's just datetime.datetime:
...
Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
...

I must say, the main reason I wanted to add an answer was to point out a common error with ìsinstance(...). This won't work since bool is an instance of int:
elif isinstance(object_type, int):
    return 'INTEGER'
elif isinstance(object_type, float):
    return 'FLOAT'
elif isinstance(object_type, bool):
    return 'BOOLEAN'

Look at this example:
>>> isinstance(True, int)
True

You need to use elif type(object_type) is int: or place the check for bool first.


text:
Q: How to edit public member variables via class variable in other .cpp files? My friend and I are learning C++ and though we have been able to beat down every problem that has come our way (and have learned a bunch by doing so) in this program, this one has been making us rack our brains all day. We have spent countless hours not only trying to solve it ourselves but also looking through Stackoverflow's related questions and doing tons of Google Searches... Finally we decided that we have to just ask and hope one of you has an idea of what our problem is.
Basically we are trying to create a text based (console only) RPG and we have gotten to the point where we are creating Player Statistics using a class defined in our one and only Header file, there are three constructors to the class (using function overloading of course) and although we are able to run the game error free it seems as though we are not able to actually edit the values of the class member variables in any way!
This is our class:
//File OverHeader.h

class PlayerStatistics
{
public:
    PlayerStatistics(int HitPoints, int MagickaPoints, int Fatigue, int Damage, int Defense, int Dodge, int Block, int SpellCastChance);
    PlayerStatistics(int Experience, int Level);
    PlayerStatistics();

    int HitPoints;
    int MagickaPoints;
    int Fatigue;
    int Damage;
    int Defense;

    // Chance Based System (Relies on Fatigue Level)
    int Dodge;
    int Block;
    int SpellCastChance;

    int Experience;
    int Level;
};

And the main function:
#include <iostream>
#include <string>
#include "OverHeader.h"

// MAIN FUNCTION DEFINITION
int main()
{
PlayerStatistics PlayerStats(20, 20, 20, 20, 20, 20, 20, 20);
PlayerStatistics PlayerStatsLevel(0, 1);

    //continued with code irrelevant to this question.
}

The trouble is that the lines in the Main Function don't actually set the integer variables in the class to those values. After those two lines the integer values should be set to (just for demonstration purposes):
int HitPoints == 20;
int MagickaPoints == 20;
int Fatigue == 20;
int Damage == 20;
int Defense == 20;
int Dodge == 20;
int Block == 20;
int SpellCostChance == 20;
int Experience == 0;
int Level == 1;

But strangely enough outputting ANY of these integers will simply output random numbers (presumably the memory addresses current values).
The three constructors are in fact defined properly (although not in the Main.cpp) here:
// PlayerCreation.cpp
PlayerStatistics::PlayerStatistics(int HitPoints, int MagickaPoints, int Fatigue, int Damage, int Defense, int Dodge, int Block, int SpellCastChance)
{

}

PlayerStatistics::PlayerStatistics(int Experience, int Level)
{

}

PlayerStatistics::PlayerStatistics()
{

}

And that is our problem, I hope I described everything clearly enough, please let me know if you can help us actually edit the values of these Class Member Variables! All help is appreciated!

A: This creates the same class in two different ways:
PlayerStatistics PlayerStats(20, 20, 20, 20, 20, 20, 20, 20);
PlayerStatistics PlayerStatsLevel(0, 1);

The first creates a variable called PlayerStats that uses the first constructor.  The second creates another variable called PlayerStatsLevel that uses the second constructor.
Now, the constructors...
// PlayerCreation.cpp
PlayerStatistics::PlayerStatistics(int HitPoints, int MagickaPoints, int Fatigue, int Damage, int Defense, int Dodge, int Block, int SpellCastChance)
{

}

PlayerStatistics::PlayerStatistics(int Experience, int Level)
{

}

This doesn't actually initialise the member variables in the class.  You have used the same names in the constructor, but that is actually going to give you grief because (to take a single example) the local variable HitPoints passed into the constructor overrides the class member HitPoints.  Now, if you want to refer to the class member you must use this->HitPoints.
So, I reiterate, nothing actually got initialised.  So you have random values in your object.  You need to do this (I'll take the shorter example):
// Using initializer list
PlayerStatistics::PlayerStatistics(int inExperience, int inLevel)
    : Experience(inExperience), Level(inLevel)
{
}

// Or using conventional assignment
PlayerStatistics::PlayerStatistics(int inExperience, int inLevel)
{
    Experience = inExperience;
    Level = inLevel;
}

Note that the other values were not initialized using this constructor.  That might be intended, or you might want to set them all to a default value.  You need to do this explicitly.
Now, it kinda looks like you wanted a single instance with all those stats set.  What you might want to do is use just one constructor - the empty constructor PlayerStatistics(), and initialize everything to something 'sensible'.  Then define functions to set the stats in chunks:
void PlayerStatistics::SetStats(int HitPoints, int MagickaPoints, int Fatigue, int Damage, int Defense, int Dodge, int Block, int SpellCastChance)
{
    this->HitPoints = HitPoints;
    this->MagickaPoints = MagickaPoints;
    // etc etc...
}

void PlayerStatistics::SetLevel(int Experience, int Level)
{
    this->Experience = Experience;
    this->Level = Level;
}

// If you want you can explicitly set the values to something in the constructor.
// It's probably good practice if you're new at this.
PlayerStatistics::PlayerStatistics()
{
    SetStats(0, 0, 0, 0, 0, 0, 0, 0);
    SetLevel(0, 0);
}

Now in your main:
PlayerStatistics player;
player.SetStats(20, 20, 20, 20, 20, 20, 20, 20);
player.SetLevel(0, 1);

Or if these are the defaults for a new player, do it in the constructor and then you never need to remember.
Hope that gets you started.  Have fun and never be afraid to experiment.

A: Those constructors are not defined properly: they take the arguments, but don't do anything with the values! Try this instead:
PlayerStatistics::PlayerStatistics(int Experience, int Level)
:
  Experience(Experience),
  Level(Level)
{

}

That's roughly equivalent to:
PlayerStatistics::PlayerStatistics(int Experience, int Level)
{
  this->Experience = Experience;
  this->Level = Level
}

Of course you want to initialize the other ones in the same way, and set unspecified fields to their defaults, but you get the idea.

A: Your constructor doesn't set the values -- constructors can have any parameters you like, and those parameters don't get assigned to data members just because they happen to have the same names.
You need:
PlayerStatistics::PlayerStatistics(
    int HitPoints, int MagickaPoints, int Fatigue,
    int Damage, int Defense, int Dodge, int Block,
    int SpellCastChance) :
        HitPoints(HitPoints),
        MagickaPoints(MagickaPoints),
        ... etc ...
{

}

(indent it how you like, I did it this way because there doesn't seem much point the only difference between my code and yours being invisible off the scroll to the right).
: HitPoints(HitPoints) ... is an "initialization list", and it means "initialize this base class or data member with that value". In your case, the value happens to have the same name as the data member, but that's fine, the compiler figures out which is which from context.


text:
Q: Upper-Bounded and Lower-Bounded Wildcards in return type of Java Generic method I was trying to solve a problem where I am not able to understand part of the answer.
Following is the class BackLister:
public class BackLister {
    // INSERT HERE
    {
        List<T> output = new LinkedList<T>();
        for (T t : input)
            output.add(0, t);
        return output;
    }
}

The question asks which can be inserted at // INSERT HERE in the BackLister class to compile and run without error?
Following are the options:
A. public static <T> List<T> backwards(List<T> input)
B. public static <T> List<T> backwards(List<? extends T> input)
C. public static <T> List<T> backwards(List<? super T> input)
D. public static <T> List<? extends T> backwards(List<T> input)
E. public static <T> List<? super T> backwards(List<T> input)
F. public static <? extends T> List<T> backwards(List<T> input)
G. public static <? super T> List<T> backwards(List<T> input)

I understand that that A and B are correct, as for for (T t : input) to work the elements in input should be of type T or subtype of T.
But I am not able to understand why D and E options are correct?
I understand the following:

*

*public static <T> List<? extends T> backwards(List<T> input)
    means that the return type should be a List of T or subclass
    of T.

*public static <T> List<? super T> backwards(List<T> input) means that the return type should be a List of T or
superclass of T.

Could somebody help me understand it?

A: There is difference between each of them and I'm going to explain most of them. Let's start with our example. I use this class hierarchy:
class Food {}
class Apple extends Food {}
class Orange extends Food {}
class RedApple extends Apple {}

List<Food> listFood = new ArrayList<>();
List<Apple> listApple = new ArrayList<>();
List<Orange> listOrange = new ArrayList<>();
List<RedApple> listRedApple = new ArrayList<>();

ow start with first one:
A. public static <T> List<T> backwards(List<T> input)

This method will only accept List<T> and return List<T> and you can not send listApple and return listRedApple. (however your return list can contain RedApple because it extends Apple but type of list must be List<Apple> and nothing else)
B. public static <T> List<T> backwards(List<? extends T> input)

You can send listRedApple and return listApple but you know that listRedApple is "? extend Apple" so in the method body java recognize T as Apple. Then if you use can add elements in listRedApple which sent as argument, you can add Apple in listRedApple which is not true!!! so compiler avoid it and give compile error. In B you can only read elements (and get it as T) but you can not add anything to it.
C. public static <T> List<T> backwards(List<? super T> input)

You can send listApple and then in method body you can add anything extends Apple because compiler see T as Apple and in a list of anything which is super of T, you can add anything extends Apple.
However this time, you can not read anything because you don't know its type except you get it as Object. (It is a list of "? super T")
As you see here there is difference between ? super and ? extend. one of them give you write access and other give you read access. This is the real use of wildcard.
D. public static <T> List<? extends T> backwards(List<T> input)
E. public static <T> List<? super T> backwards(List<T> input)

If you send listApple then you return List<? extends Apple> but you can's assign it to any of listFood or listApple or listRedApple because List<? extends Apple> maybe contain Apple or RedApple or something else and we can't assign it to any List<T> because then we can add T to that list and maybe T and ? extends T is not same. this is same for both D and E. You can assign it to List<? extends Apple> for 'E and List<? super Apple> for D and send them to a method which need them as parameter.
F. public static <? extends T> List<T> backwards(List<T> input)
G. public static <? super T> List<T> backwards(List<T> input)

Give compile errors because wildcard can not used like this.
I hope this help you.
If something is wrong, any comment is appreciated.

A: Options D and E are valid because there exist a super-subtype relationships among generic types that allow you to define a larger set of types that the method can accept or return.
Consequently, the following is valid (D):
public static <T> List<? extends T> backwards(List<T> input) {
    return List.of();
}

// there exist a super-subtype relationships among List<? extends Number> and List<Long>
List<? extends Number> list = backwards(List.<Long>of(1L, 2L));

because the type Long is a member of the type family that the wildcard ? extends Number denotes (the family of types that are subtypes of Number and the type Number itself).
The next code snippet is also valid (E):
public static <T> List<? super T> backwards(List<T> input) {
    return List.of();
}

List<? super Long> ints = backwards(List.<Long>of(1L, 2L));

because the type Long is a member of the type family that the wildcard ? super Long denotes (the family of types that are supertypes of Long and the type Long itself).
So, your understanding is correct.
Further reading.

A: Below image describes the sub-typing relation in Generics:
List<T> is a subtype of List<? super T>
Also List<T> is a subtype of List<? extends T>

This is why options D and E are correct.

You can refer the page : https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html


text:
Q: docker port command returning nothing I am following the tutorial here.
In this, you launch a container like so :
docker run --name static-site -e AUTHOR="Your Name" -d -P dockersamples/static-site
e61d12292d69556eabe2a44c16cbd54486b2527e2ce4f95438e504afb7b02810

which I have done. Then it tells you to run the command :
docker port static-site

This is meant to return the ports the container is running on, right ?
It's returning nothing for me. How come ?
sudo docker ps -l shows it has been created.
Thanks a lot.

A: On MacOS, I have following results:
$ docker run --name static-site -e AUTHOR="Your Name" -d -P dockersamples/static-site
ac25e7cdd81725dfa157ff7027d1ed6beb3839c9457b9627728d700375e7a77f

$ docker ps
CONTAINER ID        IMAGE                       COMMAND                  CREATED             STATUS              PORTS                                           NAMES
ac25e7cdd817        dockersamples/static-site   "/bin/sh -c 'cd /usr…"   6 seconds ago       Up 5 seconds        0.0.0.0:32774->80/tcp, 0.0.0.0:32773->443/tcp   static-site

$ docker port static-site
443/tcp -> 0.0.0.0:32773
80/tcp -> 0.0.0.0:32774

Please inspect the result of the column 'ports' of the command docker ps on your machine where ports and the mapped ports are also displayed.


text:
Q: how to convert functional component to class component? i am new to React.js i am trying to convert funbctional component to class component can anyone help me ?
here is my code i want to convert that code which is in functional componetn to class component
import React, { useState, useRef } from 'react';
import  {DateRangePicker}  from 'react-date-range';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { addDays } from 'date-fns';
import { useState } from 'react';
function App(){
const [state, setState] = useState([
  {
    startDate: new Date(),
    endDate: addDays(new Date(), 7),
    key: 'selection'
  }
]);
return(
<DateRangePicker
  onChange={item => setState([item.selection])}
  showSelectionPreview={true}
  moveRangeOnFirstSelection={false}
  months={2}
  ranges={state}
  direction="horizontal"
/>
);
}

can anyone help me how to fix this ?

A: import React from 'react';
import { DateRangePicker } from 'react-date-range';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { addDays } from 'date-fns';

class App extends React.Component {

  state = {
    startDate: new Date(),
    endDate: addDays(new Date(), 7),
    key: 'selection'
  };

  handleDateSelect = (item) => {
    this.setState({
      ...item
    });
  }

  render() {
    const { startDate, endDate, key } = this.state;

    return (
      <DateRangePicker
        onChange={item => this.handleDateSelect(item)}
        showSelectionPreview={true}
        moveRangeOnFirstSelection={false}
        months={2}
        ranges={{
          startDate,
          endDate,
          key
        }}
        direction="horizontal"
      />
    );
  }
}

export default App;

A: Edit: To fix "TypeError: ranges.findIndex is not a function" error, you should put your selectionRange in array to the prop.
Like this:
ranges={ [ this.state.selectionRange ] }
Not like this: ranges={ this.state.selectionRange }
For more info, check the example here: react-date-range - npm
And I think you should check here too: Function and Class Components
import React from "react";
import { DateRangePicker } from "react-date-range";
import "react-date-range/dist/styles.css"; // main style file
import "react-date-range/dist/theme/default.css"; // theme css file
import { addDays } from "date-fns";

class ComponentName extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectionRange: {
        startDate: new Date(),
        endDate: addDays(new Date(), 7),
        key: "selection"
      }
    }
  }

  render() {
    return (
      <DateRangePicker
        onChange={(item) => this.setState({selectionRange: item.selection})}
        showSelectionPreview={true}
        moveRangeOnFirstSelection={false}
        months={2}
        ranges={[this.state.selectionRange]}
        direction="horizontal"
      />
    );
  }
}


text:
Q: KENDO UI : Invalid Template Format I am very new to Kendo ui, and I am trying to create a template but I am getting the "Invalid template" error. What I want to achieve is to check if the field name is valid (exists on the current object) so I can avoid the undefined property error.
template: "
<input type='checkbox' value='#=" + field + "?#= "+ field +":\"\"#'/>#=" + field + "?#="+ field +":\"\"#
"

I am trying to reproduce the reproduce this example http://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/checkbox-filter-menu , but some objects of data I have, does not contain some properties.

A: You could use if/else instead of the ?: operator.
So adapting on that Kendo Example you mentioned, the below snippet uses the value of "field" if it exists otherwise places the alternative "\", which is what I think you were trying to achieve above
template: "
<input type='checkbox' #if("+field+"){# value='#:" + field + "#'/>#:" + field + "#
#}else{#value='\'/> \
#}#"

Alternatively the following template won't create an element at all if "field" doesn't exist:
template: "#if("+field+"){#
<input type='checkbox' value='#:" + field + "#'/>#:" + field + "#
 #}#"

For reference see the Template Syntax section here:
http://docs.telerik.com/kendo-ui/framework/templates/overview


text:
Q: Passing background parameter through tapgesture from list view to new Page in xamarin forms For some time i'm trying to create navigation service in my app while studying Xamarin. My approach here don't foolow mvvm desing pattern but at first i treid to have functionality working on which i will study further. I figured out how to navigate using ItemSelected property in listview through event fired in code-behind file and pass parameter from object placed in listview as a string. I want to changed it for more custom way by adding tap gesture on image not (imagebutton don't even fired event for new page when i added tap gesture on it in xaml file)
This worked for itemselected:
private async void SampleItem_Tapped(object sender, ItemTappedEventArgs e)
    {
        var details = e.Item as SampleModel;
        await Navigation.PushAsync(new Page1(details));
    }

new page codebehind:
    public Page1(SimpleModel sample)
    {
        InitializeComponent();

        var pageServices = new PageServices();
        BackgroundImage = sample.SampleMainBackgroundImage;

    }

This is where i need your help : ( app throwing exception when i assing as constructor of new page a string property and bound it to my string backgroundimagebinding (object reference not set to an instance of an object new page) )
private async void SampleIcon_Tapped(object sender, ItemTappedEventArgs e)
    {
        var details = e.Item as SampleModel;
        await Navigation.PushAsync(newPage1(details));

    }

A: e.Item on code below would be the visual element which I think is the image. Hence, it can't be casted as SampleModel.
private async void SampleIcon_Tapped(object sender, ItemTappedEventArgs e)
{
    var details = e.Item as SampleModel;
    await Navigation.PushAsync(newPage1(details));

}

It worked on ListView maybe because you've set the ItemsSource to a list of PageModels. Btw, It would be really helpful next time if you include all related codes. E.g. xaml part. Also, try out debugger tools so you can view the details of the objects passed on the method.


text:
Q: How to get ODP.NET to return null value for User Defined Type from out parameter in Oracle stored procedure? I am having some trouble with Odp.net as regards the UDT (User Defined Type) behavior.
My problem arises when I have a procedure containing an OUT parameter that returns a specific UDT.
When I return an instantiated UDT for the OUT parameter there is no problem.
When I return a NULL value for the OUT parameter I get a NullReference error:

A first chance exception of type 'System.NullReferenceException'
  occurred in Oracle.DataAccess.dll

I have tried setting IsNullable = True on the relevant OracleCommand parameter without any success.
I have no problem sending and receiving rather complex UDT's, e.g. UDT's with nested UDT's and collections of objects and UDT's witgh nested collections of objects.
Any ideas if this can be solved using ODP.NET other than making the Oracle procedure return an instance of the object type?

UPDATE - SOLVED:
The issue was that the UDT type with its nested UDT type was not correctly initialized to null. Using the auto generated code solved the problem.Using Oracle User-Defined Types with .NET and Visual Studio
Christian Shay, thank you for resolving the issue - the auto generated code
  is perhaps a better choice than implementing base classes to handle
  most of the behavior, although this is possible.

The Oracle stored procedure signature is:
PROCEDURE CREATE_DEFINITIONS_FOR_GROUP(
    P_GRP_NO             IN     NUMBER
   ,P_DATE               IN     DATE
   ,P_ERROR_CODE         OUT    MYSCHEMA.ERROR_CODE);

I call this code in C# using ODP.NET after opening a connection:
using (var oCmd = new OracleCommand
       {
           CommandText = "MYSCHEMA.MYPACKAGE.CREATE_DEFINITIONS_FOR_GROUP",
           Connection = oConn,
           CommandType = CommandType.StoredProcedure
        })
{
    try
    {
        oCmd.Parameters.Add(OracleParameterFactory.CreateInParam(
            "P_GRP_NO", OracleDbType.Int64, value: groupNo));
        oCmd.Parameters.Add(OracleParameterFactory.CreateInParam(
            "P_DATE", OracleDbType.Date, value: dateOfGroup));
        oCmd.Parameters.Add(OracleParameterFactory.CreateOutParamForUdtType(
            "P_ERROR_CODE", "MYSCHEMA.ERROR_CODE"));

        oCmd.ExecuteNonQuery();

        var report = oCmd.Parameters["P_ERROR_CODE"].Value as DbErrorCode;

        return report;
    }
    finally
    {
        CommandHelpers.DisposeParameters(oCmd);
    }
}

The UDT type is defined as a valid UDT type in .NET like this:
public class DbErrorCode : TypeTemplate
{
    [OracleObjectMapping("ERROR_CODE")]
    public decimal Code { get; set; }

    [OracleObjectMapping("DESCRIPTION")]
    public string Description { get; set; }
}

The base TypeTemplate class is defined like this:
public class TypeTemplate : IOracleCustomType, INullable
{
    public virtual void FromCustomObject(OracleConnection con, IntPtr pUdt)
    {
        foreach (var p in GetType().GetProperties())
        {
            // Must ignore these two properties
            if (p.Name == "Null" || p.Name == "IsNull") continue;

            var oracleObjectMappingAttribute = p.GetCustomAttributes(typeof(OracleObjectMappingAttribute), false)[0] as OracleObjectMappingAttribute;

            if (oracleObjectMappingAttribute == null) continue;

            var attributeName = oracleObjectMappingAttribute.AttributeName;

            if (p.GetCustomAttributes(typeof(IgnoreAttribute), false).Length == 0)
            {
                if (p.GetCustomAttributes(typeof(NullableAttribute), false).Length == 0)
                {
                    OracleUdt.SetValue(con, pUdt, attributeName, p.GetValue(this, null));
                }
                else
                {
                    if (p.GetValue(this, null) != null)
                    {
                        OracleUdt.SetValue(con, pUdt, attributeName, p.GetValue(this, null));
                    }
                }
            }
        }
    }

    public virtual void ToCustomObject(OracleConnection con, IntPtr pUdt)
    {
        foreach (var p in GetType().GetProperties())
        {
            // Must ignore these two properties
            if (p.Name == "Null" || p.Name == "IsNull") continue;

            var oracleObjectMappingAttribute = p.GetCustomAttributes(typeof(OracleObjectMappingAttribute), false)[0] as OracleObjectMappingAttribute;

            if (oracleObjectMappingAttribute == null) continue;

            var attributeName = oracleObjectMappingAttribute.AttributeName;

            if (!OracleUdt.IsDBNull(con, pUdt, attributeName))
            {
                p.SetValue(this, OracleUdt.GetValue(con, pUdt, attributeName), null);
            }
        }
    }

    #region INullable Members

    public bool IsNull { get; private set; }

    public static TypeTemplate Null
    {
        get
        {
            var obj = new TypeTemplate { IsNull = true };
            return obj;
        }
    }

    #endregion
}

The method in OracleParameterFactory for the UDT parameter is as follows (exception handling removed from the code to present as clean code as possible - the error produced does not come from the exception handling):
public static OracleParameter CreateOutParamForUdtType(
   string paramName, string udtName, object value, bool isNullable = false)
{
    var param = new OracleParameter
    {
        ParameterName = paramName,
        UdtTypeName = udtName.ToUpperInvariant(),
        OracleDbType = OracleDbType.Object,
        Direction = ParameterDirection.Output,
        IsNullable = isNullable
    };

    if (value != null)
    {
        param.Value = value;
    }

    return param;
}

A: Problem solved: The issue was that the UDT type with its nested UDT type was not correctly initialized to null. Using the auto generated code solved the problem.Using Oracle User-Defined Types with .NET and Visual Studio
Christian Shay, thank you for resolving the issue - the auto generated code is perhaps a better choice than implementing base classes to handle most of the behavior, although this is possible.

A: I am not certain on this, but my experience is that "oCmd.ExecuteNonQuery()" is likely returning null and needs to be returned to an object and you can then check if it is null and return and empty UDT or the on returned.  Try
TypeTemplate udtOnbj = new TypeTemplate();
object testObj = oCmd.ExecuteNonQuery();
if ( testObj == null ) { return udtObj; } else { return testObj; }


text:
Q: activeStyle does not exist on type 'IntrinsicAttributes I am trying to use NavLink in react typescript project, however, it's getting an error.
Property 'activeStyle' does not exist on type 'IntrinsicAttributes & NavLinkProps & RefAttributes'.
import React from 'react'
import { NavLink } from 'react-router-dom'

export default function Nav () {
  return (

              <NavLink
                to='/'
                activeStyle={{
                  textDecoration: 'none',
                  color: 'red'
                }}
                className='nav-link'>
                Top
              </NavLink>

              <NavLink
                to='/new'
                className='nav-link'>
                New
              </NavLink>

  )
}

A: activeStyle is deprecated in v6. You can use style function like this:
<NavLink
 to='/'
 className='nav-link'
 style={
  ({isActive}) => (
   isActive
   ? {
      textDecoration: 'none',
      color: 'red'
     }
   :{}
   )
 }
>
Top
</NavLink>

Code Sandbox

A: The NavLink API changed a bit in RRDv6, there is no longer an activeStyle prop.
NavLink

interface NavLinkProps
  extends Omit<LinkProps, "className" | "style"> {
  caseSensitive?: boolean;
  className?:
    | string
    | ((props: { isActive: boolean }) => string);
  end?: boolean;
  style?:
    | React.CSSProperties
    | ((props: {
        isActive: boolean;
      }) => React.CSSProperties);
}

You can conditionally apply your active class via a style or className prop function. Using the style prop.
const isActiveStyle = {
  textDecoration: 'none',
  color: 'red'
};

...
<NavLink
  style={({ isActive }) => isActive ? isActiveStyle : {}}
  to="/"
>
  Top
</NavLink>


text:
Q: measurable functions in product measure space Let f be a nonnegative function defined on a measurable subset E of R. Show that f is measurable if the region {(x, y) : x ∈ E, f(x) ≥ y} is a measurable subset of R2

A: Let $S=\{(x,y) | x \in E, f(x) \ge y \} \cap \{ (x,y) | y \ge 0 \}$, and note that $S$ is measurable.
Then the function $(x,y) \mapsto 1_S(x,y)$ is measurable.
Fubini Tonelli tells us that the function $x \mapsto \int_{\mathbb{R}} 1_S(x,y) dy$ is measurable. Since
$\int_{\mathbb{R}} 1_S(x,y) dy = f(x) $, we see that $f$ is measurable.


text: Q: How to retrieve youtube videos more than 500 using youtube rest api I am using this api https://gdata.youtube.com/feeds/api/videos?q=skateboarding+dog&start-index=1&max-results=10  to get the data, i am incresing the start-index parameter dynamically to get the next results. The problem is , i am able to receive 500 records but after that it is showing an exception saying "You cannot request beyond item 500."