text:
Q: Reverting a git merge while allowing for the same merge later) What's the best way to revert a committed git merge while keeping the option of merging the same branch at a later point?
This is for a situation when I merge a branch into HEAD, then decide that I do not want these changes at the present, but still want the option to merge them into HEAD at some later point.
"git revert -m 1" reverts the code to the pre-merge state, but the branch is still somehow marked as "already merged". So a repeated merge with the same branch at a later point does not work.
This should be a very common problem (and git is an evolved tool), yet I cannot find a simple clean solution (apart from destroying the git repository and pulling it from remote again). Am I missing something?

A: Sorry to say that you have wasted your branch.
But there is a workaround. The trick is to "rewrite" the merge commit temporarily so that it forgets that the branch is a parent. Assume X is the merge commit:
git replace --graft X X^   # pretend that there is just one parent
git merge branch           # merge the branch again
git replace --delete X     # remove the replacement

A: If your merge commit is not pushed yet and it is the top one, you can use reset command
git reset --hard HEAD^

Note, that all uncommitted changes will be lost.

A: If you have not yet published your merge commit (pushed to the central server), the best solution is to rewrite history to remove the merge commit.

*

*If there are no other commits after the merge commit, reset the head to the previous commit:

git reset HEAD^

*If there are other commits after the merge commit, you'll need to do a rebase and remove the merge commit, while re-applying the other commits.

git rebase -i
If you have published the merge, you will need to decide whether it is better to rewrite history to preserve proper merge potential for your branch, or simply add a revert commit. This will require talking to everyone who may have potentially downloaded the merge.
If you cannot rewrite history, you'll need to do a revert:
git revert  -m 1
In this case, a future merge of the branch will need manual intervention. You may need to cherry-pick commits that are not picked up by the merge, or revert your revert commit.


text:
Q: How to force reload data for an Android APP I have an Android device. There is a navigation APP on this Android device that plays a sound every time i reach my destination.
I want to change this sound it makes, but the actual APP doesn't have a menu to do so.
What i did so far was:
- Scan my whole device with ES explorer for audio files. I've found  one .wav file and it is the one I'm after. I deleted the file and replaced it with another .wav file of my choosing.(same name, similar size, bitrate, etc).
Didn't work. Old file still plays from who-knows-where.
I went to menu and cleared cache for the app.
Didn't work.
I restart the phone, load new maps to phone and do whatever else i can think of. Nothing works.
I can't clear data for the app and force it to reload the sound because I have settings for the app inside and no backup possible.
I believe there old sounds is saved somewhere in a temp folder but i can't access it because no root and the app doesn't work on rooted phones. The old sounds it plays isn't even anywhere on the phone, i deleted it.
Can anyone think of another option to get my new file to play?

A: During app development, a sound file such as the one to play when destination is reached might have been included in the res folder of the app.
Have a look into this: https://android.stackexchange.com/a/108691
I'm not discouraging you to pursue this further, but be prepared to find that it might not be possible(just yet).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wait UIAlertView Button I have this code in my Application:
if (self.uiSwtichState == TRUE)
        {
            if ([CLLocationManager locationServicesEnabled])
            {
                [self.textString stringByAppendingString:[[[SMSLocationModel alloc] init] getLocation]];

            }
        }
            MFMessageComposeViewController *sms = [[MFMessageComposeViewController alloc] init];
sms.messageComposeDelegate = self;
sms.body = self.textString;
sms.recipients = self.arrayOfNumbers;
[self presentModalViewController:sms animated:YES];

this code is into a method called "send".
As you can imagine, the method getLocation get the current user location and, the first time the Application run, a UIAlertView appear on the screen asking the user if he want to allow the application to get his location.
The problem is that when this UIAlertView appear, she is immediately replaced by the sms Vie Controller (MFMessageComposeViewController) and in this way the user doesn't have enough time for answer YES or NO in the UIAlertView.
There is a way for wait that the user press a button in the UIAlertView and THEN present the ModalViewController?
Thanks!

A: you could use the CLLocationManagers delegate method to wait until the authorization state changes. Save the sms viewController to an instance variable if you are not authorized to use location services. then ask the location manager to authorize you. If the authorization state changes present that view controller.
// somewhere else
self.locationManager.delegate = self;

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    NSLog(@"New Authorization State: %d", status);
    if (self.viewControllerToPresentAfterLocationDidChange) {
        if (status == kCLAuthorizationStatusAuthorized) {
            // set location of viewController
            [self presentViewController:self.viewControllerToPresentAfterLocationDidChange animated:YES completion:NULL];
        }
        else {
            // user did not authorize you to use location services
        }
        self.viewControllerToPresentAfterLocationDidChange = nil;
    }
}

- (IBAction)buttonPressed:(id)sender {
    UIViewController *vc = [[UIViewController alloc] init];
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) {
        // authorized already, no alert will appear.

        // set location of vc
        [self presentViewController:vc animated:YES completion:NULL];
    }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
        self.viewControllerToPresentAfterLocationDidChange = vc;
        // access location so alert will show
    }
    else {
        // not authorized or restricted.
    }
}

A: Yes, you can implement the AlertViewDelegate.
See UIAlertViewDelegate Documentation for further information.
Then you can use the alertView:clickedButtonAtIndex: method and present your MessageComposer when the user has clicked the alert view.

A: Maybe you can use this delegate:
- (void)didPresentAlertView:(UIAlertView *)alertView{
}

For example, initializing a boolean which can prevent of presenting this modal view controller. Then if dismissed change the boolean to allow presenting this view controller.


text:
Q: birt dynamic range parameters I'm a newbye in Birt and I'd like to develop a report that accepts a "multiple and dynamic range parameter".
Here you are an example to explain better the problem:
   Dataset:
  table: Customer
  columns: idCustomer, name
I'd like that user will be able to insert multiple range of idCustomer to retrieve names.
Ex: user may want customers for id between 205 and 300 and for id between 501 and 670 and for id between 800 and 920...
I usually do the same thing on BO Crystal Report setting "Allow multivalue" and "Allow range values" to the input parameter. Does exists something similar on Birt ?I upload an image here: http://i.stack.imgur.com/uvz7F.jpg .It's a BO screenshot for input parameter with "Allow multivalue" and "Allow range values".
Thanks
     GG

A: Short answer: no.
Longer answer: BIRT doesn't have an option to enable a single parameter to take a range of values.
It does have an option to allow a single parameter to take multiple values, but only for ListBox parameters. Also, you can only bind a single Report Parameter value to a given Dataset Parameter, meaning that you couldn't select on the multiple parameter values within the dataset query (assuming you are using a relational datasource); instead, you would need to add a filter to the dataset, based on the parameter values, in the Filters tab of the Edit Dataset dialog. (And this would still only allow you to specify multiple individual values of the parameter, not multiple ranges of values.)
(Alternatively, you could write a beforeOpen event script for the dataset that would insert the multiple values for the parameter into the dataset's query text directly, instead of binding the report parameters to the dataset parameters; however, this opens your report to the risk of SQL injection attacks. Alternatively, you could add a plugin to BIRT to bind multiple parameter values for you.)
Your options are therefore:

*

*Set up a single ListBox parameter, with multiple values enabled, allowing the users to select all individual values they want, and filter the dataset on the basis of the parameter values (or use a beforeOpen event script, or a BIRT plugin).

*Set up two parameters (for start and end of range) to allow the users to specify a single range of values to be selected, and bind the report parameters to an equivalent pair of dataset parameters in the query.

*Set up n pairs of parameters to allow the users to specify up to n ranges of values to be selected (eg. set up 10 parameters to enable the users to specify up to 5 ranges of values), and bind the report parameters to the equivalent dataset parameters in the query.

*Set up a single textbox parameter to allow the users to enter the ranges freeform (eg. in the format [205..300],[501..607]), then write a beforeOpen event script for the dataset to parse the entered parameter value for the required ranges and amend the query text accordingly.

Note that the last option is strongly deprecated because it requires significantly more work, removes the option to specify valid values and opens your report to the risk of SQL injection attacks.


text:
Q: How to minify Less file output? I'm using Less files with Bootstrap for my application and also using  Less for client-side CSS compiling. I'm wondering how I can minify the compiled CSS output with Less.
I think I need to declare something in between above lines.

A: Most popular tools for task automation are Grunt and Gulp. Both can assist you in your minification.
But to use your less files you have to convert them to .css.
You can use https://www.npmjs.com/package/grunt-contrib-less to convert your less to css and then minify then using https://www.npmjs.com/package/grunt-contrib-cssmin.


text:
Q: Do subsequent Unlocked Package version installs deploy FLS? I've created an Unlocked Package using Salesforce CLI and installed the first version in an org. I've checked the Field Level Security for each Profile and they were all correct. But when I changed the FLS for a profile and made another package version for that same package, the FLS simply wasn't being updated after installing this new version in that org.
So far I managed to update the FLS for subsequent versions by using metadata-api to deploy all the profiles to the org. But that just doesn't feel right.
Am I missing something that I should have been doing?


text:
Q: add row to a data frame that calculates sums of all numeric columns I have a data frame with first two columns characters and the rest doubles.
I want to add a row at the bottom that has the word 'Total' in the first two columns and calculates the sum of the column values in the rest.
For example let's use:
segment<- c('seg1', 'seg1', 'seg2', 'seg2', 'seg3', 'seg3')
subSegment<- c('subseg1', 'subseg2', 'subseg1', 'subseg2', 'subseg1', 'subseg2')
var.1<- c(100, 20, 30, 50, 40, 40)
var.2<- c(200, 30, 30, 70, 30, 140)
var.3<- c(50, 50, 40, 20, 30, 40)
var.4<- c(60, 50, 35, 53, 42, 20)
df<- data.frame(segment, subSegment, var.1, var.2, var.3, var.4)

This is how I did it:
df%>% # now need to add a row with totals
    add_row( segment="Total",subSegment="Total", var.1 = sum(.$var.1), var.2= sum(.$var.2), var.3 = sum(.$var.3), var.4 = sum(.$var.4))

Obviously the names and values are just examples but in my real problem I have over 8 variables and doing things this way is a waste of time.
I am looking for a more general solution that just says to add_row with first 2 columns "Total" and then ....=sum(.$....) for all columns after the third.
Maybe using something like sapply(df[c(3:ncol(df))].

A: The janitor package has this ready to go:

library(janitor)

df %>%
  adorn_totals("row", fill = "Total")

 segment subSegment var.1 var.2 var.3 var.4
    seg1    subseg1   100   200    50    60
    seg1    subseg2    20    30    50    50
    seg2    subseg1    30    30    40    35
    seg2    subseg2    50    70    20    53
    seg3    subseg1    40    30    30    42
    seg3    subseg2    40   140    40    20
   Total      Total   280   500   230   260

A: Let's add an additional row, with Total, Total in two columns, and let's calculate the sums along columns with colSums starting from column 3 till end ncol(df).
df<- rbind(df, c("Total", "Total", colSums(df[,3:ncol(df)], na.rm = TRUE)))


text:
Q: Number of IDs selected In the following sql fiddle, how would I change the view to get the desired output?
http://sqlfiddle.com/#!6/a737a/1
VIEW
select
    sum(dollars) as totalDollars,
    sum(dollars)/count(id) as factor,
    count(id) as numberOfEvents,
    id as eventID,
    event_date
from
    events
group by
    id,
    event_date

Query
select
*
from eventStats
where
event_date between '1/1/2015' and '1/16/2015'

desired output
The numberOfevents should = 2 (the actual number of events, not the number of records for each event, determined by the where clause in the query) to properly do the math in the view.

A: You can count distinct fk_id without the group by clause:
select count(distinct fk_id) as number_of_IDs
from [myTable]
where [someCondition]

A: Use distinct keyword in count function:
select
    count(distinct fk_id) as number_of_IDs
    ,id
from
    myTable
where
    someCondition
group by
    id


text:
Q: Why doesn't adding 24h worth of seconds to a Unix timestamp of right now give me the next day? let todaySeconds = Date.now();
//1591238661657
let todayDate = new Date(todaySeconds);
//Thu Jun 04 2020 05:44:21 GMT+0300 (Eastern European Summer Time

//3600 * 24 = 86400s in a day
console.log(new Date(todaySeconds + 86400));
//Thu Jun 04 2020 05:45:48 GMT+0300 (Eastern European Summer Time)

Why isn't the above Jun 05 2020?

A: JavaScript timestamps operate in milliseconds, not in seconds. You have to add 24 * 60 * 60 * 1000.

let todayMillis = Date.now();
let todayDate = new Date(todayMillis);

console.log(todayDate);
console.log(new Date(todayMillis + (24 * 60 * 60 * 1000)));

A: You are assuming you are working with seconds. You are working with milliseconds. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.


text:
Q: Why Google PageSpeed Insight will take button(with hover effect) as animation? I run Google PageSpeed Insight on my page https://www.datanumen.com
It reports the following issues:

I check back with my page, and find these are not animations at all, instead, they are just buttons. When mouse hovers on them, they will change color. Why they are taken as non-composited animation and how to solve the issues?

A: According to https://developers.google.com/web/fundamentals/performance/rendering/stick-to-compositor-only-properties-and-manage-layer-count you have to remove the transition effects for your buttons.
a.btn, a.button, .inner-page-contact form button, .testimonial-form-holder button, input[type="button"], input[type="reset"], input[type="submit"] {

    /* -webkit-transition: all 0.2s ease-in-out;
    -moz-transition: all 0.2s ease-in-out;
    -o-transition: all 0.2s ease-in-out;
    -ms-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out; */


text:
Q: How to handle certificate pop up which appears in middle of loading page using selenium webdriver Question.
Pop up displayed in middle of  loading page

1]Any line of code before and after get url  wont work because pop up comes in middle of loading page
2]Certificate is about authentication for the site.we just need to click ok on that pop up
3]Robot class and alert accept wont work because pop up comes in middle of loading page.
4]Setting are disable so setting capability wont work.
is there  any other way to handle thispop up .


text:
Q: Is it normal that accuracy decreases when advancing to the next epoch? I'm training a CNN to predict digits using the MNIST database. I'm doing Data Augmentation and for some reason accuracy sharply decreases when advancing to next epoch (iteration 60 in the image)

It has to do with data augmentation (transform = my_transforms in the code) because when I deactivate augmentation (transform = None) accuracy doesn't decrease when advancing to next epoch. But I can't explain why. Does anyone have an idea why this happens?
my_transforms = transforms.Compose([
    transforms.ToPILImage(),
    transforms.RandomCrop((25,25)),
    transforms.Resize((28,28)),
    transforms.RandomRotation(degrees=45, fill=255),
    transforms.RandomVerticalFlip(p=0.1),
    transforms.RandomHorizontalFlip(p=0.5),
    transforms.ToTensor()
    ])

dataset = MNISTDataset(transform = my_transforms)
train_loader = DataLoader(dataset = dataset, batch_size = 1000, shuffle=True)

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1,10,kernel_size=5)
        self.pool = nn.MaxPool2d(kernel_size=2,stride=2)
        self.conv2 = nn.Conv2d(10,20,kernel_size=5)
        self.fc1 = nn.Linear(20*4*4, 64)
        self.fc2 = nn.Linear(64, 10)

def forward(self,x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1,20*4*4)
        x = F.relu(self.fc1(x))
        x = F.softmax(self.fc2(x), dim=1)

        return x

net = Net()

loss_function=nn.NLLLoss()
optimizer=optim.Adam(net.parameters())

EPOCHS=2
iteracion = 0

for epoch in range(EPOCHS):
    for data in train_loader:
        inputs, labels = data
        inputs = inputs.view(-1,1,28,28)

        net.zero_grad()

        probabilities=net(inputs)

        matches=[torch.argmax(i)==int(j) for i,j in zip(probabilities,labels)]

        in_batch_acc=matches.count(True)/len(matches)

        loss=loss_function(torch.log(probabilities), labels)

        print('Loss:', round(float(loss), 3))
        print('In-batch acc:', round(in_batch_acc, 2))

        iteracion += 1

        loss.backward()
        optimizer.step()

A: I replicated your model with data augmentation and tried to plot the Accuracy and Loss and it seems that the problem is the way you are plotting.
In the following lines I attach my code and Loss and Accuracy plots:
Code:
# -- Imports -- #
import torch

from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import transforms, datasets
import torch.nn.functional as F
import matplotlib.pyplot as plt

# -- Data Loader -- #
my_transforms = transforms.Compose([
    transforms.ToPILImage(),
    transforms.RandomCrop((25,25)),
    transforms.Resize((28,28)),
    transforms.RandomRotation(degrees=45, fill=255),
    transforms.RandomVerticalFlip(p=0.1),
    transforms.RandomHorizontalFlip(p=0.5),
    transforms.ToTensor()
    ])
dataset = datasets.MNIST('../data', train=True, download=True,
                         transform = transforms.Compose([
                                            transforms.RandomCrop((25,25)),
                                            transforms.Resize((28,28)),
                                            transforms.RandomRotation(degrees=45, fill=255),
                                            transforms.RandomVerticalFlip(p=0.1),
                                            transforms.RandomHorizontalFlip(p=0.5),
                                            transforms.ToTensor()
                                            ]))
train_loader = DataLoader(dataset = dataset, batch_size = 1000, shuffle=True)

# -- Define Model -- #
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1,10,kernel_size=5)
        self.pool = nn.MaxPool2d(kernel_size=2,stride=2)
        self.conv2 = nn.Conv2d(10,20,kernel_size=5)
        self.fc1 = nn.Linear(20*4*4, 64)
        self.fc2 = nn.Linear(64, 10)

    def forward(self,x):
            x = self.pool(F.relu(self.conv1(x)))
            x = self.pool(F.relu(self.conv2(x)))
            x = x.view(-1,20*4*4)
            x = F.relu(self.fc1(x))
            x = F.softmax(self.fc2(x), dim=1)

            return x

device = 'cuda'
net = Net()
net.to(device)

loss_function=nn.NLLLoss()
optimizer=optim.Adam(net.parameters())

EPOCHS=2
iteracion = 0
accuracy = []
loss_record = []
for epoch in range(EPOCHS):
    for data in train_loader:
        inputs, labels = data
        inputs = inputs.view(-1,1,28,28)
        inputs, labels = inputs.to(device), labels.to(device)

        # -- Forward -- #
        net.zero_grad()
        probabilities=net(inputs)
        matches=[torch.argmax(i)==int(j) for i,j in zip(probabilities,labels)]
        in_batch_acc=matches.count(True)/len(matches)
        loss=loss_function(torch.log(probabilities), labels)

        # -- Statistics -- #
        accuracy.append(in_batch_acc)
        loss_record.append(loss)
        print('Loss:', round(float(loss), 3))
        print('In-batch acc:', round(in_batch_acc, 2))

        iteracion += 1

        loss.backward()
        optimizer.step()

# -- Accuracy plot -- #
iterations = range(0,120)
plt.plot(iterations, accuracy, 'g', label='Accuracy')
plt.title('Accuracy')
plt.xlabel('Iterations')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

# -- Loss plot -- #
plt.plot(iterations, loss_record, label='Loss')
plt.title('Loss')
plt.xlabel('Iterations')
plt.ylabel('Loss')
plt.legend()
plt.show()

Plots:
Accuracy plot
Loss plot
As you can see, there are not jumps when (iteration = 61) -> Next epoch


text:
Q: Thread acquires ReentrantLock which is already acquired by other thread Our application, running in a WebLogic 12c, is retrieving messages from a queuing system, where the queue we are retrieving messages from is configured as a FIFO. We are using Spring to configure the retrieval functionality and both the container (org.springframework.jms.listener.DefaultMessageListenerContainer) and the messages listener (org.springframework.jms.core.support.JmsGatewaySupport) are singletons. Furthermore, that container has configured a WorkManager by default as task executor. To guarantee that the messages are processed in the expected order (the order how they are sent to the queue), we use a ReentrantLock in the listener, and we were expecting that messages were retrieved and processed one by one. The listener code is the following one:
public class JmsReceiveAdapterImpl extends JmsGatewaySupport implements SessionAwareMessageListener {
    private final ReentrantLock lock = new ReentrantLock(true);
    [...]
    public void onMessage(Message rcvMessage, Session session) throws JMSException {
        lock.lock();
        logger.warn("Lock has been acquired by thread: " + Thread.currentThread().getId());
        try {
            [...]
        } finally {
            logger.warn("Lock is going to be released by thread: " + Thread.currentThread().getId());
            lock.unlock();
        }
    }
}
Even though two messages are placed on the queue in the correct order, and they are consumed in that order (recall that the queue is a FIFO one), somehow the two message are processed in parallel by the application as it is shown in the following log chunk:

    Lock has been acquired by thread: 28
    Backout count: 1
    Message 1 / 1 received from XXX Message ID1 received.
    Lock has been acquired by thread: 54
    Backout count: 1
    Message 1 / 1 received from XXX Message ID2 received.
    ***** ERROR *****
    Lock is going to be released by thread: 54
    Lock is going to be released by thread: 28

Why are we obtaining this behaviour? Any idea?
Thank you so much in advanced.

A: Change
logger.warn("Lock has been acquired by thread: " + Thread.currentThread().getId());

To
logger.warn("Lock has been acquired by thread: " + Thread.currentThread().getId() + " And Object " + System.identityHashCode(this));

What you are going to probably see is that the System.identityHashCode will be two different numbers.  If it were the same object the identityHashCode would be identical.  If they are different, that means they are different objects.
What that tells you is that there are more than one ReentrantLock instance and will not support mutual exclusion on the difference instances.


text:
Q: System freezes on disk I/O I am using Ubuntu 18.04 and since few weeks (I cannot say when exactly), my system is experiencing freezes when there are disk I/Os.
My system is installed on an ext4 partition of a SSD.
Even if the load is not very high, some short freezes occur, mouse moves are no longer smooth, Plasma is responding slowly, apps are often in "waiting for disk" state.
This happens for any kind of disk use : software launches, file transfer. When the system starts swapping, it becomes almost unusable.
There is no error in SMART report and I am using Windows on the same disk without anything comparable, so it should not be a hardware problem.
I have checked the partition offset and changed the IO scheduler (https://blog.vacs.fr/index.php?post/2010/08/28/Solving-Linux-system-lockup-when-intensive-disk-I/O-are-performed), and it remains the same.
I have the impression that it is linked to the interruptions management, but I don't know how to check that.
I am now running out of ideas and I hope you may help!
EDIT:
sysctl vm.swappiness
vm.swappiness = 60           #default

free -h (at startup)
              total        used        free      shared  buff/cache   available
Mem:           3.8G        780M        1.6G        117M        1.4G        2.6G
Swap:          3.7G          0B        3.7G

I found a repeatable way to create this freeze with a partition scan with GParted. At startup there is no problem but freezes seem to appear when the first bytes are written on swap. I am checking my swap configuration.
EDIT 2:
The problem appears very quickly. With this memory usage, it is already freezing:
              total        used        free      shared  buff/cache   available
Mem:           3.8G        1.7G        530M        267M        1.5G        1.5G
Swap:          3.7G         48M        3.7G

A: From the comments...
After playing around with vm.swappiness=80, we decided to try a newer kernel. We downloaded 5.5.6 from https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.5.6/, and so far the machine is working fine!
Ultimately, based on the user's normal apps, Firefox with 15 tabs, and an IDE, more RAM might very well be needed. Install RAM in matched pairs of equal type/size RAM to take advantage of memory interleaving. ie: 2 x 4G RAM, or 2 x 8G RAM.

A: (low reputation doesn't allow commenting...)
Ever found a way to mitigate this? Seems like it describes this same issue I'm having on Debian.
I'm also having I/O Disk problems in Debian. It's so weird because I don't even know how to describe the issue, is difficult searching for solutions when you don't know what exactly to search.
It seems like there are other people using Debian complaining about severe I/O problems as well. (for years too)
Something is "locking up" the entire I/O system.
I don't suffer these problems in Manjaro, could you make a test in Manjaro to see if it behaves differently there? (so we can be sure that it's an issue with Debian itself)
In my case, it's Cities Skylines, a C#/DotNet application that is having issues (DotNet games will claim all your memory and swap space regardless of the amount you have)
Screenshots with more detail for context:
https://imgur.com/a/x7LkOvV
It would be nice if someone knew of command-line launch parameters that I could use with C# applications in order to make more tests, or to somehow limit the amount of disk threads it needs. The disk seems to be overwhelmed with requests, it looks like that.


text:
Q: Javascript src with variable by get element by id Continued from previous question
I got the error "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."
So I try to use getElementbyId, and then changing the src:
<head>
<script>
  function pos(url)
  {
  var posterior = document.getElementById("post");
  posterior.src = url;
  }
</script>

In the body,
<body>
<?php ***...to retrieve ID***?>
<script type="text/javascript">
  var videoid = "<?php echo $id; ?>";  //Transfer ID to javascript
  var url="http://......"+videoid;   //Url string finished
  pos(url);   //Function call
</script>
<script id="post" type="text/javascript" src='http://xxx'></script>

Where should I execute or define the pos(url) function? The error becomes "Cannot set property 'src' of null" or "pos is not defined" if I place them on different sections.
Well If I use $(window).load on the pos function in head, the error becomes "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened." again....


text:
Q: owl-carousel issue with angularjs ng-repeat Please i am using owl-carousel for my carousel. My carousel is very similar to the one here http://thebootstrapthemes.com/live/thebootstrapthemes-zenclassified/ . I came across a similar solution Here and  Here . i then added a similar directive in my controller below.
.directive('owlCarousel', function(){
    return {
        restrict: 'E',
        transclude: false,
        link: function (scope) {
            scope.initCarousel = function(element) {
                // provide any default options you want
                var defaultOptions = {
                    autoplay:true,
                    autoplayTimeout:2500,
                    loop:false,nav : true,
                    responsiveClass:true,
                    margin: 30,
                    responsive:{
                        0:{items:1},
                        767:{items:3},
                        992:{items:4}
                    }
                };
                var customOptions = scope.$eval($(element).attr('data-options'));
                // combine the two options objects
                for(var key in customOptions) {
                    defaultOptions[key] = customOptions[key];
                }
                // init carousel
                $(element).owlCarousel(defaultOptions);
            };
        }
    };
}).directive('owlCarouselItem', [function() {
    return {
        restrict: 'A',
        transclude: false,
        link: function(scope, element) {
            // wait for the last item in the ng-repeat then call init
            if(scope.$last) {
                scope.initCarousel(element.parent());
            }
        }
    };
}]);

The above works for me except. The last item's height increase beyond the other items below.

You can see the last item display above. Please how do i resolve that and what is the cause ? Any help would be appreciated.

A: Try this
.directive('owlCarousel', function(){
    return {
        restrict: 'EA',
        transclude: false,
        link: function (scope, element, attrs) {
            scope.initCarousel = function() {
                // provide any default options you want
                var defaultOptions = {
                    autoplay:true,
                    autoplayTimeout:2500,
                    loop:false,nav : true,
                    responsiveClass:true,
                    margin: 30,
                    responsive:{
                        0:{items:1},
                        767:{items:3},
                        992:{items:4}
                    }
                };
                $(element).owlCarousel(defaultOptions);
            };
        }
    };
}).directive('owlCarouselItem',[function() {
     return function(scope) {
     if (scope.$last) {
        scope.initCarousel();
     }
    };
  }]);

Refer to this question  Here Its what worked for me.


text:
Q: Does OpenJPA have any support for batch insert? Does OpenJPA have any support for batch insert similar to Hibernate? I haven't found it in the docs, but I'm hoping I missed it. I know JPA doesn't support it in general.

A: Short answer, yes.
Longer answer, take the link to Hibernate documentation and replace the Session with a JPA EntityManager.
EntityManager em = emf.createEntityManager();
Transaction tx = em.getTransaction();

tx.begin();
for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    em.persist(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        em.flush();
        em.clear();
    }
}

tx.commit();
em.close();


text:
Q: Fitting a power law for extrapolation I am trying to figure out how to interpolate a function, and I want to be able to extrapolate a small way beyond the interpolation range. There is some background theory which leads me to expect that the behavior for large values of the dependent variable x will asymptote to  −A·x−n behaviour (maybe with some offsets). I want to find the best fit power law, but only for large values of x. Is there a good way of implementing this in Python?
I tried to do least squares for the log-linearized version of my power law, but it gave me an inappropriate fit - which I suspect is because of a coding error rather than a math mistake. I was thinking of doing this by introducing an offset into the power law, so that the log equation would be ln(−y) = ln(A) − n ln(x−x0). What I have so far is:
X_asymptote=[]
for i in aX_vals1:
    if i>20*lab_inc(T-1):
        X_asymptote.append(i)
VT1_optimized_asymptote=[]
for i in X_asymptote:
    a=aX_vals1.index(i)
    VT1_optimized_asymptote.append(VT1_optimized_val[a])
#Converting to logs. Note the minus sign! You'll need to put this back in in the unravelling.

X_asymptote_logs=[]
for i in X_asymptote:
    X_asymptote_logs.append(np.log(i))
X_asymptote_logs_array=np.asarray(X_asymptote_logs)

VT1_optimized_asymptote_logs=[]
for i in VT1_optimized_asymptote:
    VT1_optimized_asymptote_logs.append(np.log(-i))
    #VT1_optimized_asymptote_logs.append(-1*np.log(i))
VT1_optimized_asymptote_logs_array=np.asarray(VT1_optimized_asymptote)

#Linear fit
fitfunc=lambda p,x:p[0]+p[1]*x
errfunc=lambda p,x,y:(y-fitfunc(p,x))

out=scipy.optimize.leastsq(errfunc,[-4,5],args=(X_asymptote_logs_array,VT1_optimized_asymptote_logs_array),full_output=1)
pfinal=out[0]
covar=out[1]

index=pfinal[1]
amp=np.exp(pfinal[0])

xnew=np.linspace(X_asymptote_logs[0],aX_vals1_array[len(aX_vals1_array)-1],100)
ynew=VT1_optimized(xnew)
plt.title("Optimized value function, linear extrapolation")
plt.plot(aX_vals1_array, VT1_optimized_val_array, 'o', xnew, ynew, '-')
plt.ylabel('Value function with optimized asset allocation')
plt.xlabel('ratio X/Y')
plt.show()

Could anyone give me a hand with this?
Any help is much appreciated!
Update: I have a pragmatic solution to the problem. I just fitted the power law for the whole data range. It seems to have worked remarkably well, and the code now does want I want, but not in the way I was hoping to understand with this comment. The code I now have is:
#Linear fit
fitfunc=lambda p,x:p[0]+p[1]*(x)
errfunc=lambda p,x,y:(y-fitfunc(p,x))

out=scipy.optimize.leastsq(errfunc,[-4,5],args=(np.asarray(X_asymptote_logs),np.asarray(VT1_optimized_asymptote_logs)),full_output=1)
pfinal=out[0]
covar=out[1]

index=pfinal[1]
amp=np.exp(pfinal[0])
print(index,amp)

def VPL(X):
    return -(amp*(X)**(index))

def VT1_optimized1(X):
    if aX_vals1_array[len(aX_vals1_array)-1]>=X:
        VT1_op=scipy.interpolate.UnivariateSpline(aX_vals1_array,VT1_optimized_val_array,k=3,s=0,check_finite=True)
        return VT1_op(X)
    if X>aX_vals1_array[len(aX_vals1_array)-1]:
        VT1_asymptote=scipy.interpolate.UnivariateSpline(aX_vals1_array,VT1_optimized_val_array,k=5,s=0,check_finite=True)
        return VPL(X)

xnew=np.linspace(aX_vals1_array[0],aX_vals1_array[len(aX_vals1_array)-1]*2,100)

y0=[]
for i in xnew:
    y0.append(VT1_optimized1(i))
ynew=np.asarray(y0)
plt.title("Optimized value function, linear extrapolation")
plt.plot(np.asarray(aX_vals1), np.asarray(VT1_optimized_val), 'o', xnew, ynew, '-')
plt.ylabel('Value function with optimized asset allocation')
plt.xlabel('X')
plt.show()

#This seems to work almost too well! Let's check the asset allocation.

# Plotting
# xnew=np.linspace(aX_vals1_array[0],aX_vals1_array[len(aX_vals1_array)-1],100)
# ynew=VT1_optimized(xnew)
# plt.title("Optimized value function, linear extrapolation")
# plt.plot(aX_vals1_array, VT1_optimized_val_array, 'o', xnew, ynew, '-')
# plt.ylabel('Value function with optimized asset allocation')
# plt.xlabel('ratio X/Y')
# plt.show()

# xnew=np.linspace(aX_vals1_array[0],(aX_vals1_array[len(aX_vals1_array)-1]),100)
# y0=[]
# for i in xnew:
#     y0.append(VT1_optimized1(i))
# ynew=np.asarray(y0)
# plt.title("Optimized value function, lin. extrapolation")
# plt.plot(aX_vals1_array, VT1_optimized_val_array, 'o', xnew, ynew, '-')
# plt.ylabel('asset allocation')
# plt.xlabel('X')
# plt.show()
# exit()


text:
Q: Field Calculator case sensitive issue in QGIS graphical modeler I use QGIS 3.10 with the graphical modeler and I'm facing an issue while creating new field in field calculator: it seems to be case insensitive thus it does not create the field I want.
Problem description follows:

*

*Using Distance matrix algorithm, a layer is created with a field named Distance (and the name of the field can't be chosen)

*I want to rename this field to distance to be compliant with further processing tools (REST API expecting a distance attribute)

*I tried using Field Calculator to create a new field distance based on the value from the Distance field

*When I run the model, the new field isn't created

If I choose a different name for the new field (like foo) everything runs fine. But how can I create 2 different fields with only case difference (then remove one of them).
I tried using Refactor fields as an alternative, but if I don't know the list of attributes in input layer, I can't properly use it.
Am I missing something in the configuration or is it an issue I should report on qgis github ?

A: You can look at/load the attribute tables of currently existing layers in your project from the refactor fields dialogue in the modeller.
So, you create your model up to the point where you need to use refactor fields and run it once. Then you return to the modeller and add the table of the newly created layer to your model.
Or, as JClarkson pointed out in the comments, you could hand your Distance values to a dummy field, delete Distance, then create distance based on the dummy field and finally delete the dummy field.


text:
Q: Ubuntu12.10 boots up and hangs I am using Ubuntu 12.10 with gnome 3.6. It was working fine. But now after I installed some updates of gnome, I am unable to successfully login into Ubuntu. The Ubuntu boots up normally and after loading the wallpaper it hangs up. Nothing else is shown in the desktop. Alt+F2 doesn't work. Ctrl+Alt+F2 is working.
How can I resolve this problem? Is it possible to login into Unity desktop, if gnome has caused this problem?
Thanks.

A: At the login screen you can sign in to Unity. Follow the steps to get logged in fine.

As you can see, that Ubuntu Logo is circled. Click on it, and you will see this:

You should see 'Ubuntu'. Select it and click 'OK >'. Then sign in as normal.
Note: Once you click 'Ubuntu' Unity will be your default theme until you change it. To change the theme use the steps above.
Hope this helps!

A: The same is happening for me...in 3 different machines: my home machine, and 2 machines in my workplace (one of them is a VM).
At home I'm logging in using Cinammon now. It's nice, but it's not what I want, I want gnome-shell.
At work I'm logging into Gnome Classic (no effects).
What I did was open screen terminal 1 (CTRL+ALT+F1) and killall gnome-session. After that the login screen is shown, and then I chose the new default session (either Cinnamon or Gnome Classic with no effects.


text:
Q: Create a View with more Partial View and different model I'd like to have a view for use with the Tab jQuery that allow me to populate multiple tables (with the partial view). Basically I would like to be able to populate the tables of a database with a single view.
My model example:
public class Tag
{
    public int Id { get; set; }
    public string Tag { get; set; }
    public string Note { get; set; }
}

public class City
{
    public int Id { get; set; }
    public string City { get; set; }
    public string Note { get; set; }
}

my controller:
public class tabController : Controller
{
    public ActionResult tab()
    {
        var tvm = new MyDbContext();
        return View(tvm);
    }
}

and my view:
@model ??????????

@section Scripts {

}

tag

city

country

more more

            @Html.Partial("_tag", ????? )

            @Html.Partial("_city", Model?)

            @Html.Partial("_country", @Model.Country)

            @Html.Partial("_note"@*, @Model.NoteShares*@)

I see the error:

The model item passed into the dictionary is of type 'myprojMVC5.Models.tabs', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[myprojMVC5.Models.tabsl]

A: Option 1: View model
Create a view model containing properties for the collections you want to display
public class TabsVM
{
  public IEnumerable<Tag> Tags { get; set; }
  public IEnumerable<City> Cities { get; set; }
}

and in the controller, initialize an instance of the view model and populate te collections
public class tabController : Controller
{
  public ActionResult tab()
  {
    var tvm = new MyDbContext();
    TabsVM model = new TabsVM()
    {
      Tabs = tvm .Tabs(),
      Cities = tvm.Citys()
    }
    return View(model);
}

and in the view
@model yourAssembly.TabsVM
....
@Html.Partial("_tag", Model.Tags)
....
@Html.Partial("_tag", Model.Cities)

Option 2: Call child action only methods that return partial views
[ChildActionOnly]
public ActionResult FetchTags()
{
  var tvm = new MyDbContext();
  var model = tvm.Tags();
  return PartialView("_tags", model);
}

and in the view (no model required to be passed to the view)
....
@Html.Action("FetchTags") // assumes the methods will be in the same controller
....
@Html.Action("FetchCities") // or you can use @{ Html.RenderAction("FetchCities"); }


text:
Q: How to change 0% to display as 0 in Store Procedure In my sp, I have a column name as percentage. In that column it will display percentage of amount but i want to change if the percentage column displays 0% it will display as only 0.

A: Simplest one:
CASE
    WHEN [Your_Column] = '%0' THEN 0
    ELSE [Your_Column]
END AS alias

A: USE REPLACE FUNCTION IN SQLSERVER AND MYSQL:
Edited: To replace only the records which has 0% value in table.
SELECT REPLACE(COLNAME,'0%',0) FROM TABLENAME where len(colname)=2

A: Use CASE statement.
For MySQL check THIS for reference
and for MS SQL check THIS for reference
The code could be something like:
SELECT  CASE percentage WHEN '0%' THEN '0' ELSE percentage END
FROM <your_Table>
WHERE ...

A: for sql-server 2012
select IIF([your column]='0%',0,[your column])


text:
Q: How to increase the bus factor and specialize at the same time? In agile pair programming it is recommended to switch pairs every now and then so as to increase the bus factor of the team. That means, most people in the team should work on different parts of the system at different times so that everyone has an understanding of it.
Now it is impssible that everyone has an expert level of understanding of each part of the system. That's because people are urged to specialize in one area of expertise. If you are an expert database admin, what's the point of working on the user interface of the system when you switch pairs? You will not be able to do such a high quality job as someone who has extensive experience in UI design.
How can you increase the bus factor and make sure that you have specialization in your team?

A: For the main, I'd keep the pairs within discipline - so, UI guys would predominantly pair with another UI person, DB guys would pair with another DB person. If you only have one or two in a discipline, then so be it - you can't always pair when you don't have the numbers. You are right that a UI specialist would not want or be needed to fill in for a DB specialist.
But, it is a good idea to sometimes mix it up a bit - your web service experts might have an idea for the UI, or the UI might have an idea about the DB structure which would simplify something back up on the UI layer - a different perspective can be extremely useful.
Also, DB and UI are quite far apart on the chain - you would get some advantage of the middle layers pairing more frequently with either DB or UI.
As with any work methodology - pair programming isn't something to implement slavishly just to tick a box of to say "yeah, we've done that" - it's there as a tool, and needs thinking to implement.

A: Mix 'em up
Specialization is only a means to gain expertise.
Expertise does not have to come from formal training.  It is most often gained by self-study and experience.  And it is possible for programmers to be expert in multiple areas.  By pairing people with differing experience, you can spread expertise throughout the team.  After a while, instead of one database expert, and one UI expert, you will have several people who are highly capable in both.  This is good for the team, and good for the team members.


text:
Q: Binding the labels property for custom livechart in WPF I'm creating a custom LiveChart control by creating a dependency property for the SeriesCollection, Axis labels, the titles for the x and y axes. When using the control in my main project, the binding is working for all properties except for the Axis labels (xLables). Below is the code for the liveChart custom control. Your help is appreciated.
XAML code
UserControl x:Class="SalesDashboard.Controls.LiveChartUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:SalesDashboard.Controls"
             xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:LiveChartUserControl}}}">

        <lvc:CartesianChart  Series="{Binding cSeries}"  LegendLocation="Bottom">
            <lvc:CartesianChart.AxisX>
                <lvc:Axis Title="{Binding xTitle}" Labels="{Binding xLabels}"  FontSize="15">
                    <lvc:Axis.Separator>
                        <lvc:Separator Stroke="Transparent"/>
                    </lvc:Axis.Separator>

                </lvc:Axis>

            </lvc:CartesianChart.AxisX>

            <lvc:CartesianChart.AxisY>
                <lvc:Axis Title="{Binding yTitle}" LabelFormatter="{Binding Formatter}" FontSize="15">
                    <lvc:Axis.Separator>
                        <lvc:Separator Stroke="Transparent"/>
                    </lvc:Axis.Separator>
                </lvc:Axis>
            </lvc:CartesianChart.AxisY>

        </lvc:CartesianChart>
    </Grid>
</UserControl>

The code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LiveCharts;
using LiveCharts.Wpf;

namespace SalesDashboard.Controls
{
    /// <summary>
    /// Interaction logic for LiveChartUserControl.xaml
    /// </summary>
    public partial class LiveChartUserControl : UserControl
    {

        public Func<double, string> Formatter { get; set; }

        public SeriesCollection cSeries
        {
            get { return (SeriesCollection)GetValue(SeriesProperty); }
            set { SetValue(SeriesProperty, value); }
        }

        public string[] xLables
        {
            get { return (string[])GetValue(xLabelsProperty); }
            set { SetValue(xLabelsProperty, value); }
        }

        public string xTitle
        {
            get { return GetValue(xTitleProperty).ToString(); }
            set { SetValue(xTitleProperty, value); }
        }

        public string yTitle
        {
            get { return GetValue(yTitleProperty).ToString(); }
            set { SetValue(yTitleProperty, value ); }
        }

           public static readonly DependencyProperty SeriesProperty =
           DependencyProperty.Register(nameof(cSeries), typeof(SeriesCollection), typeof(LiveChartUserControl));

            public static readonly DependencyProperty xLabelsProperty =
            DependencyProperty.Register("xLables", typeof(string[]), typeof(LiveChartUserControl),
            new PropertyMetadata
            (null));

            public static readonly DependencyProperty xTitleProperty =
            DependencyProperty.Register(nameof(xTitle), typeof(string), typeof(LiveChartUserControl));

            public static readonly DependencyProperty yTitleProperty =
            DependencyProperty.Register(nameof(yTitle), typeof(string), typeof(LiveChartUserControl));

        public LiveChartUserControl()
        {
            InitializeComponent();
            Formatter = value => value.ToString("N");

        }
    }
}

The implementation
 <controls:LiveChartUserControl x:Name="Livchart1" Grid.Row="1" Grid.Column="0" cSeries="{Binding SeriesCollection}" xLables="{Binding Labels}"  xTitle="{Binding xAxixTitle}" yTitle="{Binding yAxixTitle}"/>

A: It's because of the typo. You have registered dependency property as xLables but in the binding you are using xLabels
public static readonly DependencyProperty xLabelsProperty =
        DependencyProperty.Register("xLables", typeof(string[]), typeof(LiveChartUserControl),
        new PropertyMetadata
        (null));

Labels="{Binding xLabels}"

Renaming xLables to xLabels should fix the issue.


text:
Q: What's the right way to implement integer division-rounding-up? It's very common to need to divide integers but get the result rounded up rather than down. For a while now, I've been using the following function for that mini-idiom:
template <typename S, typename T>
constexpr inline S div_rounding_up(const S& dividend, const T& divisor)
{
    return (dividend + divisor - 1) / divisor;
}

This has (at least) the following deficiences, or what may be seen as deficiencies:

*

*While it works "as promised" with negative operands - it's called div_rounding_up - it would probably make more sense to have this kind of function round away-from-zero, since x / y for negative x and positive y rounds towards zero. In other words, maybe what I should be implementing is div_rounding_away_from_zero, which would be commutative with inversion: Letting auto f = [&y](const S& x) { return div_rounding_away_from_zero(x,y); } we would have f(-x) == -f(x).

*Overflow near the end of the domain of S.

*Possibly weird behavior when sizeof(S) > sizeof(T).

*long function name...

While you can easily think of ways of addressing each of these, they then result in other possible deficiencies, like conditionals in the code, or a reliance on calculating the modulus which may be expensive.
So is there a "right way" to implement this? By "right" I mean semantically pleasing, efficient, avoiding as many of the deficiencies above, and hopefully widely-used.
Notes:

*

*If you think the function should be strictly constained to only work with non-negative arguments, say so. That would be a bit problematic IMHO since we don't want to constrain the types to be unsigned, and we don't want to check the operands' signs. That seems like something I would use a contact for - and C++ doesn't have them yet.

*Is using std::div and variants a good idea here?

*Performance is more important than readability. At worst one can add a comment.

*Code should not be single-architecture-specific (but if you want to ifdef-else for different architectures then be my guest).

*Code should not assume a specific compiler.

A:
Possibly weird behavior when sizeof(S) > sizeof(T).

It would probably be better to use a single type argument, and let the user deal with the conversion that they want. This is the approach used by the standard library math functions.

Overflow near the end of the domain of S.

A remainder based rounding does not have this problem.

reliance on calculating the modulus which may be expensive.

You are already calculating a division, which is expensive. On x86 at least, the division instruction stores the remainder in a register, and a decent implementation of std::div will use it. A modern compiler will even be able to optimize explicit use of division and remainder operation as well.

Is using std::div and variants a good idea here?

Sure.

If you think the function should be strictly constained to only work with non-negative arguments, say so.

I think you should at least require that arguments must have the same sign. The direction of rounding of both division and remainder operator (also by extension std::div since C++11) is implementation defined. With this requirement, there is no difference between rounding away from zero, and rounding up, since no supported result is negative.
template <typename T> // single type argument
constexpr T           // constexpr implies inline
div_round_up
(const T& dividend, const T& divisor)
{
    // no overflows, only 1 expensive operation
    std::div_t dv = std::div(dividend, divisor);
    return dv.quot + (!!dv.rem);
}


text:
Q: Image in ListView that goes off-screen loses its state (never set to 'loaded') The situation:
I have a large list of photos and we are loading them in a grid of thumbnails. These thumbnails are each their own component that are loaded in sets of three within the RenderRow function. Here's the Image component in question:
<Image
  style={styles.image}
  source={this.state.loaded ? { uri: image.url_small } : imagePlaceholder}
  onLoad={() => { this.setState({ loaded: true }); }}
  onLoadStart={() => { this.setState({ loaded: false }); }}
/>

The issue:
Our issue is that if you are scrolling rapidly, or have a less-than-optimal internet connection, some of the images that begin loading never have the "onLoad" called, presumably because they are no longer visible (because we scrolled beyond them in the list already).
However, when we scroll back to those images, all that is rendered is the placeholder image, and the state of the photo is never set to loaded: true. I've tried messing with the onChangeVisibleRows function on the ListView like so:
onChangeVisibleRows={(visibleRows) => {
  const visibleRowNumbers = [];
  for (const row in visibleRows) {
    visibleRowNumbers.push(row);
  }
  this.setState({ visibleRowNumbers });
}}

This seems to work as expected and in the RenderRow function I can check if that specific row is visible, and try to re-render and images in that row by passing a isVisible prop to the image component, but the image component still isn't updating when I return true from shouldComponentUpdate when the isVisible prop changes.
But to no avail.
I believe I'm on the right track, but have hit a dead end. Does anyone have an idea how I can force an image component to reload? Or is there some sort of onLoadInterrupted that might be added so that it begins loading again once it is in view?


text:
Q: c# - simplest way to sort a field from an array loaded from JSON What's the simplest way to sort a field from an array loaded from JSON.I've found some things on Anonymous Functions but I'd like to know if theres a more basic way.
 static void SortItems(Items[] items)
    {

        Console.WriteLine("Choose field to sort (Name, Weapon, Strength)");
        string userInput = Console.ReadLine();
        Items[] sortedItem;
        if (userInput.ToLower() == "name")
        {
            string[] name = items.Select( m => m.Name).ToArray();

        }

        else if (userInput.ToLower() ==  "weapon")
        {
            string[] weapon = items.Select(m => m.EquippedWeapon.Name).ToArray();

        }
        else if (userInput.ToLower() == "strength")
        {
            int[] totalStrength = items.Select(m => m.GetStrength()).ToArray();
        }

         sortedItems = Sorts.Sort(items, userInput);

        foreach (Items c in sortedItems)
        {
            Console.WriteLine("Name : {0} - Weapon: {1} - Total strength: {2}", c.Name, c.Weapon.Name,  c.strength().ToString());
        }

    }

A: If you are able to use Linq extensions, you could do something more like this
static void SortItems(Items[] items)
{

    Console.WriteLine("Choose field to sort (Name, Weapon, Strength)");
    string userInput = Console.ReadLine();
    if (!string.IsNullOrWhiteSpace(userInput))
    {
        Items[] sortedItems;
        switch (userInput.Trim().ToLower())
        {
            case ("name"):
                sortedItems = items.OrderBy(x => x.Name).ToArray();
                break;
            case ("weapon"):
                sortedItems = items.OrderBy(x => x.Weapon).ToArray();
                break;
            case ("strength"):
                sortedItems = items.OrderBy(x => x.Strength).ToArray();
                break;
            default:
                //return whatever for default
                sortedItems = items.OrderBy(x => x.Name).ToArray();
                break;
        }

        foreach (Items c in sortedItems)
        {
            Console.WriteLine("Name : {0} - Weapon: {1} - Total strength: {2}", c.Name, c.Weapon.Name,
                c.strength().ToString());
        }
    }


text:
Q: JavascriptException: Message: javascript error: arguments[0].click is not a function error using arguments[0].click through Selenium and Python I have been webscraping some websites to grab there locations for webscraping practice. This code gets me down to individual city levels of a hotel brand, but whenever I use driver.execute_script("arguments[0].click();", button) in my code (as seen in the second to last line) I get this error:
JavascriptException: Message: javascript error: arguments[0].click is not a function

Below is a sample of the code that I have written thus far.
for state in state_links:
driver = Chrome(path_to_chrome_driver)
link = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' ', '-')
driver.get(link)
city_links = driver.find_elements_by_xpath('//div[@class="countryListingContainer col-xs-12"]//ul//div//li//a//span')
city_links = [thing.text for thing in city_links]
driver.close()
for city in city_links:
    driver = Chrome(path_to_chrome_driver)
    link2 = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' hotels', '').replace(' ', '-') + '/' + city.lower().replace(' ', '-')
    driver.get(link2)
    hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')
    hotel_links = [elem.text for elem in hotel_links]
    driver.close()
    for hotel in hotel_links:
        driver = Chrome(path_to_chrome_driver)
        driver.get(link2)
        driver.implicitly_wait(15)
        driver.execute_script("arguments[0].click();", hotel)
        driver.implicitly_wait(10)

A: This error message...
JavascriptException: Message: javascript error: arguments[0].click is not a function

...implies that invoking click() on arguments[0] using execute_script() failed.

A bit of more information about the steps would have helped us to construct a canonical answer. However, presumably as you are collecting the hotel_links just after:
driver.get(link2)
hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')

So initially, hotel_links contains the WebElements. But in the next line you are overwriting the List hotel_links with the elem.text as follows:
hotel_links = [elem.text for elem in hotel_links]

So, hotel_links now contains elements of type text.
As text element doesn't support click(), hence moving forward when you try to invoke click() on the text elements through execute_script(), you see the said error.

Solution
If you need the text of the hotel links, store them in a seperate List asfollows:
hotel_links_text = [elem.text for elem in hotel_links]

Reference
You can find a couple of relevant discussions in:

*

*What does arguments[0] and arguments[1] mean when using executeScript method from JavascriptExecutor interface through Selenium WebDriver?


text:
Q: How to download file from url in Ionic 5 without using FileTransfer I'm currently developing Ionic app now and stuck at file download part. I saw many posts that FileTransfer cordova library is now deprecated in favor of XHR request.
Even though I saw many posts that the library is deprecated, I can't find any sample code (for downloading file from URL).
Could anyone please suggest me good way to download file from url without using FileTransfer plugin?

A: Downloading files from another server may cause annoying CORS error which is mostly beyond our control. The safest way is to bypass the Webview and download the file natively. You may use Native HTTP plugin
Use in Ionic 4 or above will look like:
import { Component } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
import { File } from '@ionic-native/file/ngx';

@Component({
   selector: 'app-home',
   templateUrl: './you-file.html',
   styleUrls: ['./your-file.scss'],
})

export class HomePage {
    constructor(private nativeHTTP: HTTP, private file: File) {}

     private downloadFileAndStore() {
        //
        const filePath = this.file.dataDirectory + fileName;
                         // for iOS use this.file.documentsDirectory

        this.nativeHTTP.downloadFile('your-url', {}, {}, filePath).then(response => {
           // prints 200
           console.log('success block...', response);
        }).catch(err => {
            // prints 403
            console.log('error block ... ', err.status);
            // prints Permission denied
            console.log('error block ... ', err.error);
        })
     }
  }
}

A: You can just open the url with window. But this will open a browser and
download the file there. It will do the trick although it is not pretty:
your.page.ts:
function download(url){
  window.open(url, "_blank");
}

your.html:
<a href="javascript:void(0)" (click)="download(yourUrl)">Your file name</>

A: This is the solution I used for react, downloading files MP4 and save in the cache  or documents, Filesystem is for capacitor.
const bob = await fetch(url).then((x) => x.blob());
       const base64 = await convertBlobToBase64(bob);

    const resultSaveFile = await Filesystem.writeFile({
        data: base64,
        path: 'video-edit.mp4',
        directory: directory || Directory.Cache,
        recursive: true,
      });

A: You can use simply HttpClient class (@angular/common/http) as follow:
const downloadPath = (
   this.platform.is('android')
) ? this.file.externalDataDirectory : this.file.documentsDirectory;

let vm = this;

/** HttpClient - @angular/common/http */
this.http.get(
   uri,
   {
      responseType: 'blob',
      headers: {
         'Authorization': 'Bearer ' + yourTokenIfYouNeed,
      }
   }
).subscribe((fileBlob: Blob) => {
   /** File - @ionic-native/file/ngx */
   vm.file.writeFile(downloadPath, "YourFileName.pdf", fileBlob, {replace: true});
});

Imports you will need:
import { HttpClient } from '@angular/common/http';
import { File } from '@ionic-native/file/ngx';

A: To be able to download and see files via ionic-native File I had to add additional settings inside Xcode:
confing.xml
<preference name="iosPersistentFileLocation" value="Library" />

info.plist
<key>UIFileSharingEnabled</key> <true/>
<key>LSSupportsOpeningDocumentsInPlace</key> <true/>

Download path should be File.documentsDirectory

A: You can Achieve this in the following steps :
Step 1: A download function to download from URL
downloadFile(path: string, body: Object = {}): Observable<any> {
  let headers = {} // add authentication headers and other headers as per your requirement
  return this.http.post/get(
    `${path}`, body, { headers: headers, withCredentials: true }
  )
  .catch((err) =>console.log(err))
  .map((res:Response) => res)
  .finally( () => { });
}

Step 2: Use the download function to convert it into an appropriate Blob.
this.downloadFile(`url`, postData).subscribe(
 res => {
   let options = { type: 'filetype' };
   let filename = 'filename.type';
   Util.createAndDownloadBlobFile(res._body, options, filename);
 },
 err => {
   // show the error
 }
);

Step 3: Save the Blob Data on Device using following plugin https://github.com/apache/cordova-plugin-file


text:
Q: Is it possible to do an Between two varchar values Kund = customer
We know that we lack in security in our code but so far that is not the problem and this code will not go on to an public website.
This code sorts out values from an database and puts them in a table.
We need to sort the customer S001 and everything between to S176 in a checkbox but we cant get BETWEEN to work with Varchar.
 <!doctype html>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="css.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "garp";

$conn = new mysqli ($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

/*                                                                                $query = $_GET['query']; */
$orderkund = $_GET['Orderkundinput'];
$artikel = $_GET['Artikelinput'];
$startDate =$_GET['startDate'];
$endDate =$_GET['endDate'] ;
$kund =$_GET['kund'];
$kund2 =$_GET['kund2'];
$kunds;

$min_length = 0;
$artikelQuery="";
$orderkundQuery="";
$kundQuery="";
$kund2Query="";
$kundsQuery;
if(strlen($artikel) >= $min_length){
    $artikel = htmlspecialchars($artikel);

    $artikel = mysqli_real_escape_string($conn, $artikel);
    $artikelQuery = " AND Artikelnr = '$artikel'";
}

if (strlen($orderkund) >= $min_length){
    $orderkund = htmlspecialchars($orderkund);

    $orderkund = mysqli_real_escape_string($conn, $orderkund);
    $orderkundQuery = " AND OrderKund = '$orderkund'";
}
if(strlen($kund) >= $min_length){
    $kund = htmlspecialchars($kund);

    $kund = mysqli_real_escape_string($conn, $kund);
    $kundQuery = " OR OrderKund = '$kund'";
}
if(strlen($kund2) >= $min_length){
    $kund2 = htmlspecialchars($kund2);

    $kund2 = mysqli_real_escape_string($conn, $kund2);
    $kund2Query = " OR OrderKund = '$kund2'";
}
if(strlen($kunds) >= $min_length){
    $kunds = htmlspecialchars($kunds);

    $kunds = mysqli_real_escape_string($conn, $kunds);
    $kundsQuery = " between 'S176'";
}
if (strlen($startDate) >= $min_length){
    $startDate = htmlspecialchars($startDate);

    $startDate = mysqli_real_escape_string($conn, $startDate);
    $startDateQuery = " AND Orderdatum between '$startDate' ";
}

if (strlen($endDate) >= $min_length){
    $endDate = htmlspecialchars($endDate);

    $endDate = mysqli_real_escape_string($conn, $endDate);
    $endDateQuery = "AND '$endDate'";
}

$query = $artikelQuery.$orderkundQuery.$kundQuery.$kund2Query.$kundsQuery.$startDateQuery.$endDateQuery;
if(strlen($query) >= $min_length){
$sql = "SELECT OrderHuvud.Ordernummer ,OrderHuvud.OrderserieIK ,OrderKund ,Fakturakund ,Orderdatum ,Erreferens ,Levereratvarde ,Radnummer ,Artikelnr ,Benamning ,Leveranstid ,Ursprungligtantal ,Levereratantal ,Forspris ,Bruttopris ,Varukostnad FROM garp.OrderHuvud left join garp.OrderRad on OrderHuvud.Ordernummer = OrderRad.Ordernummer where  OrderHuvud.OrderserieIK = 'K'" .$query ;
echo $sql;
$raw_results = $conn->query ($sql);
    $row_cnt = false === $raw_results ? 0 : $raw_results->num_rows;
        echo "
 Numbers of rows loaded: $row_cnt
";
    if($row_cnt > 0){
   while($raw_result = mysqli_fetch_array($raw_results)){
   echo "

".'Ordernummer'."	".'OrderserieIK'."	".'Orderkund'."	".'fakturakund'."	".'orderdatum'."	".'erreferens'."	".'leveratvarde'."	".'radnummer'."	".'artikelnr'."	".'benamning'."	".'leveranstid'."	".'Ursprungligtantal'."	".'Levereratantal'."	".'forspris'."	".'bruttopris'."	".'varukostnad'."

";
   echo "

".$raw_result['Ordernummer']."	".$raw_result['OrderserieIK']."	".$raw_result['OrderKund']."	".$raw_result['Fakturakund']."	".$raw_result['Orderdatum']."	".$raw_result['Erreferens']."	".$raw_result['Levereratvarde']."	".$raw_result['Radnummer']."	".$raw_result['Artikelnr']."	".$raw_result['Benamning']."	".$raw_result['Leveranstid']."	".$raw_result['Ursprungligtantal']."	".$raw_result['Levereratantal']."	".$raw_result['Forspris']."	".$raw_result['Bruttopris']."	".$raw_result['Varukostnad']."

";

   }
    }

    else{
   echo "No return";
    }
}
else{
    echo "Minimum length is ".$min_length;
}
$query = substr($query, 4);
$sql2 = "SELECT OrderKund,Artikelnr, SUM(Forspris) as Forspris,SUM(Levereratantal) as Levereratantal FROM orderhuvud
left JOIN orderrad on orderhuvud.Ordernummer = orderrad.Ordernummer
 where ". $query ." GROUP BY OrderKund,Artikelnr";
$result = mysqli_query($conn, $sql2) or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)){

    echo "

".'OrderKund'."	".'Artikelnr'."	".'Forspris'."	".'levereratantal'."

";
    echo "

".$row['OrderKund']."	".$row['Artikelnr']."	".$row['Forspris']."	".$row['Levereratantal']."

";
}
    ?>

A: I think this part is responsible for not giving the rows you expect.
OR orderkund = 'S001' BETWEEN 'S176' AND orderdatum BETWEEN '' AND ''

First of all, I would remove the last part since it's empty strings on each side and it doesn't really do anything.
orderdatum BETWEEN '' AND ''

I have never used the between function before, but from what I see it seems like you shouldn't have the equal comparison before the between. I would also suggest to wrap the specific between condition within parantheses so we're sure the conditions aren't mixed with eachother, so the end-result should look something like this:
OR (orderkund BETWEEN 'S001' AND 'S176') AND (orderdatum BETWEEN '' AND '')

As mentioned above, I would suggest you to remove the last part if orderdatum value is not available.

A: select  column_name from table_name  where SUBSTRING(`customer`, 2)  between 001 and 176

This is working I already tried it on MySQL
select OrderKund from orderhuvud where SUBSTRING(OrderKund, 2) between 1 and 176


text:
Q: Is a process created in Oracle for every SQL statement? After reading the Oracle docs, it´s still not clear for me if an Oracle process is created for every SQL statement or just for every connection (or not really related to both).
Any comment here would be really great.
Thanks.

A: A process is created per connection, which can then execute SQL statements for the duration of the connection.
A SQL statement may use more than one Oracle background process (for things like Parallel Query) during its execution, but these aren't forked specifically for the SQL statement.
Note that I'm ignoring things like connection pooling (DRCP) and shared servers (MTS) to keep the answer simple.

A: The Overview of Server Processes from the 11.2 Oracle Concepts Guide includes the following information:

In dedicated server connections, the client connection is associated
  with one and only one server process. On Linux, 20 client processes connected to a database
  instance are serviced by 20 server processes.
Each client process communicates directly with its server process.
  This server process is dedicated to its client process for the
  duration of the session.

A: Whenever a SQL statement is fired from oracle, it just creates a psedocode of that
SQL Statement and stores it in the Library cache (Shared SQL Area).
This is stored basically for fast retrieval and reuse the SQL statements present in Cache.
So, there would not be any process created when a SQL statement is fired.
But as Phil said,

A SQL statement may use more than one Oracle background process (for things like Parallel Query) .

SQL statement uses the background process but doesn't create it.
This link might be useful for you.
Kindly Check
 this.


text:
Q: what are the benefits of using arrow function instead of assign when declaring variable? I watched the video below
https://egghead.io/lessons/react-store-values-in-localstorage-with-the-react-useeffect-hook
in the beginning he wrote
const initialCount = Number(window.localStorage.getItem('count') || 0);

later he corrected this to below to optimize
const initialCount = () => Number(window.localStorage.getItem('count') || 0);

but I didn't get why it is optimized
let me know thanks in advance

A: For,

const initialCount = Number(window.localStorage.getItem('count') || 0);

As soon as component is mounted this line will be executed which will take some time and processing power.

const initialCount = () => Number(window.localStorage.getItem('count') || 0);

While,the above statement will be only declared because it is a function and it will be only executed once it is called. This can effect the performance.

A: When we use function, it is executed only when it is called.


text:
Q: query to print the data from multiple tables I have a list of tables as follows
tbluser
(userid, username)

tblmember
(memberid, fk_userid)

tblleader
(leaderid, fk_userid)

tbltask
(taskid, fk_memberid, fk_leaderid, taskname, taskstatus)

here the user will be a member and can be a leader too
i want to generate a query to show the list of the assigned task to the members and their leaders name.
Sl. No | Member Name | Task Name | Task Status | Leader Name
-------------------------------------------------------------------------

I am having joining issues as both member and leader table is referenced to the same table(user table).
Can anybody help me to get the query to show the data.

A: You question wasn't clear enough ,but i think your looking for this.
SELECT taskname,taskstatus,username
FROM tbltask,tblmember,tblleader,tbuser
WHERE (tblmember.memberid = tbltask.fk_memberid) AND (tbltask.fk_leaderid =
tblleader.leaderid) AND (tblleader.fk_userid = tbluser.userid);

A: SELECT
*
FROM
table1
    INNER JOIN
tabel2 ON table2.id = table1.id
    INNER JOIN
table3 ON table3.id = table2.id;

A: Sample data might have helped you better here, But I think you can try the below query -
SELECT userid AS "Sl. No",
       username "Member Name",
       taskname "Task Name",
       taskstatus "Task Status",
       Leader Name
  FROM tbluser TU
  JOIN tblmember TM ON TM.fk_userid = TU.userid
  JOIN tblleader TL ON TL.fk_userid = TU.userid
  JOIN tbltask TT ON TL.leaderid TT.fk_leaderid
                  AND TM.memberid = TT.fk_memberid;


text:
Q: Unregister callbacks from dojo.Deferred Is there any way to unregister callbacks from dojo.Deferred? If not why?

A: According to this, there isn't. Shouldn't be too hard to add one though:
dojo.Deferred.prototype.removeCallback = function(fn) {
    for (var c = this.chain, i = c.length; i--;)
        if (c[i][0] === fn) c.splice(i, 1);
    return this;
};

Usage:
var d = new dojo.Deferred;
d.addCallback(someFn);
// Remove it:
d.removeCallback(someFn);


text:
Q: Vim function to calculate ruby class definition with modules from filename? I'd like to start using vimscript to automate some more complicated parts of my workflow. I'm looking for a concrete advanced example to get me started. How would you vim guru's implement the following?
I'm in an empty buffer for a file located at lib/foo/bar/buz.rb. I want to use my file context + a binding to insert the following into the buffer:
module Foo
module Bar

  class Buz
  end

end
end

What's the vim function look like?
Bonus: Vim function to update class definition to reflect current location
I think this example will take my vim scripting to the next level. Thanks!

A: This is ultimately what I came up with.
" Generates a ruby class definition based on the current file's path
function! GenerateRubyClassDefinition()
  " parse file path
  let l:path = expand("%:.:r")
  let l:path = substitute(l:path, "lib/", "", "")
  let l:parts = split(l:path, "/")

  " extract parts
  let l:class_name = l:parts[-1]
  let l:module_names = l:parts[0:-2]

  " generate
  let l:output = ""

  " generate - module headers
  for m in l:module_names
    let l:output .= "module " . g:Abolish.mixedcase(m) . "\n"
  endfor

  " generate - class
  let l:output .= "\n"
  let l:output .= "  class " . g:Abolish.mixedcase(class_name) . "\n"
  let l:output .= "  end\n"
  let l:output .= "\n"

  " generate - module footers
  for m in l:module_names
    let l:output .= "end\n"
  endfor

  echo l:output
endfunction

The above snippet assumes you have tpope's vim-abolish plugin installed. This helps with the transformation of snakecase file paths into mixedcase object names.
Sourcing the above and calling :GenerateRubyClassDefinition() from an open file buffer will echo the target output.


text:
Q: how to sum up values of single dimentional array having same key in php For example: if strArr is ["B:-1", "A:1", "B:3", "A:5"] then your program should return the string A:6,B:2.
Your final output string should return the keys in alphabetical order. Exclude keys that have a value of 0 after being summed up.
Examples
Input: array("X:-1", "Y:1", "X:-4", "B:3", "X:5")
Output: B:3,Y:1

A: Simple homework. You have to explode each pair into an array and to sum the values for each letter. Then sort (ksort by key), check and skip if there is a 0 into the produced array:
<?php
    $sums = array();
    $arr = array("X:-1", "Y:1", "X:-4", "B:3", "X:5");
    foreach ($arr as $key => $pair) {
        $pairArray = explode(":", $pair);
        (!array_key_exists($pairArray[0], $sums))
            ? $sums[$pairArray[0]] = (int)$pairArray[1]
            : $sums[$pairArray[0]] += (int)$pairArray[1];
    }

    print_r($sums);

    ksort($sums);

    $result = array();
    foreach ($sums as $key => $value) {
        if ($value != 0) {
            array_push($result, $key . ":" . $value);
        }
    }

    $result = implode(",", $result);
    echo $result;
?>

Output:
Array
(
    [X] => 0
    [Y] => 1
    [B] => 3
)

B:3,Y:1


text:
Q: React hook is not setting my state at time const [numbers, setNumbers] = ({number1: 2, number2:0})
const [aNumber, setNumber] = (1);

    useEffect(()=>{

        },[numbers,aNumber])

const printNumbers = ()=>{
setNumbers({...numbers, number2:aNumber});
console.log(numbers);
}

return (
<>
<button onClick={printNumbers}>print a number <button/>
</>

)

when i click on the button in the console it will print {number1: 2, number2: 0}
But i want it to print {number1: 2, number2: 1} but it looks like react not update mi hook correrctly, but... when a click another time in the button it prints {number1: 2, number2: 1}, but i need it in the first click, how can i fix it?

A: You set the console log inside the printNumbers function.
Since the state update is async, you'd have to put the console.log inside the useEffect to be notified after an update. Something similar to:
useEffect(()=>{
   console.log(numbers);
},[numbers,aNumber])

const [numbers, setNumbers] = ({number1: 2, number2:0})
const [aNumber, setNumber] = (1);

const printNumbers = ()=>{
   setNumbers({...numbers, number2:aNumber});
}

A: In React, state updates are asynchronous and batched. setState is not guaranteed to run (and in practice, new values will never be available) before the proceeding code. To solve this, use a local variable to retain a copy of the new state which you can both dispatch with your setState, and log immediately:
const printNumbers = () => {
  const newNumbers = { ...numbers, number2: aNumber };
  setNumbers(newNumbers);
  console.log(newNumbers);
}


text:
Q: How do you add custom field to woocommerce product attribute I want to include a simple  in the edit attribute form.
(/wp-admin/edit.php?post_type=product&page=product_attributes&edit=55)
Is this possible? Everything i've found on SO is concerned with adding fields to products or taxonomies, if I am not wrong, product attributes are not the same as taxonomies.
I want add a custom form to my "Brand" product attribute.
Here is what I tried (with and without the pa_):
add_action('pa_brand_edit_form_fields','msp_pa_brand_form_fields');
add_action('pa_brand_add_form_fields','msp_pa_brand_form_fields');

function msp_pa_brand_form_fields () {
?>

                <?php _e('Display Type', ''); ?>

                <select name="display_type">
                    <option value="select">Select</option>
                    <option value="variation_image">Variation Image w/ label</option>
                </select>

        <?php
    }

I just need help getting some html to show up on this edit screen. My overall plan is to add this select tag to every attribute, then add a piece of code into variable.php check how a attribute is to be displayed.
Any help is greatly appreciated.

A:
With the following hooks you can add a field before or after, depending on your wishes

function action_woocommerce_before_edit_attribute_fields(  ) {
    ?>

            <?php _e('Display Type', ''); ?>

            <select name="display_type">
                <option value="select">Select</option>
                <option value="variation_image">Variation Image w/ label</option>
            </select>

    <?php
}
add_action( 'woocommerce_before_edit_attribute_fields', 'action_woocommerce_before_edit_attribute_fields', 10, 0 );

function action_woocommerce_after_edit_attribute_fields(  ) {
    ?>

            <?php _e('Display Type', ''); ?>

            <select name="display_type">
                <option value="select">Select</option>
                <option value="variation_image">Variation Image w/ label</option>
            </select>

    <?php
}
add_action( 'woocommerce_after_edit_attribute_fields', 'action_woocommerce_after_edit_attribute_fields', 10, 0 );


text:
Q: Firebase Web Storage - upload a file without specifying its name I'm using Firebase Storage and everything works great.
How can I upload a file without specifying its name?
So the file will get a unique name by Firebase, like they do in the storage.
This is an example of what i'm using now:
firebase.initializeApp(config);
var fileUpload = document.getElementById("uploadFile").files;
var storageRef = firebase.storage().ref(fileUpload[0].name);
var uploadTask = storageRef.put(fileUpload[0]);

And I want to do someting like this:
firebase.initializeApp(config);
var fileUpload = document.getElementById("uploadFile").files;
var storageRef = firebase.storage().ref();
var uploadTask = storageRef.put(fileUpload[0]);

Appreciate any help you can provide. Thanks.

A: There is no built-in API to generate file names for you in Firebase Storage.
But similar to what the Firebase Database does, you can easily generate a filename client-side that is statistically guaranteed to be unique.
One way to do this would be to generate a UUID, such as with the guid() function from this answer:
var storageRef = firebase.storage().ref(guid());

Note that you'd lose the filename extension here, which is how Firebase Storage determines the file type. So more likely you'll want to determine the filename based on the local filename but then with something before it to make it unique.
var storageRef = firebase.storage().ref(guid()+fileUpload[0].name);

Given this combination, there's a pretty good chance that just prefixing with the local timestamp is unique already:
var storageRef = firebase.storage().ref(Date.now()+fileUpload[0].name);


text:
Q: PHP Simple HTML DOM Parser: select between two div I am trying to parse this HTML

 TEXT1

 TEXT2

 TEXT3

this is view page. I want to search id1 to class1(that div id="id1" to div class="class1" to find). I am Trying like this
foreach($html->find('div#subclass-single>div.class1 a') as $e){
    echo $e->href . '
';
}


text:
Q: Can't generate APK Release because of GCM SenderId Android I have implemented GCM (Google Cloud Messaging) in my app. Google Play Services library has auto-generated values.xml in which my senderId is :
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="gcm_defaultSenderId">123</string>
</resources>

The problem is that I have other locale, and Lint during App Release is giving me an error :
Error:(3) Error: "gcm_defaultSenderId" is not translated in "fr" (French) [MissingTranslation]
Because it is automaticaly generated I can't set translable = false. How I should fix this?

A: I assume that you are using Android Studio.
Had the exact same problem with Android Studio 1.4.
First thing I tried was to edit the "File - Settings - Editor - Inspections - Android Lint - Incomplete Translation" Severity Setting to something other then 'Error'.
That did not help! I still was not able to build a release APK.
I ended up 'translating' the XML as follows:

*

*in the folder .../android/res create a new language folder values-de (replace de with your language code).

*create a file named google-services.xml in the language folder.

*Insert into the xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="gcm_defaultSenderId"><YOUR_SENDERID></string>
</resources>

After that I was able to build the release.

A: Since the last update of Android Studio (1.5) I had this issue too. I solved it by updating the Google Services dependencies to the latest version.
According to this link, indeed,

This issue should be fixed with 8.3.0 Google Play Services and 1.5.0-beta2 dependency.

Hope this helps! :)

EDIT Integration: actually, while the gcm_defaultSenderId string is now generated correctly (with translatable="false" attribute), google_app_id and ga_trackingID strings, for instance, are not.
For those still having issues, I came to the conclusion that we have to wait for Google guys to fix this issue and ignore the error in the meantime by adding to the app level build.gradle file
...
android {
    lintOptions {
        abortOnError false
    }
}
...

A: Add a lint.xml file in your project application root (under app/) and add the missing translations to be ignored there:
<lint>
    <issue id="MissingTranslation">
        <ignore regexp="ga_trackingId"/>
        <ignore regexp="gcm_defaultSenderId"/>
        <ignore regexp="google_app_id"/>
    </issue>
</lint>

These will now be ignored by lint - you can configure which properties to ignore, and you won't have to wait for updates from the google-services team for properties that they haven't thought of.
Lint-ing will still catch all other errors, so you can still enjoy the other features.

A: you will probably have another bit of autogenerated code like this:
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

Get a valid sender id from the google cloud console then you can remove the R.string.gcm_defaultSenderId from the above code and also the gcm_defaultSenderId from the resource file.

A: If you want/need upgrade to newer version of:

*

*lint (androidstudio with build-in lint)

*build tools

*compileSdkVersion

*gradle plugin

*gradle

*google-services (plugin)

*google-services dedendencies (e.g. play-services-gcm)

*(unfortunatelly) other dependencies if are transitivelly dependent to google-services

you need to choose wiselly versions of all these parts together. Since these all needs to be compatible together. Unfortunatelly, there is no compatibility table (the only I found is more a year old, so I do not link it here. If anybody know any please share a link).
So, solution is investigate which verstion of which part blocks anything else.  Which could be nightmare, so a lot of advice is to revert to last known funcional configuration. But sooner or later we will be force to upgrade.
I checked home pages of each part to find any version info, but at last I still solve it by test-and-try method.
Here is what is functional for me:

*

*androidstudio 1.5

*build tools 23.0.2

*compileSdkVersion 23

*gradle plugin 1.5.0

*gradle 2.8

*google services plugin 1.5.0

*google services dependencies 8.3.0

*lucky, no other external GS dependencies (obviously all internal modules needs to use same version)


text:
Q: TypeScript global modules declaration I'm developing a NodeJS API using TypeScript. I have several .ts file and in all of them I'm importing external modules again and again (e.g. soap, xmlParser, url, underscore, etc.).
Is there any convenient way to declare them somehow globally and use them without import them in each .ts file?
Thanks,

A:
Is there any convenient way to declare them somehow globally and use them without import them in each .ts file?

Have a file utils.ts and just export these from them. Now you only need to import utils.


text:
Q: Angular 2 : Get every application errors inside a component Goal
Catch every error of the application in a custom Angular exception handler and then display the errors to the user in a component template.
Problem
The app component subscribes to the exception handler correctly and the exception handler emits the event properly, but the callback function is never called (error=>this.errorMessage=error.message in this case).
main.ts
@Injector();
class MyExceptionHandler implements ExceptionHandler {
  errorOccured: EventEmitter<{}> = new EventEmitter();

  call(error, stackTrace = null, reason = null) {
    errorOccured.emit(error);
  }
}
bootstrap(MyAppComponent, {provide: ExceptionHandler, useClass: MyExceptionHandler}])

app.component.ts
 import { Component } from '@angular/core';
    @Component({
      selector: 'my-app',
      template: `
          <p *ngIf="errorMessage">{{errorMessage}}</p>
          <button (click)="triggerError()">Trigger Error></button>`
    })
    export class AppComponent {
        errorMessage: string;

        constructor(private errorHandler: MyExceptionHandler ) {
            this.errorHandler.errorOccured
                .subscribe(error => this.errorMessage = error.message)
        }

        triggerError() {
            throw new Error('some error');
        }
    }


text:
Q: Joomla Logic PHP Query with 4 parameters Logic Query
Hello,
We have 2 logic
a) Customer been contacted maximum times: Marking restriction on number of times a customer is been contacted. We have put in the maximum times a customer can be contacted as 2 by the vendor. Having this php code
$max = 2;
$listing = JRequest::getInt('listing');

if($listing) {
$db = JFactory::getDBO();
$db->setQuery("SELECT COUNT(`SubmissionId`) FROM #__rsform_submission_values WHERE `FormId`='".(int) $formId."' AND `FieldName`='listing' AND `FieldValue`='".$listing."' ");
$nrSub = $db->loadResult();

if ($nrSub >= $max) {
  $formLayout = '
Sorry, This customer has already been contacted maximum number of times
';
}
}

b) Maximum Number of times a vendor can contact customers in a form
$max = 10;
$user = JFactory::getUser();
$db   = JFactory::getDbo();
$query   = $db->getQuery(true);

$query->select('COUNT('.$db->qn('Username').')')
    ->from($db->qn('#__rsform_submissions'))
    ->where($db->qn('FormId').'='.$db->q($formId))
    ->where($db->qn('Username').'='.$db->q($user->get('username')));

$db->setQuery($query);
$counter = $db->loadResult();

if ($counter >= $max){
  $formLayout = '
You have already contacted 10 customers
';
}

Both are working well - Now we have to set up a condition:- in which a dealer if try to contact the same customer again whom he has contacted earlier also should show an error message
Guess it would be based on 4 paramters

Count submission and compare it with Max Parameter as 1
Formid
Listing
Username

Trying this code - but seems not respecting in the
$max = 1;
$user = JFactory::getUser();
$listing = JRequest::getInt('listing');

if($listing) {
$db = JFactory::getDBO();
$db->setQuery("SELECT COUNT('.$db->qn('Username').') FROM #__rsform_submission_values WHERE `FormId`='".(int) $formId."' AND `FieldName`='listing' AND `FieldValue`='".$listing."' ");
$nrSub = $db->loadResult();

if ($nrSub >= $max) {
  $formLayout = '
Sorry, You have already contacted this customer
';
}
}

so that it matches - if the username has already contacted once the listing id of the form - then should show an error message
May be the username parameter needs to be added in code - 1
Can someone assist, help and advise to achieve in desired - how to set up the logic query

A: If you use COUNT I think you should apply GROUP BY as well, like:
SELECT COUNT('.$db->qn('Username').') FROM #__rsform_submission_values WHERE `FormId`='".(int) $formId."' AND `FieldName`='listing' AND `FieldValue`='".$listing."' GROUP BY '.$db->qn('Username').'"


text:
Q: Date Converting in R In my dataframe that contains data pasted from the Excel file in R, the date format (taking the element in the first row & 11th column as an example) is the following:
data_agg[[1,11]]
[1] "2018-03-16 UTC"

I do want to convert the date format to "2018-03-16" without UTC. So, I wrote the following code to achieve that:
as.Date(data_agg[[1,11]])
[1] "2018-03-16"

As of now this works out perfectly. And I wanted to assign this new date format to the original place in my data frame. So I have the following code:
> data_agg[[1,11]] <- as.Date(data_agg[[1,11]])
> data_agg[[1,11]]
[1] "1970-01-01 04:53:26 UTC"

As you can see from above, after I converted the date format and reassign, somehow the element value changed to "1970-01-01 04:53:26 UTC". Can anyone shed some light on what is going on with my code? Thanks!

A: In R, dates and times are just numbers under the hood. The way that R knows to interpret them as dates/times is through an attribute attached to the variable:
> d <- Sys.Date()
> attributes(d)
$class
[1] "Date"

Now, where it gets funky, is that when you put these objects in vectors, the class attribute is attached to the vector itself, not to each element of the vector. This means that you cannot have differently-typed numeric values in the same vector.
If you want to replace all elements of a column in a data frame with their date equivalent, you can cast and assign the whole column at once:
> data_agg[,11] <- as.Date(data_agg[,11])

Edit: If what you really want is to have a bunch of date-representing strings in a vector along with other strings, then just convert your strings to dates and then back again:
> data_agg[[1,11]] <- as.character(as.Date(data_agg[[1,11]]))

or, if the string " UTC" doesn't show up in any of your other strings, you can use a direct string replacement function, like @shum suggests.


text:
Q: Add duplicate keys to a list/map I wrote a batch process over the weekend that looks at a child record's date field and updates the corresponding date on the parent record. I originally wrote it as a bunch of if statements and then added the parent id and field to a list. When I ran the batch today I get an error in debug log:

"Duplicate id in list"

This makes me think I need to add the values from the if statements to a map where I can update the record once with all the fields that it needs instead of updating the record multiple times for each possible value.
Here is a snip of batch code I have, how can I adjust to update a record once instead of multiple times.
global void execute(Database.BatchableContext BC, List<Revenue_Pipeline_Schedule__c> revPipeSchedule) {
    Map<Id, Revenue_Pipeline__c> revPipe = new Map<Id, Revenue_Pipeline__c>();

    for(Revenue_Pipeline_Schedule__c rPS : revPipeSchedule){
        if(rPS.Date__c == date.newinstance(2014,10,1)){ revPipe.put(rPS.Revenue_Pipeline__c, Oct2014__c=rPS.Amount__c));}
        if(rPS.Date__c == date.newinstance(2014,11,1)){ revPipe.put(rPS.Revenue_Pipeline__c, Nov2014__c=rPS.Amount__c));}
        if(rPS.Date__c == date.newinstance(2014,12,1)){ revPipe.put(rPS.Revenue_Pipeline__c, Dec2014__c=rPS.Amount__c));}
        if(rPS.Date__c == date.newinstance(2015,01,1)){ revPipe.put(rPS.Revenue_Pipeline__c, Jan2015__c=rPS.Amount__c));}
        if(rPS.Date__c == date.newinstance(2015,02,1)){ revPipe.put(rPS.Revenue_Pipeline__c, Feb2015__c=rPS.Amount__c));}
        if(rPS.Date__c == date.newinstance(2015,03,1)){ revPipe.put(rPS.Revenue_Pipeline__c, Mar2015__c=rPS.Amount__c));}
        .... 47 lines later
}
update revPipe;

A: Any time you need to use a map for de-duplication, the basic idea is:
Map<Id, MyObject__c> records = new Map<Id, MyObject__c>();
//...
records.put(someMyObjectId, new MyObject__c(/*data*/));

However, in your case it is more complicated because you want to set multiple fields on the same record, so a scheme where you only use put won't work, because you will clobber your own updates. You can circumvent this problem, however, if you simply initialize all the keys first.
Map<Id, Revenue_Pipeline__c> pipelines = new Map<Id, Revenue_Pipeline__c>();
for (Revenue_Pipeline_Schedule__c schedule : scope)
{
    Id pipelineId = schedule.Revenue_Pipeline__c;
    pipelines.put(pipelineId, new Revenue_Pipeline__c(Id=pipelineId));
}
// now all keys are initialized

for (Revenue_Pipeline_Schedule__c schedule : scope)
{
    if (/*condition*/)
    {
        pipelines.get(schedule.Revenue_Pipeline__c).put(/*field*/, /*value*/);
    }
}

A note on your absurdly long if chain: you can almost always reduce these unwieldy bits of logic to use a Map. In this case, I would do a Map<Date, SObjectField> that tells you where to put the data.
static Map<Date, SObjectField> dateToField = new Map<Date, SObjectField>
{
    Date.newInstance(2014, 10, 1) => Revenue_Pipeline__c.Oct2014__c,
    Date.newInstance(2014, 11, 1) => Revenue_Pipeline__c.Nov2014__c,
    Date.newInstance(2014, 12, 1) => Revenue_Pipeline__c.Dec2014__c,
    // etc...
}

Then your above code can further simplify to just a few lines:
for (Revenue_Pipeline_Schedule__c schedule : scope)
{
    SObjectField field = dateToField.get(schedule.Date__c);
    if (field != null)
    {
        pipelines.get(schedule.Revenue_Pipeline__c).put(field, schedule.Amount__c);
    }
}