text:
Q: Previous and next array should have two much common values pandas I have a dataframe like ,
Test              Test1
[1,1,1]          [1,2,2]
[1,2,2]          [1,0,1]
[1,0,1]          [1,1,0]
[2,2,0]          [0,2,2]
[1,2,0]          [1,0,2]

I am trying to compare the two arrays where 2 numbers should match and third one should be o.So like   [1,0,1]   [1,1,0]  should be matched and return true as two numbers are matching and third one is 0 . same for [2,2,0]          [0,2,2]  but [1,2,0]          [1,0,2]  this should not match as it does not have the same numbers.will return false. So,Is there any way to do this ?

A: Using this function, you can compare two tuples and check if they fulfill your requirements:
def eval_tuples(tup1, tup2):
    # Check if zeros occures once in each tuple
    if tup1.count(0) != 1 or tup2.count(0) != 1:
        return False

    # Get non-zero values
    rem1 = [x for x in tup1 if x != 0]
    rem2 = [x for x in tup2 if x != 0]

    # Check if they are equal in both tuples
    if rem1[0] != rem1[1] or rem2[0] != rem2[1]:
        return False
    return True

Here some example runs of the function:
print(eval_tuples([1,1,0], [1,0,1]))
# True
print(eval_tuples([1,1,0], [2,0,1]))
# False
print(eval_tuples([2,2,0], [0,2,2]))
# True
print(eval_tuples([1,2,0], [1,0,2]))
# False

A: This is the testing function you need (I think, assuming all values are positive)
def test_func(x):
    A = x[0]
    B = x[1]
    f = lambda X: np.unique(X, return_counts = True)
    Au, Ac = f(A)
    Bu, Bc = f(B)
    return np.all(Au == Bu) and \
           Au.size == 2 and  \
           Ac[0] == 1 and \
           Bc[0] == 1

And to apply in in pandas (not a pandas expert, but I think this should work):
df['new_col'] = df[['Test', 'Test1']].apply(test_func, axis = 1)

in any case, this question should help you apply your function over two columns.

A: Do you mean like this?
>>> def compare_tuples(x, y):
...     return (
...         # there is any series of size two which is common in both tuples
...         any(x[i:i+2] == y[j:j+2] for i in range(2) for j in range(2))
...         # there is at least one zero at third position
...         and 0 in (x[2], y[2])
...     )

>>> df = pd.DataFrame.from_records([
...     [(1, 1, 1), (1, 2, 2)],  # False
...     [(1, 2, 2), (1, 0, 1)],  # False
...     [(1, 0, 1), (1, 1, 0)],  # True - (1, 0) matches and 0 in third position
...     [(2, 2, 0), (0, 2, 2)],  # True - (2, 2) matches and 0 in third position
...     [(1, 2, 0), (1, 0, 2)],  # False
... ], columns=["Test1", "Test2"])

>>> df.apply(lambda x: compare_tuples(*x), axis=1)
0    False
1    False
2     True
3     True
4    False
dtype: bool


text:
Q: Defining Orderly/Chaotic states in terms of entropy? I'm trying to properly understand the meaning of entropy, and how the universe is moving from an orderly state to a chaotic one.
If a glass of wine (for example) only has meaning to a human, what makes a shattered spilled glass any less orderly than a full whole glass?
Or if a particle is observed, and it's probability wave collapses, isn't this moving from a 'chaotic' (uncertain and in many places), to an 'orderly' (certain, definite position) state?
Also, isn't the formation of stars, planets, galaxies etc... a move from a more chaotic state to a more orderly one?
Just trying to get some perspective into what the true meaning of entropy is and why it's important.

A:
If a glass of wine (for example) only has meaning to a human, what makes a shattered spilled glass any less orderly than a full whole glass?

Symmetries. Symmetrical systems have smaller entropy as defined by delta(S)=delta(Q)/T) because to break the symmetry energy/heat has to be expended.

Or if a particle is observed, and it's probability wave collapses, isn't this moving from a 'chaotic' (uncertain and in many places), to an 'orderly' (certain, definite position) state?

The crux in this sentence is "observed". To observe there must be interactions and the interactions of observing add energy and disorder to the system. It is only in closed hermetically systems that the entropy is 0 or increasing statement can be evaluated. Think of biological systems. They are par excellence reducing entropy in their bodies, but they are not in a closed system, they die if the y cannot continually exchange energy and chemicals with the larger surroundings increasing entropy in the exchanges.

Also, isn't the formation of stars, planets, galaxies etc... a move from a more chaotic state to a more orderly one?

In an individual star, no, the heat  goes up within when the star is formed  from the big bang debris, much faster than the temperature which starts at near zero Kelvin; also a lot of radiation is created and escapes, increasing the entropy of the universe.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting Error on Building APK - Android Studio I am a newbie and trying to build an APK in android studio. Getting the following error
Error : Android Resource Packaging:[Project Name] D:\react-app\Android\App
Error : Android Resource Packaging:[Project Name] src\main\AndroidManifest.xml:45: error:Error:no resource found that matches the given name (at 'label' with value '@string/App_name).

There are approx 9 errors showing.
Please help to resolve the problem.

A: The possible answer to your mentioned error is make sure
string.xml file under

android/app/src/main/res/values/strings.xml

should look like this
<resources>
<string name="app_name">YOUR_APP_NAME</string>
</resources>


text:
Q: Is it possible to go to the next page using Collection View and display data? I'm the middle doing some project that involve CollectionView and property list. I want to do the image grid in the Collection View, and the image is the significance to proceed to the next page.
Here I want to do:
1) User click image in the collection view
2) Image will redirect to the next page and display the data that stored in the property list. The data is display according to the image that they click.
I'm using Xcode 6.
How can I perform such process?

A: UICollectionView has a delegate which provides a method
- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath

When an item is tapped, the function above is called. Based on indexPath you can determine which item was selected.
In your storyboard, create a new UIViewController and create a segue from your UICollectionView to this UIViewController and make the segue as Push and name it 'collectionViewToUIViewController'.
In your didSelectItemAtIndexPath, call method
[self performSegueWithIdentifier:@"collectionViewToUIViewController"]

Also implement prepareForSegue where you tell the UIViewController what to display.

A: Here is the almost similar example give by Apple. It will give you a good point of reference.


text:
Q: HTML table cell goes down when add text I have a table like this:

And css file:
.rds {
    width: auto;
    margin-left:auto;
    margin-right:auto;
}

.rds tr td a:link, .rds tr td a:visited {
    display: block;
    width: 39px;
    height: 39px;
    background-image: url('images/bg.png');
    background-repeat: no-repeat;
    background-position: center;
}

.rds tr td a:active, .rds tr td a:hover {
    display: block;
    width: 39px;
    height: 39px;
    background-image: url('images/bg.png');
    background-repeat: no-repeat;
    background-position: center;
    opacity: 0.9;
}

But when I add some text to  tags, all cell goes down a bit. Only cell with text goes down.
What can I do?

A: Use vertical-align="top" on all cells. In css it could look like
td {
    vertical-align:top;
}


text:
Q: LuaJIT pointers and Garbage Collection I am trying to fully understand what LuaJIT's garbage collector will handle with FFI and what I have to manage manually so I am sure to get no leakage.
Reading LuaJIT FFI Semantics Docs about the garbage collector are the following assertions true?:

*

*If an array is allocated using ffi.new('float[?]',n) then the gc can track its references and collect as necessary?

*Using ffi.malloc(sizeof('float[n]')) must be manually handled such as ffi.free or provide a "finalizer" such as local p = ffi.gc(ffi.malloc(sizeof('float[n]')), ffi.free)?

*If a library loaded with ffi.load contained a function float * example(void); and the library is loaded into namespace Ex then in
local ptr=Ex.example()
ptr is storing a pointer and when no references to ptr exist, gc will
collect ptr and memory will be leaked?

*ffi.gc(ptr, ffi.free) lets the garbage collector know that ptr is indeed a pointer and the memory it points to can be reclaimed when ptr itself has no references?
In saying

Memory areas returned by C functions (e.g. from malloc()) must be
  manually managed, of course (or use ffi.gc()). Pointers to cdata
  objects are indistinguishable from pointers returned by C functions
  (which is one of the reasons why the GC cannot follow them).

Is it meant that even though the namespace that C library functions are given to the FFI in knows the return value to be a pointer, garbage collection cannot act autonomously performing (4)?
What is meant by Mike Pall when he says

"But even if that function [ffi.gc()] were compiled ... the GC will
  have to call the finalizer eventually, which is costly."

is he just referring to the function call to ffi.free in this case? If so, how would ffi.new get around this overhead?


text:
Q: Excel Array Formula, Multiple criteria I have a table in which multiple weeks of data is stored and I'm trying to return a value based on 2 criteria.
Column A of the data sheet contains the date the report was ran (Always on the same day of the week - 24/05/17, 31/05/17 etc)
I've managed to return the value of column H by using an array formula, based on a cell value (Date) in ''Issues Data Quality Overview'!$B$4' using the following formula:
{=IFERROR(INDEX('Issues Log'!$H$1:$H$20000,SMALL(IF('Issues Data Quality Overview'!$B$4='Issues Log'!$A$1:$A$20000,ROW('Issues Log'!$A$1:$A$20000)-MIN(ROW('Issues Log'!$A$1:$A$20000))+1,""), ROW(A2))),"")}

That returns a value such as "IID-10225-22".
Problem:
Now I need to look up that value in the same table, based on a date in another cell, and return column X. (essentially adding the returned value as a criteria).
In all honesty I'm lost as to how I'd do this.

A: @Matthew. I understand your formula gives the list of values in column H with column A values matching 'Issues Data Quality Overview'!$B$4 in an ordered list.
Does your Issues Log, column H have multiple occurrence of the same value? (example: IID-10255-22 can have a value in Issues Log, column A that is not the same value as 'Issues Data Quality Overview'!$B$4).
If not, it doesn't make sense to use the result as a lookup value to get column X, you can simply change the code to:
{=IFERROR(INDEX('Issues Log'!$X$1:$X$20000,...}

If it does have multiple occurrences and you want to get the first occurrence of the result in column H and get the value in column X, best to add a formula right next to your array formula and do a VLOOKUP.

A: I've scrapped the array formula, as it really slowed down the processing speed. Instead I've created a Unique ID (=IssueID&Date) and VLookup'd that.


text:
Q: How to declare an array of values within an array of objects using JS? I want to create an array containing objects that have a key data which is an array of values. I am trying to push values into data but it's not working for me.
My expected result looks like this:
array = [
  { data:[3,2,5] },
  { data:[5,2,1] }
]

So I want to fill the data arrays. To do this, I have tried populating the arrays with a for loop:
var array = [];
for(i=0;i<2;i++){
  for(j=0;j<3;j++){
    array[i]["data"][j].push(2);
  }
}

But this is not working for me.

A: You can't do this: array[i]["data"][j].push(2) without first initializing array[i].
In your case there's no need to initialize it with an empty array, instead you can simply assign the whole object to each [i]
What you are trying to achieve is an array of objects where each object is of the form {'data': []}
So assume you have your input coming from an array:
const initialData = [[3, 2, 5], [5, 2, 1]];

To get that data in the form you want it, you would do:

const initialData = [[3, 2, 5], [5, 2, 1]];
var array = [];
for(i=0;i < initialData.length; i++){
  array[i] = {'data':initialData[i]};
}

console.log(array)

And here is a neater approach using some of Array.prototype's methods which I recommend checking out:

const initialData = [[3, 2, 5], [5, 2, 1]];

const array = initialData.map(elem => {
  return {
    'data': elem
  };
})

console.log(array)

And if you want neaterer you can go with mplungjan's comment

A: You can initialize the array with: const array = [...Array(2)].map(() => ({ data: [] }));
Then you'll be able to access it with:
for(i=0; i<2; i++){
  for(j=0;j<3;j++){
    array[i].data[j] = 2;
  }
}

A: You could do something like this:

let items = 2
let arr = Array.from({ length: items }, (item) => item = { data: [] })
for (let i = 0; i < items; i++) {
  for (let j = 0; j < 3; j++) {
    let val = 2 // replace value here
    arr[i].data.push(val)
  }
}

console.log(arr);

A: Take a look at these changes, which modify your existing code.  For an improved method, see the bottom
Your Code

var array = [];
for(i=0;i<2;i++){
  array.push({data:[]})        // create your object
  for(j=0;j<3;j++){
    array[i]["data"].push(2);  // you don't need '[j]' because the result of 'data' key is an array, so just push onto it
  }
}

console.log(array)

Alternative Method

let arr = [...new Array(2)].map(el=>({ data: new Array(3).fill(2) }));

console.log(arr)


text:
Q: Spring @SendToUser or convertAndSendToUser is not delivering message to a different authenticated user than the logged in user I am new to spring websocket. I tried different ways to send message to specific user. But failed. What am trying is say, i have two users jhon & alex. When Jhon logged in he can send message to Alex.
@MessageMapping("/message")
public void processMessageFromClient(@Payload Message msg, Principal principal) throws Exception {
    OutputMessage out = new OutputMessage(principal.getName(), msg.getText(),
            new SimpleDateFormat("HH:mm").format(new Date()));
    //*msg.getTo() gives the target user alex*
    messagingTemplate.convertAndSendToUser(msg.getTo(), "/queue/reply", out);
}

With the above code the message dosn't send to alex (also an authenticated user), in fact nothing happens at this point. However if i change msg.getTo() to principal.getName() which is the username for the current logged in user, this sends the message to the current logged in user i.e., jhon. But I want to send to alex.
Here us the socket configuration.
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic/", "/queue/");
    config.setApplicationDestinationPrefixes("/app");
    config.setUserDestinationPrefix("/user");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ict-socket-endpoint").setAllowedOrigins("*");
}

}
And below is the javascript client

    var ws;
    function setConnected(connected) {
        $("#connect").prop("disabled", connected);
        $("#disconnect").prop("disabled", !connected);
        if (connected) {
            $("#conversation").show();
        } else {
            $("#conversation").hide();
        }
        $("#greetings").html("");
    }

    function connect() {
        // connect to stomp where stomp endpoint is exposed
        var socket = new WebSocket("ws://localhost:8084/ict-socket-endpoint");
        ws = Stomp.over(socket);
        var header = {
            "name" : "alex"
        }
        ws.connect(header, function(frame) {
            ws.subscribe("/user/queue/errors", function(message) {
                alert("Error " + message.body);
            });
        ws.subscribe("/user/queue/reply", function(message) {
            console.log("message ====" + JSON.stringify(message.body));
            showGreeting(message.body);
        });
        }, function(error) {
            alert("STOMP error " + error);
        });
    }

    function disconnect() {
        if (ws != null) {
            ws.close();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendMsg() {
        var opts = {
            from: 'bhaba', //loggedIn user
            to: 'alex', //target user
            text: $("#name").val(),
            disconnect: 'disconnect'

          };
        var data = JSON.stringify(opts);
        ws.send("/app/message", {}, data);
    }

    function showGreeting(message) {
        $("#greetings").append(" " + message + "");
    }

    $(function() {
        $("form").on('submit', function(e) {
            e.preventDefault();
        });
        $("#connect").click(function() {
            connect();
        });
        $("#disconnect").click(function() {
            disconnect();
        });
        $("#send").click(function() {
            sendMsg();
        });
    });

Am tired of trying now. Need help. Thanks!


text:
Q: неправильно работает выходной слой нейросети есть 4 слоя(y1,y2,y3,y4) на выходе которых по 2 нейрона и функция активации "softmax"
я обьединяю их в 1 общий слой 4х2 = 8 нейронов и обучаю сеть,
но softmax не срабатывает и вместо чисел в пределах (0,1) я вижу значения за их пределами.

помогите разобраться в чем причина
y1 = layers.Dense(2, activation="softmax", name='y1')(x)
y2 = layers.Dense(2, activation="softmax", name='y2')(x)
y3 = layers.Dense(2, activation="softmax", name='y3')(x)
y4 = layers.Dense(2, activation="softmax", name='y4')(x)
x = layers.add([y1, y2, y3, y4])
outputs = layers.Dense(8)(x)
model = keras.Model(inputs, outputs, name="predict_4_periods")
model.summary()
# exit()
model.compile(optimizer='adam',
             loss='binary_crossentropy',
             metrics=['accuracy'])


text:
Q: applying a 20% discount for students to magento store I am trying to apply a student discount to some of my products but I can only see a way of applying a discount to the product itself, so everyone gets the discount!  What I really want is somewhere for students to enter a code to get their discount, how can I achieve this please?

A: If you want to create a discount with coupon code, you should create a shopping cart price rule. So the students can add the products to cart and enter the coupon code on shopping cart page to get the discount for the products.

*

*In Magento backend go to Promotions > Shopping Cart Price Rules.

*Click Add New Rule on the top right.

*Complete all required options. Set Coupon field to Specific Coupon and enter a coupon code on below text field. On conditions tab, configure settings for discount products that should be found in cart. On actions tab, configure setting to apply rules only for discounted product.


text:
Q: facebook link to join users Is there a way to create a link like www.facebook.com/wallpapers.3d in order the user to click and be redirected to the facebook group? I can only use the link from groups which is like http://www.facebook.com/group.php?gid=315018914695

A: Not programming related, but the answer is no. Only pages, applications, and users can have nice URLs, not groups.


text:
Q: How to label time series data for CNN I want to classify time series data using a CNN (given model).
My input signal data is given as shape = (nr. channels x samples x nr. trials) where:

*

*nr. channels = number of sensors recording simultaneously

*samples = split my signal into 3s windows so the training data will have the same length 3s x sample rate

*nr. trials = by splitting the signal into windows, I obtain X chunks

The time series/signal data is subject based, for each subject I have numerous signals recorded. The labels are also subject based and not signal based (so it's not an event classification problem, but more of a global subject classification one), meaning that for each subject's recording I will have the same label. Example:
SUBJECT 1 -> 12 recorded signals of about 2 min each -> split into 3s windows -> all of which will have the same label
So I have an excel table where for each subject I have an associated class. I have extracted these labels and I've tried shaping them as (1 x samples x nr. trials).
The model I'm using requires the NHWC (trials, channels, samples, kernels) format so I have reshaped my training data as:
X train shape = (2642, 14, 384, 1)
y train shape = (2642, 1, 384, 1)

But I get a
ValueError: Data cardinality is ambiguous:
   x sizes: 14
   y sizes: 1
Make sure all arrays contain the same number of samples."

How would I need to shape my labels data? Reshape it as (2642, 14, 384, 1) making it the same shape as the training data? Or?

A: Ended up solving it by trying different things.
The labels, y_train, array had to be shaped as
(trials, 1)

where trials in my case was the number of windows generated by windowing the signal


text:
Q: Ways to prevent broken pipe? ClientAbortException:  java.net.SocketException: Broken pipe

If I am wright, this happens when user aborts current operation or makes another request, before the last one is finished.
Can this reflects on browsing user or is this (always) just a Catalinas exception?
Are there any ways to avoid this exception?

A: Try defining a filter for all resources in your webapp, and catch & discard the exception there. I'm not sure if it will work, but give it a try.
In 99% of the cases this exception can be ignored, because it's mainly called by user disconnects (i-net breaks, user hits stop, closes browser, etc)


text:
Q: Regex with Javascript to retrieve content from a loop This seems simple but I have never done a regex so just a simple question from regex experts of JS.
var str = 'luckyy1 born on october 21, 1986 sdf2 born on september 22, 1985 erere born on November 23, 1984 ';

I got values successfully as: luckyy1, sdf2, erere
But I need it as luckyy1+october+21+1986,sdf2+september+22+1985,erere+... and so on (may be i need regex right??)
Any help would be appreciated.

A: Try this:
str = $("
").html(str).text();
str = str.replace(/,?/g, '').replace(/born on?/g, '').split(' ').join('+')

DEMO

A: While I recommend not parsing HTML with regex, this is sufficiently simple enough you should be able to do it.
"test"\s*>(.+?\d{4})
That will capture anything after a "test"> tag, and end at 4 numbers (the year in your example).
Your info is space delimited in group 1. After that, I recommend splitting on spaces to get your individual elements to play with.
Play with the regex.

A: Basically, you want to strip the html tags?
Give this a try:
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");

from http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
If you wish to get separate strings for each dom element (as your example suggests), you may transverse the DOM elements with jQuery and strip each one separately.
EDIT:
Something like this:
var $s = jQuery( the_string );
var result = [];
$s.each(function(i, item){ result.push( $(item).text().replace(/(<([^>]+)>)/ig,"") ); });

A: Strictly with the markup you provided you can do something like this:
var values = $('
luckyy1 born on october 21, '+
  '1986 sdf2 born on september 22, 1985 ' +
  'erere born on November 23, 1984
')
  .contents()
  .map(function(){
    return $(this).text().replace('born on', '').trim();
}).get();

console.log(values); // ["luckyy1", "october 21, 1986", "sdf2", "september 22, 1985", "erere", "November 23, 1984"]

Only thing I changed was added a wrapping div to the string. You can then use values.join('+') to concat with a +, and more string replace on whitespace.
values.join('+').replace(/\s/g, '+'); // to make all whitespace `+`

A: This is dirty solution but somehow may help you...
var str = 'luckyy1 born on october 21, 1986 sdf2 born on september 22, 1985 erere born on November 23, 1984 ';

var r= /]*>(.*)<\/a> born on ([\w]*) ([\d]*), ([\d]*) ]*>(.*)<\/a> born on ([\w]*) ([\d]*), ([\d]*) ]*>(.*)<\/a> born on ([\w]*) ([\d]*), ([\d]*)/;

r.exec(str).splice(1).join('+');


text:
Q: AngularJS IE8 Issues I have been unable to render a list in IE8 specifically. All other browsers execute the following code as intended, however, IE8 completely ignores the function completely. Any tips, suggestions and/or solutions are greatly appreciated, Cheers.
alert("workflow.js"+ " this call goes off in IE8");

$scope.makeAndGetList = function(list) {
    //todo: lj: IE8 doesn't make it here
    //alert("workflow.js"+ " no IE");
    var parts = list.split('.'),
        current = $scope.workflow;

    _.each(parts, function(part, index) {
        if (current[part] == undefined) {
            current[part] = (index == parts.length - 1) ? [] : {};
        }
        current = current[part];
        //todo: lj: IE8 doesn't make it in here
        // app.appAlert("workflow.js"+ " line 19");
    });

alert("workflow.js - this functions correctly executes in IE8");

Here is the HTML as requested:
<sa-list list="makeAndGetList('areas_of_need')" edit="true" model="areas_of_need" array-mode="true">
    <sa-lookup style="multiselect" override="false" list="areas_of_need.terms" model="areas_of_need" model-key="need" label="{{locale.iprc.areas_of_strengths_and_needs.needs}}"></sa-lookup>
</sa-list>

A: Not sure if this is your issue (can you post a jsfiddle with your directives?), but here's a possibility. IE 8 can handle angular directives only as attributes (not elements). Luckily, it is easy to change an angular element into an attribute. E.g., for a directive "saList", where the html says <sa-list>, rewrite the html as <div sa-list> (and make sure your directive has the property restrict: 'A', not restrict: 'E'). See an example (that works in IE 8) here: http://jsfiddle.net/dannystaten/hQn9F/

A: Take a look at ieshiv I wrote it for angular-ui project. Gives you an easy way to incorporate.

A: Also try upgrading to 0.2.0 version of Angular UI Bootstrap. I was facing similar issues for "Alert" control. After upgrading it to 0.2.0 and using it as attribute resolved my issue


text:
Q: Git permission error but didn't start new account Whenever I try to upload a file to git, I get an error like this.
    remote: Permission to DennisMarkham/trainTime.git denied to DennisMarkham.
fatal: unable to access 'https://github.com/DennisMarkham/trainTime.git/': The requested URL returned error: 403

Other people who get this error have started new accounts.  I have not.  I've been using git for four years, using the same account.  This has not always happened.  Before git started requiring access token instead of passwords, I was fine.  IIRC, though I'm not sure, I think I was able to upload sometime after this.  Now, however, I always get this error.  I didn't start a new git account, so what's the deal?


text:
Q: How to test if modifier with keycode is down I have this code:

import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;
import java.awt.Toolkit;

public class KeyListener implements KeyEventDispatcher
{
    @Override
    public boolean dispatchKeyEvent(KeyEvent e)
    {
        if(e.getID() == KeyEvent.KEY_PRESSED)
        {
            if(e.isDown(Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) && e.getKeyCode() == KeyEvent.VK_V)
            {
                paste();
            }
        }
    }
}

The problem is that e.isDown doesn't exist.
What alterntives can use so that it is cmd+V for macs and control+V for other OS'es?

A: KeyEvent extends InputEvent so you can use the isControlDown() method of InputEvent.
Edit: I found this link which shows how to create a KeyStroke for the command key:
http://lists.apple.com/archives/java-dev/2007/May/msg00243.html
So instead of using a KeyEventDispatcher, you should be using Key Bindings. Key Bindings allow you to invoke an Action for a given KeyStroke. Swing was designed to use Key Bindings.


text:
Q: Sending data through axios post gives null data in mysql.Can anyone tell me what is the problem export class AddCategory extends Component {
    state = {
        categoryForm: {
            category: {
                elementType: 'input',
                elementConfig: {
                    type: 'text',
                    placeholder: 'Enter Category'
                },
                value: '',
                validation: {
                    required: true
                },
                valid: false,
                touched: false
            }
        }
    };

    checkValidity(value, rules) {
        let isValid = true;

        if (!rules) {
            return true;
        }

        if (rules.required) {
            isValid = value.trim() !== '' && isValid;
        }

        return isValid;
    }
    inputChangedHandeller = (event, controlNameOne) => {
        const copyLoginFrom = {
            ...this.state.categoryForm,
        };
        const newCopy = {
            ...copyLoginFrom[controlNameOne]
        };
        newCopy.value = event.target.value;
        newCopy.valid = this.checkValidity(newCopy.value, newCopy.validation);
        newCopy.touched = true;
        copyLoginFrom[controlNameOne] = newCopy;
        let formIsValid = true;
        for (let inputIdentifier in copyLoginFrom) {
            formIsValid = copyLoginFrom[inputIdentifier].valid && formIsValid;
        }
        this.setState({
            categoryForm: copyLoginFrom,
            formIsValid: formIsValid
        });
    }

    dataPost = (event) => {
        event.preventDefault();
        const formData = {};
        for (let addressData in this.state.categoryForm) {
            formData[addressData] = this.state.categoryForm[addressData].value;
        }
        const newAddress = {
            newAddressData: formData
        }
        console.log("Hello......." + newAddress);
        const parentId = this.state.parent_id;
        const options = {
            method: 'POST',
            headers: {
                Authorization: "Bearer " + localStorage.getItem("token")
            },
            data: formData,
            url: 'http://localhost:8080/admin/category/'
        }
        axios(options);
    }
    render() {
        const formElementsArray = []; //converting state object to the array I can loop throuh
        for (let key in this.state.categoryForm) {
            formElementsArray.push({
                id: key,
                config: this.state.categoryForm[key]
            });
        }

        let form = ( <
            form onSubmit = {
                this.dataPost
            } > {
                formElementsArray.map(forElement => ( <
                    Input key = {
                        forElement.id
                    }
                    elementType = {
                        forElement.config.elementType
                    }
                    elementConfig = {
                        forElement.config.elementConfig
                    }
                    value = {
                        forElement.config.value
                    }
                    invalid = {
                        !forElement.config.valid
                    }
                    shouldValidate = {
                        forElement.config.validation
                    }
                    touched = {
                        forElement.config.touched
                    }
                    elementGet = {
                        (event) => this.inputChangedHandeller(event, forElement.id)
                    }
                    />
                ))
            }

            <
            button className = "btn btn-primary"
            disabled = {
                !this.state.formIsValid
            } > Submit < /button> <
            /form>
        )
        return ( <
            div >
            <
            div className = {
                styles.Login
            } > {
                form
            } <
            /div> <
            /div>
        )
    }
}

I am trying to send data using axios but the output I am getting in mysql table is Null.Can anyone tell me what is the problem with my code.I tried printing the sent data on console and output I am getting is [object Object] I tried using stringify method but It gives error of header while posting data

A: try qs which is a query string parser:
npm install qs

and then :
 import qs from "qs"

// in your body

     const options = {
            method: 'POST',
            headers: {
                Authorization: "Bearer " + localStorage.getItem("token"),
               'Content-Type': 'application/x-www-form-urlencoded' // need to add content type
            },
            data: qs.stringify(formData),
            url: 'http://localhost:8080/admin/category/'
        }


text:
Q: Excel VBA: "Run-time error '49': Bad DLL calling convention" calling C++ dll I am attempting to call a C++ DLL from Excel-VBA.
I know the DLL function is being executed as I inserted fputs() logging calls to track execution and the stamps are showing up in my log file. The problem is, whenever the DLL function returns, I get Error 49.
Here is the declaration in VBA:
Private Declare Function InitMCR Lib "MCRBoilerplate.dll" Alias "?initMCR@@YGXXZ" ()

and here is the declaration in C++
__declspec(dllexport) void __stdcall initMCR() { ... }

Why am I getting this Error 49 behavior, even though the DLL calls appear to be working?

A: In VBA, functions that return void need to be declared as Sub instead of Function
So the declaration in VBA should be:
Private Declare Sub InitMCR Lib "MCRBoilerplate.dll" Alias "?initMCR@@YGXXZ" ()

See MSDN page on VBA Declare statement

A: A quick point: your problem might not be a parameter mismatch in your external function, or in the declaration that imports it - there's a known compiler glitch in VBA that raises error 49.
'Stacker pstraton's answer to 'Excel - Runtime Error 49: Bad DLL calling convention'
You're not completely blameless - you probably have a parameter mismatch with a returned type that should work (Long populating an Int, Variants populating just about anything) in the calling function - but I have never heard of anyone banishing a persistent Runtime Error 49 by better coding. You just recompile, or export and reimport the modules.
The worst of it is that a genuine Forty-Niner is far harder to debug than it needs to be: the statement that triggers the error message usually isn't a call to the misdeclared external function. If you're lucky, it's the 'Exit Sub' of the caller; and some of the time it's something further up the stack that you can trace back to the bad call; but, sometimes, it isn't obvious at all and there's no deterministic debugging strategy at all.


text:
Q: iOS random crash because of memory corruption My app has many random crashes recently. Fabric shows the crash rate is about 1%. The crash session number and the crash user number is very close, which means it's very random.
The crash shows several different callstacks on Fabric, here are three of them.
==========1===============
#0. Crashed: com.apple.main-thread
0  QuartzCore                     0x188715730 CALayerGetSuperlayer + 20
1  UIKit                          0x188dd6fa0 -[UIView(Hierarchy) superview] + 44
2  UIKit                          0x188dd7a88 -[UIView nextResponder] + 108
3  UIKit                          0x188e9d99c -[UIResponder _containsResponder:] + 56
4  UIKit                          0x188ecfc80 -[UITransitionView transition:fromView:toView:removeFromView:] + 576
5  UIKit                          0x188f13238 -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 1536
6  UIKit                          0x188f12aec -[UITabBarController _setSelectedViewController:] + 360
7  UIKit                          0x188fda30c -[UITabBarController _tabBarItemClicked:] + 336
8  UIKit                          0x188e11398 -[UIApplication sendAction:to:from:forEvent:] + 96
9  UIKit                          0x188fda160 -[UITabBar _sendAction:withEvent:] + 468
10 UIKit                          0x188e11398 -[UIApplication sendAction:to:from:forEvent:] + 96
11 UIKit                          0x188dfa474 -[UIControl _sendActionsForEvents:withEvent:] + 612
12 UIKit                          0x188fd9d98 -[UITabBar(Static) _buttonUp:] + 128
13 UIKit                          0x188e11398 -[UIApplication sendAction:to:from:forEvent:] + 96
14 UIKit                          0x188dfa474 -[UIControl _sendActionsForEvents:withEvent:] + 612
15 UIKit                          0x188e10d34 -[UIControl touchesEnded:withEvent:] + 592
16 UIKit                          0x188dcff54 _UIGestureRecognizerUpdate + 8536
17 CoreFoundation                 0x18431c2a4 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
18 CoreFoundation                 0x184319230 __CFRunLoopDoObservers + 360
19 CoreFoundation                 0x184319610 __CFRunLoopRun + 836
20 CoreFoundation                 0x1842452d4 CFRunLoopRunSpecific + 396
21 GraphicsServices               0x18dc9b6fc GSEventRunModal + 168
22 UIKit                          0x188e42f40 UIApplicationMain + 1488

======================2=======================
#0. Crashed: com.apple.main-thread
0  QuartzCore                     0x18e7ca1d0 CALayerGetSuperlayer + 20
1  UIKit                          0x191e4e9d4 -[UIView(UIKitManual) superview] + 128
2  UIKit                          0x1915d3a5c -[UIView nextResponder] + 120
3  UIKit                          0x19197d620 -[UIResponder _canChangeFirstResponder:toResponder:] + 64
4  UIKit                          0x19165c01c -[UIResponder becomeFirstResponder] + 224
5  UIKit                          0x19169b118 -[UINavigationController navigationTransitionView:didStartTransition:] + 760
6  UIKit                          0x1917758ac -[UINavigationController _startCustomTransition:] + 3852
7  UIKit                          0x19168f7bc -[UINavigationController _startDeferredTransitionIfNeeded:] + 676
8  UIKit                          0x19168f424 -[UINavigationController __viewWillLayoutSubviews] + 64
9 UIKit                          0x19168f388 -[UILayoutContainerView layoutSubviews] + 188
10 UIKit                          0x1915d5cc0 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1200
11 QuartzCore                     0x18e7c6274 -[CALayer layoutSublayers] + 148
12 QuartzCore                     0x18e7bade8 CA::Layer::layout_if_needed(CA::Transaction*) + 292
13 QuartzCore                     0x18e7baca8 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32
14 QuartzCore                     0x18e73634c CA::Context::commit_transaction(CA::Transaction*) + 252
15 QuartzCore                     0x18e75d3ac CA::Transaction::commit() + 504
16 QuartzCore                     0x18e75de78 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 120
17 CoreFoundation                 0x18b4549a8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
18 CoreFoundation                 0x18b452630 __CFRunLoopDoObservers + 372
19 CoreFoundation                 0x18b452a7c __CFRunLoopRun + 956
20 CoreFoundation                 0x18b382da4 CFRunLoopRunSpecific + 424
21 GraphicsServices               0x18cded074 GSEventRunModal + 100
22 UIKit                          0x19163dc9c UIApplicationMain + 208

=========3========
#0. Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x18fe4c1a0 objc_retain + 16
1  UIKit                          0x1974fba5c -[UIView nextResponder] + 120
2  UIKit                          0x1978a45ec -[UIResponder _resignIfContainsFirstResponder] + 156
3  UIKit                          0x1974fb76c -[UIView(Hierarchy) _willMoveToWindow:] + 568
4  UIKit                          0x197507d88 -[UIView(Internal) _addSubview:positioned:relativeTo:] + 424
5  UIKit                          0x197773000 __53-[_UINavigationParallaxTransition animateTransition:]_block_invoke_2 + 1556
6  UIKit                          0x19750e964 +[UIView(Animation) performWithoutAnimation:] + 104
7  UIKit                          0x1976e0950 __53-[_UINavigationParallaxTransition animateTransition:]_block_invoke + 260
8  UIKit                          0x1977fd388 +[UIView(Internal) _performBlockDelayingTriggeringResponderEvents:] + 220
9 UIKit                          0x1976e0450 -[_UINavigationParallaxTransition animateTransition:] + 1060
10 UIKit                          0x19769d818 -[UINavigationController _startCustomTransition:] + 3704
11 UIKit                          0x1975b77bc -[UINavigationController _startDeferredTransitionIfNeeded:] + 676
12 UIKit                          0x1975b7424 -[UINavigationController __viewWillLayoutSubviews] + 64
13 UIKit                          0x1975b7388 -[UILayoutContainerView layoutSubviews] + 188
14 UIKit                          0x1974fdcc0 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1200
15 QuartzCore                     0x1946ee274 -[CALayer layoutSublayers] + 148
16 QuartzCore                     0x1946e2de8 CA::Layer::layout_if_needed(CA::Transaction*) + 292
17 QuartzCore                     0x1946e2ca8 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32
18 QuartzCore                     0x19465e34c CA::Context::commit_transaction(CA::Transaction*) + 252
19 QuartzCore                     0x1946853ac CA::Transaction::commit() + 504
20 UIKit                          0x1974f3308 _afterCACommitHandler + 256
21 CoreFoundation                 0x19137c9a8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
22 CoreFoundation                 0x19137a630 __CFRunLoopDoObservers + 372
23 CoreFoundation                 0x19137aa7c __CFRunLoopRun + 956
24 CoreFoundation                 0x1912aada4 CFRunLoopRunSpecific + 424
25 GraphicsServices               0x192d15074 GSEventRunModal + 100
26 UIKit                          0x197565c9c UIApplicationMain + 208

I have no idea which page or what action caused this crash, and I can't reproduce this either.
Also tried Xcode analytics, zombie, memory instrument, with no luck.
Please let me know if you have any comments.


text:
Q: Does Entity Framework save related classes automatically? Let's assume that we have such classes
public class A{
    string someField { get; set; }
    public virtual B B {get; set; }
}

public class B {
   int someIntField {get; set; }

   [ForeignKey("Id")]
   [Required]
   public virtual A A { get; set; }
}

In code I create new instances for both of them and making relation like:
A a = new A () { someField = "abcd"};
B b = new B () { someIntField = 42 };

A.B = b;
B.A = a;

Should I using DBContext to save both classes like that:
using (var db = new myDbContext()) {
    myDbContext.As.Add(A);
    myDbContext.Bs.Add(B);
    myDBContext.SaveChanges();
}

Or saving it like that:
using (var db = new myDbContext()) {
    myDbContext.As.Add(A);
    myDbContext.SaveChanges();
}

is enough to store related objects into database?

A: From your example, if you instantiate new entity objects and then assign the child to the parent object's property, then EF will actually create a new child instance (record) and map it to the parent as a reference.
Your code snippet is a bit confusing because you've got reference from A to B and B to A but consider the following:
if you had 2 entities:
public class A
{
    public int Id;
}

public class B
{
    public int Id;
    public A A;
}

and when saving you did something like this:
A a = new A();
B  b = new B();
b.A = a;
dbcontext.SaveChanges();

then EF will create a new record for A, a new record for B and add the reference of newly created A record to B.
See this post for further details

A: Saving the object that contains the other object is enough. It will automatically persist the changes to contained objects as well.
You could just create a small example and see for yourself what works.

A: using (var db = new myDbContext()) {
   myDbContext.As.Add(A);
   myDbContext.SaveChanges();
}

that should be enough.


text:
Q: Can we notifiy .net application to update data from database instead of pooling concept? My concern is to ping .net web application to pick the updated data from SQL server db and showing the same on ui instead of manual pooling concept. I dnt want to use javascript time intervals.
In research i found Signal R but still asking you all for other concepts which can be opted.
So my question is What are the ways by which i can notify application to retrieve updated data from db?

A: Signal R is best one for push notification on web UI in .net.

A: Signal R is the best option to refresh data from database to UI


text:
Q: dependencies checked into git repository - composer install changed a lot of files - don't want to check them in or remove them I am working on a project that I didn't create. After installing it on my local system and running composer install and npm install, I end up with 1700+ files changed. I believe that if I would commit them, it would screw up our staging environment. Please correct me if I am wrong.
I can't exclude them with .gitignore since they are checked in. How can I hide them in git without removing them from my local system and not changing/removing them in the repository?


text:
Q: Matplotlib does not display hatching when rendering to pdf I am attempting to use the hatching feature in matplotlib, which works fine when displaying to screen. However when I save the figure to pdf format, the hatch marks are not rendered:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,2*np.pi,100)

plt.figure()
plt.fill(x,np.sin(x),color='blue',alpha=0.5,hatch='/')
plt.show()
plt.savefig('./test.pdf',format='pdf')

I am using matplotlib 1.0.1 in pylab on OS X 10.6.6. This may be a platform specific issue having to do with the backend renderer, but I'm not sure. Any suggestions would be most appreciated.

A: Looks like a bug. Please file it in the github issue tracker.
In the meantime, here's a workaround:
plt.fill(x,np.sin(x),color='blue',alpha=0.5)
plt.fill(x,np.sin(x),color='None',alpha=0.5,edgecolor='blue',hatch='/')

A: TL;DR: use alpha=.99 to render hatches when exporting in PDF
It's nearly 2020 and the bug still exists when using plt.bar(). When rendering in PNG, everything is rendered properly. However, PDF export has a glitch when rendering hatches. Hatches are not visible, sometimes visible when zooming-in/out (sometimes not when tested on different computers), it is not clear where the bug comes from.
We realized it's linked with the alpha option. When using alpha=.5, the color is 50% visible, as well as hatches (50% visible as well). Good step, we have almost visible hatches. Therefore, let's just try with alpha=.99 so that everything is nearly 100% visible.
It works! Houray!
In our workaround, no need to duplicate lines like in previous answer. Keep the color option as it is and just set alpha=.99.


text:
Q: Google GeoCharts: how to remove header in custom HTML tooltip? I have a Google GeoChart with custom HTML tooltip.
All is fine except that tooltip title won't go away

google.charts.load('current', {
  'packages': ['geochart'],
  'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});

google.charts.setOnLoadCallback(drawRegionsMap);

function drawRegionsMap() {
  var data = google.visualization.arrayToDataTable([
    [
        {label: 'Country', type: 'string'},
        {label: 'Popularity', type: 'number'},
      {label: 'Tooltip', 'type': 'string', 'role': 'tooltip', 'p': {'html': true}}
    ],
    ['Germany', 200, makeTooltip('Germany', 200)],
    ['United States', 300, makeTooltip('USA', 300)],
    ['Brazil', 400, makeTooltip('Brazil', 400)],
    ['Canada', 500, makeTooltip('Canada', 500)],
    ['France', 600, makeTooltip('France', 600)],
    ['RU', 700, makeTooltip('Russia', 700)]
  ]);

  var options = {
    legend: 'none',
    tooltip: {isHtml: true}
  };

  function makeTooltip(label, value){
    return '
'+label+'
'+value+'
';
  }

  var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));

  chart.draw(data, options);
}

The same configuration with a Bar Chart works perfectly

google.charts.load('current', {
  'packages': ['corechart'],
  'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});

google.charts.setOnLoadCallback(drawRegionsMap);

function drawRegionsMap() {
  var data = google.visualization.arrayToDataTable([
    [
        {label: 'Country', type: 'string'},
        {label: 'Popularity', type: 'number'},
      {label: 'Tooltip', 'type': 'string', 'role': 'tooltip', 'p': {'html': true}}
    ],
    ['Germany', 200, makeTooltip('Germany', 200)],
    ['United States', 300, makeTooltip('USA', 300)],
    ['Brazil', 400, makeTooltip('Brazil', 400)],
    ['Canada', 500, makeTooltip('Canada', 500)],
    ['France', 600, makeTooltip('France', 600)],
    ['RU', 700, makeTooltip('Russia', 700)]
  ]);

  var options = {
    legend: 'none',
    tooltip: {isHtml: true}
  };

  function makeTooltip(label, value){
    return '
'+label+'
'+value+'
';
  }

  var chart = new google.visualization.ColumnChart(document.getElementById('regions_div'));

  chart.draw(data, options);
}

What am I missing? An answer to my similar problem suggest to add showTitle: false, but it does not work... Should I really deal with CSS to hide the title?
Thanks

A: it's an issue specific to GeoChart.
you can remove by using object notation on the first column.
provide the value, and a blank formatted value.
{v: 'Germany', f: ''}

see following working snippet...

google.charts.load('current', {
  'packages': ['geochart'],
  'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});

google.charts.setOnLoadCallback(drawRegionsMap);

function drawRegionsMap() {
  var data = google.visualization.arrayToDataTable([
    [
        {label: 'Country', type: 'string'},
        {label: 'Popularity', type: 'number'},
      {label: 'Tooltip', 'type': 'string', 'role': 'tooltip', 'p': {'html': true}}
    ],
    [{v: 'Germany', f: ''}, 200, makeTooltip('Germany', 200)],
    [{v: 'United States', f: ''}, 300, makeTooltip('USA', 300)],
    [{v: 'Brazil', f: ''}, 400, makeTooltip('Brazil', 400)],
    [{v: 'Canada', f: ''}, 500, makeTooltip('Canada', 500)],
    [{v: 'France', f: ''}, 600, makeTooltip('France', 600)],
    [{v: 'RU', f: ''}, 700, makeTooltip('Russia', 700)]
  ]);

  var options = {
    legend: 'none',
    tooltip: {isHtml: true, trigger: 'both'}
  };

  function makeTooltip(label, value){
    return '
'+label+'
'+value+'
';
  }

  var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));

  chart.draw(data, options);
}


text:
Q: SP 2013 Nested IF statement calculated column I'm trying to make a nested IF statement where: less than or equal to 45 is green; greater than 45 and less than or equal to 90 is gold; and greater than 90 is red
The individual code works fine by itself, but I can't seem to nest them.
(less than or equal to 45 is green)
="<span style='font-weight:bold; font-size:48px; color:"&IF(Count<=45,"green"&";'>●")

(greater than 45 and less than or equal to 90 is gold)
="45,"gold"&";'>●")

(greater than 90 is red)
="90,"red"&";'>●")

A: ="StartOffWithAnyTextYouNeedLikeOpeningSingleQuotes" &
IF([FIElD]<=45,"green",IF(AND([FIELD]>45,[FIELD]<=90),"gold","red")) &
";'>dot AndFinishOffAnythingElse"

Start it off with whatever you are building, then add in the green/gold/red, then finish off with our closing quotes.


text:
Q: Trying to add a foreign key in SQLPLUS command line CREATE TABLE sales_rep
(
    slsrep_number VARCHAR (20),
    first VARCHAR (20) NOT NULL,
    last VARCHAR (20) NOT NULL,
    CONSTRAINT slsrep_number_pk PRIMARY KEY (slsrep_number)
);

CREATE TABLE customer
(
    customer_number VARCHAR (20),
    CONSTRAINT customer_number_pk PRIMARY KEY (customer_number)
);

ALTER TABLE customer
    ADD CONSTRAINT fk_slsrep_number FOREIGN KEY (slsrep_number)
        REFERENCES sales_rep(slsrep_number);

ERROR AT LINE 3 ORA-00904: "SLSREP_NUMBER": INVALID IDENTIFIER

What am I doing wrong?

A: You have no column called slsrep_number in the customer table.  Just do:
CREATE TABLE customer
(
    customer_number VARCHAR(20),
    slsrep_number VARCHAR(20),
    CONSTRAINT pk_customer_number PRIMARY KEY (customer_number),
    CONSTRAINT fk_slsrep_number FOREIGN KEY (slsrep_number) REFERENCES sales_rep(slsrep_number)
);

You can use a separate alter table, but you might as well put it into the table definition.


text:
Q: How to make Qicon fill entire QTableWidgetItem or grid in QTableWidget I have worked on QTableWidget,the question is how to make a Qicon to fill in the entire grid or QTableWidget in QtableWidget,even stretch with width or height of the grid,thank you.

Code as below:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon

class Table(QWidget):
    def __init__(self):
        super(Table, self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle("QTableWidget Example")
        self.resize(400,300)
        self.layout=QHBoxLayout()
        self.TableWidget=QTableWidget(2,3)

        self.TableWidget.setHorizontalHeaderLabels(['Nmae','Sex','Weight(kG)'])

        self.newItem=QLineEdit('Jack')
        self.TableWidget.setCellWidget(0,0,self.newItem)

        self.newItem=QLineEdit('Male')
        self.TableWidget.setCellWidget(0,1,self.newItem)
        self.newItem=QLineEdit('160')
        self.TableWidget.setCellWidget(0,2,self.newItem)

        self.newItem=QTableWidgetItem(QIcon("./icon/1.png"),'')
        self.TableWidget.setItem(1,0,self.newItem)

        self.newItem=QTableWidgetItem(QIcon("./icon/2.png"),'')
        self.TableWidget.setItem(1,1,self.newItem)

        self.newItem=QTableWidgetItem(QIcon("./icon/2.png"),'')
        self.TableWidget.setItem(1,2,self.newItem)

        self.layout.addWidget(self.TableWidget)

        self.setLayout(self.layout)

if __name__ == '__main__':
    app=QApplication(sys.argv)
    win=Table()
    win.show()
    sys.exit(app.exec_())

A: You need to use an item delegate, then check if the index has valid data for the decoration role and, in that case, draw it instead of using the default painting function.
class ImageDelegate(QStyledItemDelegate):
    def paint(self, painter, opt, index):
        decoration = index.data(Qt.DecorationRole)
        if decoration is not None:
            if isinstance(decoration, QIcon):
                decoration = decoration.pixmap(opt.rect.size())
            # decoration role can also contain a QColor, we only want a pixmap
            if isinstance(decoration, QPixmap):
                painter.drawPixmap(opt.rect, decoration)
                return
        super().paint(painter, opt, index)

class Table(QWidget):
    # ...
    def initUI(self):
        # ...
        self.delegate = ImageDelegate(self.TableWidget)
        self.TableWidget.setItemDelegate(self.delegate)


text:
Q: Prepend or append PI before / after the root element with lxml With lxml, how can I prepend processing instructions before the root element or append PIs after de root element with lxml.
Currently, the following example doesn't work:
from lxml import etree

root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
print(etree.tounicode(root))

I get:
<ROOT/>

Instead of:
<?foo?><ROOT/>

A: You need to use ElementTree, not just Element in tounicode():
from lxml import etree

root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
print(etree.tounicode(root.getroottree()))

Output is almost what you wanted:
<?foo ?><ROOT/>

Extra space character after foo showed up because lxml renders PI as pi.target + " " + pi.text.

A: Actually, an Element is always attached to a ElementTree even if it looks "detached":
root = etree.XML("<ROOT/>")
assert root.getroottree() is not None

When we use addprevious/addnext to insert a processing instruction before/after a root element, the PIs are not attached to a parent element (there isn't any) but they are attached to the root tree instead.
So, the problem lies in the usage of tounicode (or tostring). The best practice is to print the XML of the root tree, not the root element.
from lxml import etree

root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
root.addnext(etree.ProcessingInstruction("bar"))

print(etree.tounicode(root))
# => "<ROOT/>"

print(etree.tounicode(root.getroottree()))
# => "<?foo ?><ROOT/><?bar ?>"


text:
Q: how to combine firstname and lastname as fullname in SQL with group by I want to concat firstname and lastname as fullname in SQL with group by.
Ex: Display customerNumber, amount(total by customerNumber from tbl_payment), fullName(firstName, ' ', lastName) from tbl_customers
I've researched but did not get what I wanted.

A: Concatenate the FIRSTNAME and LASTNAME columns as FULLNAME in an SQL query with a GROUP BY clause :-
  SELECT
  CUSTOMERNUMBER,
  SUM(AMOUNT) AS TOTAL,
  CONCAT(FIRSTNAME, ' ', LASTNAME) AS FULLNAME
FROM TBL_CUSTOMERS
GROUP BY CUSTOMERNUMBER, FIRSTNAME, LASTNAME;


text:
Q: Scale UIView using UISlider I'm trying to scale an UIView using a UISlider but the result is not good with this approach:
- (void)setScale:(float)scale {
   CGAffineTransform transform = CGAffineTransformScale(myView.transform, scale, scale);
            myView.transform = transform;

}

thanks

A: You want to change the scale based on the identity transform (which represents the object without any changes). This code works:
- (void)sliderDidChangeValue:(id)sender
{
    // the slider
    UISlider *slider = sender;

    // get your view or use the ivar if you have it in one
    UIView *view = [self.view viewWithTag:12];

    CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, slider.value, slider.value);
    view.transform = transform;
}

When you create the slider you may want to start the value at 1 if your view is starting at full size.


text:
Q: How to cause Error in substrate without using ensure? I want to just panic in a match statement without checking any conditions.
e.g.
pub fn add_citizen(origin, profile_hash:Vec<u8>) -> dispatch::DispatchResult {
     let who = ensure_signed(origin)?;
     let citizenid_option = CitizenId::<T>::get(&who);
     match citizenid_option {
            Some(citizen_id) => {
                    ensure!(citizen_id, <Error<T>>::ProfileExists);

                }
                None => {

                }

            }

     let count = CitizenCount::get();
     Ok(())
}

Is there no other way to panic other than using ensure!


text:
Q: MS Graph API: OneDrive resource not found I'm building a Windows service that connects to OneDrive for Business via the Graph API using this method:
https://graph.microsoft.io/en-us/docs/authorization/app_only
I've successfully authenticated my application and have a token for making calls to Graph API.  I have given my Azure AD application permissions to both Windows Azure Active Directory and Microsoft Graph (all application and delegated permissions have been selected for both).
My goal is to get the contents of a folder that resides in a specific user's OneDrive.  I need to make the following Graph API call:
//graph.microsoft.com/v1.0/users('user-guid')/drive/items/long-item-id-here/children

I can execute this request successfully using Microsoft Graph Explorer (logged in with my Office 365 credentials).  When I try to make the same call as an application (using the auth token received above), I get an "itemNotFound" code with the message "The resource could not be found." (request-id:
5e814dce-c4c2-4615-90e6-ea8ab90cbc49).  However, I am able to query the root and the "folder.childCount" property shows the correct number of children in the root:
//graph.microsoft.com/v1.0/users('user-guid')/drive/root

I've set the folder's sharing to "All Authenticated Users" and I still receive "The resource could not be found" from the API call.
Any ideas on what I'm missing here?

A: The marked answer is no longer the case. You can now access OneDrive and SharePoint resources using a Client Credentials grant (aka "App Only").
The applicable scopes are Files.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite.All

A: The application is using App-only authorization which is currently not supported for accessing OneDrive for Business through Microsoft Graph API. Please use delegated flow, which is used by Graph Explorer.


text:
Q: How to stub RSpec update action? New to RSpec and having trouble stubbing out an update method (needs to be stubbed) and am running into this error. I have tried a bunch of different ways and can't seem to solve it. I tried to include only the necessary code.
/spec/controllers/admin/business_controller_spec.rb:
require 'spec_helper'

RSpec.describe Admin::BusinessesController, type: :controller do
  render_views

  before(:all) do
    @business = build_stubbed(:business)
  end

  describe '#update' do
    before(:each) do
      allow(Business).to receive(:find).and_return(@business)
      @new_name = Faker::Company.name
      @params = { id: @business.id, business: { name: @new_name } }
    end

    it 'updates business name' do
      expect(@business).to receive(:update_attributes).with(name: @new_name, confirm_flag: @business.confirm_flag, phone_primary: @business.phone_primary).and_return(true)
      xhr :patch, :update, id: @business.id, business: { name: @new_name }
      expect(@business.name).to eq(@new_name)
    end
  end
end

/app/controllers/admin/businesses_controller.rb
class Admin::BusinessesController < Admin::BaseAdminController

  def update
    @business.update_attributes(business_params)
  end

  def business_params
    params.require(:business).permit(:name, :active_flag).merge(confirm_flag: true, phone_primary: '')
  end

end

When I run this test I get this error:
Failures:

  1) Admin::BusinessesController#update updates business name
 Failure/Error: @business.update_attributes(business_params)

   #<Business:0x007fc43c4f5738> received :update_attributes with unexpected arguments
     expected: ({:name=>"Fadel, Larson and Hettinger", :confirm_flag=>true, :phone_primary=>"7832900175"})
          got: ({"name"=>"Fadel, Larson and Hettinger", "confirm_flag"=>true, "phone_primary"=>""})
   Diff:
   @@ -1,4 +1,4 @@
   -[{:name=>"Fadel, Larson and Hettinger",
   -  :confirm_flag=>true,
   -  :phone_primary=>"7832900175"}]
   +[{"name"=>"Fadel, Larson and Hettinger",
   +  "confirm_flag"=>true,
   +  "phone_primary"=>""}]

So it looks like the phone_primary is causing the problem and I change my test expectation line to be:
  describe '#update' do
    before(:each) do
      allow(Business).to receive(:find).and_return(@business)
      @new_name = Faker::Company.name
      @params = { id: @business.id, business: { name: @new_name } }
    end

    it 'updates business name' do
      expect(@business).to receive(:update_attributes).with(name: @new_name, confirm_flag: @business.confirm_flag, **phone_primary: ''**).and_return(true)
      xhr :patch, :update, id: @business.id, business: { name: @new_name }
      expect(@business.name).to eq(@new_name)
    end
  end

and i get the failure:
Failures:

  1) Admin::BusinessesController#update updates business name
 Failure/Error: expect(@business.name).to eq(@new_name)

   expected: "Flatley Inc"
        got: "Samara Kuhic"

And now the names aren't matching

A: I ended up stubbing the reload by using assigns. My tests are now passing with this:
 describe '#update' do
   before(:each) do
     allow(Business).to receive(:find).and_return(@business)
     @new_name = Faker::Company.name
   end

   it 'updates business name' do
      expect(@business).to receive(:update_attributes).with(name: @new_name, confirm_flag: true, phone_primary: '').and_return(@business)
      xhr :patch, :update, id: @business.id, business: { name: @new_name }
      expect(assigns(:business)).to eq(@business)
      expect(response.status).to eq(200)
    end
  end

Not sure if this is the preferred way but it's passing for me. Looks like assigns will be deprecated in Rails 5

A: If you check your original code, in your controller you have this:
def business_params
  params.require(:business).permit(:name, :active_flag).merge(confirm_flag: true, phone_primary: '')
end

you're always setting confirm_flag to true and phone_primary to ''(empty string). And in your test you have this:
expect(@business).to receive(:update_attributes).with(name: @new_name, confirm_flag: @business.confirm_flag, phone_primary: @business.phone_primary).and_return(true)

so, if you check confirm_flag you're setting it to @business.confirm_flag which in this case in fact is true and it's fine with what you're setting in the controller, but the problem comes with phone_primary which is being set to @business.phone_primary, and in this case @business.phone_primary is 7832900175, and that's why it is failing.
So, to fix this, you either have to change your test to:
expect(@business).to receive(:update_attributes).with(name: @new_name, confirm_flag: @business.confirm_flag, phone_primary: '').and_return(true)

or change your controller code to permit phone_primary from the params, which will also fix your error.


text:
Q: PyQt Checkbox List with lambda signal I create some QCheckBoxes from a dict using the dict keys as checkbox text.
Then I connect the signal to the update function using a lambda expression.
What I want to pass to this update function is the text of the checkbox so each lambda has its specific argument.
Nevertheless I always get the text of the last added widget, no matter which checkbox I click.
Do I miss something crucial about the concept of signal passing using lambda?
import sys
from PyQt5.QtWidgets import QDialog, QCheckBox, QVBoxLayout, QApplication, QSlider, QLabel

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        layout = QVBoxLayout()

        cb_dict = {"cb1": False, "cb2": True, "cb3": False}
        cb_widget_list = list()

        for checkbox in cb_dict:
            widget = QCheckBox(checkbox)
            widget.stateChanged.connect(lambda: self.update(checkbox))
            cb_widget_list.append(widget)

        for widget in cb_widget_list:
            layout.addWidget(widget)
        self.setLayout(layout)

    def update(self, origin: str):
        print("Checkbox {} has changed".format(origin))

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

So the output is always Checkbox cb3 has changed.

A:
void QCheckBox::stateChanged(int state)
This signal is emitted whenever the checkbox's state changes, i.e., whenever the user checks or unchecks it.
state contains the checkbox's new Qt::CheckState.

Since you want to pass another parameter, you should do this:
        widget.stateChanged.connect(
            lambda state, checkbox=checkbox: self.update(state, checkbox)  # +++
        )

import sys
from PyQt5.QtWidgets import QDialog, QCheckBox, QVBoxLayout, QApplication, QSlider, QLabel

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        layout = QVBoxLayout()

        cb_dict = {"cb1": False, "cb2": True, "cb3": False}
        cb_widget_list = list()

        for checkbox in cb_dict:
            widget = QCheckBox(checkbox)
            widget.stateChanged.connect(
                lambda state, checkbox=checkbox: self.update(state, checkbox)  # +++
            )
            cb_widget_list.append(widget)

        for widget in cb_widget_list:
            layout.addWidget(widget)
        self.setLayout(layout)

    def update(self, state, origin: str):                                      # + state
        print("Checkbox {} has changed: {}".format(origin, state))

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())


text:
Q: Laravel 8 on sub-domain I have been searching, searching and searching with no success.
I'm very new to Laravel and the learning curve is pretty steep to build a simple 4 page web site !! :)
I have set-up a sub-domain using cpanel and the proper document root for the sub-domain.
I have copied the complete Laravel 8 project to the sub-domain document root.
When I access the sub-domain, I'm getting the Laravel 404 page.
I have changed the index.php to Hello and it get's served. So the sub-domain is properly set-up.
sub-domain: xyz.website.com
Document root: /xyz/public where public is the public folder inside of a Laravel project.
First Question
How do I turn on logging to get more details as to what is happening !!
I have ensured that the .env file has the following:
APP_DEBUG=true and APP_LOG_LEVEL=debug
I cannot see any logging happening. I've looked in the storage/logs folder and it is empty.
Second Question
I have seen many posts stating that the .htaccess needs to be changed.
Not sure that this is applicable for sub-domains with the proper document root configured.
As you can see, I'm in dire need of some help and any feedback would be greatly appreciated.


text:
Q: removing entire rows to make the two datasets the same size I need help removing the rows for which the elements in the first column (V1) do not correspond to those in the column (X1). My dataset is much larger, I just used this example to make it easier to understand.
         V1   V2   V3            X1  X2  X3
 [1,]     1    2    3     [1,]    1   2   3
 [2,]     2    2    3     [2,]    1   2   3
 [3,]     1    2    3     [3,]    1   2   3
 [4,]     1    2    3
 [5,]     3    2    3

For this example I would require the code to remove the rows [2,] and [5,] as they are different from what you have in X1 (The general idea is to fix my dataset so they have the same elements and remove those that are in V but not in X).
The code I thought is this:
for(k in 1:nrow(V)){
    if(V[k,1]!=X[k,1]){
       V[-k,]
    }
 }

but it does not work because the size for V is different than X.
Any help would be greatly appreciated!!

A: We can use %in% to get the logical index of elements of 'V1' (in matrix 'm1') that is present in 'X1' (from 'm2'), negate (!) to get elements not present, and use that as row index to subset the 'm1'.
m1[!m1[,'V1'] %in% m2[, 'X1'],]
#     V1 V2 V3
#[1,]  2  2  3
#[2,]  3  2  3


text:
Q: Image Feature Extraction in PyTorch I am going through difficulties to understand this code snippet.
import torch
import torch.nn as nn
import torchvision.models as models

def ResNet152(out_features = 10):
      return getattr(models, "resnet152")(pretrained=False, num_classes = out_features)

def VGG(out_features = 10):
      return getattr(models, "vgg19")(pretrained=False, num_classes = out_features)

In this code segment, features for an input image is extracted by ResNet152 and Vgg19 model. But I have the question, from whether which part of these models the features are being extracted whether the part is last pooling layer or the layer before the classification layer or something else.

A: Note that getattr(models, 'resnet152') is equivalent to models.resent152.
Hence, the code below is returning the model itself.
getattr(models, "resnet152")(pretrained=False, num_classes = out_features)
# is same as
models.resnet152(pretrained=False, num_classes = out_features)

Now, if you look at the structure of the model by simply printing it, the last layer is a fully-connected layer, so that is what you're getting as features here.
print(ResNet152())

ResNet(
  (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
...
  (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
  (fc): Linear(in_features=2048, out_features=10, bias=True)
)

The same is the case for VGG().


text:
Q: Jquery code requires two individual clicks I have some issues with JQuery.
Code;
$(document).ready(function(){
    $("#area_results").click(function(){
        $("#areaclickpass2 a").click(function(){
            var value = $(this).html();
            var input = $('#inf_custom_TESTclubarea');
            input.val(value);
            $("#area_results").hide(); // hide results after click
        });
    });
});

The current website is requiring 2 clicks to input the value into a field.
I understand why it's doing this (Best solution I can think of to achieve the outcome), however I was curious whether it is possible to achieve the same result by only using a single click.
Thanks for your time.

A: Create a variable that counts up with each click and execute your code when that variable equals 2.
$(document).ready(function(){
    var click_count = 0;
    $("#area_results").click(function(){
         click_count++;
         if(click_count==2){
              var value = $(this).html();
              var input = $('#inf_custom_TESTclubarea');
              input.val(value);
              $("#area_results").hide(); // hide results after click
          }
     });
});

A: You are binding a event handler within another event handler. #areaclickpass2 will not be handled unless you click on #area_results first.
Just move $('#areaclickpass2') event binding out of #area_results scope:
$("#area_results").click(function(){
     //may not even be necessary to have this
});

$("#areaclickpass2 a").click(function(){
   var value = $(this).html();
   var input = $('#inf_custom_TESTclubarea');
   input.val(value);
   $("#area_results").hide(); // hide results after click
});


text:
Q: Notation for indexing the factorizations of a number? Background
Given any $n \in \mathbb{N}$, the ordered factorization count of $n$ can be computed and is traditionally written $H(n)$. This is, essentially, the number of unique decompositions of $n$ into products of not-necessarily-prime factors.
For example, the number 30 can be decomposed 13 different ways: { 2×3×5, 2×5×3, 2×15, 3×2×5, 3×5×2, 3×10, 5×2×3, 5×3×2, 5×6, 6×5, 10×3, 15×2, 30 }.
Question
Let $F(n,i)$ be the $i$th ordered factorization of $n$, where $1 \le i \le H(n)$. When enumerating the set of all ordered factorizations of $n$, what notation is used to codify the tuple $(n,i)$, that is, how do we denote "the $i$th factorization of $n$" succinctly?
I have been using the invented syntax n#i. But what is the standard notation in mathematics for this concept?
Here is another example:
120#1 = 2 x 2 x 2 x 3 x 5
120#2 = 2 x 2 x 2 x 5 x 3
120#3 = 2 x 2 x 2 x 15
120#4 = 2 x 2 x 3 x 2 x 5
120#5 = 2 x 2 x 3 x 5 x 2
120#6 = 2 x 2 x 3 x 10
120#7 = 2 x 2 x 5 x 2 x 3
120#8 = 2 x 2 x 5 x 3 x 2
120#9 = 2 x 2 x 5 x 6
120#10 = 2 x 2 x 6 x 5
120#11 = 2 x 2 x 10 x 3
120#12 = 2 x 2 x 15 x 2
120#13 = 2 x 2 x 30
120#14 = 2 x 3 x 2 x 2 x 5
120#15 = 2 x 3 x 2 x 5 x 2
120#16 = 2 x 3 x 2 x 10
120#17 = 2 x 3 x 4 x 5
120#18 = 2 x 3 x 5 x 2 x 2
120#19 = 2 x 3 x 5 x 4
120#20 = 2 x 3 x 10 x 2
120#21 = 2 x 3 x 20
120#22 = 2 x 4 x 3 x 5
120#23 = 2 x 4 x 5 x 3
120#24 = 2 x 4 x 15
120#25 = 2 x 5 x 2 x 2 x 3
120#26 = 2 x 5 x 2 x 3 x 2
120#27 = 2 x 5 x 2 x 6
120#28 = 2 x 5 x 3 x 2 x 2
120#29 = 2 x 5 x 3 x 4
120#30 = 2 x 5 x 4 x 3
120#31 = 2 x 5 x 6 x 2
120#32 = 2 x 5 x 12
120#33 = 2 x 6 x 2 x 5
120#34 = 2 x 6 x 5 x 2
120#35 = 2 x 6 x 10
120#36 = 2 x 10 x 2 x 3
120#37 = 2 x 10 x 3 x 2
120#38 = 2 x 10 x 6
120#39 = 2 x 12 x 5
120#40 = 2 x 15 x 2 x 2
120#41 = 2 x 15 x 4
120#42 = 2 x 20 x 3
120#43 = 2 x 30 x 2
120#44 = 2 x 60
120#45 = 3 x 2 x 2 x 2 x 5
120#46 = 3 x 2 x 2 x 5 x 2
120#47 = 3 x 2 x 2 x 10
120#48 = 3 x 2 x 4 x 5
120#49 = 3 x 2 x 5 x 2 x 2
120#50 = 3 x 2 x 5 x 4
120#51 = 3 x 2 x 10 x 2
120#52 = 3 x 2 x 20
120#53 = 3 x 4 x 2 x 5
120#54 = 3 x 4 x 5 x 2
120#55 = 3 x 4 x 10
120#56 = 3 x 5 x 2 x 2 x 2
120#57 = 3 x 5 x 2 x 4
120#58 = 3 x 5 x 4 x 2
120#59 = 3 x 5 x 8
120#60 = 3 x 8 x 5
120#61 = 3 x 10 x 2 x 2
120#62 = 3 x 10 x 4
120#63 = 3 x 20 x 2
120#64 = 3 x 40
120#65 = 4 x 2 x 3 x 5
120#66 = 4 x 2 x 5 x 3
120#67 = 4 x 2 x 15
120#68 = 4 x 3 x 2 x 5
120#69 = 4 x 3 x 5 x 2
120#70 = 4 x 3 x 10
120#71 = 4 x 5 x 2 x 3
120#72 = 4 x 5 x 3 x 2
120#73 = 4 x 5 x 6
120#74 = 4 x 6 x 5
120#75 = 4 x 10 x 3
120#76 = 4 x 15 x 2
120#77 = 4 x 30
120#78 = 5 x 2 x 2 x 2 x 3
120#79 = 5 x 2 x 2 x 3 x 2
120#80 = 5 x 2 x 2 x 6
120#81 = 5 x 2 x 3 x 2 x 2
120#82 = 5 x 2 x 3 x 4
120#83 = 5 x 2 x 4 x 3
120#84 = 5 x 2 x 6 x 2
120#85 = 5 x 2 x 12
120#86 = 5 x 3 x 2 x 2 x 2
120#87 = 5 x 3 x 2 x 4
120#88 = 5 x 3 x 4 x 2
120#89 = 5 x 3 x 8
120#90 = 5 x 4 x 2 x 3
120#91 = 5 x 4 x 3 x 2
120#92 = 5 x 4 x 6
120#93 = 5 x 6 x 2 x 2
120#94 = 5 x 6 x 4
120#95 = 5 x 8 x 3
120#96 = 5 x 12 x 2
120#97 = 5 x 24
120#98 = 6 x 2 x 2 x 5
120#99 = 6 x 2 x 5 x 2
120#100 = 6 x 2 x 10
120#101 = 6 x 4 x 5
120#102 = 6 x 5 x 2 x 2
120#103 = 6 x 5 x 4
120#104 = 6 x 10 x 2
120#105 = 6 x 20
120#106 = 8 x 3 x 5
120#107 = 8 x 5 x 3
120#108 = 8 x 15
120#109 = 10 x 2 x 2 x 3
120#110 = 10 x 2 x 3 x 2
120#111 = 10 x 2 x 6
120#112 = 10 x 3 x 2 x 2
120#113 = 10 x 3 x 4
120#114 = 10 x 4 x 3
120#115 = 10 x 6 x 2
120#116 = 10 x 12
120#117 = 12 x 2 x 5
120#118 = 12 x 5 x 2
120#119 = 12 x 10
120#120 = 15 x 2 x 2 x 2
120#121 = 15 x 2 x 4
120#122 = 15 x 4 x 2
120#123 = 15 x 8
120#124 = 20 x 2 x 3
120#125 = 20 x 3 x 2
120#126 = 20 x 6
120#127 = 24 x 5
120#128 = 30 x 2 x 2
120#129 = 30 x 4
120#130 = 40 x 3
120#131 = 60 x 2
120#132 = 120

Note that this question is similar to, but not a duplicate of, the related question: What is the pair $(n,k)$ called where $n$ is and integer and $k$ is the ordered factorization index? That question asks what are the tuples called, whereas the present question asks what is the standard notation for writing the indexes.


text:
Q: Track WPF Grid Column Width Upon Resizing I am using Grid splitter to resize columns in wpf application. I want some event that occurs when I am done with resizing. Grid Splitter has no events in it.
So I try using events from grid columns
  void col_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        _dragStart = true;
        _currentColWidth = (sender as ColumnDefinition).ActualWidth;

    }

    bool _dragStart;
    double _currentColWidth;
    void col_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        _dragStart = false;
        if ((sender as ColumnDefinition).ActualWidth != _currentColWidth)
        {

        }
    }

This is the screenshot of the application and these are the two columns with and without resizing

A: Bind the gridsplitter position (or some width in the column) against a property. In the Binding use the delay option (new in .NET 4.5)
This was introduced for Slider-Controls, etc. which update much too often. Set the delay to a few hundred milliseconds, then you only get the final updated value.
See more here: http://www.jonathanantoine.com/2011/09/21/wpf-4-5-part-4-the-new-bindings-delay-property/

A: What do you mean with GridSplitter doesn't have any events ?
XAML
<Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="Column1" Width="Auto"/>
        <ColumnDefinition x:Name="Column2" Width="*"/>
    </Grid.ColumnDefinitions>
<GridSplitter x:Name="GridSplitter1" VerticalAlignment="Stretch" DragCompleted="GridSplitter1_DragCompleted" HorizontalAlignment="Right" Grid.Column="0" Background="Black" BorderBrush="Black" BorderThickness="2" Width="2"/>

CODE:
 void GridSplitter1_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
    {
        void GridSplitter1_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
    {
        MessageBox.Show("Column1 : " + Column1.Width + "\n" + "Column2: " + Column2.Width);
    }
    }

Works very fine for me


text:
Q: Redirect the page if the print is successful - JavaScript javascript:window.print();
document.location.href = "https://www.google.com/";

I use above code to print a page I'm in then redirects it. What it does is it redirects the page if the print is successful or fail.
How can I redirect the page if the page is successfully printed only ?

A:
How can I redirect the page if the page is successfully printed only ?

By giving the user a nice big clear link to follow if the print works. That's it. That's all you can do.
Even on browsers that support it (Firefox and IE), the onafterprint event fires even if the user cancels the print dialog box, so it's completely useless. I, for one, would be really cheesed off with a web page I wanted to print if it redirected me somewhere else when I chose print, then canceled (for whatever reason) with the intention of going back to print it.
Then there's the whole issue of what "succesfully" means. Even if the user told it to go ahead and print, and the job got sent to the printer, that doesn't mean the printing was successful. Print queues notwithstanding, it's quite common to have to actually go back to the source and say "print" again when something goes wrong.
And then, there's the UX side of it. Even if the print was entirely successful, do you think a user really wants you to decide where they go next? No. Give them the option of going where you want them to go, but leave control in their hands — where it belongs.


text:
Q: How to deal with mini blocks of sections in BEM naming convention? markup 1: -
below I've created  "about section" block. in this block have some mini blocks  like:-  stats and  features.
`

about title

about sub title

stats title

stats sub title

features icon

features title

`

Question from about code:-
Should i need to create new css file to each block like about.css, about-stats.css and about-features.css or create one file for this block about.css ?
markup: 2
`

about title

about sub title

stats title

stats sub title

features icon

features title

`

question from above code:-
should we mix child blocks with parent block or markup 1 is good ?


text:
Q: How can i add data programatically in linqqtosql? i dislike below methods.  Because more fields (suchas 150 fields) it is not good method. There is any SetValue method to add datato sql linqtosql for submitchanges?

 MyClass c = new MyClass ();
              c.FirstField = "bvnvb";
              c.......
              c...
              c...

             // Too many rows there is...
              engCtx.MyClass.InsertOnSubmit(c);
              engCtx.SubmitChanges();

How can i do with a loop method via using linq?
it is simple request why don't understand it is clear. i don't want to make it above is there any method like below?

foreach(...........)
engCtx.MyClass.Add(item);

A: It's not clear what you want.
The LINQ part of this is only two lines.
The "creating an object the way you want it part" is longer, but it's your object, it's under your control.  Add a ctor which takes a number of parameters.  Add SetXXXX() methods which set a number of properties at once.  (Use partial classes if the main part of tha main is generated)


text:
Q: rxjava 2.0 what is the difference between Observable.subscribe and Observable.subscribeActual? The documentation just says
protected abstract void subscribeActual(Observer<? super T> observer)
Operator implementations (both source and intermediate) should implement this method that performs the necessary business logic.
There is no need to call any of the plugin hooks on the current Observable instance or the Subscriber.

A: Observable.subscribe comes from the base interface definition in ObservableSource and is the main subscription method for Observables: internal and external components use it to run a flow in a standard way.
However, certain actions may be necessary for all kinds of Observables to be executed before the operator's business logic gains access to the incoming Observer, for example, applying plugin hooks and protecting against crashing subscribe implementations. So instead of requiring every operator to duplicate this preparation logic, they are in a single place and a new abstract method is present to deal with the customization of an Observable.


text:
Q: Animate position of div on scroll position What's the best way to animate the position of a div on scroll position? Essentially, when you reach a certain point on the page... a fixed element will animate up.
I have included below what I currently have... but it's a little slow and seems to slide up... slowly... half way... then complete. Any thoughts?
var shareHeight = $('.related-share-container').height();
$('.related-share-container').css('bottom',-shareHeight);
$(window).scroll(function() {
     if ($(window).scrollTop() + $(window).height() > $(document).height() - 150) {
        $('.related-share-container').stop().animate({ bottom: 0 }, 500);
     } else {
         $('.related-share-container').stop().animate({ bottom: -shareHeight }, 500);
     }
});

UPDATE FOR REWARD
This is the dev site I am working on: http://goo.gl/KcFdE6 and as you can see, if you scroll to the bottom and stop, it slides up fairly well, BUT, if you keep scrolling... it's interacting with the animation and you can a really jumpy/slow transition. Any ideas?

A: It is happening cause for each scroll movement previous animation get stopped and new begins, which is slower than previous one cause it has less distance to animate. Thus you need some flag in your code to prevent same animation triggering again and again.
Modified JS:
Here I am using done class as a flag.
var shareHeight = $('.related-share-container').height();
$('.related-share-container').css('bottom',-shareHeight);
$(window).scroll(function() {
     if ($(window).scrollTop() + $(window).height() > $(document).height() - 150) {
         if(!$('.related-share-container').hasClass('done'))
             $('.related-share-container').addClass('done').stop().animate({ bottom: 0 }, 500);
     } else {
         if($('.related-share-container').hasClass('done'))
             $('.related-share-container').removeClass('done').stop().animate({ bottom: -shareHeight }, 500);
     }
});

A: If I understood you correctly you want an element which is somewhere on the page to scroll once it's on a specific position of the viewport.
Check this fiddle: http://jsfiddle.net/6bZab/11/
JS:
var oldElemBottom;

function isScrolledIntoView(elem) {
  var win = $(window),
    marginBot = 20,
    docViewTop = $(window).scrollTop(),
    docViewBottom = docViewTop + $(window).height(),
    elemTop = $(elem).offset().top,
    elemBottom = elemTop + $(elem).height();

  if (typeof oldElemBottom !== 'undefined'){
    elemBottom = oldElemBottom;
  }
  if ((win.scrollTop() + win.height()  - marginBot) >= elemBottom){
    oldElemBottom = elemBottom;
    return true
  } else {
    return false
  };
}

CSS:
#container {
  width: 100%;
  height: 1000px;
}

#elem {
  width:80px;
  height:50px;
  background:#333;
  color:#FFF;
  text-align:center;
  right: 0;
}

.first{
  background-color: green;
  height: 1000px;
}

.absolute_pos{
  position: absolute;
  top: 600px;
}

Element is scrolling as soon as the bottom of the viewport + marginBot passes the element. It's fixed afterwards until it's goin top again.

A: Going off the fact that you mention the iffy animation rather than actual div placement, the problem is that your js code executes every time you scroll, even if you are already animating.  This causes you to stop the animation and restart it.  This is the cause of the slow and laggy animation effect you are seeing.
What you need to do is keep track of if you are animating and react based on that so the animation has a chance to complete.
//...
var isAnimating = false;

$(this).bind('scroll', function() {
    //jQuery does have a :animated selector as well that can handle this
    if(!isAnimating){
        isAnimating = true;
        var y = $(this).outerHeight() + api.getContentPositionY() + 600 >= api.getContentHeight();

        if (y) {
            $('.related-share-container').animate({ 'margin-bottom': 0 }, { queue: false, duration: 300 }, 'slow', function(){ isAnimating = false; });
        } else {
            $('.related-share-container').animate({ 'margin-bottom': -shareHeight - 30 }, { queue: false, duration: 300 }, 'slow', function(){ isAnimating = false; });
        }
    }
});

Warning!  Code not tested but is an approximation of needed code  You will need to take into account that if they are scrolling up, it is okay to stop the animation and reverse direction.

A: First check this demo
CSS
.related-share-container{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    z-index: 9999;
    padding: 15px 0;
    font-size: 16px;
    display:none;
}

download animate.css file and link to your file
JS
$(window).scroll(function(e) {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 150) {
            $('.related-share-container').removeClass('rotateOutUpLeft').addClass('animated rotateInUpLeft').show();
        } else {
            $('.related-share-container').removeClass('rotateInUpLeft').addClass('rotateOutUpLeft');
        }
    });

Its working perfect. don't forget to download animate.css file and add to your site. you can choose animation effect.

A: You have 2 options, both of which are good, but the latter is better:
A. Use a debounced function - in other words, you want to throttle the scroll listener so that it only happens once out of every X milliseconds, so if someone is mid-scroll, it won't happen.
Libraries such as lodash provide this as _.debounce(fn, time);
If you don't use a library, this can be achieved like this (I'm using the code from your current site):
        var shareHeight = $('.related-share-container').height();
        $('.related-share-container').css('height',shareHeight);
        $('.project-content-container').css('margin-bottom',shareHeight);
        $('.related-share-container').css('margin-bottom',-shareHeight - 30);
        var timeout,
            elem = $(this);
        elem.bind('scroll', function() {
            clearTimeout(timeout);
            timeout = setTimeout(function(){
                var y = elem.outerHeight() + api.getContentPositionY() + 600 >= api.getContentHeight();
                if (y) {
                    $('.related-share-container').stop(true).animate({ 'margin-bottom': 0 }, { queue: false, duration: 300 });
                } else {
                    $('.related-share-container').stop(true).animate({ 'margin-bottom': -shareHeight - 30 }, { queue: false, duration: 300 });
                }
            }, 50); //50ms debounce time
        });

B. Animate in steps - in other words, each time your animate function will be called, it will not animate the full size of the container, but will only animate the amount that was scrolled (or a set step size). This is actually a much better solution, since currently, if someone scrolls down and the huge footer pops up, it's almost impossible to scroll back up.
 Libraries such as tween.js make this easy.

A: I'd use css transitions instead of jquery animate as follows, so that you don't have to worry about the animation queue.
(Using css, You could even make use of hardware acceleration)
css
.element-to-animate {
 /*your style rules*/
 transform: translate3d(0, 0, 0);
 transition:height .5s linear;
}
.hide {
 height:0 !important;
}

script:
var sliderTop = $(window).height() - 150;
$(window).scroll(function () {
 var scrollTop = $(window).scrollTop();
 if (scrollTop > sliderTop) {
    if ($('.overlay').hasClass('hide'))
      $('.overlay').removeClass('hide');
 } else {
    if (!$('.overlay').hasClass('hide'))
       $('.overlay').addClass('hide');
 }
});

Demo


text:
Q: After typo3 update - text does not wrap around image, images are not displayed in columns After the typo3 update to version 8.7 I am having an issue with images.
First text is no longer wraping around images although the alignment for the image is set to wrap around the text. See here: http://www.vbl.org
Second images are no longer displayed in columns, although number of columns is set to 5. See here: http://www.vbl.org/berichte/bildberichte-2018/halbziit-2-juni-2018.html
Why is this happening?

A: I think you missed some CSS.
In your compressed CSS at least one include (gray-theme.css) results in a 404.
And maybe the markup has changed, so HTML and CSS does not match any longer.

A: In TYPO3 8 the extension css_styled_content has a second optional template. Add static template from extension css_styled_content: TypoScript Content Elements CSS.


text:
Q: IBM Cloud Private 3.1.1 EE Installation Error I'm doing a fresh installation of IBM Cloud Private 3.1.1 in a lab environment with the following components :

*

*1 x boot node

*1 x master node

*1 x proxy node

*1 x worker

*1 x management node

*1 x VA node

*1 x etcd node

The installation failed at the task : "addon : Installing logging chart".
All nodes are using Ubuntu 16, and the installation was initiated from the boot node with root user credentials
Looked into the tiller log, I found :
[tiller] 2018/11/30 12:30:44 executing 7 post-install hooks for logging
[tiller] 2018/11/30 12:30:44 deleting post-install hook logging-elk-elasticsearch-tls-init for release logging due to "before-hook-creation" policy
[kube] 2018/11/30 12:30:44 Starting delete for "logging-elk-elasticsearch-tls-init" Job
[kube] 2018/11/30 12:30:44 Using reaper for deleting "logging-elk-elasticsearch-tls-init"
[kube] 2018/11/30 12:30:44 building resources from manifest
[kube] 2018/11/30 12:30:44 creating 1 resource(s)
[kube] 2018/11/30 12:30:44 Watching for changes to Job logging-elk-elasticsearch-tls-init with timeout of 10m0s
[kube] 2018/11/30 12:30:44 Add/Modify event for logging-elk-elasticsearch-tls-init: ADDED
[kube] 2018/11/30 12:30:44 logging-elk-elasticsearch-tls-init: Jobs active: 0, jobs failed: 0, jobs succeeded: 0
[kube] 2018/11/30 12:30:44 Add/Modify event for logging-elk-elasticsearch-tls-init: MODIFIED
[kube] 2018/11/30 12:30:44 logging-elk-elasticsearch-tls-init: Jobs active: 1, jobs failed: 0, jobs succeeded: 0
[tiller] 2018/11/30 12:38:53 warning: Release logging post-install ibm-icplogging/templates/es-searchguard-init-job.yaml could not complete: watch closed before Until timeout
[tiller] 2018/11/30 12:38:53 warning: Release "logging" failed post-install: watch closed before Until timeout
[storage] 2018/11/30 12:38:53 updating release "logging.v1"
[tiller] 2018/11/30 12:38:53 failed install perform step: watch closed before Until timeout

Any suggestion would be nice.

A: Are You Have Been Followed System Requirement ?
https://www.ibm.com/support/knowledgecenter/SSBS6K_3.1.1/supported_system_config/hardware_reqs.html
*Other Problem :
To resolve the OOM (OutOfMemory) issue we could try to double both the limit and the java opts (ES_JAVA_OPTS) for elasticsearch, You can run the following command:
kubectl edit -n kube-system statefulset logging-elk-data
and double the parameters.


text:
Q: Spelling of Vietnamese names in formal context I am a professor and I have a Vietnamese student called, say, Nguyen Hoang Thang. How should I write his name in the official documents, such as his diploma or transcript? How should his name be indicated in published scientific journal articles he authors?
(Not duplicate of this question because that question is not about formal rules, and the answers mainly say "different people prefer different spellings of their names", which does not answer my question.)
His passport specifies:
Full name: Nguyen Hoang Thang

It is clear to Vietnamese native speakers (him included) that Nguyen is his family name, Hoang is his middle (additional) name, and Thang is his (main) given name, roughly corresponding to Kennedy - Fitzgerald - John or Bianchi - Lee - Mary.
I do realize that I can ask him, but even if John Fitzgerald Kennedy prefers to be called Jack, as a professor I cannot indicate his preferred spelling in his diploma -- there must be formal rules for this. My question is about these formal rules.
So how should we write the name of my student in the following formal contexts?
The transcript certifies that:
Last name: Kennedy, First name: John Fitzgerald (or John? John F.?)
Last name: Nguyen, First name: Hoang Thang? Thang Hoang? Thang? Thang H.? H. Thang?

The degree is bestowed upon:
John Fitzgerald Kennedy
Nguyen Hoang Thang?
Thang Hoang Nguyen?
Hoang Thang Nguyen?

Authors of the journal paper:
John F. Kennedy
Nguyen H. Thang?
Thang H. Nguyen?
H. Thang Nguyen?

Authors of the journal paper:
J.F. Kennedy
Nguyen H.T.?
T.H. Nguyen?
H.T. Nguyen?

A: Per Wikipedia on Vietnamese Names there is a convention for this.

Vietnamese personal names generally consist of three parts: one patrilineal family name, one or more middle name(s) (one of which may be taken from the mother's family name), and one given name, used in that order. The "family name first" order follows the system of Chinese names and is common throughout the Chinese cultural sphere. However, it is different from Chinese, Korean, and Japanese names in the usage of "middle names", as they are less common in China and Korea and do not exist in Japan. Persons can be referred to by the whole name, the given name or a hierarchic pronoun, which usually connotes a degree of family relationship or kinship, in normal usage.
Due to the frequency of the major family names such as Nguyễn, Trần, and Lê, persons are often referred to by their middle name along with their given name in Vietnamese media and youth culture.
Examples:
Nguyễn Tấn Dũng is the former Prime Minister of Vietnam. Nguyễn is his family name, Tấn is his middle name, and Dũng is his given name. In formal usage, he is referred to by his given name ("Mr. Dũng"), not by his family name ("Mr. Nguyễn").
Likewise, the famous general and military leader, Võ Nguyên Giáp, is referred to by his given name, i.e. "General Giáp".

Despite other Asian naming conventions following the use of the family name as the primary index, Vietnamese names tend to follow the opposite for Indexing purposes per CMOS

According to the English-language Chicago Manual of Style, Vietnamese names are indexed according to the final given name and not according to the family name, with a cross-reference placed in regards to the family name. Ngô Đình Diệm would be listed as "Diem, Ngô Dinh" and Võ Nguyên Giáp would be listed as "Giáp, Võ Nguyên".

The CMOS convention seems to be used in many other places, too.  Though there's some debate on the subject.
Since this seems to be the most commonly used convention in English and lines up with Vietnamese usage, I'd suggest giving his name as Thang, Nguyen Hoang on formal papers (Thang, NH when abbreviated in a citation).
Nguyen Hoang Thang on a diploma.  This will probably line up better with his passport as well, rather than trying to shoehorn it into English.