text:
Q: How to conditionally assign value to a variable in a Makefile (BSD + GNU)? I have a (from my point of view) rather complicated Makefile.
That is mostly because I wanted colors there and other unnecessary things.
Anyway, might I jump right into my question:
Apart from Linux I newly support *BSD, thus I need to check for the platform in use on several places. Is conditional variable assignment possible in a Makefile? Something like:

platform := [ $$(uname) = Linux ] && echo Linux || echo BSD or other

Of course this does not work, but hopefully, you get my point.

I need a solution, that works both with the BSD make, and the GNU make.

A: Beware before using this solution
A compliment of Renaud Pacalet: What you are assigning to your make variables are shell commands, not the result of their execution by the shell. It will seriously limit the use you can make of them (basically to recipes). You will not be able to use them as targets, prerequisites, other variables definitions, conditions of make conditionals.
Expanding on MadScientist's comment
I quote:

Note != was added to GNU make in version 4.0. It won't work in older versions.

And also simplifying the bunch of unnecessary ifs, we could get a working version on possibly all versions of both GNU and BSD make like the below approach.
An alternative approach through the shell
platform_id = $$( uname -s )

platform = $$( \
    case $(platform_id) in \
        ( Linux | FreeBSD | OpenBSD | NetBSD ) echo $(platform_id) ;; \
        ( * ) echo Unrecognized ;; \
    esac )

Important notes:

*

*You need to use the standard = lazy assignments here. With immediate assignment operator :=, it does not work in BSD make.

*You need to use ( ... ) in the case statement. Otherwise, it would not work on OpenBSD

Successfully tested on:

*

*Linux Mint 19.0 Cinnamon (based on Ubuntu 18.04)

*FreeBSD 11.2

*OpenBSD 6.4
I am still working on making NetBSD 8.0 work in VirtualBox, so I cannot yet confirm this one.

Further testing on older versions of these systems necessary, so if you have one of them significantly older, please do test it, thank you.

A: The != shell assignment operator is apparently supported on both BSD and GNU make:
platform_id != uname -s

platform != if [ $(platform_id) = Linux ] || \
    [ $(platform_id) = FreeBSD ] || \
    [ $(platform_id) = OpenBSD ] || \
    [ $(platform_id) = NetBSD ]; then \
        echo $(platform_id); \
    else \
        echo Unrecognized; \
    fi

Note that the assignments are really evaluated by the shell: it is the result of this evaluation that gets assigned to the make variables, not the shell commands.
Solution that requires GNU make. It works with GNU make on BSD, but not with BSD make.
One possibility is to use the if GNU make function:
platform := $(if $(patsubst Linux,,$(shell uname -s)),BSD or other,Linux)

Another one is to rely only on the shell conditionals:
platform := $(shell [ $$(uname) = Linux ] && echo Linux || echo BSD or other)

The GNU make conditionals can also be used:
ifeq ($(shell uname -s),Linux)
    platform := Linux
else
    platform := BSD or other
endif


text:
Q: Link to a service contained in third party library(jar) I know and have tried creating system services in android as described here : http://processors.wiki.ti.com/index.php/Android-Adding_SystemService
The question is regarding how to use a third party jar placed in frameworks which contains the service implementation. AIDL files are provided which exposes the functions of the service.
My question is, after building the source, how can I bind to the service from a third party app, provided the following in source tree:
(1) jar - Linux/android/vendor/companyname/libs/frameworks
(2) AIDL - Linux/android/frameworks/base/core/java/ny/co/companyname/bluetooth/api
Please let me know if any clarifications regarding the above mentioned is required.
Any help is much appreciated
PS:
For testing, we used the lib(jar) and AIDL as part of an android application,and we can see the service getting bound correctly using bindservice, by observing the logs inside onServiceConnected callback.

A: For services to work correctly, the stub must be generated in the R.java file.
Now here (might be because of ADT bug), for generating stub definition in R.java file, you will have to keep the AIDL file in your src folder with the same named package.
In your case, in your project's src folder, create a package
Linux/android/frameworks/base/core/java/ny/co/companyname/bluetooth/api
and place your AIDL file in it.
You might meet the fate. :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find authors who ONLY wrote history books New to SQL, although catching on - stuck on this query.
This works, although Paddy O'Furniture should not be showing up as this author hasn't written any book and his au_id does not appear in the title_authors table. Please help.
Find authors who ONLY wrote history books
select a.au_id, a.au_lname, a.au_fname

from authors a

where not exists(

    select ta.au_id

    from title_authors ta

    join titles t

    on t.title_id = ta.title_id

    where t.type != 'history'

    and a.au_id = ta.au_id

)
Output:
A01 Buchman Sarah
A07 O'Furniture Paddy

A: Paddy O'Furniture is in your result because no matching rows were discovered in the correlated subquery. i.e. no rows exist for that author and hence where not exists is true.
select a.au_id, a.au_lname, a.au_fname
from authors a
inner join title_authors ta ON a.au_id = ta.au_id
inner join titles t on ta.title_id = t.title_id
group by a.au_id, a.au_lname, a.au_fname
having count(case when t.type <> 'history' then 1 end) = 0

The approach above uses a case expression within a count() function so that if any books have a non history type this count will be greater than zero. The having clause enables using aggregated values to filter the final result (having is used is AFTER the group by clause, and is not a substitute for a where clause).

A: You are close.  Adding JOIN to title_authors on the outer query will filter out authors who have not written a book.
select a.au_id, a.au_lname, a.au_fname
from authors a
join title_authors ta1 on ta1.au_id = a.au_id
where not exists(
    select 1
    from title_authors ta
    join titles t on t.title_id = ta.title_id
    where t.type != 'history' and ta1.id = ta.id
)

The title_authors in the inner query can actually be removed.
select a.au_id, a.au_lname, a.au_fname
from authors a
join title_authors ta on ta.au_id = a.au_id
where not exists(
    select 1
    from titles
    where t.type != 'history' and title_id = ta.title_id
)

A: While your approach can work if you use another exists to make sure the author wrote at least a history book, here's another approach using conditional aggregation:
select a.au_id, a.au_lname, a.au_fname
from authors a
    join title_authors ta on a.au_id = ta.au_id
    join titles t on ta.title_id = t.title_id
group by a.au_id, a.au_lname, a.au_fname
having sum(case when t.type != 'history' then 1 else 0 end) = 0

Online Demo


text:
Q: Diagram to express parallelism in a process workflow I'm modelling part of a software architecture on which several processes run as a workflow. The architecture involves data parallelism, where a certain serial process produces N pieces of data which need to be distributed to N processes that must run in parallel.
I'm looking for a good way of expressing parallelism in a diagram. The objective of this diagram is to be informative and will be included in a paper about the system architecture. It does not need to be a formal model or strictly follow UML.
I've drawn 3 ways of representing the parallelism, one of which (2) basically follows the UML 2.0 Activity Diagram. I would like to know which one, if any, will more clearly convey the parallelism. What other information this sort of diagram should include?

A: The second way you depict not only follows the UML 2.x activity diagram notation but is also used in the Petri net formal modeling language. Indeed Petri net formalism is the source of UML 2.x activity diagram notation.
Using a Petri-net-like semantic for representing parallelism increases the potential audience who can understand your diagrams.
At the opposite, I read the third way as a choice among several options, just like a state machine.
Finally in my opinion, the first way just looks confuse and amateurish.

A: If there is standard way to represent something, you should use it.
I suppose that your audience has the minimum of technical knowledge required to understand your document. Therefore, I can reasonably suppose that your audience should have basic knowledge of UML so the diagram should be self-explaining. If you use your own convention you will have to also document it.


text:
Q: setting a view name when used nested_route in Django I'm new to django. I want to test my ViewSet(Django = 1.11) but I got this error message.
django.urls.exceptions.NoReverseMatch: Reverse for 'license' not found. 'license' is not a valid view function or pattern name.

I want to figure out what should I put in the reverse() as parameter.
urls.py
urlpatterns += util.get_nested_route_urls(
router=router, lookup='member', domain='license', view_set=MemberLicenseViewSet,
base_name='member_license')

test.py
class MemberLicenseViewSetTestCase(APITestCase):
     url = reverse("license")
     factory = APIRequestFactory()
     views = MemberLicenseViewSet.as_view


text:
Q: What happens at hardware level when we feed a code? I wanted to know what hardware is installed in 8051 such that whenever i write a program it accepts it and execute it.
My query is what happens at the hardware level whenever i feed a program to 8051.

A: Opcode - the unique identifier for each possible instruction that a computer can run. Physically, it is a unique string of binary bits which is represented in Assembler as a token (so a human can read it without memorizing a string of ones and zeroes)
Program - a bunch of ones and zeroes (or low and high electrical signals) consisting of the sequence of opcodes and their arguments (numbers) to be executed when the system runs.
Program Memory - This physically stores the program. The ones and zeroes are physically stored in a configuration transistors. In SRAM, the transistors act as a form of latch to tie the node to either the positive voltage rail or GND, which represent either HI or LO.
In DRAM, the voltage is stored inside the parasitic capacitor that is parts of a transistor.
In flash, it is stored as a charge inside the structure of the transistor that modifies the transistor's behaviour. This might sound like a capacitor, but it isn't.
On a magnetic harddrive it is stored as the polarity of a ferromagnetic domain.
Opcode circuitry - the physical manifestation of the opcode. It is circuitry that reads the appropriate arguments that it will operate with or on from the instruction register, processes them, and loads the result somewhere. Each opcode has one and the this circuitry will processes the data and delivers the result into a register somewhere.
Instruction Register - the register that stores the instruction line which is about to be parsed and read/decoded/translated. It is loaded from wherever the program counter register is pointing at in the bits that form the program memory
Instruction Decoder - this circuitry reads the opcode ID field in the instruction register and sends a signal to activate the appropriate opcode circuitry which results in execution of the opcode.
It's basically a giant comparison engine that compares the current opcode against a bunch of available opcodes and if it matches, it outputs a signal to trigger the associated opcode circuitry. One way to imagine it is as an array of multi-bit comparators with each comparator having an output to trigger one of the opcode circuits. Each comparator examines the bits in the field of the instruction register that represents the opcode ID and compares it against a fixed value which is the bits for the opcode ID it is responsible for. If it matches, it fires a signal to the opcode circuitry to trigger it.
Or you can imagine it as a giant lookup table that takes the bits in the opcode ID field of the instruction register as an input. It's output consist of one signal line going to each opcode circuit to trigger it. The lookup table is such that only one signal line is active for any given valid input (after all, you don't want a single opcode to end up triggering two opcode circuits to run. That just doesn't make sense.)
The decoder also reads the bits in the fields of the instruction register that represent the arguments for that opcode and passes them on to the opcode circuitry so it knows what it is working with. It is a crazy, chip spanning network of signals. Alternatively, the opcode circuitry might directly access those other fields in the instruction register to obtain their operands.
So in a sense, it is just a highly evolved version of a circuit consiting of AND gate circuit where one input is fed with a toggle switch and the other input is fed with a 1 or 0, depending on when you want the activity to trigger, and the output feeds a circuit that "does something specific".


text:
Q: Declaring mime type for html-email I want to create a html email and I've read a lot about how to do it. There is one piece of information I can't find. How should I declare the mime type? I tried with:
meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

but it doesn't work.
Later edit:
I am trying to set the content-type of the mail to text/html but I don't know how. All this when writing from a regular email client. I have to declare it in the mail body? Or in the mail header (if so, how do I o it?)?

A: The end tag for meta tag is used only in xhtml/xml. If you are using html, you should use it inside <head> tags like:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

A: Basically email clients ignore any META tags with Content type in them (at least as of 2013-10-17).
You need to set a the content type declaration in a special header in the email server.
More information about this issue can be found at http://www.emailonacid.com/blog/details/C13/the_importance_of_content-type_character_encoding_in_html_emails
If this makes no sense to you, then I'm afraid you're out of luck. The only reliable solution I've found is to convert any special characters to their HTML entity equivalent. The link above has a link to a tool that does this for you.
Hope that helps!

A: Are you trying to set the content-type declaration within the message header sent to the mail server? If so, you should set it this way, in a line itself:
Content-Type: text/html; charset=UTF-8

A: This applies to php:
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';

// Additional headers
$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';

// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));

http://php.net/manual/en/function.mail.php#example-4180


text:
Q: Webpack not creating submodules in the library namespace I'm trying to build a Webpack config allowing me to create multiple modules in a specific namespace. I have a the following config:
module.exports = {
    entry: {
        'one': './src/modules/one/one.module.js',
        'two': './src/modules/two/two.module.js',
        'three': './src/modules/three/three.module.js',
    },
    output: {
        filename: '[name].module.js',
        path: path.resolve(__dirname, 'dist'),
        library: ['myModules', '[name]'],
        libraryTarget: 'umd',
    },
    ...
};

The problem is, that it creates a global namespace: myModules, but the submodules are not visible. I'm not able to create a new instance by running new window.myModules.one();. How can I fix that?

A: Assuming that you're using ES modules and that you have a default export for each module, you would have to access the default property.
new window.myModules.one.default();

Webpack 3 added the output.libraryExport option, which allows you to assign a specific export to the library target. Instead of having an object with the exports, you could have just the default export in place. For this you need to set output.libraryExport to 'default'.
output: {
    filename: '[name].module.js',
    path: path.resolve(__dirname, 'dist'),
    library: ['myModules', '[name]'],
    libraryTarget: 'umd',
    libraryExport: 'default',
},

With that you can use it as you've wanted.
new window.myModules.one();


text:
Q: How to represent an interaction term with three continuous variables? I built a model estimating the survival probabilities of birds based on 1. PC1 scores, 2. PC2 scores (for both, I have more than 2000 points), and 3. a climate variable (a total of 12 climate variables which represent the different sampling years). I'm particularly interested in the estimation of the interaction between climate and PC1, and climate and PC2.
I want to find a way to represent that interaction. I understand that usually, people are representing the interaction as 2 lines. If they cross, there is an interaction.
In my model, I have linear and quadratic term which makes it more difficult to see the "lines crosses". If two parabola are crossing, is this considered as an interaction?
I also saw people representing 3d interactions like this.
This is what I have so far. (You can download the file and open it in your browser to see it properly.)
So here are my questions:

*

*Does an interaction in 3D is the crossing of surfaces or the way they are warped?

*How should I represent that interaction so that it's meaningful?

*Is it more difficult to find mathematically a significant interaction between variables in 3D?

Here is an example I did so far. Does that make sense? Do you think there is a better way to represent that interaction? Does it look like (without looking at the parameter value) there is an interaction?


text:
Q: ".eth() method not found" when returning Http struct in a function I want to establish an http connection to a Ganache test blockchain.
Going through the GitHub page of the web3 crate I found this example:
#[tokio::main]
async fn main() -> web3::Result<()> {
    let _ = env_logger::try_init();
    let transport = web3::transports::Http::new("http://localhost:7545")?;
    let web3 = web3::Web3::new(transport);

    let mut accounts = web3.eth().accounts().await?;

    ...

    Ok(())
}

However I want to implement the connection setup in a function. So I tried the following:
async fn establish_web3_connection_http(url: &str) -> web3::Result<Web3<Http>>{
    let transport = web3::transports::Http::new(url)?;
    Ok(web3::Web3::new(transport))
}

...

#[tokio::main]
async fn main() -> web3::Result<()> {
    let web3_con = establish_web3_connection_http("http://localhost:7545");

    println!("Calling accounts.");
    let mut accounts = web3_con.eth().accounts().await?;

    Ok(())
}

This results in the following error:
Error
I am not sure why I do not return the correct value. There is not error when I
don't call web3_con, so the function seems to be fine.
Is the return value somehow wrong, or how I call it?

A: establish_web3_connection_http() is an async function, so it returns a future. You're trying to call .eth() on the future, when you probably want to call it on the value produced by the future.  You need to await the result of this function:
let web3_con = establish_web3_connection_http("http://localhost:7545").await?;
//                                                                    ^^^^^^^

However, you don't do any awaiting in establish_web3_connection_http(), so there's no reason it needs to be async in the first place.  You could just remove async from its signature instead:
fn establish_web3_connection_http(url: &str) -> web3::Result<Web3<Http>>{


text:
Q: How to implement Mongodb connection pooling in lambda function using pymongo I am using aws lambda function, python and monogdb atlas. I have executed  the below code.
client = MongoClient('mongodb+srv://app_user:123456@accesdev-dxjpa.mongodb.net/test')
db = client.test

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=1))
    user_profile = db.user_profile
    Email = event['email']
    res = Email.find('@')
    if res == -1:
        disuname = list(user_profile.find({"username" : Email},{"name": 1, "photo": 1, "bio": 1}))
        uid = json.dumps(disuname, default=json_util.default)
        return json.loads(uid)

    else:
       disuname = list(user_profile.find({"email": Email},{"name": 1, "photo": 1, "bio": 1}))
       uid = json.dumps(disuname, default=json_util.default)
       return json.loads(uid)

In this above code execute, mongodb connections size will increase and it will reach maximum size. I heard the concept of mongodb connection pooling but i didn't understand how to implement it in pymongo in lambda function. Can you please help me the solution.

A: These below lines are from the link given below, this should be a great explanation or a better starting point - Please read through :
Every MongoClient instance has a built-in connection pool per server in your MongoDB topology. These pools open sockets on demand to support the number of concurrent MongoDB operations that your multi-threaded application requires. There is no thread-affinity for sockets.
The size of each connection pool is capped at maxPoolSize, which defaults to 100. If there are maxPoolSize connections to a server and all are in use, the next request to that server will wait until one of the connections becomes available.
The client instance opens one additional socket per server in your MongoDB topology for monitoring the server's state.
For example, a client connected to a 3-node replica set opens 3 monitoring sockets. It also opens as many sockets as needed to support a multi-threaded application's concurrent operations on each server, up to maxPoolSize. With a maxPoolSize of 100, if the application only uses the primary (the default), then only the primary connection pool grows and the total connections is at most 103. If the application uses a ReadPreference to query the secondaries, their pools also grow and the total connections can reach 303.
It is possible to set the minimum number of concurrent connections to each server with minPoolSize, which defaults to 0. The connection pool will be initialized with this number of sockets. If sockets are closed due to any network errors, causing the total number of sockets (both in use and idle) to drop below the minimum, more sockets are opened until the minimum is reached.
The maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced can be set with maxIdleTime, which defaults to None (no limit).
The default configuration for a MongoClient works for most applications:
client = MongoClient(host, port)

Create this client once for each process, and reuse it for all operations. It is a common mistake to create a new client for each request, which is very inefficient.
To support extremely high numbers of concurrent MongoDB operations within one process, increase maxPoolSize:
client = MongoClient(host, port, maxPoolSize=200)

… or make it unbounded:
client = MongoClient(host, port, maxPoolSize=None)

Once the pool reaches its maximum size, additional threads have to wait for sockets to become available. PyMongo does not limit the number of threads that can wait for sockets to become available and it is the application's responsibility to limit the size of its thread pool to bound queuing during a load spike. Threads are allowed to wait for any length of time unless waitQueueTimeoutMS is defined:
client = MongoClient(host, port, waitQueueTimeoutMS=100)

A thread that waits more than 100ms (in this example) for a socket raises ConnectionFailure. Use this option if it is more important to bound the duration of operations during a load spike than it is to complete every operation.
When close() is called by any thread, all idle sockets are closed, and all sockets that are in use will be closed as they are returned to the pool.
Ref: Connection pooling in pymongo


text:
Q: Display series labels at the end of each line in Highcharts Editor I am a beginner in Highcharts and I am trying to achieve what has been explained in the following case using the Highcharts Editor:
Highcharts Line Chart, display series name at the end of line series
I don't know if the same can be achieved by just using the Editor's interface but if custom code needs to be used, I can do that in the Custom Code tab of the Editor.
I tried inputting in the Custom Code section of the Highcharts Editor the code written by jlbriggs but nothing happens.
Is it possible to get a basic explanation on how to achieve what I want?
Below is the HTML code I took from the graph I created in Highcharts Editor.

I just need the names of each series to be displayed at the end of each line rather than in the legend.

A: In the "Custom code" section you need to merge your custom options with the options from the editor. There should be an example of how to do that. In essense:
Highcharts.merge(true, options, {
  // custom code
});

For example, you could use Highcharts.merge in the following way to achieve this:
Highcharts.merge(true, options, {
  plotOptions: {
    series: {
      dataLabels: {
        enabled: true,
        formatter: function () {
          // if last point
          if(this.point === this.series.data[this.series.data.length-1]) {
            return this.series.name;
          }
        }
      }
    }
  }
});

See this Highcharts Cloud example of it in use.


text:
Q: Script to move or unpack files (rtorrent when finished script) The concept
So I´ve been struggling for a while now with a script that will run when rtorrent has finished a download. The script should check the third argument from rtorrent and act accordingly.
.rtorrent.rc:
system.method.set_key = event.download.finished,unrar_move_files,"execute={/home/holmen/script/testrt.sh,$d.get_base_path=,$d.get_name=,$d.get_custom1=}"

The script looks like this:
#!/bin/bash
# First, copy the downloaded material to the storage drive
# then unpack the files (if the unrar returned successful)
# lastly remove the rar files with rm -rfv command

hdfilm1=/media/store1/HD-film
hdfilm2=/media/store2/HD-film
download=/media/store3/Download

# Copy the downloaded material to correct storage drive
rsync -r --info=progress2 "$download"/"$2" "$3"

if [ "$3" = "$hdfilm1" ] || [ "$3" = "$hdfilm2" ]; then
        # Check folders and subfolders of the downloaded material
        while IFS= read -r dir; do
                # Find and unpack archive files
                if [ "$(find $dir | egrep -i '\.r00|\.001|part01\.rar|part001\.rar|subs\.rar')" ]; then
                        rarFile=`ls $dir | egrep -i '\.r00|\.001|part01\.rar|part001\.rar|subs\.rar'`;
                        searchPath="$dir/$rarFile"
                        yes no | nice -n 15 unrar x -o+ "$searchPath" "$dir"
                        remFile=`ls $dir | egrep -i '\.(rar|sfv|r([0-9]{2}))$'`;
                        remPath="$dir/$remFile"
                        rm -rfv $remPath
                fi
        done < <(find "$3"/"$2" -type d)
fi

This works basically but i have trouble when trying to delete the archive files (after they are unpacked). When adding a remove script in the while loop the script just removes files in the specific subfolder its in at the moment.
The script unpacks:
/media/store1/HD-film/Movie.folder/*.rar
/media/store1/HD-film/Movie.folder/Subs/*.rar

but only removes the rar files in this folder
/media/store1/HD-film/Movie.folder/Subs/

How can I fix so my script removes the archive files also in the parent folder?
Edit: I have tried putting the rm command after the unrar command with && but the result is the same.
if [ "$(find $dir | egrep -i '\.r00|\.001|part01\.rar|part001\.rar|subs\.rar')" ]; then
     rarFile=`ls $dir | egrep -i '\.r00|\.001|part01\.rar|part001\.rar|subs\.rar'`;
     searchPath="$dir/$rarFile"
     remFile=`ls $dir | egrep -i '\.(rar|sfv|r([0-9]{2}))$'`;
     remove="$dir/$remFile"
     yes no | nice -n 15 unrar x -o+ "$searchPath" "$dir" && rm -rfv "$remove"
fi

A: I've found a solution for my problem with this script unrarall. I've implemented it in my script.
#!/bin/bash

# Variables
hdfilm1=/media/store1/HD-film
hdfilm2=/media/store2/HD-film
tvshow1=/media/store0/Serier
tvshow2=/media/store2/Serier
download=/media/store3/Download

# Copy the downloaded material to correct storage drive
rsync -r --info=progress2 "$download"/"$2" "$3"

if [ "$3" = "$hdfilm1" ] || [ "$3" = "$hdfilm2" ] || [ "$3" = "$tvshow1" ] || [ "$3" = "$tvshow2" ]; then
        /home/holmen/script/unrarall --clean=rar,proof_folders,sample_folders,sample_videos,empty_folders "$3"/"$2"
fi


text:
Q: Show different output based on the ${selectedcount} I wants the Prediction Formula  to display as:
if ${selectedcount} > 30
Display as ${selectedcount} / 3 + 5
if ${selectedcount} < 30
Display as ${selectedcount} / 3 - 5
P/S: Not the calculation but just the formula

Currently the Prediction Formula row doesn't captured the ${selectedcount} from Current total number of students as shown below:
Screencapture

I've removed some unrelated codes, I hope it helps. Please assist on the above. Thank you.
Expected output
if ${selectedcount} > 30

if ${selectedcount} < 30

A: Store the sign and denominator before rendering based on your condition.
Something like this.
function myFunction() {

   var predicDenom = parseInt(selectedcount) > 30 ? '3+5 : '3-5'; //Store the denominator based on number of students
   var predicSign = parseInt(selectedcount) > 30 ? '>' : '<'; // Also store the sign

    document.getElementById("demo").innerHTML = `

         Current total number of students:
         ${selectedcount} students

    Prediction Formula:
    Number of students ${predicSign} 30
 Average = number of students / ${predicDenom}

`

  }


text:
Q: Unable to use Google Calendar API in Meteor - OAuth problems? I'm working on a web app that uses the Google Calendar API (for now, I just want to be able to retrieve and display a list of events from a calendar), but I haven't been able to properly make the API call. Technically, it is made, but I don't get a response since I'm not authenticated. I know I need OAuth credentials, but I'm not sure where exactly to set those up (I already have my client id and secret).
Here is my code, in body.js:
import { Template } from 'meteor/templating';
import { HTTP } from 'meteor/http'

import './body.html';

Template.body.helpers({
    test() {
        HTTP.get("https://www.googleapis.com/calendar/v3/calendars/michelleran707@gmail.com/events", function(error, response) {
            console.log(response);
        });
    },
});

And in body.html, I call test in a random place using {{test}}. (I'm not sure if this is correct code, since I'm new to Meteor.)
As for OAuth, I searched around and this was the code I ended up using:
import { Accounts } from 'meteor/accounts-base'

Accounts.loginServiceConfiguration.remove({
  service: "google"
});

Accounts.loginServiceConfiguration.insert({
  service: "google",
  clientId: "my id",
  secret: "my secret"
});

Both of these JavaScript files I've imported into main.js. However, I'm still unable to properly make the API call. What am I missing?

A: Resolved - I tinkered with the code from the official Quickstart and got the OAuth working. Seems like I just overlooked that in the beginning.


text:
Q: My StackExchange DataExplorer Account doesn't show up in my Accounts! I recently got my StackExchange DataExplorer Account. Why doesn't show up on my normal account under "Accounts"?
Is StackExchange DataExplorer somehow special?

A: The data explorer isn't as tightly integrated into the network as the Q&A sites, StackExchange.com, and Area 51 are.  This is status-bydesign, for a couple reasons.

*

*Data Explorer is an open source project, tight integration with our login system becomes complicated accordingly

*Unlike the other sites, your activity on data.se isn't really likely to be of much interest to other members of the community

*It'd be a really weird fit display wise, Area 51 is already a bit odd out but Data.SE is really wildly different


text:
Q: React Weather Application not fetching the data when it is online I am trying to learn react and try to make a simple react app. It has some bugs that I could not fixed them like to get the weather dat submit button needs to clicked twice.  At least, I was getting the weather when I click twice:) on the local. The main problem start when I upload it netlify for deploying https://myweatherapp12.netlify.app  This is the link if you want to check it. When I submit the form, it does not fetch the data from weather API.
I add the code that handle the onSubmit. Thanks for help..

function updateInput(event) {
    event.preventDefault();
    setcity1(city);
    setcountry1(country);
     const API_KEY = "49354479869ae18d7dfbe48bbd9eced7";
    fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city1},$Turkey&appid=${API_KEY}`).then((res) => { if (res.status >= 200 && res.status < 299) { return res.json() } else { sethata(true) }}).then((data) => setweatherResponse(data));

    setgoster(true);
    console.log(city1);
    console.log(country1)


text:
Q: Biber with printglossaries Texmaker I'm trying to compile my document with Biber and the glossary in Texmaker. However, my glossary never compiles.
I edited Bib(la)tex so that it points to Biber's location in Texlive.
\documentclass{report}

\usepackage[english]{babel}

\usepackage{sectsty}
\usepackage{graphicx}
\usepackage[acronym, automake]{glossaries}
\input{glossary-entries}
\usepackage{framed}

\makeglossaries

\usepackage[backend=biber, style=apa, sorting=none]{biblatex}
\addbibresource{references.bib}

\usepackage{fullpage}

\edef\restoreparindent{\parindent=\the\parindent\relax}
\usepackage{parskip}
\restoreparindent

\makeindex

\begin{document}
\pagenumbering{Roman}

\chapterfont{\centering}

\pagebreak
\setcounter{page}{3}

\tableofcontents{}

\chapter{Chapter 1}

\pagenumbering{arabic}

\pagebreak

\section{Section 1.1}

\section{Section 1.2}

\acrlong{SoC}

\section{Section 1.3}

\chapter{Chapter 2}

\section{Section 2.1}

A \gls{test}

\section{Section 2.2}

\section{Section 2.3}

\subsection{subsection 2.3.1}

\subsection{subsection 2.3.2}

\chapter{Chapter 3}

\printbibliography

\printglossary
\printglossary[type =\acronymtype]

\listoffigures

\end{document}

The glossary file is not required but here it is:
\addcontentsline{toc}{chapter}{Thischapter}

\newglossaryentry{test}{
name = test,
description ={test}
}

\newacronym{SoC}{SoC}{SoC}

I can get my bibliography with "pdflatex" -synctex=1 -interaction=nonstopmode %.tex|"path_to_biber/biber" %.bcf|"pdflatex" -synctex=1 -interaction=nonstopmode %.tex|"pdflatex" -synctex=1 -interaction=nonstopmode %.tex|open %.pdf (PdfLatex + Bib(la)tex + PdfLatex (x2) + View PDF). However, if I try to run these 5 commands one by one I run into warnings. Why? Those warnings are not required since it compiles if I directly run the command as a Quick Build but here they are:
PdfLatex:
LaTeX Warning: Command \underbar has changed.
LaTeX Warning: Command \underline has changed.
Package biblatex Warning: 'babel/polyglossia' detected but 'csquotes' missing.

Bib(la)tex: works
PdfLatex (x2): same errors as above.
I would like to know which user command I should create in user commands to compile bibliography and glossary in my document. I would like the acryonyms to appear on the page where the glossary appears. How can I make them appear in the table of contents?
Thanks in advance.

A: I think the MWE I put together will answer your three questions.
In my system (TeXstudio)  the code runs several times automatically until it finish. (pdflatex.exe -synctex=1 -interaction=nonstopmode   -shell-escape %.tex)
Otherwise after a couple of compiles you should run biber, and compile again twice.
makeindex runs on every build. But if the glossay did not appear run makeindex and compile again.
The  LaTeX Warning: Command \underbar  has changed. Check if current package is valid. is coming from sectsty.sty. Don't worry unless you want use sectsty for underlining section titles.
Add \usepackage{csquotes} to the preamble. Loading csquotes is recommended when using babel or polyglossia together biblatex, so quoted texts are typeset using to the rules of the  main language.

Try this code.
% !TeX TS-program = pdflatex

\documentclass{report}

\usepackage[english]{babel}

\usepackage{sectsty}  % LaTeX Warning: Command \underbar  has changed.
\usepackage{graphicx}
\usepackage{framed}

\usepackage[acronym, automake,toc, section=section]{glossaries} % show as section

\newglossaryentry{test}{%
    name = {random test},
    description ={a random test done by a nonexpert user}
}

\newacronym{SoC}{SoC}{System on a Chip}

\makeglossaries
\glstoctrue % put Glossary and Acronyms in TOC

\usepackage{csquotes} % for biblatex <<<<<<<<<<<<
\usepackage[backend=biber, style=apa, sorting=none]{biblatex}
\addbibresource{biblatex-examples.bib}  % using .bib included in the distribution

\usepackage{fullpage}

\edef\restoreparindent{\parindent=\the\parindent\relax}
\usepackage{parskip}
\restoreparindent

%\usepackage{imakeidx}% Required to make an index
%\makeindex % Create the files required for indexing

\begin{document}
    \pagenumbering{Roman}

    \chapterfont{\centering}
    \pagebreak
    \setcounter{page}{3}

    \tableofcontents

    \chapter{Chapter 1}

    \pagenumbering{arabic}
    \pagebreak

    \section{Section 1.1}

    \section{Section 1.2}

    \acrlong{SoC}

    \section{Section 1.3}

    \chapter{Chapter 2}
    \section{Section 2.1}
    \section{Section 2.2}
    \section{Section 2.3}
    \subsection{subsection 2.3.1}
    \subsection{subsection 2.3.2}

    \chapter{Chapter 3}

    Doing a \gls{test} on a \acrlong{SoC} might be inconclusive and might breaks everything. See \autocite{companion}.

    \printbibliography

    \chapter{All together}
    \printglossary
    \printglossary[type =\acronymtype]

    \listoffigures

\end{document}


text:
Q: Encrypting on NETMF, decrypting on .NET I was trying to use XTEA encryption on NETMF using the code from blog post Encryption Compatibility Between .NET Micro Framework and the Full .NET Framework. The code used on the micro framework is the following.
public static string Encrypt(string message)
{
    var key = "0x081632";
    var data = Encoding.UTF8.GetBytes(message);
    var xteaKey = Encoding.UTF8.GetBytes(key);
    var xtea = new Key_TinyEncryptionAlgorithm(xteaKey);
    var encryptedBytes = xtea.Encrypt(data, 0, data.Length, xteaKey);
    var encryptedString = ConvertBase64.ToBase64String(encryptedBytes);
    return encryptedString;
}

The Base64 result is sent to an Azure web service. However, I am unable to decrypt this. I have tried several situations, but the .NET code is returning different results for the same key and message on .NET and NETMF.
Is there a solution for this situation, or any other encryption scheme I can use? I prefer not to use RSA, as it can be a real performance hit on NETMF.
Decryption code.
var k = Encoding.UTF8.GetBytes("0x081632");
message = message.Replace("!", "+").Replace("*", "/"); // base64 on .netmf is different
var m = Convert.FromBase64String(message);
var xteaNet = new Key_TinyEncryptionAlgorithm(k); // class from blog
var decBytes = xteaNet.Decrypt(m, 0, m.Length, k);
var decString = Encoding.UTF8.GetString(decBytes);

It may be a little/big endian difference, but I'm not sure what parts of the code would have to be changed to allow for this.
For testing, I tried to encode with data 8 long, and key 8 long, and now the result on both systems are equal. Data is "01234567", key is "0x081632", result after base64 "2BwR4Xe2sIk=".

A: I created a new .NET micro framework v4.1 console application using a copy/paste of the encrypt method.
In the same solution I added a new .NET 4.0 test project, which referenced the sample Key_TinyEncryptionAlgorithm class from the blog. I used the returned value from the Encrypt method 2BwR4Xe2sIk= and this was used as the test data for the unit test which decrypted the string successfully back into 01234567.
I would assume your transport mechanism is causing the problem. The message over the wire is being modified and so what arrives at your service is not equivalent to what left the device.
Perhaps just a classic serialization problem...
All x86 and machines are little-endian. The .NET Micro Framework emulator reports via SystemInfo.IsBigEndian that the emulated environment is little-endian as well.
It is common to tranmit data over a network in big-endian order though. If you want to reverse the bytes on the recieving end the following method should flip the order for you. I put this into the Key_TinyEncryptionAlgorithm class.
private static byte[] ReverseBytes(byte[] inArray)
{
  byte temp;
  int highCtr = inArray.Length - 1;

  for (int ctr = 0; ctr < inArray.Length / 2; ctr++)
  {
      temp = inArray[ctr];
      inArray[ctr] = inArray[highCtr];
      inArray[highCtr] = temp;
      highCtr -= 1;
   }
   return inArray;
}

And usage in the decryption method.
Console.WriteLine(BitConverter.ToString(m));
m = Key_TinyEncryptionAlgorithm.ReverseBytes(m);
Console.WriteLine(BitConverter.ToString(m));

Produces this output

D8-1C-11-E1-77-B6-B0-89
89-B0-B6-77-E1-11-1C-D8


text:
Q: Java generics warning requiring guru meditation I have some Java code like the following snippet (the example is simplified from the original code). A yellow squiggle and warning message appear, as indicated by the code comment below. The message is: "This method invocation is unsafe since the passed arguments may be of a wrong type."
abstract class Seek<T> {
    abstract <S> Seek<S> seek(S... o);
    abstract <T2> void map(Func<T,T2> call);
    interface Func<I,O> {
        public O call(I x);
    }
    public <X2> void go(Func<T,X2> c, T some) {
        seek(some).map(c); // <- yellow squiggle here on 'c'
    }
}

Why does the warning appear? What is the best way to fix this?
Note:
I'm using the AIDE development environment for Android.
EDIT: I fixed an error in the code after reading the answer from @tsolakp and @LouisWasserman.

A: map should only have T2 as a type parameter, not T.  Right now the T shadows the T from the Seek<T> class, that is, you have two type variables named T that are actually different, and you don't want that.

A: Actually there are three warnings in that code:

*

*
Type safety: Potential heap pollution via varargs parameter o
  at abstract <S> Seek<S> seek(S... o);

*
The type parameter T is hiding the type T at abstract <T,T2> void map(Func<T,T2> call);

*
Type safety: A generic array of X1 is created for a varargs parameter at seek(some).map(c);

It can be clean of warnings
A. take out varargs parameter from generic like:
abstract class Seek<T> {
   abstract <S> Seek<S> seek(S o); // <- no more yellow squiggle
   abstract <T1,T2> void map(Func<T1,T2> call); // <- no more yellow squiggle
   interface Func<I,O> {
      public O call(I x);
   }
   public <X1,X2> void go(Func<X1,X2> c, X1 some) {
      seek(some).map(c); // <- no more yellow squiggle here on 'c'
   }
 }

B. define arrays explicitly like:
  abstract class Seek<T> {
  abstract <S> Seek<S> seek(S[] o);        // <- no more yellow squiggle
  abstract <T2> void map(Func<T,T2> call); // <- no more yellow squiggle
  interface Func<I,O> {
    public O call(I x);
  }
  public <X1,X2> void go(Func<X1,X2> c, X1[] some) {
    seek(some).map(c); // <- no more yellow squiggle
  }
}

but,  S[] o is quite not the same as S... o.  It can take only Array explicitly. Maybe you need to reconsider your design?
IMHO: I really do not understand needs to have that many Generic type parameters at the same time on class and methods level...

A: The warnings I get from compiling your code are related to the generic array creation from the seek(S...) method.
If you can change this to be a List<S>, you can invoke it using Arrays.asList():
abstract class Seek<T> {
    abstract <S> Seek<S> seek(List<S> o);

    // ...

    public <X1,X2> void go(Func<X1,X2> c, X1 some) {
        seek(Arrays.asList(some)).map(c);
    }
}

A: Change T to T1 in the map method.
You will also get generic array warning too. Here is modified version with no warnings:
abstract static class Seek<T> {

    abstract <S> Seek<S> seek(List<S> s);

    abstract <T1,T2> void map(Func<T1, T2> call);

    interface Func<I,O> {
        public O call(I x);
    }

    public <X1,X2> void go(Func<X1,X2> c, X1 some) {
        seek( Arrays.asList(some) ).map(c);
    }
}

After some comments it appers that OP might have intended to make map method to be bound with Seek class generic type. If thats the case we can use this solution, as suggested by @Louis Wasserman and @Andy Turner:
abstract static class Seek<T> {

    abstract <S> Seek<S> seek(List<S> s);

    abstract <T2> void map(Func<T, T2> call);

    interface Func<I,O> {
        public O call(I x);
    }

    public <X1,X2> void go(Func<X1,X2> c, X1 some) {
        seek( Arrays.asList(some) ).map(c);
    }
}


text:
Q: Reflection issue of Android BluetoothService class I want to call some methods like isEnabled(), getAddressFromObjectPath(), etc. of BluetoothService class, but this class is mark with @hide.
I know I have two possible ways to do what I want, one is remove the @hide, and the other is using reflection. I choose to use second one.
From the example of source code, I found that
    Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
    IBinder b = (IBinder) method.invoke(null, "bluetooth");

    if (b == null) {
        throw new RuntimeException("Bluetooth service not available");
    }

    IBluetooth mBluetoothService = IBluetooth.Stub.asInterface(b);

However, what it gets is the IBluetooth not BluetoothService although BluetoothService extends IBluetooth.Stub indeed.
So my questions are as follows:
(1) Could I get the BluetoothService class by reflection just like previous example code ?
(2) If my first question is negative, I call getAddressFromObjectPath() directly by reflection method like following
    Method method = Class.forName("android.server.BluetoothService").getMethod("getAddressFromObjectPath", String.class);
    String b = (String) method.invoke(???, PATH);

what the object dose I need to fill in the invoke() method, BluetoothService ???
Any suggestion would be greatly appreciated !!!

A: After surveying on the internet, I got the answer. If I want to invoke a non-static method, I need to get the class and constructor first. Use the constructor to construct the instance and  then I could invoke the non-static method by this instance.
However, I could not do that on BluetoothService class because if I do the constructor again, it would cause a lot of problem !
I decide to modify the IBluetooth.aidl to add the methods I need because BluetoothService extends IBluetooth. If I could get the IBluetooth instance, I could call the methods I need. Maybe, this is not a good solution but I think it would work.
Thanks a lot.


text:
Q: Feature Detection in OpenCV Python Bindings I've combed the web looking for a way to get the OpenCV 2.3.1a feature extraction/descriptor bindings to spit out any flavor of image features/descriptors(STAR/SURF/ORB/SIFT/FAST). I am well aware that OpenCV has a method called "goodFeaturesToTrack. This doesn't help me as there are no feature descriptors (which is what I really need). I have followed the documentation as listed here:
http://opencv.itseez.com/modules/features2d/doc/feature_detection_and_description.html
Nothing seems to work. I've tried all of the flavors of descriptors/features. I've tried using single and multiple channel images (i.e. color and black and white) and multiple image formats (8bit and 32f). I have worked with the current distribution and building the bindings from the source repo. Most of the methods result in a "unknown is not a numpy array" error. Here is an example:
SimpleCV:1>import cv2
SimpleCV:2>img = Image("aerospace.jpg")
SimpleCV:3>bwimg = img._getGrayscaleBitmap()
SimpleCV:4>bwimg
SimpleCV:4><iplimage(nChannels=1 width=600 height=400 widthStep=600 )>
SimpleCV:5>surfer = cv2.SURF(0.5,4,2,False,False)
SimpleCV:6>points = surfer.detect(bwimg,None)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/Library/Python/2.6/site-packages/SimpleCV-1.2-py2.6.egg/SimpleCV/Shell/Shell.pyc in <module>()
-

TypeError: <unknown> is not a numpy array
SimpleCV:7>

It is worth noting that I am using SimpleCV to load the image, but the method _getGrayscaleBitmap() returns the gray 8bit IPL image used by OpenCV. I am sure this works as I use it with hundred of other OpenCV methods without incidence.
So can anyone point me to a WORKING example of this code on the web. I have combed through dozens of examples and found nothing that works.

A: Kat, this works for me:
s = cv2.SURF()
mask = uint8(ones(gray.shape))
keypoints = s.detect(gray,mask)

I can plot the key points and all. To get the descriptors you can try this
k,d = s.detect(gray,mask,False)
d = d.reshape((-1,128))
print d.shape, len(k)

d should have the same length at the list of key points.
I have this example in the OpenCV chapter here:
http://www.maths.lth.se/matematiklth/personal/solem/book.html

A: Looks like you have a PIL image. Try converting to a numpy image:
npImage = np.array(img)


text:
Q: Component Move file is causing java.io.IOException, and is trying to move to a wrong folder I have a Move file component in my flow:
<sub-flow name="MoveFileToErrorDirectorySubFlow" doc:id="51f387ca-5faa-4ba4-af87-008a1698e104" >
    <file:move doc:name="MoveFileToErrorDir" doc:id="c99d732d-2fc5-4512-b50d-c97c9b4e8aff" sourcePath="${invoices.import.path}" targetPath="${invoices.error.path}" config-ref="XMLFile"/>
</sub-flow>

invoices.import.path is pointing to /home/user/invoices/import/invoice
invoices.error.path should be pointing to /home/user/invoices/import/invoice/error
But when I am trying to run the flow by pasting a file into /home/user/invoices/import/invoice/
I get an error:

Message               : An error occurred while executing 'move' operation on file '/home/user/invoices/import/invoice' to '/home/user/invoices/import/invoice/error/invoice': Cannot move directory: /home/user/invoices/import/invoice to a subdirectory of itself: /home/user/invoices/import/invoice/error/invoice

First thing, why I am getting an error:

java.io.IOException: Cannot move directory: /home/user/invoices/import/invoice to a subdirectory of itself: /home/user/invoices/import/invoice/error/invoice

Second thing, why the target directory is /home/user/invoices/import/invoice/error/invoice instead of /home/user/invoices/import/invoice/error
Third thing, i am trying to move a file but it seems that it is trying to move a whole directory - to a wrong path as mentioned above...
What am I doing wrong here?

A: It seems that you are trying to move a directory (/home/user/invoices/import/invoice) instead of a file inside that directory (let say /home/user/invoices/import/invoice/report.csv as an example). The connector expects sourcePath path to be the path to the file, including the file name. The extension is part of the name by the way so don't miss it.
On the other hand, targetPath is expected to be a directory.
That explains all the issues.

*

*Your sourcePath points to a directory. You can not move a directory into one of its own subdirectories. That doesn't make sense in any file systems I know of.

*Because it is trying to move /home/user/invoices/import/invoice into /home/user/invoices/import/invoice/error, the resulting target would be to create an invoice sub directory of the error subdirectory, or /home/user/invoices/import/invoice/error/invoice.


text:
Q: Convert Salesforce IDs from 15 digit to 18 digit using sql code/function We are currently pulling in data from SalesForce to SQL Database tables.  There are 2 custom fields on different objects that were created for the Lead ID and a look up for which event/task is linked (this can be an account id, contact id, or lead id).  Both of these are pulling over the 15 digit ID.
I am trying to find out if there is any SQL code or a SQL function that will allow me to convert that 15 digit to an 18 digit ID.
I need to have that 18 digit ID to join back to the other objects.
We have already tried using the CASESAFEID(Id) function in SalesForce, but with the API that was already set up and the visibility levels our particular ETL is not showing that field.  Also, we would need to get a consultant to mess with the look up column.
I would like to take the 15 digit ID and convert it to the 18 digit code. If the SalesforceID is 0035000002tAzbu, how do I get the converted 18 digit value to be 0035000002tAzbuACC.  I need to get that last 3 digits using SQL query or SQL function.

A: you could write a custom function in your sql database.
e.g. in snowflake, you can make a function like this

CREATE OR REPLACE FUNCTION dw.my_schema.f_sfdc_ch15_to_ch18("txt" string)
    RETURNS string
    LANGUAGE JAVASCRIPT
    AS '
    if ( txt == undefined || txt == "" || typeof txt == "undefined" || txt == null) {
        return ;
    } else {
        var id15, id18;

        if (txt.length == 18) {
            return txt;
        } else if (txt.length == 15) {
            id15 = [txt.trim()];
        } else {
            return "";
        }
        for ( var x=0; x < id15.length; x++ ) {
            var s = "";
            for ( var i=0; i<3; i++) {
                var f = 0;
                for (var j=0; j<5; j++) {
                    var c = id15[x].charAt(i*5+j);
                    if (c>="A" && c<="Z") {
                        f+=1<<j;
                    }
                }
                s += "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345".charAt(f);
            }
            id18 = id15[x]+s;
        }
    }
    return id18.toString();
    ';

and use it like this
select dw.my_schema.f_sfdc_ch15_to_ch18(id15) from mytable;

A: This value can be computed. Check out this flowchart.
Source: https://stackoverflow.com/a/29299786/3135974


text:
Q: trying to get an absolute positioned div to center within another relative positioned div http://jsfiddle.net/zjRga/55/
I want a div to open up that will appear over top of the current div and won't shift the elements so I'm using absolute positioning, but I want it to be centered horizontally and vertically within that relative div wherever its at on the page and I can't seem to get it goin right.
UPDATE:
Solved. I was rackin my head on this for hours. For whomever this may help in the future
http://jsfiddle.net/zjRga/60/
Short answer: jQuery- element.position()

A: Your question is a little unclear. Here is a stab at what you may want: http://jsfiddle.net/zjRga/59/. Note the changes to #editItemDialog. If this is not exactly what you are looking for, I think at least it will show you how to center an absolutely positioned div that has a width and height set on it.

A: You need to check the height and width of the element you're centering on and set the top and left accordingly.
$('.labelEdit').click( function() {
    var x = $("#editDialog").width() / 2 - $("#editItemDialog").outerWidth() / 2;
    var y = $("#editDialog").height() / 2 - $("#editItemDialog").outerHeight() / 2;
    $("#editItemDialog").css({"top": y, "left": x});
    $('#editItemDialog').show('slow');
});

Basically, we're setting the top corner at the midpoint of the target div minus half the height of the dialog and the left at the midpoint minus half the width of the dialog.

A: $('#editItemDialog').hide();
$('#closeEditItemDialog').click( function() {
   $('#editItemDialog').hide('slow');
});

$('.labelEdit').hover( function() {
               $(this).parent().prev().css('border', 'solid 1px blue');
             }, function() {
                $(this).parent().prev().css('border', 'solid 1px white');
});

$('.labelEdit').click( function() {
   $('#editItemDialog').center();
   $('#editItemDialog').show('slow');

});
jQuery.fn.center = function () {
   this.css("position","absolute");
   this.css("top", (($(window).height() - this.outerHeight()) / 2) +        $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) +  $(window).scrollLeft() + "px");
return this;
}

I got this from this answer


text:
Q: Why might _CrtSetBreakAlloc not cause a breakpoint? I'm using Visual CRT's memory leak detection routines from <crtdbg.h>; when I call _CrtDumpMemoryLeaks one allocation is reported consistently on every invocation of the program:
{133} normal block at 0x04F85628, 56 bytes long.
 Data: <                > B0 81 F8 04 B0 81 F8 04 B0 81 F8 04 CD CD CD CD

The address varies but {133} is always the same.
According to MSDN's instructions on How to set breakpoints on memory allocation number, I should be able to set a breakpoint on the 133rd allocation with this call:
_CrtSetBreakAlloc(133);

and I can also verify in the watch window that {,,msvcr90d.dll}_crtBreakAlloc is indeed set to 133. After the program exits, the leak report still lists #133 (along with some higher numbers), but no breakpoint occurs. Why might this be and how do I get the breakpoint to occur?
Potentially relevant info:

*

*VS2008, using the "multi-threaded debug DLL" CRT

*My code is a DLL that gets loaded by a third-party product

*"Normal" breakpoints work just fine; stepping through works fine; __asm int 3 works fine too.

*No other value for _crtBreakAlloc causes a breakpoint either (not the ones I tried anyway)

*#133 is the lowest number in the leak report

A: Major forehead slapping... One "obvious" reason is if allocation #133 occurred before the breakpoint was set...
It's just that the first leak turns out to occur before my DLL gets invoked. In fact it's not necessarily a leak, because I call _CrtDumpMemoryLeaks when the DLL is unloaded - not when the parent application is done deinitializing.
As for "Potentially relevant info #4" in my original question - well I did try a few values, but somehow none were higher than 133...

A: It sounds like you might be compiling your app with a non-debug lib, eg. if you use the release version of the lib that should break your app, it will not do that. It's possible that this happens because you use the 3rd party app. It's also possible that the non-debug dll is loaded in place of the debug one at runtime.
Try to see if the right DLL-s are loaded for your app while debugging and also that the app or DLL is actually debugged. (Sometimes you explicitly have to load the dll or exe into the debugger.)
This is all that I can think of without seeing more details about this...


text:
Q: Setting image as bitmap in multiple imageViews I have two imageViews and when the user clicks on a button, it sends them to the gallery to choose an image. The image they choose then shows up in the imageView where they can then either do one of two things depending on what they are setting:
1) The background
2) The icon
I had the background working fine but now I am trying to include the option to set the icon. I have the imageView for the icon here (in widget.xml):
 <ImageView
    android:id="@+id/bwidgetOpen"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher"
    android:contentDescription="@string/desc"/>

Here is my two classes for the coding:
Personalize.java:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Personalize extends Activity implements View.OnClickListener {
Button button;
ImageView image;
ImageView image2;
Button btnChangeImage;
Button btnChangeImageForIcon;
Button btnSetBackground;
private static final int SELECT_PICTURE = 1;
private static final int SELECT_PICTURE_2 = 2;
private String  selectedImagePath;
Bitmap background;
Bitmap b2;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalize);
Log.d("Personalize", "OnCreate called");

image = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2Icon);

Button btnChangeImage = (Button) findViewById(R.id.btnChangeImage);
btnChangeImage.setOnClickListener(this);

Button btnChangeImageForIcon = (Button) findViewById(R.id.btnChangeImageForIcon);
btnChangeImageForIcon.setOnClickListener(this);

Button btnSetBackground = (Button) findViewById(R.id.btnSetBackground);
btnSetBackground.setOnClickListener(this);

Button btnLinkToFeedback = (Button) findViewById(R.id.btnLinkToFeedback);

Button btnSetIcon = (Button) findViewById(R.id.btnSetIcon);
btnSetIcon.setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnChangeImage:
launchImageChooser();
break;
case R.id.btnChangeImageForIcon:
launchImageChooser();
break;
case R.id.btnSetBackground:
setBackgroundImageInDragAndDrop();
break;
case R.id.btnSetIcon:
setIconImageInWidget();
break;
}
}

private void setIconImageInWidget() {
// TODO Auto-generated method stub
Log.d("Personalize", "setIconImageInWidget() called");
Intent i = getIntent();
//Convert bitmap to byte array to send back to activity
// See: http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android
scaleDownBitmapForIcon(b2, 500, this.getBaseContext());
Log.d("Personalize", "Scale Bitmap Chosen For Icon");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b2.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]byteArray = stream.toByteArray();

i.putExtra("myIconBitmap", byteArray);
setResult(RESULT_OK, i);
finish();
}

public static Bitmap scaleDownBitmap(Bitmap background, int newHeight, Context c) {

final float densityMultiplier = c.getResources().getDisplayMetrics().density;

int h= (int) (500*densityMultiplier);
int w= (int) (h * background.getWidth()/((double) background.getHeight()));

background=Bitmap.createScaledBitmap(background, w, h, true);
// TO SOLVE LOOK AT HERE:http://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
return background;
}

public static Bitmap scaleDownBitmapForIcon(Bitmap b2, int newHeight, Context c) {

final float densityMultiplier = c.getResources().getDisplayMetrics().density;

int h= (int) (500*densityMultiplier);
int w= (int) (h * b2.getWidth()/((double) b2.getHeight()));

b2=Bitmap.createScaledBitmap(b2, w, h, true);
// TO SOLVE LOOK AT HERE:http://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
return b2;
}

private void setBackgroundImageInDragAndDrop() {
Log.d("Personalize", "setBackgroundImageInDragAndDrop() called");
Intent i = getIntent();
//Convert bitmap to byte array to send back to activity
// See: http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android
scaleDownBitmap(background, 500, this.getBaseContext());
Log.d("Personalize", "Scale Bitmap Chosen");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
background.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]byteArray = stream.toByteArray();

i.putExtra("myBackgroundBitmap", byteArray);
setResult(RESULT_OK, i);
finish();
}

private void launchImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_PICTURE);
startActivityForResult(intent, SELECT_PICTURE_2);
Log.d("Personalize", "launchImageChooser called");
}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(column_index);
if(cursor != null) {
cursor.close();
}
return imagePath;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{

if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
    Uri selectedImageUri = data.getData();
    selectedImagePath = getPath(selectedImageUri);
    background = getAndDecodeImage(selectedImagePath);
    if(background != null){
        image.setImageBitmap(background);
    }
} else if (requestCode == SELECT_PICTURE_2)
{
    Uri selectedImageUri = data.getData();
    selectedImagePath = getPath(selectedImageUri);
    Bitmap b2 = getAndDecodeImage(selectedImagePath);
    if(b2 != null){
        image2.setImageBitmap(b2);
    }
}
}
}

private Bitmap getAndDecodeImage(String  selectedImagePath){
try {
    Log.d("Personalize", "selectedImagePath: " + selectedImagePath);
    FileInputStream fileis=new FileInputStream(selectedImagePath);
    BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
    byte[] bMapArray= new byte[bufferedstream.available()];
    bufferedstream.read(bMapArray);
    Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);

    if (fileis != null)
    {
        fileis.close();
    }
    if (bufferedstream != null)
    {
        bufferedstream.close();
    }
    return bMap;
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
return null;
}

public boolean saveImageToInternalStorage(Bitmap image) {
   try {
      FileOutputStream fos = this.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
      image.compress(Bitmap.CompressFormat.PNG, 100, fos);
      fos.close();
      return true;
   } catch (Exception e) {
   return false;
   }
}

}

Then Drag_and_Drop.java:
package com.example.awesomefilebuilderwidget;

IMPORTS

public class Drag_and_Drop_App extends Activity {
private static final int SET_BACKGROUND = 10;
private static final int SET_ICON = 20;

private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
public AppInfoAdapter adapter;
final SwipeDetector swipeDetector = new SwipeDetector();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // set layout for the main screen
    setContentView(R.layout.drag_and_drop_app);
    Log.d("D&D", "onCreate called");
}
public Bitmap getThumbnail(String filename) {
     Bitmap thumbnail = null;
     try {
     File filePath = this.getFileStreamPath(filename);
     FileInputStream fi = new FileInputStream(filePath);
     thumbnail = BitmapFactory.decodeStream(fi);
     } catch (Exception ex) {
     Log.e("getThumbnail() on internal storage", ex.getMessage());
     }
     return thumbnail;
     }

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     Log.i("Drag_and_Drop_App", "requestCode: " + requestCode + ", resultCode: " + resultCode);
     if(requestCode == SET_BACKGROUND && resultCode == RESULT_OK){
     byte[] byteArray = data.getByteArrayExtra("myBackgroundBitmap");
     Bitmap myBackground = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
     setBackgroundImage(myBackground);
     }
     else if(requestCode == SET_ICON && resultCode == RESULT_OK){
         byte[] byteArray = data.getByteArrayExtra("myIconBitmap");
         Bitmap myIcon = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
         setBackgroundImageForIcon(myIcon);
     }
     }

     @SuppressLint("NewApi")
     private void setBackgroundImage(Bitmap bitmap) {
     RelativeLayout yourBackgroundView = (RelativeLayout) findViewById(R.id.rl_drag_and_drop_app);

     Drawable d = new BitmapDrawable(getResources(), bitmap);

     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
     yourBackgroundView.setBackgroundDrawable(d);
     } else {
     yourBackgroundView.setBackground(d);
     }
     }

     @SuppressLint("NewApi")
     private void setBackgroundImageForIcon(Bitmap bitmap) {
     LinearLayout yourIconView = (LinearLayout) findViewById(R.id.widgetXMl);

     Drawable dq = new BitmapDrawable(getResources(), bitmap);

     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
     yourIconView.setBackgroundDrawable(dq);
     } else {
     yourIconView.setBackground(dq);
     }
     }

     }

The issue that I have right now is that when I click the button to choose a icon image, I go to the gallery and choose a picture but then it reloads the gallery and makes me choose another image (which ends up going to the other image view as well). How can I fix this?
Here is my Personalize.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/personalizetextView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/customize"
    android:textSize="30sp"
    android:gravity="center"
    android:layout_marginTop="20dip"/>

<TextView
    android:id="@+id/personalizetextviewChangeBackground"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/customizebackground"
    android:gravity="center" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:maxWidth="100dp"
    android:maxHeight="100dp"
    android:scaleType="fitCenter"
    android:contentDescription="@string/descForBackground"

    />

<Button
    android:id="@+id/btnChangeImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/change_background" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/set_background"
    android:id="@+id/btnSetBackground" />

 <TextView
    android:id="@+id/personalizetextviewChangeIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/change_icon"
    android:gravity="center" />

<ImageView
    android:id="@+id/imageView2Icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:maxWidth="100dp"
    android:maxHeight="100dp"
    android:scaleType="fitCenter"
    android:contentDescription="@string/descForIcon"
     />

<Button
    android:id="@+id/btnChangeImageForIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/change_icon" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/set_icon"
    android:id="@+id/btnSetIcon" />

  <Button
        android:id="@+id/btnLinkToFeedback"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@null"
        android:text="@string/Send_Feedback"
        android:textColor="#21dbd4"
        android:textStyle="bold" />

</LinearLayout>

Also, is there a way that I can clean up my code so that I am not repeating as much?
I understand that this is A BUNCH of code to look through but I would really apperciate it if someone could.
Thanks!

A: it reloads the gallery and makes me choose another image
Because you are calling startActivityForResult two times
startActivityForResult(intent, SELECT_PICTURE);
startActivityForResult(intent, SELECT_PICTURE_2);

in launchImageChooser(). change this code.


text:
Q: ggplot on ggmap with coloured point dependent on value My data set denotes the location (lat, long) of bee hives and how many in that location are positive for a parasite.
plotting the locations on a map is fine but I would like to change the colours of the points that have a parasite presence e.g. heading 'Positive' > 0
I have tried the following code but I can't + to a map it tells me it can't add 0 to a plot
myMap + ggplot(honeybee, aes(x= Long, y= Lat)) +
  geom_point(aes(colour = cut(Positive, c(-1, 0, 5))), size = 1) +
  scale_color_manual( values = c("red", "black"),
                     name = "Parasite", labels = c("Absent", "Present"))

Essentially I want the above code fitted to a ggmap

A: I am not sure where you get your map, since you did not include the data, but here's how you could do it with ggmap. There's no need to call ggplot again. Just include your honeybee datasource directly in the layer
library(ggmap)
m <- get_map("New York City", zoom=14,maptype="toner",source="stamen")
myMap <- ggmap(m)
honeybee <- data.frame(Lat=runif(20,min=40.69, max=40.73),
                       Long=runif(20, min=-74.03, max=-73.98),
                       Positive = rnorm(20))

myMap +
  geom_point(data=honeybee,
             mapping=aes(x= Long, y= Lat, colour = Positive>0),
             size = 5) +
  scale_color_manual( values = c("red", "yellow"),
                      name = "Parasite",
                      labels = c("Absent", "Present"))

Which produces


text:
Q: How to know whether my Android BroadcastReceiver is registered or not I am using an BroadcastReceiver for action related to sd card events like mount / unmount.
Now the situation is my receiver is not working. My application only have an BroadcastReceiver no GUI, no Activity, no layout. So now I want to debug the code so I want a message to be printed when I am installing the application. So I am looking for an method like an onCreate() which Service and Activity have. I have read the official document of BroadcastReceiver here
http://developer.android.com/reference/android/content/BroadcastReceiver.html
I was unable to find a method like that. So how can I know whether my android BroadcastReceiver is registered or not. Which method I have to use for getting the info whether my android BroadcastReceiver is registered or not. Is there any other way I can get the infothat mu receiver is registered and in tents are not working.
Here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceiversdcardinsertionremoval"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver
            android:name="SDCardStateChangeListener"
            android:enabled="true"
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_UNMOUNTED" />
                <action android:name="android.intent.action.MEDIA_REMOVED" />
                <action android:name="android.intent.action.MEDIA_EJECT" />
                <action android:name="android.intent.action.MEDIA_BAD_REMOVAL" />

                <data android:scheme="file" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

and my  SDCardStateChangeListener.java which extends BroadcastReceiver
package com.example.broadcastreceiversdcardinsertionremoval;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class SDCardStateChangeListener extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equalsIgnoreCase(Intent.ACTION_MEDIA_REMOVED)
                || action.equalsIgnoreCase(Intent.ACTION_MEDIA_UNMOUNTED)
                || action.equalsIgnoreCase(Intent.ACTION_MEDIA_BAD_REMOVAL)
                || action.equalsIgnoreCase(Intent.ACTION_MEDIA_EJECT)) {

            Log.d("action", "Sd Card Event");

        }
    }

}

A: In this case you are not explicitly registering a receiver, you are declaring it in manifest, no need to register it again. All components whose manifest has a matching receiver filter, will be invoked (Package service keeps track of this stuff). In this case an object of class SDCardStateChangeListener will be instantiated and its  onReceive() method will be called.
You can just put a breakpoint or log message as first statement inside onRecieve() method to see if it is invoked or not.

A: If you have android:exported="false" you will never receive any broadcasts sent from outside your own app.


text:
Q: jupyter notebook shows error message for matplotlib Bad key "text.kerning_factor" import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

Bad key "text.kerning_factor" on line 4 in
/home/samyak/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/stylelib/_classic_test_patch.mplstyle.
You probably need to get an updated matplotlibrc file from
https://github.com/matplotlib/matplotlib/blob/v3.1.3/matplotlibrc.template
or from the matplotlib source distribution

A: I had the same problem and I solved it by upgrading Matplotlib using the code:
conda upgrade matplotlib

or
pip install --upgrade matplotlib

A: I encountered the same issue today (using version 3.2.1).
My solution: Reinstall matplotlib :)

A: I noticed the version of matplotlib that print(matplotlib.__version__) returned was different from the version that pip show matplotlib showed! When I checked the folder ./Anaconda3/Lib/site-packages I noticed there were two versions of matplotlib (and a few other packages, too). For some reason when I upgraded matplotlib (and other packages), the old versions were not uninstalled. I used
pip uninstall matplotlib

twice to remove both versions, then installed matplotlib again. This solved the problem.

A: I also encountered the same problem. Reinstalling matplotlib didn't work for me. I downgraded matplotlib to version 2 using:
conda install matplotlib=2
It worked. Hope this helps.

A: It seems to be the case that one of style config files is for matplotlib 3.1 despite that 3.2 is installed.

*

*Go to /home/samyak/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/stylelib/

*open _classic_test_patch.mplstyle and comment out the line of text.kerning_factor:6
It worked for me.

A: For me it sufficed to install/upgrade the current version of matplotlib from conda-forge instead of the default channel (no previous uninstall necessary):
conda install -c conda-forge matplotlib

A: *

*Install matplotlib from the active environment.

*Go to './Anaconda3/Lib/site-packages' and manually delete all the matplotlib folders you see there. Make sure you are in the same environment if you have more than one.

*Re-install 'matplotlib' using conda install -c conda-forge matplotlib.

It should work.

A: i uninstalled matplotlib from my active environment and then reinstalled using
conda install -c conda-forge matplotlib
that did the trick!


text: Q: Is there a way to fix all naming rule violations at once in Visual Studio 2019? I have a C# class created by someone else whose properties are all in lower case. Visual Studio shows all these as warnings for Naming Rule Violation. It lets me fix them one by one, but I have not been able to find a way to change them in the entire document. Is it possible to do so without ReSharper?


text:
Q: Is a corresponding CSS necessary for a js functionality to work? I am trying to use bootstrap-collapse.js and it seems to work only when I include the bootstrap-min.css but as soon as I include the CSS, my whole site looks messy. How can I use Bootstrap functionality (Carousel, Collapse etc) without applying the CSS? Or is it not possible?

A: D.J.,
The short answer is that yes, you do need to include bootstrap-min.css for bootstrap-collapse.js to work properly.
Once you've included it, there are a few tricks to keep bootstrap from messing up the existing CSS on your site.
The most basic approach is to use more creative CSS class names for your own CSS. For example, bootstrap uses the class name "container" to create a responsive fixed width div.  So to avoid a conflict you could just use something different for your own container class, eg "DJs-container".
You can also use nested css classes in conjunction with CSS IDs to help avoid this.  Here's an article that might help you:  https://css-tricks.com/multiple-class-id-selectors/

A: EDIT:
Yes.  Collapse in particular is dependent upon the collapse, in and collapsing classes for its transitions.  Just copy out the classes that you need and add them to your custom css.  It looks to me that these are the ones that are needed.
If you're using UI Bootstrap 0.13, you have to make sure to add ngAnimate for the transitions.
.collapse {
  display: none;
}
.collapse.in {
  display: block;
}
tr.collapse.in {
  display: table-row;
}
tbody.collapse.in {
  display: table-row-group;
}
.collapsing {
  position: relative;
  height: 0;
  overflow: hidden;
  -webkit-transition-property: height, visibility;
  -o-transition-property: height, visibility;
     transition-property: height, visibility;
  -webkit-transition-duration: 0.35s;
  -o-transition-duration: 0.35s;
     transition-duration: 0.35s;
  -webkit-transition-timing-function: ease;
  -o-transition-timing-function: ease;
     transition-timing-function: ease;
}


text:
Q: Migrate Vaadin 8 to 14: Widgetset 'xx.MyAppWidgetset' does not contain an implementation for com.vaadin.mpr.MprUIContent We are migrating from Vaadin 8 to Vaadin Flow 14. In order to migrate piece by piece, MPR is used. We use Flow 14's Route for navigation. For each view we created a MprRouteAdapter. This is proved a nice approach in a small project, but when we move to relatively bigger project with some addons, navigating to a view shows the following message and the view does not show:
Widgetset 'xx.MyAppWidgetset' does not contain an implementation for
com.vaadin.mpr.MprUIContent. Check the connector's @Connect mapping, the widgetset's GWT module
description file and re-compile your widgetset. In case you have downloaded a vaadin add-on
package, you might want to refer to add-on instructions.

Below is MyAppWidgetset.gwt.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.1//EN"
    "http://google-web-toolkit.googlecode.com/svn/tags/2.5.1/distro-source/core/src/gwt-module.dtd">
<module>
    <inherits name="com.vaadin.DefaultWidgetSet"/>
    <inherits name="com.vaadin.mpr.MprWidgetSet" />

    <inherits name="org.vaadin.addons.WidgetSet" />

    <inherits name="org.vaadin.risto.formsender.widgetset.FormSenderWidgetset" />

    <inherits name="org.vaadin.hene.popupbutton.widgetset.PopupbuttonWidgetset" />

    <inherits name="org.tepi.listbuilder.WidgetSet" />

    <inherits name="com.vaadin.addon.onoffswitch.WidgetSet" />

    <inherits name="org.vaadin.addon.leaflet.Widgetset" />

</module>

The goal update-widgetset and compile have been added in maven build file.
Do I miss anything? Please help me to figure out the issue.
Thanks in advance.

A: The issue is resolved by removing MyAppWidgetset.gwt.xml and annotation @MprWidgetset.


text:
Q: Database cardinality and efficiency If I have an "off the shelf application" set up in an organisation that has a SQL Server backend database and I wish to check the entire efficiency of the database - that is I wish to check how good the following are in the database;

*

*cardinality and normalisation

*Indexing

*Redundant data etc

Is there any software tools that will analyse the database and show any flaws and inefficiencies and duplicate records?


text:
Q: Django JSONField filter greater than an attribute value I have the following Django model:

class Student(models.Model):
student_id = models.CharField(primary_key=True, max_length=10)

student_info = JSONField()

My data looks like:

{
"student_id": "1",
"student_info":{
"student_name": "Parker",
"age": "21",
"num_classes": "5",
"highest_score": "75",
"credits_complete": "13",
"credits_remaining":"20"
}
}

I want to select all students with credit complete greater than 13. I tried the following which returns me an empty Queryset:

Student.objects.filter(student_info__credits_complete__gt='13')

Any idea how to filter greater than or less than the attribute value in JSONField?
Thanks!


text:
Q: Is it better practice to performSegueWithIdentifier or presentViewController If I am using storyboards, is it better practice to create a segue and use performSegueWithIdentifier or just use presentViewController to move the user from one View Controller to the next.
For this example, let's assume we are using Swift 5 and I have 2 view controllers: a TableView of Contacts on MainViewController and the details of that Contact on DetailViewController.
In my code, I am using presentViewController, but as I am new to iOS development, I'm not sure if this is the best approach.

A: Let's assume for purposes of illustration that the situation in the storyboard is as follows:
ViewController1
    |----> modal segue "toVC2" emanating from ViewController1
        |----> ViewController2, identifier "VC2"

Then in ViewController1 code there is absolutely no functional or effective difference between these two things:

*

*Call performSegue with identifier "toVC2"

*Call instantiateViewController on the storyboard with identifier "VC2" and call present
Having said that, I will make a case for each way being "better" than the other.
Why the segue might be better
The segue in my example doesn't look much better because we still have to use code to call performSegue. However, suppose that the segue emanates not from the view controller but from a button in the view controller's view. That is an action segue and now the segue will be performed automatically when the user taps our button, with no code needed to perform it. You don't even need to know the identifier. (String identifiers are a great way to make a mistake.)
Why instantiate and present might be better
There is something very horrible about segues, whether it's an action segue or a manually triggered segue with performSegue — namely, when (as so often happens) you want to pass data from the first view controller to the second. If you use a segue, you must do the data-passing in an implementation of prepare(for:sender:). This is very messy because you have to check the segue identifier and cast the destination to the correct class. Moreover, if there is more than one segue, prepare becomes a messy bottleneck. And if we also called performSegue, we are operating in two different places — the method where we called performSegue, and the separate implementation of prepare.
By contrast, if we call instantiateViewController, what comes back to us is the view controller instance itself. We still have to cast, but now we can pass the data right then and there, without "waiting" for prepare and without passing through a bottleneck. Thus this is a far more legible and encapsulated way of proceeding.
Also, this may seem obvious, but a nice thing about saying present is that this tells us right there in the code what the transition is. If you just use a segue identifier, the fact that this is a modal segue is hidden off in the storyboard.
Which do I prefer?
Neither. I prefer not to use storyboards at all for presented view controllers if I can help it. I use a view controller and eponymous nib. That way, I simply instantiate the view controller itself and pass it the data and present it, with no need to cast and no need for any identifiers.
So am I saying that storyboards are no good at all?
No. Storyboards have the virtue of mapping out the scene structure of your app, especially if you do use segues. If you are not going to use a segue to a view controller, however, then I don't really see the point of keeping that view controller in a storyboard in the first place. The eponymous nib mechanism is clearer and cleaner. Moreover, I regard the prepare(for:sender:) mechanism as a near-fatal flaw in the entire storyboard architecture; a huge majority of mistakes shown on Stack Overflow are a consequence of this flaw.
[EDIT Note that a lot of my objections to segues will fall away in iOS 13, where the source view controller will be able to use code to call an initializer of the destination view controller.]

A: Both of them do the same thing, But i usually use Present so when i want to change the behaviour for example, make the button open another VC, i just change the identifier, i don't have to remove the segue and create a new one.
Also many segues would make your storyboard look spaghetti


text:
Q: Fresh install of archived Android Studio not successful I am trying perform a fresh install of an archived version of Android Studio to match what was installed on my university's lab computers last year in Dec 2021.
I have performed the following steps:

*

*(1) Installed "Android Studio Arctic Fox (2020.3.1) Patch 4" from https://developer.android.com/studio/archive on Mac (Apple Silicon) using the "Standard" installation settings of the wizard

*(2) Once installed, I open the SDK Manager to (a) uninstall the installed/current version of SDK and (b) instead install Android 12.0 (S) Version 32 -- this is because our university's lab computers  were configured a year ago with Android 12.0 (S) Version 32.

*(3) Next, I installed the AVD for Pixel 4 with API 29 -- this is because our university's lab computers were configured with this AVD.

*(4) When I create a new Android Studio project and set the "Minimum SDK" to API 29, I get the following error when I try to compile/run my project:

Can't determine type for tag '?attr/colorSurface'

I cannot seem to find out how to perform a fresh install of this archived version of Android Studio to get it back to a stable state as it was in late 2021.
Any suggestions or advice would be so greatly appreciated!


text:
Q: Let $G$ be a group such that $|G| =81$, $P$ be a set such that $|P|=98$ . Prove that $|P^G| = 3k+2$ with $k$ an integer Let $G$ be a group such that $|G| =81$, $P$ be a set such that $|P|=98$. Prove that $|P^G| =  3k+2$ with $k$ an integer, where  $|P^G|$ is the set of elements of $|P|$ that are fixed by every element of $G$
My attempt:
Note that $G$ is a $p$-group, because $|G|=3^4$.
Moreover, we know that ${\rm Orb}_P(x)$ divide  $|G|$, in other words, $|{\rm Orb}_P(x)|$ must be a positive integer power of $3$ or $3^0$.
But $|{\rm Orb}_P(x)|$ must divide $|P|$ then $|{\rm Orb}_P(x)|=1$ for all $x \in P$
Here I'm stuck. Can someone help me?

A: An important piece of information that is missing from your setup: $G$ acts on the set $P$!
Anyway, like you said, each orbit must have cardinality $1$, $3$, $9$, $27$, or $81$. Also, $P$ is the disjoint union of its orbits. So, letting $a, b, c, d, e$ be the numbers of orders of the aforementioned cardinalities, we have
$$a + 3b + 9c + 27d + 81e = 98.$$
Also note that (by definition) $a = \lvert P^G \vert$. Can you use this to show that $\lvert P^G \rvert = 3k+2$ for some integer $k$?

A: For any $G$-set, $P$, the orbit equation reads:
$$|P|=\left|P^G\right|+\sum_i\frac{|G|}{\left|\operatorname{Stab}(p_i)\right|}\tag 1$$
where $\operatorname{Stab}(p_i)\lneq G$, for every $i$. In your case, $|G|=3^4$, so $3$ divides $\sum_i\frac{|G|}{\left|\operatorname{Stab}(p_i)\right|}$. Therefore, from $(1)$:
$$98\equiv \left|P^G\right|\pmod 3\tag 2$$
namely:
$$2\equiv |P^G|\pmod 3 \tag 3$$


text:
Q: the screen is locked when I open settings in ubuntu 18.04 Hi I am new in Linux and I recently installed Ubuntu 18.04 until now when I open the setting it works fine now it looks the screen also my keyboard and the mouse are connected with USB and in the lock screen they work very slow
I did not install anything on my machine I am using gnome
what do I need to do? and why this happening? thanks


text:
Q: É possível colocar labels em ListView? Eu tenho várias ListView's que uso para navegação, e coloquei como conteúdo id's.
Então, uma lista que deveria apresentar nomes de países, está apresentando o id dos países.
Existe algum modo de manter esses id's na lista mas exibir o nome para os usuários?
Eu preciso manter os ids para fazer as pesquisas no banco.

A: Você precisará de um Adapter que herde de BaseAdapter. Isso irá te possibilitar que seu Adapter aceite outros objetos.
Para isso, você ira precisar criar um modelo Pais que tenha como atributo o seu id e o nome do país e passar para o seu Adapter e, por fim, definir este Adapter para o seu ListView.
Tente algo assim:
Pais:
public class Pais {
    private final int id;
    private final String nome;

    public Pais(int id, String nome) {
        this.id = id;
        this.nome = nome;
    }

    public int getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }
}

item_pais.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_nome"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

MeuAdapter:
public class MeuAdapter extends BaseAdapter {

    private final List<Pais> paises;
    private final LayoutInflater inflater;

    MeuAdapter(List<Pais> paises, Context context) {
        this.paises = paises;
        //LayoutInflater para inflar o seu Layout
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return paises.size();
    }

    @Override
    public Object getItem(int position) {
        return paises.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_pais, null);
        }

        ViewHolder holder = (ViewHolder) convertView.getTag();

        if (holder == null) {
            holder = new ViewHolder();
            holder.tvNome = (TextView) convertView.findViewById(R.id.tv_nome);
        }

        //Recupeando o seu pais de acordo com a posição
        Pais pais = paises.get(position);

        //Definindo o texto do item da sua linha
        holder.tvNome.setText(pais.getNome());

        convertView.setTag(holder);

        return convertView;
    }

    class ViewHolder {
        TextView tvNome;
    }
}

MainActivity:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<Pais> paises = new ArrayList<>();
        paises.add(new Pais(0, "Brasil"));
        paises.add(new Pais(1, "Argentina"));
        paises.add(new Pais(2, "Portugal"));

        MeuAdapter meuAdapter = new MeuAdapter(paises, this);

        ListView listView = (ListView) findViewById(R.id.sua_list_view);
        listView.setAdapter(meuAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Pais pais = (Pais) parent.getAdapter().getItem(position);

                //Recuperando o ID do país.
                Toast.makeText(MainActivity.this, String.valueOf(pais.getId()), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

A: Tem sim, para esse caso a solução são os Adapter. A maioria dos componentes visuais são projetados no padrão MVC (acho que é muito conhecido no ambiente web).
Bem, a ListView tem um modelo (que é um conjunto de dados internos), esse conjunto de dados pode ser "injetado" através de um Adapter que nada mais é do que o comportamento para renderizar a View.
Documentação

A: Sem o código fica um pouco complicado, mas imagino que você esteja preenchendo a ListView usando um CursorAdapter, certo?
(Deve ser parecido com o que eu fiz aqui )
Se for o caso, no método bindView() é quando você "seta" o texto, nesse caso, não use o ID. Crie um método para receber o ID e retornar o nome do país.


text:
Q: How to run a process that have an argument containing new-lines? I have a command that have the structure :
xrdcp "root://server/file?authz=ENVELOPE&Param1=Val1" local_file_path
The problem is that ENVELOPE in text that should be unquoted in command line
and it contains a lot of new-lines
I cannot use repr as it will replace new-line with \n
Moreover subprocess seems to automatically use repr on the items from the list arguments
In bash this command is usually run with
xrdcp "root://server/file?authz=$(<ENVELOPE)&Param1=Val1" local_file
So, is there a way to run a command while keeping the new lines in the arguments?
Thank you!
Later Edit:
my actual code is :
envelope = server['envelope']
complete_url = "\"" + server['url'] + "?" + "authz=" + "{}".format(server['envelope']) + xrdcp_args + "\""
xrd_copy_list = []
xrd_copy_list.extend(xrdcp_cmd_list)
xrd_copy_list.append(complete_url)
xrd_copy_list.append(dst_final_path_str)
xrd_job = subprocess.Popen(xrd_copy_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = xrd_job.communicate()
print(stdout)
print(stderr)


text:
Q: Subdomain redirect to URL Parameter while keeping other url params intact I've looked like crazy for an answer to this - and I haven't been able to find one as of yet. My apologies in advance if I've missed something.
I'm looking to convert a subdomain to a url parameter while maintaining the other url pieces.
Such as:
http://sub.domain.tv/value redirects to http://domain.tv/value?campus=sub
This is what I've tried after looking through numerous posts on here:
# campus
RewriteCond %{HTTP_HOST} ^sub.domain.tv$ [NC]
RewriteRule ^(.*)$ http://domain.tv/$1/?campus=sub [R=301,L]

which worked fine for redirecting sub.domain.tv to domain.tv?campus=sub, but does not work with the rest of the URL parameters (so heading to sub.domain.tv/value does nothing).
I've tried other examples with the %1 and $1 being used as variables, such as with this post:
htaccess subdomain redirct with last url parameter but I don't understand the difference (and the examples I've tried did not work).
Thanks for taking a look! :) I very much appreciate it!

A: Have you tried the [QSA] parameter.  This will add any remaining Query parameters to campus=sub