Squeeze Some of Singleton Dimensions in Matlab

Question: How can I squeeze only a subset of singleton dimensions of a matrix in Matlab? The squeeze function removes them all.
I keep the index to those dimensions in a vector called "dims".
Comment: @LuisMendo I guess it makes sense to not add that tag for this question. Also creating a new tag for this specialized one doesn't make sense yet. Thank you for your efforts on checking with those meta folks.
Comment: @Divakar That tag's definition says "The singleton is a design pattern to ensure that exactly one application-wide instance of a particular class exists". So obviously it refers to the OOP concept of singleton, not to singleton dimensions. But you may be right: is it correct to remove a tag based on its definition, when its name does apply to the answer? Feel free to roll my edit back if you find it appropriate
Comment: For future reference: remove seems to be the best action, [according to Meta](http://meta.stackoverflow.com/q/255209/2586922) @Divakar
Comment: @Luis Was removing the tag - `singleton` a good idea, given this is mainly based on that kind of tag?
Comment: @LuisMendo I am not too picky about it. It's okay as it is now I guess given the definition. Thanks on bring up the definition text though!
Comment: @Divakar I'll search/ask in Meta about this (the name applies, the definition doesn't: remove?)
Comment: @LuisMendo Haven't got much idea about adding new tags or editing the definitions of the existing ones really.
Answer: In Matlab, there is no tailing singleton dimension. A n*m*1 matrix is automatically a n*m matrix. Knowing this, your problem could be solved permuting the dimensions you don't want to the end:
X=ones(2,1,2,1,2,1,2,1,2,1)
%dimensions you want to keep in any case
dims=[2:4];
%Notice, S is [2,1,2,1,2,1,2,1,2], last dimension already "gone"
S=size(X)
%keep if size>1
dimensions_to_keep=S>1
%and keep if in "dims" list
dimensions_to_keep(dims)=1
%now permute dimensions you don't want to the end
Y=permute(X,[find(dimensions_to_keep),find(~dimensions_to_keep)])

Answer: Code
%// Input matrix is assumed as A
sz = size(A)
t2 = sz~=1
t2(dims)=1
out = reshape(A,sz(t2)) %// out is the desired output

If you are crazy about dense codes, you can try this -
sz = size(A)
out = reshape(A,sz(sort([dims find(sz~=1)])))

Answer: @Divakar's answer takes dims as being "what to keep". For "what to drop", below basically converts one into the other and pastes into that answer:
sz = size(A);
keepdims = 1:numel(sz);
keepdims = keepdims(~arrayfun(@(i)ismember(i, dims_user), keepdims));
no_squeeze = sz~=1;
no_squeeze(keepdims) = 1;

new_sz = sz(no_squeeze);
if numel(new_sz) == 1  % can't reshape into 1D
    new_sz = [1 new_sz];
end
out = reshape(A, new_sz);

Example size(out)s with A = randn(1, 1, 3, 1, 4)
dims_user = 1;    % 1     3     1     4        | drops dim1
dims_user = 2;    % 1     3     1     4        | drops dim2 (same effect)
dims_user = 3;    % 1     1     3     1     4  | ignores drop request
dims_user = 4;    % 1     1     3     4        | drops dim 4
dims_user = 1:2;  % 3     1     4              | drops dims 1, 2
dims_user = 1:3;  % 3     1     4              | drops dims 1, 2, ignores 3
dims_user = 1:5;  % 3     4                    | == `squeeze(A)`

The ignoring mimics Python's numpy.squeeze. Also handles the 1D edge case.


Adding Animation to Widgets during Scroll in Flutter

Question: I am working on a Flutter project and would like to add animations to widgets as I scroll through the screen. Specifically, I want each widget to load with a certain animation when it comes into view during scrolling.
I have tried a few approaches but haven't been successful so far. Can anyone guide me on how to achieve this in Flutter?
Comment: something like https://pub.dev/packages/flutter_staggered_animations ?
Comment: @IncorrectMouse Thank you for answering.
it's working but using this package animation can been load at initial time but i need to add while user can scroll screen data animation can be load at that time so how to do in flutter.?
Answer: You can use visibility_detector: ^0.4.0+2 package and wrap with your widget
or control your animation timing using  onVisibilityChanged function.


Common strategies and counters

Question: Is there a resource that can give me a list of popular strategies (not builds), and effective counters to them?
E.g. - rush can be countered by wall-in-natural, fast expand countered by rush, etc... ?
Comment: ripper, we have [a meta site](http://meta.gaming.stackexchange.com/) in which we can discuss anything about this site (rather than about games themselves); please avoid such discussions on the main site.
Answer: http://wiki.teamliquid.net/starcraft2/Main_Page
Comment: Could you perhaps elaborate on this one? Perhaps just list some of the strategies instead of just posting a link

Common strategies and counters


Replace String with dynamicaly ending in php

Question: I have a large String, containing "items1" and "items2" ...
I don't know how much of these items exists. So I don't know until which number it is counting.
Now I need to replace all these parts of the String to "items"
Example:
asdfHelloBla"items2"HahaHabicht"items3"test => asdfHelloBla"items"HahaHabicht"items"test

Can anyone help me?
Can I do this with regular expressions?
Comment: Do you mean you want to remove digits that appear after a static string `item` inside double quotes? Did you try anything?
Comment: Where's the input coming from? That doesn't look like anything sane.
Comment: @JonStirling: Consisder a random string.
Comment: Will there be quotes inside the input string? Or are those just for clarification?
Answer: You can do this using the following code:
<?php
    $string = 'asdfHelloBla"items2"HahaHabicht"items3"';
    $to_replace = array('"items1"', '"items2"', '"items3"');
    echo str_replace($to_replace, '"items"', $string);
?>

the str_replace function is used as follows:
str_replace(search, replace, subject);

It can accept an array as the 'search' argument and then replaces any of the matches with the 'replace' argument.
You need to add all you want to replace in the $to_replace array that is in this case "item1", "item2" and so on and it should work fine. One more thing, you need to know the maximum limit till where the list goes.
If you know the maximum limit, you can use a loop to replace '"item1"', '"item2"'.... with '"item{$n}"'
Hope this helps :)


Why does my MCPE command not work in MCJE?

Question: I'm using the following code in MCPE:
tp @e[type=husk] @e[type=wolf]

Java Edition shows the @e[type=wolf] in red.
What is the correct way to write this command?
Comment: Please only write with proper English on StackExchange. I've edited your post to make it more clean.
Comment: Possible duplicate of [Need to make target selector only select one entity](https://gaming.stackexchange.com/questions/348970/need-to-make-target-selector-only-select-one-entity)
Answer: Look at the error message:
Only one entity is allowed, but the provided selector allows more than one at position 0: <--[HERE]

When only one entity will be accepted, it is your job to make sure the target selector returns only one entity. Unlike Bedrock Edition, if your target selector allows more than one entity to be selected, even if it will return only one entity when run, it throws an error.
You need to use the limit=1 parameter to limit your target selection to one entity.
tp @e[type=husk] @e[type=wolf,limit=1]


Show banner at login with LightDM

Question: I just upgraded to Ubuntu 11.10 and I was wondering if it's possible to show a login banner with text... my company's IT policy requires that some generic text be shown at login. I've seen where you can change the background, so I guess I could make a background with the text in it, but I wanted to see if there is another way.
In Ubuntu 11.04, I was able to do this with the following commands...
<code>sudo -u gdm gconftool-2 --type string  --set /apps/gdm/simple-greeter/banner_message_text "`cat issue.txt`"
sudo -u gdm gconftool-2 --type string  --set /apps/gdm/simple-greeter/banner_message_text_nochooser "`cat issue.txt`"
sudo -u gdm gconftool-2 --type boolean --set /apps/gdm/simple-greeter/banner_message_enable true
</code>
Comment: I've tried asking a more general question about lightdm themes - http://askubuntu.com/questions/69151/how-do-i-set-my-own-theme-in-lightdm-in-11-10 - which if answered well might help you.
Answer: Answers provided to Hamish Downer's question about LightDM themes linked in the comment to my original question include a suitable answer to this question as well.
Comment: If your question is now answered, you should accept this answer so that the question shows up as answered. Or, you can flag it for closure as a duplicate.

Show banner at login with LightDM


class pointer error: does not have a type

Question: one of my class variables that is a pointer to another class is giving a error of no type. can figure it out after a few days thinking about it, anyone see a mistake? also for some reason the line
 r->setright(NULL)

crashes the program
#include "gridnode.h"
#include "grid.h"
#include "basenode.h"
class grid
{
    public:
        grid();
        void print();
    protected:
        gridnode *head;//error of no type here
};
#endif // GRID_H

and my node class
class gridnode:public basenode
{
public:
    char mark;
    gridnode *l, *r, *u, *d;
    gridnode(){
        l->setleft(
        r->setright(NULL);//crashes
        u->setup(NULL);
        d->setdown(NULL);
    }
    //set and get functions
protected:
};

any help greatly apreciated.
Comment: Hi @jack3939. Currently, there is not enough information to answer this question. If this is crashing on `setright` then could you please share that Implementation?
Comment: this program is basically a 2d array implemented with linked lists. set right should just set the variable r to the node to the right of the current node, but it will not set the one to the right as NULL.currently setright and setdown cause the program to crash, but setup and setleft work fine.
Answer:
one of my class variables that is a pointer to another class is giving a error of no type.

gridnode has not been defined yet when you try to use it.  That can happen if you have circular references in your .h files, for instance.  Since you are just declaring a pointer, you can use a forward declaration instead:
#ifndef GRID_H
#define GRID_H

// there should be no include of grid.h here
// move the gridnode.h and basenode.h includes to grid.cpp instead

class gridnode; // forward declaration

class grid
{
    public:
        grid();
        void print();

    protected:
        gridnode *head;
};

#endif // GRID_H

also for some reason the line
r->setright(NULL)

crashes the program

Inside the gridnode constructor, you are calling methods on l, r, u, and d pointers that have not been initialized to point at anything.  You are invoking undefined behavior by calling methods on them.  You probably meant to set the pointers themselves to NULL instead, eg:
gridnode(){
    l = NULL;
    r = NULL;
    u = NULL;
    d = NULL;
}

Or:
gridnode() :
    l(NULL),
    r(NULL),
    u(NULL),
    d(NULL)
{
}


Can I change an outlet circuit to 240V (NEMA 6)?

Question: I'm in an American house sitting in a jurisdiction that applies NEC 2014 unaltered. I've got a home office room with all the outlets on one 20A circuit. It is legal to 2014 code in all respects.
Who cares why, maybe I collect European pinball machines, maybe I just need a lot more power in the room, between my server grade PC and window air conditioner.   I decide I want to convert that outlet circuit to 240V and install all NEMA 6-20 outlets.  Pic

It's wired in NM 12/2 but I mark the white wire with red tape at every accessible point.  Ground but no neutral.  I have the requisite AFCI or GFCI breaker if required (whatever the circuit had before).
What code of Code compliance issues am I going to run into?  After all, I do have outlets in all the right places.
Now suppose I also wanted to power a permanently installed light fixture.  I want to use one rated for 240V.  Any code issues there?
Answer: No problem.  As long as you install a double pole breaker, make the white wire an ungrounded conductor (including marking as you describe), and change all the receptacles and devices to 240 volt devices.
Answer: I see there is no accepted answer yet, so here are my concerns:
NEC 210.6(A) would allow only loads greater than 6 amps (1440 VA) because this "home office" would be part of a "dwelling unit".  This rule also seems to disallow the use of 240V luminaires in a dwelling unit.
NEC 210.52 requires 125-volt receptacles for a "Dwelling Unit".  If you convert "all the outlets" to 240V then you'd have to add a new circuit for 125-volt to stay in compliance anyway.


How to get a default string value from resources in SafeArgs?

Question: I'm just learning a Android NavigationUI, and try set a toolbar title using string default value from Safe Args. But have some problem about it.
'String resources' file:
    <string name="title_add_item">Add new items</string>

Navigation graph file. Set label as Title: {title} argument.
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/mainFragment">

<fragment
    android:id="@+id/addNewItemFragment"
    android:name="com.myapplication.AddNewItemFragment"
    android:label="Title: {title}"
    tools:layout="@layout/fragment_add_new_item" >
    <argument
        android:name="title"
        app:argType="string"
        android:defaultValue="@string/title_add_item" />
</fragment>
<fragment
    android:id="@+id/mainFragment"
    android:name="com.myapplication.MainFragment"
    android:label="fragment_main"
    tools:layout="@layout/fragment_main" >
    <action
        android:id="@+id/action_to_add_items_fragment"
        app:destination="@id/addNewItemFragment" />
</fragment>

If {app:argType="string"} I got an error :
 Caused by: org.xmlpull.v1.XmlPullParserException: unsupported value 'Add new items' for string. You must use a "reference" type to reference other resources.

If  {app:argType="reference"} app works, but i have a number in title (i think it's a resource id):

Of course I can assign the value of the toolbar title in the code by getting it from the arguments. But is it possible to change this code so that the title filled in correctly?
Comment: I found that it's a [bug](https://stackoverflow.com/a/64831977/4694013)
Answer:
References to resources are supported only in reference types. Using a
resource reference in any other type results in an exception.

Feel free to star the existing issue: https://issuetracker.google.com/issues/167959935. For the time being, u can hardcode the string value with app:argType="string" or try setting programmatically until it gets resolved.

https://developer.android.com/guide/navigation/navigation-pass-data#supported_argument_types
https://stackoverflow.com/a/55701078/4694013
Answer: Take a look over here.
You don't need to use arguments to set a static title.
You can just set the title you want to appear in the toolbar to the fragment in the navigation graph with android:label.
<fragment
    android:id="@+id/addNewItemFragment"
    android:name="com.myapplication.AddNewItemFragment"
    android:label="@string/title_add_item"
    tools:layout="@layout/fragment_add_new_item" >

Then setup the toolbar using setupWithNavController
val navController = findNavController(R.id.nav_host_fragment)
val appBarConfiguration = AppBarConfiguration(navController.graph)
findViewById<Toolbar>(R.id.toolbar)
    .setupWithNavController(navController, appBarConfiguration)

This way you don't need to override onSupportNavigateUp and the title will automatically update once you navigate to another fragment.
If for some reason you really want to combine the argument with the value in android:label then there is no other way but using app:argType="reference" and combining the two in your code.
Comment: Yes, but idea was automatic set title from "defaultValue" saveArg variable if that variable doesn't set.
Answer: You can just make it as a reference type and set it and get as reference/resource with getString(args.title)
nav_graph.xml
<fragment
    android:id="@+id/choose_scanner"
    android:name="com.myapp.ChooseScannerFragment"
    tools:layout="@layout/fragment_choose_scanner">
    <action
        android:id="@+id/action_scan_with_camera"
        app:destination="@+id/qr_scanner" />
</fragment>

<fragment
    android:id="@+id/qr_scanner"
    android:name="com.myapp.ScanFragment"
    tools:layout="@layout/fragment_scan">
    <argument
        android:name="show_back_button"
        android:defaultValue="false"
        app:argType="boolean" />

    <argument
        android:name="title"
        android:defaultValue="@string/connect_printer_device"
        app:argType="reference" />

    <argument
        android:name="message"
        android:defaultValue="@string/scan_printer_message"
        app:argType="reference" />
</fragment>

ChooseScannerFragment
 findNavController().navigate(ChooseScannerFragmentDirections.actionScanWithCamera(
                    showBackButton = true,
                    title = R.string.step_1_scan_reference,
                    message = R.string.scan_reference_message
                ))

ScanFragment.kt
binding.message.text = getString(args.message)
        binding.title.text = getString(args.title)
        binding.back.visibility = if (args.showBackButton) View.VISIBLE else View.INVISIBLE


SQL*Plus ignores colsep option

Question: So we are trying to dump the content of our oracle database to a .CSV file but when executing the following command
set colsep ',' echo off newpage 0 space 0 pagesize 0 linesize 3000 feed off head off trimspool on
spool C:\Users\whocares\Desktop\test.CSV
select ID, LOCATION_ID from club;
spool off

the output looks as follows:
...

     17499        902
     17500        902
     17501        902
     17502        902
     17503        902
     17504        902
     17505        902
     17506        902
     17507        902
     17508        902
     17509        902

...

and sqlplus seems to completely ignore the set colsep ',' option.
To get a valid csv output we need to have the output look like this:
...

17499,902
17500,902
17501,902
17502,902
17503,902
17504,902
17505,902
17506,902
17507,902
17508,902
17509,902

...

So how do you properly use the set colsep option?
We don't have much experience with sqlplus and for some reason other stackoverflow solutions didn't seem to work for us.
Answer: SET COLSEP replaces SET SPACE, and that's so since Oracle 9.2 (see Obsolete SQL*Plus Commands).
If you use them both, there's no separator:
SQL> set colsep ','
SQL> select * from dept where rownum = 1;

    DEPTNO,DNAME               ,LOC
----------,--------------------,--------------------
        10,ACCOUNTING          ,NEW YORK

SQL> set space 0
SQL> select * from dept where rownum = 1;

    DEPTNODNAME               LOC
--------------------------------------------------
        10ACCOUNTING          NEW YORK

SQL> set space 1
SQL> select * from dept where rownum = 1;

    DEPTNO DNAME                LOC
---------- -------------------- --------------------
        10 ACCOUNTING           NEW YORK

SQL>

So - remove SET SPACE.

Another option is to concatenate columns. Yes, that's a tedious job but it works, e.g.
SQL> select deptno ||','|| dname ||','|| loc from dept;

DEPTNO||','||DNAME||','||LOC
---------------------------------------------------------------
10,ACCOUNTING,NEW YORK
20,RESEARCH,DALLAS
30,SALES,CHICAGO
40,OPERATIONS,BOSTON

SQL>

If there are many tables involved, you could write a query which will write a query for you:
SQL> select 'select ' || listagg(column_name, '||'',''||') within group (order by column_id) ||
  2         ' from '  || table_name result
  3  from user_tab_columns
  4  where table_name = 'DEPT'
  5  group by table_name;

RESULT
--------------------------------------------------------------------------------
select DEPTNO||','||DNAME||','||LOC from DEPT

SQL>

Now just copy/paste the result and run it.
Comment: Ah alright. That works. However our database contains many empty columns and removing `SET SPACE` produces a bunch of spaces between the `,`(commas) for the empty fields. In order to reduce file size: is there really no way we can combine `SET SPACE` and `SET COLSEP` or would we have to run some script on the output csv file to remove these unwanted spaces?
Comment: I've added some more info. Have a look, please.

SQL*Plus ignores colsep option


Is it safe to send credit card IDs to clients?

Question: PayPal will give you an ID for each credit card you create e.g. CARD-5BT058015C739554AKE2GCEI:
CreditCard creditCard = CreditCard.get(apiContext,
                    "CARD-5BT058015C739554AKE2GCEI");

Is it safe to send this ID to the client?
Answer: It's safe as PayPal tokenization service complies with EMV standard for securing transactions.
The vault-and-pay card-ID (token) can be only used thru PayPal OAuth authentication on your REST APP to

Exchange for card details with PayPal REST Vault service.
Be set as a payment funding source (credit_card_token object) on payment API, within the same REST application where it gets vaulted

While the tokenized ID is unreadable/meaningless for a customer, you may optionally display the user-friendly infor : card type mark (VISA, MC, AMEX, etc) and the last 4-digit card number in your customer's profile


Call a C preprocessor macro multiple times (through a variable)

Question: I'd like to clean up my assembly code and povide a way to call "NOP" multiple times through a macro:
#define NOP() asm(" nop")

#define NOP_N( N ) \
    NOP(); \
    NOP(); \
    .... call NOP() N times

I can't figure if this is possible in a macro.
Obviously, for performance reasons, I don't want something like this:
#define NOP_N( n ) { register int i; for(i=0;i<n;i++) asm(" nop"); }

Which defeats the purpose of NOP:
L17:                                    ; NOP_N(3);
        nop
        addi      1,r0                  ; Unsigned
        cmpi      3,r0
        blo       L17

The code is in C and assembly, so no C++ can be involved in here. Also, the compiler is fairly old and doesn't support variadic macros...
Comment: @Mogria: Well if xgbi can use C++, then this could be done fairly simply via template metaprogramming, and no preprocessor trickery would be necessary at all.
Comment: how do you write it as macro for `N`, `call NOP() N times`,  N has to be know at coding time
Comment: Possible duplicate: http://stackoverflow.com/q/11532883/946850
Comment: Also related: http://stackoverflow.com/q/319328/946850
Comment: The code is in C and assembly, so no C++ can be involved in here. Also, the compiler is fairly old and doesn't support variadic macros...
Answer: I don't think a solution for unbounded N is possible. For bounded N you could do something along the following lines:
#define REPEAT_0(WHAT)
#define REPEAT_1(WHAT) WHAT REPEAT_0(WHAT)
#define REPEAT_2(WHAT) WHAT REPEAT_1(WHAT)
#define REPEAT_3(WHAT) WHAT REPEAT_2(WHAT)

#define NOP_N(N) REPEAT_##N(asm("nop");)

The first part can be autogenerated easily. The technique employed for the second part is sometimes called token pasting.
Comment: That's the closest that I can foresee as possible without variadic macros.
Answer: what about this and Is the C preprocessor Turing complete?:
#define EVAL(...)  EVAL1(EVAL1(EVAL1(__VA_ARGS__)))
#define EVAL1(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__)))
#define EVAL2(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__)))
#define EVAL3(...) EVAL4(EVAL4(EVAL4(__VA_ARGS__)))
#define EVAL4(...) EVAL5(EVAL5(EVAL5(__VA_ARGS__)))
#define EVAL5(...) __VA_ARGS__

AND REPEAT_INDIRECT
#define REPEAT(count, macro, ...) \
    WHEN(count) \
    ( \
        DEFER(REPEAT_INDIRECT) () \
        ( \
            DEC(count), macro, __VA_ARGS__ \
        ) \
        DEFER(macro) \
        ( \
            DEC(count), __VA_ARGS__ \
        ) \
    )
#define REPEAT_INDIRECT() REPEAT

//An example of using this macro
#define M(s, i, _) i
EVAL(REPEAT(8, M, ~)) // 0 1 2 3 4 5 6 7

AND FOREVER:
#define FOREVER() \
    ? \
    DEFER(FOREVER_INDIRECT) () ()
#define FOREVER_INDIRECT() FOREVER
// Outputs question marks forever
EVAL(FOREVER())

Comment: Care to elaborate what this code does? Otherwise the link is great in a comment but does not qualify for an answer.
Answer: If you really want to do this in the preprocessor (and have a C99 compliant compiler) you could use P99_UNROLL from P99.
But you are completely underestimating the optimization that modern compilers are capable. As long as the bounds are compile time constants, a good compiler with optimization should just unroll the code for you. Look into the assembler to be sure (gcc has -S for that).
But you probably could help the compiler a bit by coding this "correctly":
#define NOP_N(N) for(register unsigned i=0; i < (N); i++) asm(" nop")

That is, have the loop counter local to the for and use an unsigned type such that there can't be theoretical issues with overflow.
Comment: The thing is that the compiler *is* old. I checked that using a for loop will actually initialize the integer and not unroll the loop.


Pygame doesn't CLOSE

Question: Can someone PLEASE tell me what I'm doing wrong. I can't get my stupid program to close. It has a spinning circle(windows) and it doesn't close upon quit or keypress on the space bar.
 def visualize(self):
    pygame.init()
    main_surface = pygame.display.set_mode((1024, 768))

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                break
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    break
                pygame.display.flip()
    pygame.quit()

I'm not sure if the inside of my program matters much, but if it does, I'll add it. I would REALLY appreciate your help!
Answer: The break will just exit the innermost loop, which is the for loop. You should have a condition variable for your while loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            break
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                break
            pygame.display.flip()

Pygame doesn't CLOSE


In a Razor view how can I insert the page title without a <?

Question: In my ASP.NET MVC 3 Razor layout view I want my page title to always be "My Website" and if ViewBag.Title is set I want to append that to the title, using a hyphen as a separator. I want this code to be on a single line
This code fails :
<title>My Website @if( string.IsNullOrEmpty( ViewBag.Title) == false){ - @ViewBag.Title}</title>

With

The if block is missing a closing "}"
  character.  Make sure you have a
  matching "}" character for all the "{"
  characters within this block, and that
  none of the "}" characters are being
  interpreted as markup.

Presumably because @: assumes that the rest of the line is markup. I can't use a span tag to help Razor because the browser title becomes "My Website - span Home span".
Yes I can spread this over two or three lines, but I don't want to. This works but is it my only option with Razor ?
<title>My Website @if( string.IsNullOrEmpty( ViewBag.Title) == false){ @: - @ViewBag.Title
}</title>

Comment: You could apply the `-` to the title in an ActionFilter, and keep the view a little neater
Answer: You need to use the <text> pseudo-tag.
<title>My Website @if(!string.IsNullOrEmpty(ViewBag.Title)) { <text>- @ViewBag.Title</text> }</title>

Comment: Yes that's it cheers, both you and archil gave me instant correct answers, thanks both
Answer: i think you need razor explicit text markup
 <title>My Website @if( string.IsNullOrEmpty( ViewBag.Title) == false){ <text>-</text> @ViewBag.Title}</title>


How should I connect flexible plastic duct to a metal duct?

Question: I have an insulated duct like this: https://www.homedepot.com/p/Master-Flow-4-in-x-12-ft-Insulated-Flexible-Duct-R6-Silver-Jacket-F6IFD4X144/203420974
The actual tube inside is some kind of plastic. When attaching this to a metal duct, do I seal it with metal tape or duct tape? Or should I use those metal collars that can be tightened with a screw?
Comment: plastic flex duct is about the worst product you can use for ducting.  Is this for a bathroom fan?
Comment: For future reference: "metal collars that can be tightened with a screw" is commonly called a "hose clamp" or "duct clamp". In the UK, they're called "Jubilee clips". May have other names elsewhere in the world.
Answer: Use a strap-type duct clamp.
Duct tape has no modern HVAC application that I'm aware of. Metal foil tape is a seal, not a fastener, as it tears easily.
Answer: This is literally what duct tape was invented for.


weird argument value for Javascript function when single vs multiple arguments

Question: Sorry in advance if this has been asked before, but I wasn't able to find it from my searches.
output observed in developer mode for
Firefox 50.1.0
Chrome 55.0.2883.87
** maybe this is what I'm doing wrong, but don't just look at console.log in developer mode, but also click on the details of the object for that specific console.log call
I came across this code from Learning Advanced JavaScript, and I added some console.log calls to understand it better. However, the outputs for my console.log calls do not make sense to me.
I expect the output of the console.log("p00, ...) call to be the same, but the output is different depending on whether the first "return root" is commented or not.
When the first "return root" is not commented, then the console.log("p00, ...) displays an Object with a single property - it being "name". This is what I expect and makes sense to me.
When the first "return root" is commented, then the console.log("p00, ...) displays an Object with two properties - they being "name" and "city".
Why is this happening here ??
.
Below is the Javascript code:
function merge(root){
    console.log("p00, root is ", root);
    console.log("p01, arg length is ", arguments.length);
    console.log("p02, arg is ", arguments);

    // comment out this return call and see the difference
    return root;

    for ( var i = 1; i < arguments.length; i++ ) {
        for ( var key in arguments[i] ) {
            root[key] = arguments[i][key];
        }
    }

    return root;
}

var v1 = {name: "John"};
var v2 = {city: "Boston"};
var merged = merge(v1, v2);
console.log("p03, merged is ", merged);

observed output in Firefox:
first return root uncommented
first return root uncommented
first return root commented
first return root commented
Comment: It was a misunderstanding on my part on how output is displayed in Firefox and Chrome.

Conclusion - for console.log("p00 ...), outputs are the same for both cases, but console provides a reference to the Object, so it will show the final state of the Object when you try to see more details regarding that Object. The JSON.stringify was a great suggestion to see a snapshot of the object.
Comment: your images show the argument, root, is the *same* either way in the first console.log. only the *last* console.log changes with the //return - it will show either the unchanged or merged results, respectively, which is what you see on the right side.
Comment: Thanks goes out to @sweaver2112 and Mike C.
Answer: The console provides a reference to the object you're logging out. That means you're seeing the state of the object after your function has finished running.
If you want to see a snapshot of an object's state, you could try converting it to JSON.

// Be sure to open your real console for this
function reference(obj) {
  console.log(obj);
  obj.b = 2;
}

function json(obj) {
  console.log(JSON.stringify(obj));
  obj.b = 2;
}

reference({ a: 1 });
json({ a: 1 });


Warped Table Top

Question: This is my first project.  I got the table top glued but then i believe, because of not clamping properly, i got a warp on one side in my board.
Please advise: If i try to screw the board to my base by force, I.E. apply pressure on the board and  screw it to the base, would that stay strong or is there an alternate way i can resolve the warp ?
Also would it help if i place a heavy weight on the warped side and clamp the other sides and leave it for a day.

Thanks
Raj
Comment: Have you tried screw that into something substantial and letting it works its way out?   Or have you tried wetting it and weighting it down?   Gravity usually works these things out.   Those are two quick methods I have used.   You could also just sit on the side that is bowed up for a couple weeks until it is even :)
Comment: I am thinking of trying to put a weight on the top but not sure of wetting would it affect my glue ?
Comment: by wetting is it soak it in water or just spray some water on top ?
Comment: I don't think the glue matters right?   Wet it - hose whatever.   Let it sit outside in the grass and sun concave side down.   Take a look every half hour.   This isn't about science - the wood will do what it wants.   This is more like throwing darts at a board while blindfolded.   If it get flat or close to flat, fasten it to something.   You biggest problem isn't flattening it, its that the light table structure underneath may not have the heft to keep this from bowing again.  Once it gets flatter you still need to hit it with a planer/sander.
Comment: Thanks mate will give it a try and sand it immediate once its flat..Hope my base keeps it from not bowing
Comment: @GeorgeAnderson , place that as an answer, I would elaborate how the choice of material is why the warping happened, not the clamping. Sanding the high spots and drawing down is the way to go. The joints look like saw teeth the way the twisted wood is  making the top act. As a cabinet maker friend of mine says "there is a flat top in there somewhere"
Comment: You could permanently bolt angle iron to the boards...on the underside of the table.
Answer: DMoore is right in letting it sit outside on the grass will def. bow it as the wood absorbs moisture, but it'll probably go right back to where it was before when it dries.
If it were my project, I'd let it fully stabilize and work at flattening it. Plane or belt sander are good tools to use. To save work, maybe just get the worst of it flattened and then maybe your table frame could pull out the rest of the bow.
Looking at the growth rings, the OP made a classic beginners mistake. You should have alternated the orientation of the growth rings to reduce warping.   IE: one board's growth rings pointed up the next down, and so on.
Congratulations on getting into woodworking, but have patience because there's a learning curve there!
Comment: Good answer.   You have to at least try.   I would say I have done this method with a good 50 pieces of wood and been happy with 15-20.    All up to the wood gods.

Warped Table Top


Fundamental group of $\{z\in\mathbb{C} \mid |z|\geq 1\}$

Question: I was wondering how I can prove that $A:=\{z\in\mathbb{C} \mid |z|\geq 1\}$ is not homeomorphic to $\mathbb{C}^*$ using fundamental groups.
I do not very much about algebraic topology, I can prove that $\mathbb{C}^*$ is homotopic (equivalent) to $S^1$ so that $\pi_1(\mathbb{C}^*)$ is isomorphic to $\mathbb{Z}.$
Not sure about $A.$ What is the fundamental group of $A$?
I can prove that $A$ is not homeomorphic to  $\mathbb{C}^*$ using one point compactification. I am just curious.
Answer:

Note that $A$ is strong deformation retract into $S^1$ via
  $D:A×I\rightarrow S^1,D(a,t)=(1-t)a+t\frac{a}{||a||}$ . Therefore
  fundamental group of $A$ isomorphic to fundamental group of $S^1$.

For more information, now I prove here that $A:=\{z\in C : |z|≥1\}$ is not homeomorphic to $C^*:=C-\{0\}$ using fundamental group.
If possible let $C^*$ is homeomorphic to $A$ via some homeomorphism $f:A\rightarrow C^*$ then $B:=A-\{1\}$ is homeomorphic to $D:=C-\{0,a\}$ for some $a\in C^*$. Note that B is deformation retract to subspace $ E:=\{z\in C : ||z||= 2\}$ via $g:B×I:\rightarrow E, g(b,t)=(1-t)b+2t\frac{b}{||b||}$ i.e fundamental group of $B$ again isomorphic to $Z$. But notice that $D$ is deformation retract to a subspace $D'\ homeomorphic\ to\ S^1\lor S^1$ and fundamental group of $S^1\lor S^1$ is $Z*Z=a\ free\ group$ which is certainly non-abelian.
Comment: Ok very nice argument. Thank you for sharing this.
Answer: It is a deformation of  $S^1$ (consider $h_t(z)=tz+(1-t){z\over{|z|}}$) so its fundamental group is $\mathbb{Z}$.


Android 2.3.4 SSL problem

Question: After upgrading to Android 2.3.4, I am getting following exception:
javax.net.ssl.SSLException: Read error: ssl=0x*: I/O error during system call, Connection timed out
 at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_read(Native Method)
 at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:788)

Previous versions of Android were working OK. Any hints?
Answer: I have specified SSL timeout explicitly and everything is working again:
val schemeRegistry = client.getConnectionManager.getSchemeRegistry
schemeRegistry.register(new Scheme("https", SSLCertificateSocketFactory.getHttpSocketFactory(timeout,
      new SSLSessionCache(context)), 443))

Android 2.3.4 SSL problem


How to read lists and int from a file?

Question: I'm trying to make a coding system based on Enigma but I'd like to add a twist to it. In order to make to program customizable by the user id like to create "files" wich contains parameters that my prgramm will use to then crypt the message. It includes lists as well as integers. How can I read them?
I have tried using a split method and seperating my lists with "/" but the lists are considered as strings.
Here is an example of the paramaters I would like to assign to, in order, list1, list2, list3, list4, trigger1, trigger2, trigger3 that I tried to seperate with "/":
[6,18,20,12,17,26,19,4,10,22,13,7,14,1,21,9,2,16,3,23,24,8,15,11,25,5]/[1,-5,6,3,-4,2,-4,-4,-3,5,-1,1,-2,-2,-1,3,4,2,5,-4,-4,-4,2,-2,1,5]/[5,-1,-1,-1,-1,1,4,-3,-1,4,1,1,-4,2,-5,4,0,-3,-1,1,-2,0,2,2,-1,-3]/[2,-1,2,0,-3,2,-1,-1,0,2,-1,2,-2,-1,1,4,2,0,-2,-5,2,-1,3,0,-3,-1]/11/5/17

f=open("param.txt")
param=f.read()
list_tbl,param=param.split("/",1)
list_pattern1,param=param.split("/",1)
list_pattern2,param=param.split("/",1)
list_pattern3,param=param.split("/",1)
trigger1,param=param.split("/",1)
trigger2,param=param.split("/",1)
trigger3=param

When I try using the lists, they cannot be used because they are strings.
Comment: Welcome to StackOverflow.  Please read and follow the posting guidelines in the help documentation.  [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here.  We cannot effectively help you until you post your MCVE code and accurately describe the problem.
We should be able to paste your posted code into a text file and reproduce the problem you described.
Comment: Possible duplicate of [Convert string representation of list to list in Python](http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python)
Answer: Have a look at ast.literal_eval which will basically do what you want i.e. make a list out of a string such as this:
from ast import literal_eval
my_string = '[0, 1, 2, 3]'
my_list = literal_eval(my_string)

To create multiple variables you can use a dictionary instead and then just fetch it by a key e.g.:
my_dict = {}
for i in range(10):
    my_dict['list' + str(i)] = <some value>

which is definitely prettier than wasting lines on creating each variable.

How to read lists and int from a file?


How to fill Gridview from two different database tables but the record is not duplicate in Grid

Question: I have a User privilege form, where I load grid from Administrator table, then I insert data from GridView with a Checkbox property in a new User table in database, it works perfectly.
But in next condition I want to load grid from both of two tables, first User table where the data is shown with Checkbox checked true property, and the second Administrator table, where data is shown with check box checked false property.
If u understand my question, so please help me.
My Code is:
protected void CmdUserRights_Click(object sender, ImageClickEventArgs e)
{
    StrSql = "Select Name from Sys.tables";
    StrSql = StrSql + " Where Name='" + "User_" + CboUserId.Text + "'";
    DataSet rs = (DataSet)MethodClass.ConnectionToQuery(StrSql);
    if (rs.Tables[0].Rows.Count <= 0)
    {
        StrSql = "Select * from User_Administrator";
        StrSql = StrSql + " Order by serial_no asc";
        DataSet rs2 = (DataSet)MethodClass.ConnectionToQuery(StrSql);
        GvUserPrivilege.DataSource = rs2.Tables[0];
        GvUserPrivilege.DataBind();
    }
    else
    {
        StrSql = "Select * from " + "[User_" + CboUserId.Text + "]";
        StrSql = StrSql + " Order By serial_no asc ";
        DataSet rs4 = (DataSet)MethodClass.ConnectionToQuery(StrSql);
        if (rs4.Tables[0].Rows.Count > 0)
        {
            GvUserPrivilege.DataSource = rs4.Tables[0];
            GvUserPrivilege.DataBind();
            foreach (GridViewRow rows in GvUserPrivilege.Rows)
            {
                CheckBox ChkBoxRows = (CheckBox)rows.FindControl("chk");
                ChkBoxRows.Checked = true;
            }
        }
        else
        {
        }
    }
}

Comment: The statement is a bit unclear, but if you have two related tables, then it would be better to write a Join query with all conditions implemented in SQL and bind your GridView to that query. Best regards,
Answer: Agree with Alex Bell.
Try to join tables like this:
SELECT
    Administrator.*,
    (User.somefield IS NOT NULL) checked
FROM Administrator
LEFT JOIN User
    ON [join condition here]

If some record exists in User table, then expression (User.somefield IS NOT NULL) will be true (you need to use some NOT NULL column for this). Otherwise, it will be false.


How to draw an image based on data stored on an array in Google Colab

Question: I need to create something like this

in Google Colab. I have all the data on an array. First, I tried using matplotlib to create a horizontal bar chart. I made this based on the examples given on their documentation:
import matplotlib.pyplot as plt
import numpy as np

n = 4
bars1 = (20, 35, 30, 35)
bars2 = (25, 32, 34, 20)
ind = np.arange(n)    # the x locations for the groups

fig, ax = plt.subplots()

p1 = ax.barh(ind, bars1)
p2 = ax.barh(ind, bars2, left=bars1)

ax.set_ylabel('Bars')
ax.set_title('Divisions of each bars')

plt.yticks(ind)

# Label with label_type 'center' instead of the default 'edge'
ax.bar_label(p1, label_type='center')
ax.bar_label(p2, label_type='center')

plt.show()

and this is the result of this code

This looks good, but has a major limitation: I need to have the same number of intervals on every bar, which doesn't always happen on the first picture. Which library could I use to recreate something like this? I tried searching but I don't know exactly how to specify my problem.
Comment: Where does it say you need the same number of intervals?
Comment: I tried making `bars1` smalled and got a shape missmatch error. And if I do something like `bars1 = (20, 35, 30, 0)` I get the 0 written on the chart.
Comment: What if you replace that `0` with `NaN`?
Comment: @MattDMo if I do this `bars1 = (20, 35, 30, float("NaN"))` the 4th bar doesn't get drawn.
Comment: Where did you get the image? Do you know what that style of displaying numbers is called?
Comment: @MattDMo the image was sent to me by a friend. I believe it was made using Excel.
Answer: I think you can achieve that with the code you already wrote.

The first thing let's consider is that each bar needs to have an
accumulated value = 100 (it can be any number) let's called MAX.

Then for each bar, you calculate the actual value you have, and if
it's less of our MAX, add the MAX - current value to your bar.

like that we will have all bars at MAX value.
but you will not have the exact same number of sections in each bar if one of those is already at MAX value. to fix that you will need to calculate the MAX value by finding the maximum value in your bars and add x value to it.
code :
import matplotlib.pyplot as plt
import numpy as np

def get_added_bar(bars):
    max = 0
    new_limit = 0
    added_val = 5
    vertic_sums = []
    added_bar = []
    for x in bars:
        t=0
        for item in x:
            if t > len(vertic_sums)-1:
                vertic_sums.append(item)
            else:
                vertic_sums[t]  = vertic_sums[t]+item
            if vertic_sums[t] > max:
                max = vertic_sums[t]
            t=t+1
    new_limit = max + added_val
    t=0
    for x in vertic_sums:
        added_bar.append(new_limit-vertic_sums[t])
        t=t+1
    return tuple(added_bar)

def sum_bars(bars) :
    vertic_sums = []
    for x in bars:
        t=0
        for item in x:
            if t > len(vertic_sums)-1:
                vertic_sums.append(item)
            else:
                vertic_sums[t]  = vertic_sums[t]+item
            t=t+1
    return tuple(vertic_sums)

n = 4
# 0 for missing value
bars1 = (0, 35, 30, 35)
bars2 = (25, 32, 0, 20)
added_bar = get_added_bar((bars1,bars2)) #

ind = np.arange(n)    # the x locations for the groups

fig, ax = plt.subplots()

print((bars1,bars2,added_bar))

p1 = ax.barh(ind, bars1)
p2 = ax.barh(ind, bars2, left=bars1)
p3 = ax.barh(ind, added_bar, left=sum_bars((bars1,bars2)), color='white')

ax.set_ylabel('Bars')
ax.set_title('Divisions of each bars')

plt.yticks(ind)
print(ind)

# Label with label_type 'center' instead of the default 'edge'
ax.bar_label(p1, label_type='center')
ax.bar_label(p2, label_type='center')
# ax.bar_label(p3, label_type='center')

plt.show()

you can check, I created a working example here:
https://replit.com/join/mgpidbnqfb-amirping
you can change any value in your bars with 0 if it's missing and you will still have it working
Comment: My problem is that I can only have a fixed number of "sections" on each bar, and my example doesn't. See the comment I added to the question.
Comment: Please post some code to demonstrate what you're talking about. It's not very clear at the moment.
Comment: Please post the code *as text, in the answer itself*. Links to external sites can change or rot, and this answer would be useless without it. It's also not appreciated when you link to sites that require membership/logins.
Comment: I'm sorry but I'm not getting the results shown in the image on Google Colab. There are no errors being throw, but the chart doesn't look anything like this. It also isn't showing correctly on replit.
Answer: The trick to getting a section to not appear is to add a value of np.nan, not float("nan"). So, using this data:
bars1 = (20, 35, 30, 35)
bars2 = (25, 32, 34, np.nan)

results in this graph:
Comment: The problem was that I was using NaN on `bars1`. `float("nan")` also works if I use it on `bars2`. I'm wondering now if I can recreate what I need using this.


How to remove  from Walker_Nav_Menu of wordpress

Question: I want to remove
 from Walker_Nav_Menu ,I am getting default
 in menues ,I have tried to rename container in but it is not working

About Us

Contact us

Enquiry

Home

Product

Sample Page

code to print menu
<?php wp_nav_menu( array( 'theme_location' => 'main-menu' ) ); ?>

$defaults = array( 'menu' => '', 'container1' => '', 'container_class' => 'false', 'container_id' => '', 'menu_class' => '', 'menu_id' => '',
    'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '
%3$s
',
    'depth' => 0, 'walker' => '', 'theme_location' => '' );

Comment: `'menu_class' => ''` is one of the arguments you can pass which will remove the menu class?
Comment: Also give the code from which you are getting that menu.
Comment: I have mentioned code to print menu
Comment: Still div is not getting removed , i have changed 'menu_class' => ''  but div remain as it is
Answer: You can use the container argument to declare if you want to use a div or ul.
$args = array(
    'theme_location' => 'main-menu',
    'container' => 'ul'
);

echo wp_nav_menu($args);

Comment: where should i ,make this change ,in  waker_nav_menu ?
Comment: You should replace the code you use to output your menu, with the code provided (Remember to add  after it)
Comment: same problem , div before   not getting removed
Comment: Are you using any sort of caching systems, e.g. WP Super Cache? If so you may need to purge the cache.
Comment: not using any  caching systems ,only making changes in nav-menu-template.php ,
Comment: So you are editing the core file inside of wp-includes?
Comment: Core files should not be edited, instead you should use filters and actions to edit the output before it reaches the page. If you would like to still edit the core file do this change: Line 227 (Starts with $defaults) and change 'container' => 'div' to 'container' => 'ul'
Comment:  is still not getting removed ,from where should,div can be removed
Comment: If you go to your theme functions.php file (wp-themes/{your current theme}/functions.php) and add this code:

add_filter('wp_nav_menu_args', function($args) {
 $args['container'] = 'ul';
 return $args;
});
Comment: I am using blankslate theme is that making any difference
Comment: It shouldn't but they may be overriding the container argument, so the change in my last comment should fix that
Comment: In function.php there is a line add_filter( 'the_title', 'blankslate_title' ); should i edit it ?
Comment: *Update*: I have had a look at the blankslate theme, if you open wp-contents/themes/blankslate/header.php, change `array( 'theme_location' => 'main-menu' )` to `array( 'theme_location' => 'main-menu', 'container' => 'ul' )`
Comment: I have made changes,  wp_nav_menu( array( 'theme_location' => 'main-menu', 'container' => 'ul' ) ); but not working ,
Comment: @JamieSimmonds It will not remove ``. Your code will add `ul` instead of removing.
Comment: Could you try `array( 'theme_location' => 'main-menu', 'container' => false )` *Update*: I see you got your answer already :)
Answer: All you need to add is false in container argument to achieve this.So it will be something like container=>false.
But it will only work if you have correct theme_location. For an example, If you are using default menu in wordpress without creating any menu or without assigning any location to created menu, then above suggestion will not work.
So to make it work, create menu and assign location to it and make sure your wp_nav_menu also contains same location.
Edited
Replace your theme's header.php Line 21 with following code:
<?php wp_nav_menu( array( 'theme_location' => 'main-menu', 'container'=>false, 'menu_class'=> 'your_class_name' ) ); ?>

Comment: I have tested it ! You might be missing something ..Try some debugging please :)
Comment: @abhiAhere Are you kidding me ? ` 'main-menu', 'container'=>false ) ); ?>` This code is working perfectly fine. You must not added your menu to `main-menu` location.
Comment: ok,it was my fault,but if i want to add class to first ul ,how it can be done?
Comment: Thanks, that helped me a lot too! I know it's slightly off topic but is there away to add classes onto the list-items and anchors using the `wp_nav_menu` array? Total novice here!
Comment: @user1406440 Yes.It is possible. You can create your own class extending wordpress menu class. [Reference](https://codex.wordpress.org/Class_Reference/Walker#General_Menu_Example)


VirtualBox 5.0.40 crashes the whole host since update to kernel 4.13.0-26-generic

Question: I received the updates through normal Software Updater, 10-Jan-2018. After this VirtualBox would not start any VM, complaining about dkms and asking to make modprobe vboxdrv. Following the advice I reinstalled virtualbox-dkms with:
sudo apt-get --reinstall install virtualbox-dkms

After this and a reboot I tried to start a VM which freezed the whole machine and a hard reboot was necessary.
Is there a way to make VirtualBox work with the latest kernels?
EDIT:
As suggested by N0rbert, the command:
apt-cache policy `dpkg -S VirtualBox | head -n1 | sed -e 's/://g' | awk '{print $1}'`
gives:

virtualbox-qt:
  Installed: 5.0.40-dfsg-0ubuntu1.16.04.2
  Candidate: 5.0.40-dfsg-0ubuntu1.16.04.2
  Version table:
 *** 5.0.40-dfsg-0ubuntu1.16.04.2 500
        500 http://fr.archive.ubuntu.com/ubuntu xenial-updates/multiverse amd64 Packages
        100 /var/lib/dpkg/status
     5.0.18-dfsg-2build1 500
        500 http://fr.archive.ubuntu.com/ubuntu xenial/multiverse amd64 Packages

EDIT (on 29-Mar-2018): Issue is resolved for me, with the Ubuntu Ubdate from today. I have seen that it had some virtualbox-updates, therefore I tried to boot with the most recent kernel again. Then I had to run
sudo apt-get --reinstall install virtualbox-dkms
And after this my virtual machines in VirtualBox started working without crashing the whole computer. Finally!
Comment: Please update your post with output of: `apt-cache policy \`dpkg -S VirtualBox | head -n1 | sed -e 's/://g' | awk '{print $1}'\``.
Comment: I have found KVM/QEMU to be much more stable across kernel updates - the price that I pay for this is that there is not yet support for 3D graphics acceleration.
Comment: @Takkat: But I VirtualBox 5.2.4 is **not** part of Ubuntu 16.04 - I just looked up with synaptic!? I have chosen on purpose the VirtualBox from the Ubuntu distribution to be in sync with the kernel and to avoid headaches like these.
Comment: Try to upgrade virtualbox to current release 5.2.4. Some kernel issue for newer kernels were resolved in the meantime.
Answer: Upgrading to VirtualBox 5.2 using oracle repository worked for me.
Here are the steps (legacy doc here):
1) Add oracle repository :
sudo add-apt-repository "deb http://download.virtualbox.org/virtualbox/debian xenial contrib"

Modify this command to suit your ubuntu version if you are not using Ubuntu 16.04 (xenial).
2) Add GPG keys for repository :
wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add -
wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -

3) Check GPG keys :
sudo apt-key finger Oracle

should give show the following fingerprints :
B9F8 D658 297A F3EF C18D  5CDF A2F6 83C5 2980 AECF
Oracle Corporation (VirtualBox archive signing key)

7B0F AB3A 13B9 0743 5925  D9C9 5442 2A4B 98AB 5139
Oracle Corporation (VirtualBox archive signing key)

4) Install VirtualBox 5.2
sudo apt update && sudo apt install virtualbox-5.2

In my case I had errors and I had to remove virtualbox-dkms package and run /sbin/vboxconfig :
sudo apt remove --purge virtualbox-dkms
sudo  /sbin/vboxconfig

Depending on your desktop environment, the launcher menu icon may have disappeared. In that case, recreate it manually; the command is simply virtualbox.
Comment: I also had to install the 5.2 extension pack, like this: `curl -O http://download.virtualbox.org/virtualbox/5.2.0/Oracle_VM_VirtualBox_Extension_Pack-5.2.0-118431.vbox-extpack ;
sudo VBoxManage extpack install Oracle_VM_VirtualBox_Extension_Pack-5.2.0-118431.vbox-extpack`
Comment: This works for me. Still, if you rather not spend time downloading, installing and configuring, see @therefriedbean post.
Comment: After installing the newer version, my VMs still wouldn't start. See Andy's answer on how to fix this.
Comment: For the first step, `sudo echo "..." > /etc/..` won't work when run as a normal user because only the `echo` runs under `sudo`. IMO the best way to handle this is probably `echo "..." | tee -a /etc/...`
Comment: @EvanED Thanks, I edited my answer to use `add-apt-repository` which I think is more self explanatory. For those who want to use `sources.list.d` the command is `echo "deb http://download.virtualbox.org/virtualbox/debian xenial contrib" | sudo tee /etc/apt/sources.list.d/oracle-virtualbox.list`.
Comment: didn't work for me because VBOX 5.2 cant open my earlier used images, it says that it can't access the image  (*.vdi file)
Comment: At the moment this is the solution. Or a manual download from the virtualbox 5.2.6 site. Seems the latest kernel has issues with earlier virtualbox versions.
Comment: to avoid future problems `virtualbox` should be **completely unistalled** with something like `sudo apt-get remove virtualbox*` or `sudo aptitude remove virtualbox` **before installing the new version**. **||** additional the line `wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -` is just needed for systems older than Ubuntu 16.04 (xenial) or Debian 8 (jessie); so it can or rather should be left out on these or newer versions.
Comment: can't install virtualbox-5.2 it says:   E: Unable to locate package virtualbox-5.2
E: Couldn't find any package by glob 'virtualbox-5.2'
E: Couldn't find any package by regex 'virtualbox-5.2'
what should i do??
Comment: @FatemehKarimi I think it means that either you haven't added the repository correctly (`add-apt-repository` command), or you haven't updated apt database (`sudo apt update`). Hope that helps.
Answer: Cross referencing:
Official bug tracking this issue is:
https://bugs.launchpad.net/bugs/1736116
There are solutions there for installing VB  5.1.30 as well as 5.2.4. Some users are reporting QT dependency issues with 5.2.4, so 5.1.30 might be a safer bet.
Several options for installing either version are listed there, and the discussion is ongoing, so I am not going to reproduce here.
Comment: i experienced the same qt-issues (just optical ones) in `virtualbox-5.1` as in `virtualbox-5.2`...
Comment: Also, detailed instructions at https://superuser.com/a/1305277/53547
Answer: When you boot your machine change which kernel you boot into by going into "Advanced options for Ubuntu".
Pick the version number like 4.10 -- Should start working until this gets fixed.
Comment: This is indeed what I did. I booted in the previous kernel and am waiting until Ubuntu updates it's virtualbox to work with their latest kernel.
Comment: that might work, but the newer kernels (that don't work together with virtualbox) bring fixes for meltdown/spectre!
Answer: So, in my case, the kernel modules were not removed properly.
Here are the details:
root@Dell5280 [~]# cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.3 LTS

root@Dell5280 [~]# uname -r
4.13.0-31-generic

Problem:
root@Dell5280 [~]# modinfo vboxdrv
filename: /lib/modules/4.13.0-31-generic/updates/dkms/vboxdrv.ko
version: 5.0.40_Ubuntu r115130 (0x00240000)
license: GPL
description: Oracle VM VirtualBox Support Driver
author: Oracle Corporation
srcversion: 6D8B4900A693FC50489A130
depends:
name: vboxdrv
vermagic: 4.13.0-31-generic SMP mod_unload

FIX:
root@Dell5280 [~]# rm /lib/modules/4.13.0-31-generic/updates/dkms/vboxdrv.ko

root@Dell5280 [~]# modinfo vboxdrv
filename: /lib/modules/4.13.0-31-generic/updates/dkms/vboxdrv.ko
modinfo: ERROR: could not get modinfo from 'vboxdrv': No such file or directory
[1] root@Dell5280 [~]# /sbin/vboxconfig
vboxdrv.sh: Stopping VirtualBox services.
vboxdrv.sh: Building VirtualBox kernel modules.
vboxdrv.sh: Starting VirtualBox services.

root@Dell5280 [~]# modinfo vboxdrv
filename: /lib/modules/4.13.0-31-generic/misc/vboxdrv.ko
version: 5.2.7 r120349 (0x00290000)
license: GPL
description: Oracle VM VirtualBox Support Driver
author: Oracle Corporation
srcversion: 4880B21EFF1B605D6402982
depends:
name: vboxdrv
vermagic: 4.13.0-31-generic SMP mod_unload
parm: force_async_tsc:force the asynchronous TSC mode (int)

After this, everything works (at least in my case)
Hope it helps.
I posted the reply at https://bugs.launchpad.net/ubuntu/+source/virtualbox/+bug/1736116
Comment: This helped me too after downloading virtualbox 5.2.6 from the website.


MySQL SELECT DISTINCT ... ORDER BY without a temporary table or filesort

Question: I have a query running on a table with half a million rows.  I have a composite index called wafer_name_date on the columns (wafer_name, date).  By adding the index, this query now takes .06 seconds, but still reports using a temporary table and filesort.  Is there any way to avoid this?  thanks!
EXPLAIN SELECT DISTINCT wafer_name FROM flash ORDER BY date\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: flash
         type: range
possible_keys: NULL
          key: wafer_name_date
      key_len: 767
          ref: NULL
         rows: 4308
        Extra: Using index for group-by; Using temporary; Using filesort

Comment: What is your table structure? (the result of `SHOW CREATE TABLE your_table`)
Answer: Your query is a bit awkward, because "date" is not included in the result set.  Yet, you are ordering by date.  I would expect something like:
select wafer_name, min(date)
from flash
group by wafe_name
order by min(date)

As the explain says, the execution plan using the index for the grouping (distinct) values.  This produces a single value for wafer_name and an arbitrary value for date.  It is pulling the arbitrary date from the index (rather than looking it up on the corresponding page).
However, it then needs to sort the results by date.  It can't use the index you defined, because this is by wafer_name first, and you only have one date per wafer_name.  So it saves out the data and does a sort.
I can't think of a way around this.


Issue with Javascript file order and Bundling and Minification

Question: I include moment in my ASPNET BundleConfig
<code>                    "~/Scripts/bootstrap.min.js",

                    "~/Scripts/moment-with-locales.min.js",
</code>
I have two web servers:

A: Windows Server 2008, IIS 7.5, .NET 4.6.2
B: Windows Server 2012, IIS 8.0, .NET 4.6.2

When using B, in Firebug, I see the GET for both come back as 200 OK, but in the Console I see "moment is not defined".

I've also tried plain old moment.js in place of -with-locales but I get the same error.
Furthermore, the failure does not happen on A.
How could the webserver matter such that the file loads in the browser but the object isn't there?
Answer: If the server is responding with the moment.js file when a request is made for moment.js than your server is not where the issue lies.
The issue lies with your Javascript, you are using moment in your Javascript before moment.js has been loaded in the browser. The error says "moment is not defined", it is not a 404 error as your server might return if it could not find the moment.js file.
The order the Javascript files could be different in Server B's response(s) compared to Server A's response(s)
Comment: One thing I neglected to add is the Server A is minifying and bundling the scripts where was Server B isn't. Could that have something to do with moment not being loaded before it is used?
Comment: @JohnMc Yes, with ASP.NET bundling and minification, you set the order the of the Javascript files response  in a C# file, if there is no bundling and minification, the order is different and it is defined in your index.html or a .cshtml
Comment: @JohnMc No minification itself makes no difference, the order of the Javascript files could be different on Server A compared to Server B
Comment: Alright that makes sense in theory. But I can't see how my non-minimized response from Server B could be any different to prevent the error. Firebug's Script tab shows


segmentation error while using return statement returning recursive function

Question: #include<stdio.h>

float small_array_recursion(const float[],int);

int main(){
    float array[]={-34,-89,3,9.67,45,12};

    int size=6;

    float value=small_array_recursion(array,size);

    printf("%s%.2f","smallest value in the array is ",value);
}

float small_array_recursion(const float array1[],int size){
    int len=size-1;

    static float min=3.36e9;

    if(len==0){
        return array1[0]<min?array1[0]:min;
    }
    else if(array1[len]<min){
        min=array1[len];
        return small_array_recursion(array1,len);
    }
    else
       return small_array_recursion(array1,len);
}

Comment: Sorry, this is not a recursion problem. Having a hammer does not mean that everything around you is a nail...
Comment: Given `array1[0]>max`, where is `max` defined?  Best to post a [mcve].
Comment: Write floats as floats, like 'float array[]={-34.0, -89.0, 3.0, 9.67, 45.0, 12.0};' (use decimal point)
Comment: Apart from that, the code is (still) rubbish. 'max' is missing as already stated. And I can not (yet) recognize any useful logic in this code.
Answer:
Write floats as floats, like 'float array[]={-34.0, -89.0, 3.0, 9.67, 45.0, 12.0};' (use decimal point)

The code is correct, if you replace variable "max" by "min".

For special case 'len==0', the following two lines need to be added
if(array1[len]<min)
min=array1[len];

to cover the case, if the first array element is the smallest one.
Then, the full, correct code is:
#include<stdio.h>

float small_array_recursion(const float[],int);

int main(){
    float array[]={-34., 89.,3.,9.67,45.,12.};

    int size=6;

    float value=small_array_recursion(array,size);

    printf("%s%.2f","smallest value in the array is ",value);
}

float small_array_recursion(const float array1[],int size){
    int len=size-1;

    static float min=3.36e9;

    if(len==0){
        if(array1[len]<min)
        min=array1[len];
        return min;
    }
    else if(array1[len]<min){
        min=array1[len];
        return small_array_recursion(array1,len);
    }
    else
       return small_array_recursion(array1,len);
}

Anyway, while the example is working. The return values of the function
don't go anywhere when called from within the function. This is possible,
because variable 'min' was declared as static. It might be a good exercise
to achieve the recursion without variable "min" being static.
Yes, like commented by Fe2O3, this clearly is not a recursion problem,
to find the minimum of an array. I agree. Well, it could be seen as an
exercise where recursion can be applied.
Adapted code with recursion without a static variable "min".
#include<stdio.h>

float small_array_recursion(const float[],int,float);

int main(){
    float array[]={34., 89.,993.,9.67,45.,120.};
    int size=6;
    float min=3.36e9;
    float value=small_array_recursion(array,size,min);

    printf("%s%.2f\n","smallest value in the array is ",value);
}

float small_array_recursion(const float array1[], int size, float min){

    int len=size-1;
    float localmin;

    localmin=min<array1[len] ? min : array1[len];

    if(len>0)
    {
        return small_array_recursion(array1, len, localmin);
    }
    else
    {
        return localmin;
    }
}

Comment: it is an excercise asked to do it by recursion. I understand there are multiple ways to do this. i mistakenly wrote max instead of min. Even if it is done, it still shows segmentation error in VS code editor.
Comment: Then, please also accept the answer (means: vote up = arrow up on the left side of the answer). Or if there is still something else about it, like within VS code editor, let us know.
Comment: i am not eligible to vote up
Comment: Please read here: https://stackoverflow.com/help/someone-answers which says: "To mark an answer as accepted, click on the check mark beside the answer to toggle it from greyed out to filled in."
Answer: This is not well suited to recursion. If this were an 'interview question', attempting recursion would be a 'fail'.
And, unless there is a space constraint, double is more likely a better size for the floating point values.
#include <stdio.h>

int main() {
    // use spaces to make your values readable
    double array[] = { -34.0, -89.0, 3.0, 9.67, 45.0, 12.0 };

    int minInd = 0;
    for( int i = 1; i < sizeof array / sizeof array[0]; i++ )
        if( array[ i ] < array[ minInd ] )
            minInd = i;

    printf( "Smallest value in the array is %.2f", array[ minInd ] );

    return 0;
}

Output:
Smallest value in the array is -89.00


Fetch all values from column in mysql table and sum the values in java

Question: Name   Id
aa      1
bb      5

I use this to fetch all values from id column
SELECT id FROM name_table;

I want to sum the values in the id column. To be clear, I am making a financial application and want to add up all the money recorded in the msql database
Answer: If you want to just get sum of all ID values, then this would work:
SELECT SUM(id) FROM name_table

Comment: Why would you sum IDs?
Answer:     int sum = 0;
    while (res.next()) {
    int i = res.getInt(1); or rs.getString("id "); //using column name
    sum = sum + i;
    System.out.println(sum);
 OR
  String q= "SELECT SUM(id) as totalSum FROM tableName";
  PreparedStatement pst = connectio.prepareStatement(q);
  ResultSet rs = pst.executeQuery();
   if (rs.next()) {
    sum = rs.getString("totalSum");
   System.out.print("total sum" + sum);
    } else {
  System.out.print("Query didn't return any results");
  }


"Clear All" shortcut in IntelliJ IDEA run console log

Question: Does anyone know a keyboard shortcut to clear the console log in IntelliJ??
I have looked everywhere and I don't seem to find it
Answer: There is no default shortcut, you have to add it:
Comment: Unfortunately, you have to put the focus on the console before executing the shortcut
Comment: Is there any way to clear console upon deploying or running app?
Comment: What did you bind it to? I can't find a good key combination
Answer: on mac you can do it with cmd + k
Comment: cmd + k opens the commit page
Comment: i believe you have to focus on terminal for the shortcut to work ?


Connecting two single pole switches

Question: I am replacing two old switches in a bathroom.  I purchased two standard single pole switches from home depot (two screws on one side, ground screw on the other)  the old switches had a wire connecting the two switches.
I'm assuming the line from the panel feeds one switch, the jumper wire feeds the other switch and the other two wires power their respective light sources.  I've tried multiple connections and am getting the same problem.  The switches do not work independently.
One switch seems to power both of them, so when i turn that switch on, both lights turn on,  then the other switch can turn on and off it's light only if the other switch is on.
What am i doing wrong?
Any help would be greatly appreciated!
Comment: my photos were to big to post so i will try and send a link... https://photos.app.goo.gl/GLWDvjuCq3K72zSu5
Comment: A picture showing the wires & switches would help a lot.
Comment: Yes, can you post photos of the inside of the box in question please?
Comment: i would like to post some pics of the wiring but for the life of me, i can't figure out where to post pics??
Answer: Pretty sure you have crossed up the hot wire. Disconnect all three wires from switches, temporarily connect or bump all three two-wire combinations. Only one combination will power neither light, the solo wire will be the hot that needs to be jumpered between switches.

Connecting two single pole switches


How to handle drop down menus using Selenium on Python?

Question: I am trying to select an item from drop down menu after i open the page automatically with selenium.
print(driver.find_element_by_class_name("col-xs-6 bold text-right").text)

This is one of my codes tried to access the text. But it gives this error.
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".col-xs-6 bold text-right"}
  (Session info: chrome=86.0.4240.75)

In this picture you can see which menu and which section i need to select item from.
NOTE** After the page in the picture just opened, when i click to look at the paths first it navigate me to  == $0 when i click to look at the paths again it navigates me to
Thank you in advance.
Comment: Please add the code you used to select the option in the drop down.
Comment: `selected = Select(driver.find_element_by_xpath("/html/body/div[1]/div[1]/div[2]/div[1]"))
selected.select_by_index(0)` or `driver.find_element_by_xpath("/html/body/div[1]/div[1]/div[2]/div[1]").click()`
Comment: You need 2 clicks. One to open the drop down and another to click the item in the list.
Comment: But when i run the click section it gives me error. If you give me an example i would be glad.
Answer: First, "col-xs-6 bold text-right" class selector doesn't match with the image attached.
Second, to select the drop-down menu items in selenium, you have to click the drop-down element first, and then menu-item.
Comment: Can you show me an example about this ? Because i am trying to click but it is not working.
Comment: Let me have the url and test credentials if needed.
Comment: Or you can let me have the HTML content so that I can test on my side.


Select a particular record from a table using checkboxes

Question: I would like to have records on a table be selected using a checkbox.
For example if I have a table that stores Name,Contact and Country of an individual. I would like to be able to select individual records using checkboxes and be able to submit their values to a database.
      Name      Contact           Country
      Sam       email@example.com      India
      Jane      email@example.com     USA

The database part is no issue, just need to be able to collect the values stored here.
Comment: Have you tried something and found yourself stuck?
Comment: Not yet. I'm quite new to HTML and I am unable to get the programming logic.
Answer: There's a bunch of different ways you could go about this task. I'll present one way.
The idea is that you get a list of all the checkboxes(input elements, of type checkbox) in the (html) table of interest. From there, if the box is chcked, you find out which cell element contains it. You then find which (html) table row contains that cell. You can then use the cells collection of that row to get the various pieces of data in that row.
HTML

Name	Contact	Country	Selected

Sam	email@example.com	India	<input type='checkbox'/>

Jane	firstname.lastname@example.com	USA	<input type='checkbox'/>

<button onclick='showSelected()'>Show selected</button>

Javascript
function showSelected()
{
    // get all checkbox elements that exist in the table of interest
    var checkBoxes = document.querySelectorAll('#infoTable input');

    var i, n = checkBoxes.length;
    var msg = 'Selected items:\n';

    for (i=0; i<n; i++)
    {
        var curCheckbox = checkBoxes[i];
        if (curCheckbox.checked == true)
        {
            var containingCell = curCheckbox.parentNode;
            var containingRow = containingCell.parentNode;

            var curName = containingRow.cells[0].innerHTML;
            var curContact = containingRow.cells[1].innerHTML;
            var curCountry = containingRow.cells[2].innerHTML;

            msg += curName + ' - ' + curContact + ' - ' + curCountry + '\n';
        }
    }
    alert(msg);
}

See it in action here: http://jsfiddle.net/xphaL/


solving 3 simultaneous 2nd order ODEs

Question: I have done first order simultaneous ODEs of this form, but only homogeneous so I am not sure how to vary my method for the equations below:
$$\frac{d^2x}{dt^2}+k(2x-y)=0,\,\frac{d^2y}{dt^2}+k(2y-x-z)=0,\,\frac{d^2z}{dt^2}+k(2z-y)=e^{-t}$$
It is the final equation being equal to $e^{-t}$ that puts me off. I started by putting it in the form:
$$\frac{d^2}{dt^2}
\begin{pmatrix}
x\\y\\z
\end{pmatrix}
=-k\begin{pmatrix}
2x-y\\2y-x-z\\2z-y
\end{pmatrix}
+\begin{pmatrix}
0\\0\\e^{-t}
\end{pmatrix}$$
Which can then be rewritten as:
$$\frac{d^2}{dt^2}
\begin{pmatrix}
x\\y\\z
\end{pmatrix}
=-k\begin{pmatrix}
2&-1&0\\-1&2&-1\\0&-1&2
\end{pmatrix}
\begin{pmatrix}
x\\y\\z
\end{pmatrix}
+\begin{pmatrix}
0\\0\\e^{-t}
\end{pmatrix}$$
I would normally start by letting:
$$\begin{pmatrix}
x\\y\\z
\end{pmatrix}
=\begin{pmatrix}
X\\Y\\Z
\end{pmatrix}e^{\lambda t}$$
and finding the eigenvalues and eigenvectors of $M-I\lambda^2$, where $M$ is the matrix
EDIT:
The initial conditions are:
$$x(0)=x'(0)=y(0)=y'(0)=z(0)=z'(0)=0$$
Answer: Assuming you know the Laplace Transform technique, Calling $X = (x,y,z)^{\dagger}$
$$
s^2 X(s) + k M X(s) = \left(\begin{array}{c}0\\ 0\\ \frac{1}{s+1}\end{array}\right)
$$
hence
$$
X(s) = \left(I_3 s^2+k M\right)^{-1}\left(\begin{array}{c}0\\ 0\\ \frac{1}{s+1}\end{array}\right) = \left(
\begin{array}{c}
 \frac{k^2}{(s+1) \left(s^6+6 k s^4+10 k^2 s^2+4 k^3\right)}\\
\frac{k}{(s+1) \left(s^4+4 k s^2+2 k^2\right)} \\
\frac{\left(s^2+k\right) \left(s^2+3k\right)}{(s+1) \left(s^2+2 k\right) \left(s^4+4 k s^2+2 k^2\right)} \\
\end{array}
\right)
$$
Comment: I have never seen this technique before but have used Laplace transforms, thanks!

solving 3 simultaneous 2nd order ODEs


Is Pokemon's progress saved to the cartridge or the 3DS system it's played on?

Question: I want to have two separate games of Ultra Moon, but I only have one console. If I have two copies of Ultra Moon, will they have different progress if swap them in the same 3DS?
Answer: Yes. Pokémon games have always and still do save your progress to the physical cartridge, not the console itself.
Answer: According to Nintendo, all 3DS games are saved to the cartridges they are played on (unless they are games downloaded from the eShop). The only information saved to the 3DS system itself by some games is StreetPass and SpotPass info.
Pokémon Ultra Moon is no exception, all information is stored on the Game Card.
Answer: You can only have one digital copy of a specific game on a console at a time, and it can only have one save file at a time.
Save files for physical copies are stored in the cartridge. As a result, different physical copies have their own saves tied to them, even for the same game.


Problem with internet access on virtualbox

Question: I installed Virtualbox on Windows 10 machine and then installed ubuntu 14.04. But I have a problem with the internet access that I can't connect the ethernet network, while I still normally able to connect in my windows machine. And one thing that I want to ask is in my Network setting, the option Enable Network Adapter is disabled, I can not choose it, does anyone have an idea?
Comment: Do you try with bridged mode .
Comment: yes, but it still also not able to choose Network Adapter
Answer: I think you need to check the option that says "Cable connected."
Answer: It's disabled because you accessing the settings of your VM while guest OS is running. You should shut it down first, and then try to use NAT instead of Bridged mode.
Comment: aha, yes now i can choose the network adapter, but i still cant connect to the internet T.T
Comment: @Son did you also try to select different hardware like described [here](http://askubuntu.com/questions/143776/no-internet-connectivity-in-virtual-box-with-both-host-and-virtual-os-being-12-0)? Try to select different adapters. Maybe this will solve your problem.
Answer: I had deleted the guest account on my instance and INSERTED my MAC address from hardware into Ubuntu network settings. I used Bridged adapter and PCNET fast III. (Virtual box on MAC)
This is my first answer so go easy on me!
Answer: Following settings worked for me:

I also refreshed the MAC number (see the refresh button next to MAC number, press that.)


How to limit web site access to USA only

Question: how do I limit my website access to USA only, using ASP Classic (windows server). I read about htaccess, but not sure how to implement that to ASP classic programming language.
Comment: The .htaccess file is specific to Apache servers and Classic ASP runs on IIS only.  Anyway, you would need to block IP ranges, and that's something which you would need to do with your server firewall settings rather than through Classic ASP.  This question is worth a read http://stackoverflow.com/questions/2111246/how-to-limit-web-site-access-to-usa-or-north-america-only
Comment: Also @John blacklisting IPs is a poor implementation as they are easily spoofed.
Comment: You will have all the success that Netflix had: i.e. none
Answer: You can add htaccess-functionality by implementing an IIS-Module (i.e. Helicon Ape) which allows you to set IP-Ranges. Such a module has to be installed on your Windows Webserver (Server 2008 and above) and will be configured in your IIS-Manager. Once this is done you are able to use htaccess in nearly the same way as on an Apache Server.
Another (theoratical) way is to do a server-side check on the remote IP-address.
First you need to retrieve the remote IP-address
remote_addr = Request.ServerVariables("REMOTE_ADDR");

Then you can compare against given ranges
function compareIps(ip, lowrange, highrange)
   dim octetIPArray(4) as integer, octetIPLowArray(4) as integer, octetIPHighArray(4) as integer
   compareIps = False
   octetArray = split(ip, '.', -1, vbtextcompare)
   octetIPLowArray = split(lowrange, '.', -1, vbtextcompare)
   octetIPHighArray = split(highrange, '.', -1, vbtextcompare)

   for i = 0 to 3
      if octetArray(i) >= octetIPLowArray(i) and octetArray(i) <= octetIPHighArray(i) then
         compareIps = True
         exit function
      end if
   next
    end function

if compareIps(remote_addr, "126.96.36.199","184.108.40.206")=True then
   response.end
end if

Please note that in case of US IP-traffic there are quite a few ranges to block (nearly 7.000).
As already commented, IPs can be spoofed so it's not a 100% safe method at all.


OSM plant pbf and Osmosis Extracting data

Question: I'm trying to extract various landmarks from the osm planet-latest pbf.
For testing purposes I'm currently trying to extract schools, but the command is taking way to long its already been 20 minutes.  The following is my osmosis command on my Linux machine.
<code>osmosis/bin/osmosis --rbf planet-latest.osm.pbf --nkv keyValueList="amenity.college" --wx ssxschools.osm
</code>
Can some one please tell me if I'm doing anything wrong or does it usually take this long. If so what can I do to optimize the speed of extracting the data.
BTW I'm using an aws r4xl2 machine running on linux with 8 vcpu and 61 gib of memory. I thought renting a machine with a good amount of memory would help.
Comment: Ok so I let the command ride out osmosis read and extracted all the data for a particular amenity in 46 minutes for one instance and then for another instance it took 48 minutes which is not bad. Hopefully someone finds this helpful.
Answer: The planet file is huge and compressed. I wouldn't expect this command to finish within 20 minutes. However you can give osmium a try, it is said to be faster than osmosis.
Comment: Thanks Scai any idea how long it takes on average to parse amenities from the complete file?
Comment: Unfortunately no, I've never done that. If you intend to do this on a regular basis or for multiple amenities you should rethink your approach. To speed up the process you can either import the planet into a database (this takes more time than a single osmosis/osmium query, though) and query this database instead. Alternatively you can install a local Overpass API instance. If you just need to query a smaller area you can try one of the public Overpass API instances instead.
Comment: Thanks regarding my command  keyValueList="amenity.college"  is there any way I can get all amenities in one call for example  keyValueList="amenity.* "    with a wild card?  or lets say a group of amenities.

Example
   keyValueList="amenity.college,amenity.bar,amenity.restaurant"
Comment: Probably yes. However I'm not an osmosis user and don't know how to do this. Please ask a new question.


C# WinForms Try Catch Inside a class

Question: I am using a service reference which connects to internet and I want to show message in a message box if ever the connection fails. How will I call message box in the member function of the class which has void return type? This is the member function of the class:
 public void ReverseGeocodePoint()
    {
        try{
        string results = "";
        string key = "abc";
        ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();

        // Set the credentials using a valid Bing Maps key
        reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
        reverseGeocodeRequest.Credentials.ApplicationId = key;

        // Set the point to use to find a matching address
        GeocodeService.Location point = new GeocodeService.Location();
        point.Latitude = latitude;
        point.Longitude = longitude;

        reverseGeocodeRequest.Location = point;

        // Make the reverse geocode request
        GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
        //This will connect to the server
        GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);

        if (geocodeResponse.Results.Length > 0)
            results = geocodeResponse.Results[0].DisplayName;
        else
            results = "No Results found";

        address = results;
    }} catch{ //here I want to show a msgbox but the problem is, this is not the form class}

Comment: Posting code would help in understanding your problem better.
Comment: You need to show us your code. Both what you have that works and what you have tried to write that doesn't.
Answer: Don't catch the exception in that class if there's nothing you can do about it there. Just let it bubble up and catch it where you can do something about it:
public class MyForm : Form
{
    public void SomeMethod()
    {
        try
        {
            var sc = new ServiceClass();
            sc.ReverseGeocodePoint();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

In ReverseGeocodePoint(), remove the try/catch statements.

C# WinForms Try Catch Inside a class


.htaccess convert a url parameter in folders

Question: I try to convert a url parameter in folders using RewriteRule.
Anyone can help me?.
Origin: search.php?term=red&cat=colors
Destination: /search/red/colors
Answer: The top part of this answer clarifies how URLs get rewritten and redirected. Using "convert" is not really clear, as there's 2 completely different things that can happen.
To change a URL like /search.php?term=red&cat=colors to the nicer looking variation, you need to match against the actual request and redirect the browser:
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD)\ /search\.php\?term=([^&]+)&cat=([^&\ ]+)
RewriteRule ^ /search/%2/%3/? [L,R=301]

This makes it so when someone types in their browser the URL: http://mysite.com/search.php?term=red&cat=colors, they get externally redirected to http://mysite.com/search/red/colors, changing the URL in the address bar.
Then in order to internally rewrite the nicer looking URL and route it back to the php script:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?search/([^/]+)/([^/]+)/?$ /search.php?term=$1&cat=$2 [L]

This does the reverse, but only internally so that the URL in the browser's address bar remains unchanged while the content is served from search.php. You can do one or the other depending on what your need is, or you can do both if you need this to happen in both directions.


GridView limiting number of items displayed

Question: I have an arraylist of images that I want to display in a gridview, but I only want 12 of them to be displayed at a time, and then have one change images every few seconds, however I'm having trouble figuring out how to even limit the number of images displayed to 12. I'm using a custom adapter, extending baseAdapter. Any help is appreciated.
Answer: What if you start to solve this by returning 12 in the getCount method of your custom BaseAdapter?
Comment: Right, thanks. I actually tried that before and was getting another error that I thought caused the problem (it turns out network issues were the actual cause of the problem.

In regards to how the grid view actually updates the grid, when I call notifyDataSetChanged(), does it redraw EVERY single one, or does it redraw only the one that's changed?
The reason I'm asking is because I'm now able to have a random one change every time by using an arraylist of size 12 to hold them as a buffer, and randomly replace one of the values with a new value. However, I want to add an transition of
Comment: some sort, which would require that only the one changed be animated.
Comment: If you want to animate just the item changed, then you shouldn't update nor call `notifyDataSetChanged`, but create some sort of custom view (as the gridview item) that you will change and animate it self.
Comment: Wait, just to clarify, so let's say I created the custom view already. When I change the gridview item, it will update itself on the screen without me having to call notifydatasetchanged?


Definition of induced representation

Question:
Definition. Suppose that $H$ is a subgroup of the finite group $G$ and $\sigma \colon H \to \operatorname{GL}(W)$ is a representation of $H$. Then the induced representation from $H$ up to $G$ denoted $\pi = \operatorname{Ind}_H^G \sigma$ is a group homomorphism $\pi \colon G \to \operatorname{GL}(V)$, where
  $$
  V =
  \{
    f \colon G \to W
    \mid
    \text{$f(hg) = \sigma(h)f(g)$, for all $h \in H$, $g \in G$}
  \}.
$$
  The representation $\pi(g)$ is then defined on $f \in V$ by
  $$
  \text{$[\pi(g) f](x) = f(xg)$, for all $x,g \in G$}
$$

Can someone explain this definition to me? I don't understand what $\pi$ is given by? Its a function that maps $g$ to what in $\text{Aut}(V)$? Can someone explain the line $[\pi(g)f](x)=f(xg)$? I don't know what I am missing, but what is the representation given by?
Comment: Possibly related: https://math.stackexchange.com/questions/266346/understanding-induced-representations, https://math.stackexchange.com/questions/1016578/equivalence-of-induced-representation
Answer: Given any vector space $W$, there is a natural representation of the group $G$ on the space $W^G$ of all set maps $f:G\to W$. This representation is given by $(g\cdot f)(\tilde g):=f(\tilde gg)$ for all $\tilde g\in G$. So $g$ acts on $f$ by precomposition with the right translation by $g$. (It is easy to see that this defines a representation without any assumptions on $W$.)
Now if you have given a subgroup $H\subset G$ and a representation of $H$ on $W$, then this gives rise to a $G$-invariant subspace $V\subset W^G$. This is the subspace of functions which are $H$-equivariant in the sense that $f(h\tilde g)=h\cdot(f(\tilde g))$ for all $h\in H$ and $\tilde g\in G$. So you can restrict the above action of $G$ to this invariant subspace, and this is exactly the induced representation in your question.
The construction of an induced representation is easier to understand in the setting of Lie groups. The equivaraint functions can be considered as functions defined on the space of cosets $H\backslash G$. If $G$ is a Lie group and $H\subset G$ is a closed subgroup, then this coset space is a smooth manifold and the representation $W$ of $H$ gives rise a vector bundle over the coset space endowed with a natural $G$-action. This gives rise to a representation of $G$ on the space of smooth sections of the vector bundle, which can be identified with smooth functions $G\to W$ which are equivariant in a similar sense as above.
Answer: We start with a known representation of the subgroup $H$, and construct a representation of the group $G$. In this sense, the latter representation will be "induced" by the former; hence the term.
The known representation of $H$ is acting in the space of linear operators ${\rm{GL}}(W)$, where $W$ is a linear space (say, that of all square-integrable functions). However, the induced representation of $G$ will be acting  on a subspace $V\subset W$ of the {\it{Mackey functions}}, those defined by the subsidiary condition
$$
V = \{
    f \in W
    \mid
    \text{$f(hg) = [\sigma(h)f](g)$, for all $h \in H$, $g \in G$}
    \}.
$$
The induced representation $G \to {\rm{GL}}(V)$ is implemented by the operators
$$
\pi_g f(x) = f(xg)\quad\mbox{for all}\quad g,\,x\in G
$$
Had the function $f$ belonged to the space $W$, we would have said that this is a map $G\to {\rm{GL}}(W)$, and would have stopped there. However, we agreed that $f$ obeys the subsidiary condition; so $f\in V$, wherefrom
$$\pi:\quad G\to{\rm{GL}}(V).$$
This enables us to make one more step. Consider the quotient space $H\backslash G$ of cosets $Y = Hg$ and choose a ``representative'' $r(Y)$ for each coset $Y$. Then a coset $Y$ can be written as $Y = H~r(Y)$. As soon as we apply the definition of the induced representation to a representative,
$$
\pi_g f(r(Y)) = f(r(Y)~g),
$$
we can employ the subsidiary condition to find the representation for the entire coset.  To do so, we start out with
$$
\pi_g f(r(Y)) = f(r(Y)~g) = f( r(Y)~g~r^{-1}(Yg)~r(Yg) )
$$
and note that the coset $Yg$ has a representative of its own, $r(Yg)$, so it can be presented as
$$
Yg = h(Y,g)~r(Yg)\quad\mbox{where}\quad h(Y,g)\in H~.
$$
Combining the last two equations, we see that $h(Y,g) = r(Y)~g~r^{-1}(Yg)$, and we finally write down:
$$
\pi_g f(r(Y)) = f(r(Y)~g) = f(~h(Y,g)~r(Yg)~) = \sigma(h(Y,g)) f(r(Yg))~.
$$
It is therefore sufficient to define the induced representation on the cosets (technically, on the cosets' representatives), whereafter the subsidiary condition automatically extends the definition to the entire group $G$.
With $r$ denoting a section, i.e., a map from cosets to representatives, the above equation assumes the form
$$
\pi_g f\circ r (Y)  = \sigma(h(Y,g))~f\circ r(Yg)~.
$$
Obviously,
$$
\omega = f\circ r
$$
is a function acting on the coset space. Such functions are named Wigner functions, and in their terms our equation can be written down as
$$
\tilde{\pi}_g\omega (Y) = \tilde{\sigma}(h(Y,g))~\omega(Yg)~,
$$
where $\tilde{\pi}_g\omega (Y) \equiv \pi_g f(r(Y))$ and $\tilde\sigma(h)\omega(Y)\equiv\sigma(h)f(r(Y))~$.
We now see that this is a transformation law of the Wigner functions. The multiplier $\tilde{\sigma}(h(Y,g))$, called the Wigner rotation, is responsible for the Thomas precession in quantum physics.

Definition of induced representation


How can I adjust the z-index of a form in Microsoft Access

Question: I maintain a fairly large ms-access 2003 application.  One of the recent changes that I was asked to make was to add a popup dialog box to warn used of a particular situation when the opened a form which is itself a pop up (although not modal) form.
Unfortunately, the new popup modal form comes up behind the original one, getting the user interface into an impossible position (you cannot close the modal dialog box because it is hidden, but you cannot move the others out the way because the modal dialog is preventing you).
I've temporarily made the new box come up to the very side of the screen but it is far from ideal.
Is there a way to specify the Z index of a form so I can control the layering? (or any other solution)
Answer: The only way to control this is by the order in which you open the forms.
I.e. you have to first open the original popup form, then open the new modal popup.
You could also consider using MsgBox() instead of the new form.
Comment: Yes, strictly true, VERY strictly/! I was opening dialog from within the Current event and it was not displaying on top.  I added a slight delay (using the timer) and now it always appears on top
Comment: I should add something else for the unwary.  If the form has no records, then the Current event doesn't occur. I ended up doing it, with a longer timer, in the Open event.


How to 'add' two numbers using a bitwise operator?

Question: I have two numbers, and either can be any number. I want to add those numbers together, but in a special "binary" way.
So suppose I have the following two numbers: 7 and 9. In their binary form they are:
0111 = 7
1001 = 9

I need a way to add 7 and 9 together in their binary form, but only where the two bits differ. If they differ, then the different bit should be set to a 1.
With the example of 7 and 9, the result I want is:
0111 = 7
1001 = 9
---- +
1111

Is there a way to perform such an operation in PHP?
Comment: `If they differ, then the different bit should be set to a 1` Then why the last digit is `1` instead of `0`?
Comment: Actually, 7+9=16 which is 10000 in binary.
Comment: Do you mean binary or? I.e. each bit that is 1 in at least one of the numbers is 1 in the result? This would mean the result of your operation on the inputs 0011 and 1010 would be 1011. If yes, you really probably mean binary or.
Answer: Bitwise operators:
$result = 7 | 9;

Answer:
If they differ, then the different bit should be set to a 1

What you are asking is called bitwise exclusive OR
echo 7^9;
// = 1110

But you are showing it should be 1111 which is actually bitwise OR,
echo 7|9
// = 1111

Answer: Your description asks for a bitwise XOR, but the example you give demonstrates a regular bitwise OR. Before you can solve any problem, you need to clearly define it.


Magento Get Products By Manufacturer

Question: I have the following code which gets me a list of manufacturers:
    $attribute = Mage::getModel('eav/entity_attribute')
                    ->loadByCode('catalog_product', 'manufacturer');

    $valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
                ->setAttributeFilter($attribute->getData('attribute_id'))
                ->setStoreFilter(0, false);

    $preparedManufacturers = array();
    foreach($valuesCollection as $value) {
        $preparedManufacturers[$value->getOptionId()] = $value->getValue();
    }

    if (count($preparedManufacturers)) {
        echo "
Manufacturers

";
        foreach($preparedManufacturers as $optionId => $value) {
            echo "
" . $value . " - (ID:" . $optionId . ")
";
        }
        echo "
";
    }

How do I get the first product of each manufacturer?
Thanks
Comment: Thank you very much.  I have just tried it and it is working :-).
Comment: Do you know by any chance how I could paginate this? eg. get 10 records per page.
Answer: try this
     if (count($preparedManufacturers)) {
    echo "
Manufacturers

";
    foreach($preparedManufacturers as $optionId => $value) {

    $firstProductId=Mage::getModel('catalog/product')->getCollection()
        ->addStoreFilter(0)
        ->addAttributeToFilter('manufacturer',$optionId)->getFirstItem()->getId();
        echo "
" . $value . " - (ID:" . $optionId . ")
";
    }
    echo "
";
}

Magento Get Products By Manufacturer