text:
Q: Vue.js: How to rerun your code whenever you change slides in your vue carousel I am very new to vue.js and fumbling my way though it, forgive me if my terms are incorrect. I am creating a touchscreen application that needs to be ADA compliant (only the bottom part of the screen is accessible, so i have to use buttons for interaction).
I have a parent component with a carousel creating an array of slides, pulling data from my child component.
parent component HTML
<carousel :navigateTo="selectedListIndex" @pageChange="OnPageChange">
  <slide v-for="(member, index) in selectedList" :key="index">
     <MemberBioPage :member="member"/>
  </slide>
</carousel>

parent component SCRIPT:
export default {
  data () {
    return {
      currentPage: 0
    }
  },
  components: {
    MemberBioPage,
    Carousel,
    Slide
  },
  computed: {
    selectedList () {
      return this.$store.state.selectedList
    },
    selectedListIndex () {
      return this.$store.state.selectedListIndex
    }
  },
  methods: {
    OnPageChange (newPageIndex) {
      console.log(newPageIndex)
      this.currentPage = newPageIndex
    }
  }
}

within my child component, i have bio copy being pulled from my data and arrow buttons that allow you to scroll the text. There is an outer container and an inner container to allow the scrolling and based on the height that the content takes up in the container will determine when the arrows disable or not.
child component HTML:

{{ member.name }}

         <img class="btn-scroll" v-bind:class="{ 'active': scrollVar < 0 }" @click="scrollUp" src="@/assets/arrow-up.png">

          newHeight }" @click="scrollDown" src="@/assets/arrow-down.png">

child component SCRIPT:

I am able to get the height of the first bio i look at, but on page change it keeps that set height. I basically want the code in mounted to be able to rerun based on the index of the slide i am on. I need 'newHeight' to update on each page change. I tried grabbing the 'currentPage' from my parent component using props, but it pulls undefined.
here is all a snippet from my data to show you what data i currently have:
{
  index: 12,
  name: 'Name of Person',
  carouselImage: require('@/assets/carousel-images/image.jpg'),
  imgSrc: require('@/assets/bio-page-image-placeholder.jpg'),
  shortBio: '
a bunch of text being pulled
',
  pin: require('@/assets/image-of-pin.png')
}

this is also my store just in case
const store = new Vuex.Store({
  state: {
    foundersList: founders,
    chairmanList: chairmans,
    selectedList: founders,
    selectedListIndex: -1
  },
  mutations: {
    setSelectedState (state, list) {
      state.selectedList = list
    },
    setSelectedListIndex (state, idx) {
      state.selectedListIndex = idx
    }
  }
})

A: Alright, so this is a good start. Here's a few things I would try:

*

*Move the code you currently have in mounted to a new method called calculateHeight or something similar.

*Call the method from your scrollUp and scrollDown methods.
So your final code would look something like this:
export default {
  props: [
    'member', 'currentPage'
  ],
  data () {
    return {
      scrollVar: 0,
      outerHeight: 0,
      innerHeight: 0,
      newHeight: -10
    }
  },
  mounted () {
    this.calculateHeight();
  },
  methods: {
    calculateHeight() {
      this.outerHeight = document.getElementsByClassName('bio-container')[0].clientHeight
      this.innerHeight = document.getElementsByClassName('inner-scroll')[0].clientHeight
      this.newHeight = this.outerHeight - this.innerHeight
    },
    scrollUp () {
      console.log(this.scrollVar)
      this.scrollVar += 40
      this.calculateHeight()
    },
    scrollDown () {
      console.log(this.scrollVar)
      this.scrollVar -= 40
      this.calculateHeight()
    },
    showVideo () {
      this.$emit('showContent')
    }
  }
}


text:
Q: Google Script - Sending Email from drop-down I am trying to fix a code I found online. My goal is that once the Summary tab, column I is edited with the drop-down "approved" for the sheet to send an email to the person on the name in column D.
The email is found in the range tab though. This is what I have so far...
var admin_email='taniapeche@gmail.com';

function triggerOnEdit(e)
{
  sendEmailOnApproval(e);
}

function checkStatusIsApproved(e)
{ var sheet = SpreadsheetApp.getActive().getSheetByName('Summary');
  var range = e.range;

  if(range.getColumn() <= 9 &&
     range.getLastColumn() >=9 )
  {
    var edited_row = range.getRow();

    var status = SpreadsheetApp.getActiveSheet().getSheetName('Summary').getRange(edited_row,9).getValue();
    if(status == 'Approved')
    {
      return edited_row;
    }
  }
  return 0;
}

function sendEmailOnApproval(e)
{ var sheet = SpreadsheetApp.getActive().getSheetByName('Range');
  var approved_row = checkStatusIsApproved(e);

  if(approved_row <= 0)
  {
    return;
  }

  sendEmailByRow(approved_row);
}

function sendEmailByRow(row)
{
  var values = SpreadsheetApp.getActiveSheet().getSheetName('Range').getRange(row,1,row,5).getValues();
  var row_values = values[0];

  var mail = composeApprovedEmail(row_values);

 //SpreadsheetApp.getUi().alert(" subject is "+mail.subject+"\n message "+mail.message);

  MailApp.sendEmail(admin_email,mail.subject,mail.message);

}

function composeApprovedEmail(row_values)
{
  var first_name = row_values[1];

  var last_name = row_values[2];

  var email = row_values[3];

  var message = "The following mileage is approved: "+first_name+" "+last_name+
    " email "+email;
  var subject = "Mileage approved "+first_name+" "+last_name

  return({message:message,subject:subject});
}

This is how to sheet looks:
https://docs.google.com/spreadsheets/d/1lWORvuwAHducEIiL-VVidJ-wjujE344udPbWCZpE1kw/edit?usp=sharing
Thanks for the help :)

A: First of all, because you want the script to send an email (an action which requires your authorization), you have to install the edit trigger, either manually or programmatically. If you do it programmatically, you can install the trigger by running this function once:
function createTriggerOnEdit(e) {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger("sendEmailOnApproval")
  .forSpreadsheet(ss)
  .onEdit()
  .create();
}

As a result of this, the function sendEmailOnApproval will fire every time the spreadsheet is edited. This function could be something along the following lines (check inline comments for detailed explanation):
function sendEmailOnApproval(e) {
  // Get the edited range and sheet using the event object:
  var range = e.range;
  var editedSheet = range.getSheet();
  var textToSearch = "Approved"; // Set which value will cause the email to be sent
  // Check that edited cell is in column I, its value is "Approved" and its sheet is "Summary":
  if (range.getColumn() === 9 && range.getValue() === textToSearch &&
        editedSheet.getName() === "Summary") {
    var rowIndex = range.getRow(); // Get index of the edited row
    var name = editedSheet.getRange(rowIndex, 4).getValue(); // Get corresponding name in column D
    var rangeValues = e.source.getSheetByName("Range").getDataRange().getValues(); // Get values in sheet "Range"
    // Iterate through the rows in "Range", looking for the name retrieved from sheet "Summary"
    for (var i = 0; i < rangeValues.length; i++) {
      var rowValues = rangeValues[i];
      if (name === rowValues[0]) { // Check if name matches the one in column D from "Summary"
        var mail = composeApprovedEmail(rowValues); // Compose email (your function)
        MailApp.sendEmail(admin_email, mail.subject, mail.message); // Send email
        return; // End execution so that the script stops iterating through the rows in "Range"
      }
    }
  }
}

Notes:

*

*The function composeApprovedEmail is called in this sample. It's the same as the one you provided. The rest of functions you provided are not used.

Reference:

*

*Installable Triggers

*Event Objects: Edit

redpajama_set_name: RedPajamaStackExchange


text:
Q: c# Sockets sending Length of the Data I m using Tcp Protocol on my server/client Application , since its stream oriented protocol i need to keep receiving till i hit the size of the data sent .
if i send The Length of data First
 byte[] Data; //this is the data
 byte[] DataLength = BitConverter.GetBytes(Data.Length); // Length of the data

while The Size of DataLength can't exceed 4 bytes
Socket.Receive(BufferLength,0,4,0); // receiving lenth

does it still  not confirmed to receive the bytes that holds the full length of the data that will be sent in one receive ? so that i can know how much i need to call the receive method for the nexts coming bytes ?
edit : i only want to know one receive call can't get the length of the data that will be sent ? can't surely get 4 bytes in one call ?
for Example My data Length is 1024 I took that length i encoded it to byte[] then i send it first does one call is able to get that length in one call ?


text:
Q: Is there a way to map local in proxyman based off of parameters attached to the body of a url? I have a url:
https://cn.company.com/appv2/search
and want to have a different map local depending on the request coming with a different parameter in the body (i.e. it is NOT attached to the url like https://cn.company.com/appv2/search?cursor=abc. Instead it is in the body of the request { cursor: abc }.
Any idea on if this can be done in proxyman?
I basically want to be able to stub pagination through the proxy without waiting on a server implementation. So I'd have no cursor on the first request, server would return a cursor and then use that on the next request and get a different response from server on the request so that I can test out the full pagination flow.

A: Yes, it can be solved with the Scripting from Proxyman app.

*

*Use Scripting to get the value of the request body

*If it's matched, use Scripting to mimic the Map Local (Mock API also supports)

Here is the sample code and how to do it:

*

*Firstly, call your request and make sure you can see the HTTPS Response

*Right-Click on the request -> Tools -> Scripting

*Select the Mock API checkbox if you'd like a Mock API

*Use this code

/// This func is called if the Response Checkbox is Enabled. You can modify the Response Data here before it goes to the client
/// e.g. Add/Update/Remove: headers, statusCode, comment, color and body (json, plain-text, base64 encoded string)
///
async function onResponse(context, url, request, response) {

  // get the value from the body request
  var cursorValue = request.body["cursor"];

  // Use if to provide a map local file
  if (cursorValue === "abc") {

    // Set Content Type as a JSON
    response.headers["Content-Type"] = "application/json";

    // Set a Map Local File
    response.bodyFilePath = "~/Desktop/my_response_A.json";

  } else if (cursorValue === "def") {
    // Set Content Type as a JSON
    response.headers["Content-Type"] = "application/json";

    // Set a Map Local File
    response.bodyFilePath = "~/Desktop/my_response_B.json";
  }

  // Done
  return response;
}

Reference

*

*Map Local with Scripting:  https://docs.proxyman.io/scripting/snippet-code#map-a-local-file-to-responses-body-like-map-local-tool-proxyman-2.25.0+


text:
Q: What will be runtime time complexity in terms of O(n) for following code snippet? I looked nested interdependent loops and I'm not able to figure out what will be the time complexity for following code:
void check(int n)
{
    int i,j,k;
    for(i=0;i<=n/2;i++)
    {
        for(j=0;j<=i*i;j++)
        {
            for(k=0;k<j*j;k++)
            {
                printf("HELLO");    //any O(1) task
            }
        }
    }
}

A:

For calculating the time complexity we can ignore the lower order terms. The highest power of 'i' is 6 so

We know that :

Hence

A: I think it is O(N^7) as the formula of the total steps is

I do not know how to resolve the summations as well so I ask a question here, and have a nice explanation from the accepted answer
https://math.stackexchange.com/questions/2341496/how-to-resolve-this-kind-of-summation-formula/2341524#2341524
I do not know if it is appropriate to reference a question by me as an answer, but the post surely does answer your question and I believe it will help you to solve similar problems in the future

EDITED:
Thanks to @hk6279, I've overlooked the formula, it should be 1 instead of k in the deepest loop.
Yet the same principle of the reference should work as well.

A: Well, I thought it's too difficult, but no. Little mathematical support gives me perfect answer.
First of all, we've to consider how much times printf() function gets executed.
When i=1, it'll execute 1 time,
when i=2, same will execute 1+4+9+16 times, when i=3, it'll follow (1+4+9+16+25+36+49+64+81) times.
Remembering the pattern, when i = n, execution will be like (sum of squares of n^2 natural number)times.
Now finding time complexity:
(sum of 1 square terms) + (sum of 4 square terms) + (sum of 9 square terms) + ...... + (sum of n^2 square terms) = approximately (n^2)(n^2 +1)(2* n^2 +1)/6 + constants
-->obviously n^6 is the max term in the expression, O(n^6) will be time complexity


text:
Q: How to change the yAxis font size in amcharts version 5? (vue js 3) This is my code:
I added this code snippet. But unfortunately, there was no change
 {
    category: "javad",
    direction: "rtl",
    align: "right",
    fontSize: 50,
    textAlign: "right",
  },

output:

As you can see, the word "Javad" is not fully displayed in the Category (yAxis) section!

A: all my code is:
<template>

</template>

A: Adding this code solved the problem completely:

    yAxis.get("renderer").labels.template.setAll({
      oversizedBehavior: "wrap",
      textAlign: "center",
      maxWidth: 150,
    });


text:
Q: Autocomplete datalist on Thymeleaf I'm building a view with Thymeleaf templates, which contains a form that provides a way to bind the value of my inputs with the attributes passed in the model. The backend was developed using Spring 4.
The following snippet includes an autocomplete datalist with the data of  the namelist object, which was added to the model as an attribute. Said namelist is an ArrayList of a class with the fields int id and String name.

<form th:action="@{/}" method="POST" th:object="${example}">
    <div class="form-group">
        <input list="names" class="form-control" id="nameinput" th:field="${example.num.id}">  </input>
        <datalist id="names">
            <option th:each="row : ${namelist}" th:value="${row.id}" th:label="${row.name}">
        </datalist>
        <button>submit</button>
    </div>
</form>

The value of the selected option is already bound to example.num.id, which is the expected and desired behaviour. However, when loading the view on a web browser (tested on latest Firefox and Chrome), it is represented like this:

As you can see, the id's are showing. However, I'm trying to emulate the behaviour of a <select>; the value should not be shown, just the text or label.
Is there a better way to achieve this? Am I not using the datalist properly?


text:
Q: ProgressDialog: How to prevent automatic dismissing of Dialog inside setButton-Listener? i have following Scenario:
Im showing a ProgressDialog in the UI-Thread and on the same time doing a Networkdiscovery in a Backgroundthread. This works just fine. The Dialog has a Stop-Button, so the User can decide if he wants to stop the discovery.
Now here is my Problem: To stop the discovery some heavy workload-process is also done in a Backgroundthread so the Progresswheel in the UI-Thread does not hang up. In theory the Progresswheel should continue spinning until the Backgroundthread has finished its work. But the setButton(...)-Method automatically dismisses the ProgressDialog, once it reaches the Methodend and by that time the Thread has not finished its work yet. Currently I have no chance to dismiss the Dialog manually through a Messagehandler from the Backgroundthread, because it got dismissed by the OS automatically.
This is a portion of my code:
//Initialize ProgressDialog
ProgressDialog discoveryProgressDialog;
discoveryProgressDialog = new ProgressDialog(context);
discoveryProgressDialog.setTitle("Discover Network");
discoveryProgressDialog.setCancelable(true);
discoveryProgressDialog.setIndeterminate(false); //setting this to true does not solve the Problem

//add Buttonlistener to Progressdialog
discoveryProgressDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Stop", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
                stopDiscoveryTask(); //starts the Backgroundthread
                //something here to wait for Thread-Finishing and not freezing
                //the UI-Thread or something to prevent dismissing the
                //Dialog automatically
    }//<--- End will be reached directly after Backgroundthread has started which triggers automatically the dismiss of the Progress-Dialog
});

A: I found a so so good solution to fix this problem:
1. Derive your class from ProgressDialog.
2. Override dismiss() method, and do nothing there to prevent it from dismissing automatically.
3. In order to dismiss it manually, add a new method.
4. After the background thread ends, call this new method.
public class MyProgressDialog extends ProgressDialog {
    @Override
    public void dismiss() {
        // do nothing
    }
    public void dismissManually() {
        super.dismiss();
    }
}

A: Use a Service to control the spawning of new background threads.  Then use either a ResultReceiver or Messenger to pass back UI updates such as progress status (ie start, update, finish);
You can pass the ResultReceiver or Messenger as a Parcelable (no work involved) in the Intent used to start the Service.

A: One way might be to have your own cusom dialog view, instead of a ProgressDialog, where you can control when it disappears.


text:
Q: IndexError: index 2047 is out of bounds for axis 0 with size 1638 I want to train my dataset with training data and validation data.
Total data is 2048, train data is 1638, and validation data is 410 (20% of total).
Here are my codes

*

*loading data (org: total training data)
 org_x = train_csv.drop(['id', 'digit', 'letter'], axis=1).values
 org_x = org_x.reshape(-1, 28, 28, 1)
 org_x = org_x/255
 org_x = np.array(org_x)
 org_x = org_x.reshape(-1, 1, 28, 28)
 org_x = torch.Tensor(org_x)

 x_test = test_csv.drop(['id','letter'], axis=1).values
 x_test = x_test.reshape(-1, 28, 28, 1)
 x_test = x_test/255
 x_test = np.array(x_test)
 x_test = x_test.reshape(-1, 1, 28, 28)
 x_test = torch.Tensor(x_test)

 y = train_csv['digit']
 y = list(y)
 print(len(y))
 org_y = np.zeros([len(y), 1])
 for i in range(len(y)):
   org_y[i] = y[i]
 org1 = np.array(org_y, dtype=object)

*splitting data (org: total training data)
 from sklearn.model_selection import train_test_split

 x_train, x_valid, y_train, y_valid = train_test_split(
    org, org1, test_size=0.2, random_state=42)

*transform
 transform = transforms.Compose([transforms.ToPILImage(),
                         transforms.ToTensor(),
                         transforms.Normalize((0.5, ), (0.5, )) ])

*dataset
 class kmnistDataset(data.Dataset):
 def __init__(self, images, labels=None, transforms=None):
     self.x = images
     self.y = labels
     self.transforms = transforms

 def __len__(self):
     return (len(self.x))

 def __getitem__(self, idx):
     data = np.asarray(self.x[idx][0:]).astype(np.uint8)

     if self.transforms:
         data = self.transforms(data)

     if self.y is not None:
         return (data, self.y[i])
     else:
         return data

 train_data = kmnistDataset(x_train, y_train, transform)
 valid_data = kmnistDataset(x_valid, y_valid, transform)

 train_loader = DataLoader(train_data, batch_size=16, shuffle=True)
 valid_loader = DataLoader(valid_data, batch_size=16, shuffle = False)

I'll skip the model structure.

*training(Here, I got the error message)
n_epochs = 30

valid_loss_min = np.Inf

for epoch in range(1, n_epochs+1):
    train_loss = 0
    valid_loss = 0

###################
# train the model #
###################
model.train()
for data in train_loader:
    inputs, labels = data[0], data[1]
    optimizer.zero_grad()
    output = model(inputs)
    loss = criterion(output, labels)
    loss.backward()
    optimizer.step()
    train_loss += loss.item()*data.size(0)

#####################
# validate the model#
#####################
model.eval()
for data in valid_loader:
    inputs, labels = data[0], data[1]
    output = model(inputs)
    loss = criterion(output, labels)
    valid_loss += loss.item()*data.size(0)

train_loss = train_loss/ len(train_loader.dataset)
valid_loss = valid_loss / len(valid_loader.dataset)

print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
    epoch, train_loss, valid_loss))

Although I checked the data size, I got the error message below.

index 2047 is out of bounds for axis 0 with size 1638

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-42-b8783819421f> in <module>
     11     ###################
     12     model.train()
---> 13     for data in train_loader:
     14         inputs, labels = data[0], data[1]
     15         optimizer.zero_grad()

/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py in __next__(self)
    433         if self._sampler_iter is None:
    434             self._reset()
--> 435         data = self._next_data()
    436         self._num_yielded += 1
    437         if self._dataset_kind == _DatasetKind.Iterable and \

/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py in_next_data(self)
    473     def _next_data(self):
    474         index = self._next_index()  # may raise StopIteration
--> 475         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    476         if self._pin_memory:
    477             data = _utils.pin_memory.pin_memory(data)

/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/_utils/fetch.py in fetch(self,
possibly_batched_index)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/_utils/fetch.py in <listcomp(.0)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

<ipython-input-38-e5c87dd8a7ff> in __getitem__(self, idx)
     17
     18         if self.y is not None:
---> 19             return (data, self.y[i])
     20         else:
     21             return data

IndexError: index 2047 is out of bounds for axis 0 with size 1638

Can you explain why and how to solve it?

A: At first glance, you are using incorrect shapes: org_x = org_x.reshape(-1, 28, 28, 1). The channel axis you be the second one (unlike in TensorFlow), as (batch_size, channels, height, width):
org_x = org_x.reshape(-1, 1, 28, 28)

Same with x_test
x_test = x_test.reshape(-1, 1, 28, 28)

Also, you are accessing a list out of bound. You accessed self.y with i. Seems to me you should be returning (data, self.y[idx]) instead.


text:
Q: Curve Fitting in Python not fitting my curve I am currently doing a curve fit on some data to be input. My function is (where Ti is initial hot temp Ta is cold temp and c is the half life):
def extract_parameters(Ts, ts):
    def model(t, Ti, Ta, c):
        return (Ti - Ta)*math.e**(-t / c) + Ta
    popt, pcov = cf(model, ts, Ts, p0 = (10, 7, 6))
    Ti, Ta, c = popt
    xfine = np.linspace(0, 10, 101)
    yfitted = model(xfine, *popt)
    pl.plot(Ts, ts, 'o', label = 'data point')
    pl.plot(xfine, yfitted, label = 'fit')
    pylab.legend()
    pylab.show()

When I enter:
extract_parameters(np.array([1,2,3,4,5,6,7,8,9,10]), np.array([10.0,9.0,8.5,8.0,7.5,7.3,7.0,6.8,6.6,6.3]))

My graph starts to fit right at the end but while my data starts at 10 my curve starts at about 240 and then sweeps down, which is not what I want. I thought setting p0 would help but it doesn't appear to help at all.

A: You have swapped Ts and ts in the argument to cf.  It should be Ts (independent variable) follwed by ts (dependent variable).
popt, pcov = cf(model, Ts, ts, p0 = (10, 7, 6))


text:
Q: How can I disable href of anchor in codeigniter? I am using multiple pagination in single web page. here I am using jquery-ajax for pagination. but even if I am keeping "base_url" option as blank I am unable to hold redirection of anchor.
$config['base_url'] = '';
$config['per_page'] = 10;
$config['num_links'] = 2;
$config['anchor_class'] = "onclick='return show_new_page();'";

A: In your case I would create a custom library
(read about it here)
Go the /system/libraries and copy pagination.php file from here to the /application/libraries
Rename it to something you like. Open it, find create_links function, find anchors, edit it the way you want.
Load your custom pagination into your controller's function.
Also, don't forget to change the class name of the library to the name of the file.


text:
Q: How to make NSPopUpButton accept firstResponder status? I have an NSPopUpButton and even a simple subclass of NSPopUpButton.
In the subclass I have:
- (BOOL)acceptsFirstResponder { return YES; }
- (BOOL)refusesFirstResponder { return NO; }
Now it's easy enough to tell the window to make the button first responder, and that works on launch, but I need this to also occur as nextResponder from tabbing out of an NSTextField.
Once focus is on any NSTextField, it never seems to be able to move back to the popupbutton.
What am I missing here?
It seems like it should be really simple.
ANSWER: firstResponder is not the thing to use here. A subclass is needed (as I suspected) and simply needs to override the following to return YES:
- (BOOL)canBecomeKeyView { return YES; }  (thanks Peter Hosey)

A: In your NSPopUpButton subclass, try overriding canBecomeKeyView instead.


text:
Q: Does there exist an entire function $h$ such that $p, q, r$ are the constant multiplies of $h$? Let $p, q, r$ be non-vanishing non-constant entire holomorphic functions such that $$p+q+r = 0$$
Does there exist an entire function $h$ such that $p, q, r$ are the constant multiplies of $h$?

A: Since $r$ doesn't vanish, then $p/r$ and $q/r$ are entire and don't vanish.
We have that $p/r+q/r=-1$. By Picard's theorem either $q/r$ is constant or there is a point in which $q/r=-1$, since $q/r$ already skips the value $0$ and it can't skip yet another one. At that point $p/r$ would vanish, which is a contradiction. Therefore $q/r$ is constant and therefore so is $p/r$. Take $h:=r$. Then $p=(p/r)h$, $p=(q/r)h$, and $r=1h$.


text:
Q: Altura da div no load Como deixar o campo as 2 divs com a mesma altura do #result4 que eu dei um load?
<script>
$(document).ready(function() {
    $( ".buscascript<?php echo "$row[id]"; ?>" ).click(function() {
        $( "#fechargame" ).show();
        $( "#result4" ).show();
        $( "#result5" ).show();
        $( "#result4" ).load( "busca.php?game=<?php echo "$row[id]"; ?>" );
        var altura = $("#result4").height();
        $( "#publicidade1a" ).height(altura);
        $( "#publicidade" ).height(altura);
    });
});
</script>

A: Tente assim:
    <script>
    $(document).ready(function() {
        $( ".buscascript<?php echo "$row[id]"; ?>" ).click(function() {
            $( "#fechargame" ).show();
            $( "#result4" ).show();
            $( "#result5" ).show();
            $( "#result4" ).load( "busca.php?game=<?php echo "$row[id]"; ?>", function(){
                var altura = $("#result4").height();
                $( "#publicidade1a" ).height(altura);
                $( "#publicidade" ).height(altura);
            });
        });
    });
</script>

A function() que está no load é a função que indica o termino do carregamento executado pelo load. Nesse momento, você já tem a altura correta para colocar nas tags publicidade1a e publicidade.


text:
Q: Cant get value from redis when using @Transactional annotation in spring I've Code like this for get redis value in
'val partnerData = partnerUnitService.getByUuid(partnerUnitId?.toString())'
but if iam using @Transactional annotation icant get the value,
why this happen?
@Transactional
    fun register(user: KeycloakAuthenticationToken, request: Request): ResponseEntity<Any> {
        log.trace("Call function register")

        return try {
            val partnerData = partnerUnitService.getByUuid(partnerUnitId?.toString())```

thanks


text:
Q: How to forward asynchronous events to parent classes? I'm unsure as to what is the best approach for passing events down the line to parent classes and in need of some feedback.
The example code below tries to illustrate what I want to achieve.
namespace test {
public delegate void TestCompletedEventHandler(object sender,
    TestCompletedEventArgs e);

    public class Manager {
        CarList m_carlist = null;

        public CarList Cars {
            get { return m_carlist; }
            set { m_carlist = value; }
        }

        public Manager() {
            Cars = new CarList(this);
        }

        public void Report(bool successfull) {
            //...
        }
    }

    public class CarList : List<Car> {
        protected internal event TestCompletedEventHandler
            Car_TestCompleted = null;

        protected readonly Manager m_manager = null;

        public Manager Manager {
            get { return m_manager; }
        }

        public CarList(Manager manager) {
            m_manager = manager;
        }

        public void Test() {
            foreach(Car car in this) {
                bool ret = car.Test();
                manager.Report(ret);
            }
        }

        public void Add(Car car) {
            //Is this a good approach?
            car.TestCompleted +=
                new TestCompletedEventHandler(Car_TestCompleted_Method);
            base.Add(car);
        }

        private void Car_TestCompleted_Method(object sender,
            TestCompletedEventArgs e)
        {
            if(Car_TestCompleted != null) Car_TestCompleted(sender, e);
        }
    }

    public class Car {
        protected internal event TestCompletedEventHandler
            TestCompleted = null;

        public bool Test() {
            //...

            if(TestCompleted != null) TestCompleted(this,
                new TestCompletedEventArgs())
        }
    }

    public class TestCompletedEventArgs : EventArgs {
        //...
    }
}

using test;
Manager manager = new Manager();
manager.Cars.Car_TestCompleted +=
    new TestCompletedEventHandler (Car_TestCompleted_Method);
manager.Cars.Test();

Another more specific example:
//Contains DataItems and interfaces for working with them
class DataList
{
    public List<DataItem> m_dataitems { get; set; }
    public TestManager m_testmanager { get; set; }
    // ...
}

class DataItem
{
    // ...
}

//A manager class for running tests on a DataList
class TestManager
{
    public List<TestSource> m_sources { get; set; }
    public WorkerManager m_workermanager { get; set; }
    // ...
}

//A common interface for Tests
abstract class TestSource
{
    public event EventHandler<EventArgs<object>> Completed = null;
    protected TestManager m_owner { get; set; }

    public abstract void RunAsync();
    // ...
}

//A test
class Test1 : TestSource
{
    public virtual void RunAsync()
    {
        //Add commands
        //Run workers
        //Report progress to DataList and other listeners (like UI)

        //Events seem like a bad approach since they need to be forwarded through many levels of abstraction
        if(Completed != null) Completed(this, new EventArgs<object>(null));
    }
    // ...
}

//Manages a number of workers and a queue of commands
class WorkerManager
{
    public List<MyWorker> m_workers { get; set; }
    public Queue<Command> m_commands { get; set; }
}

//Wrapper for BackgroundWorker
class MyWorker
{
    // ...
}

//Async command
interface Command
{
    // ...
}

A: I think you may have just over implemented this a bit... It looks like you are trying to use async operations. Even if you are using sync operations though, typically you'd just use callback methods instead of events in a case like this...
Here is an example of things to change to use callbacks here:
//new delegate
public delegate void CarReportCallback(Car theCar, bool result);

//in the Manager class, make report conform to delegate's signature
public void Report(Car theCar, bool result)
{
    //do something, you know which car and what the result is.
}

//in the CarList class pass a reference to the report method in
public void Test()
{
    foreach(Car car in this)
    {
        car.Test(manager.Report);
    }
}

//in the Car class use the delegate passed to invoke the reporting
public void Test(CarReportCallback callback)
{
    //... do stuff
    callback(this, isTestCompleted);
}

A: It wouldn't make sense to just have each car call an event which calls an event on the parent list. I would do it more like this:
namespace test {
    public delegate void TestCompletedEventHandler(object sender,
    TestCompletedEventArgs e);

    public class Manager {
        CarList m_carlist = null;

        public CarList Cars {
            get { return m_carlist; }
            set { m_carlist = value; }
        }

        public Manager() {
            Cars = new CarList(this);
        }

        public void Report(bool successful) {
            //...
        }
    }

    public class CarList : List<Car> {
        protected readonly Manager m_manager = null;
        protected List<Action<object, TestCompletedEventArgs>> delegatesList = new List<Action<object, TestCompletedEventArgs>>();

        public Manager Manager {
            get { return m_manager; }
        }

        public CarList(Manager manager) {
            m_manager = manager;
        }

        public void Test() {
            foreach(Car car in this) {
                bool ret = car.Test();
                manager.Report(ret);
            }
        }
        public void Add(TestCompletedEventHandler e) {
            foreach (Car car in this) {
                car.OnTestCompleted += e;
            }
            delegatesList.Add(e);
        }
        public void Add(Car car) {
        foreach(Action a in delegatesList)
        {
            car.OnTestCompleted += a;
        }
            base.Add(car);
        }
    }

    public class Car {
        protected internal event TestCompletedEventHandler OnTestCompleted = null;

        public bool Test() {
            //...
            if (OnTestCompleted != null) OnTestCompleted(this, new TestCompletedEventArgs());
        }
    }

    public class TestCompletedEventArgs : EventArgs {
        //...
    }
}

using test;
Manager manager = new Manager();
Manager.Cars.Add(new Car());
manager.Cars.Add(new Car());
manager.Cars.Add(new Car());
manager.Cars.Add((sender, args) =>
{
    //do whatever...
})
manager.Cars.Test();
manager.Cars.Add(new Car());

A: It seems reasonable, but I'm not really sure what the use case is and how this would be used.
You've got a strong concept of containment going on, but I'm not really sure why.  Also, it's kind of weird that the CarList 'sort of' seems to have ownership of the individual cars.
Additionally, I don't know why Test() on the Car class would both return a result and raise an event.  It seems like you're having two different paths to return the same data.  And the Manager class seems completely redundant with the CarList class at first glance.
What is the problem you're actually trying to solve here?  That might help me with defining a good solution to it.


text:
Q: Apache POI setAutobreaks(false) not functioning as expected I am trying to print an excel generated using the Apache POI and the manual page breaks are not functioning as expected I have set the following
    sheet.setAutobreaks(false);
    sheet.setRowBreak(50);
    sheet.setColumnBreak(20);

But as you can see below both the auto page break(doted lines) and the Manual page Breaks are coming and users have to manually drag the dotted lines to take a proper print out

A: I went into the same problem. I wasn't able to eliminate the auto breaks, so I moved them using following code to the end of the last page:
sheet.setFitToPage(true);
XSSFPrintSetup printSetup = sheet.getPrintSetup()
printSetup.setFitWidth( (short) 1)
printSetup.setFitHeight( (short) 0)

A: Following code (groovy) generates two workbooks.
    testPageBreaks(false) //generates sheet with auto page breaks (see image 1)

    testPageBreaks(true) //generates sheet with auto page breaks but at the very last cell of the sheet (see image 2)

    def testPageBreaks(boolean fitToPage) {
        Workbook wb = new XSSFWorkbook()
        Sheet sheet = wb.createSheet()

        def r = sheet.createRow(90)
        def c = r.createCell(30)
        c.setCellValue("last cell")

        sheet.setRowBreak(30)
        sheet.setRowBreak(60)
        sheet.setRowBreak(90)

        if ( fitToPage ) {
            sheet.setFitToPage(true)
            XSSFPrintSetup printSetup = sheet.getPrintSetup()
            printSetup.setFitWidth( (short) 1)
            printSetup.setFitHeight( (short) 0)
        }

        ByteArrayOutputStream ostream = new ByteArrayOutputStream()
        wb.write(ostream)

        response.contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        response.setHeader('Content-Disposition', "attachment; filename=test.xlsx")
        response.setIntHeader('Content-Length', ostream.size())
        ostream.writeTo(response.outputStream)
        response.outputStream.flush()
    }

Image 1 - testPageBreaks(false)

Image 2 - testPageBreaks(true)


text:
Q: The mysqli|mysql extension is missing. Please check your PHP configuration Решил перенести phpmyadmin из одного поддомена на другой (на том же сайте). Добавил поддомен в CNAME, изменил адрес в вирт хостах apache и nginx, но теперь при заходе на новый поддомен phpmyadmin выдает ошибку:

The mysqli|mysql extension is missing. Please check your PHP configuration. See our documentation for more information.

При попытке зайти на сайт:

Fatal error: Uncaught Error: Call to undefined function mysqli_connect()

Ничего, кроме адреса вирт хостов в apache/ngninx я не менял и не трогал. До этого всё было в порядке.
Сервер - Centos 7, php7, mariadb10.


text:
Q: Delete ranges of lines, but skip the comments which come in between the lines I have a file with the following contents:
Windows user
I love windows
Windows 10
# I like it
# I want to keep these two lines
Just started with my job
New to shell scripting as well
New to Mac
Please help!

#EOF

I want to delete all the lines:
starting from "I love windows" to "New to shell scripting as well", but keep the comments that are present between these lines.
So, the desired output should appear as below:
Windows user
# I like it
# I want to keep these two lines
New to Mac
Please help!

#EOF

I used sed command to delete the range of lines using the line numbers
sed '2,7d' file

But this command deletes the comments as well, which I want preserved.

A: Try using:
sed '2,7{/^[[:blank:]]*#/!d}' infile

This is normally deleting lines from 2~7 but not the lines that starts with a hash as known as a commented line.
The [[:blank:]] character class is used to match and keep those lines that it's a commented line but took whitespaces at behind too either zero or more whitespace.
To be more specifically using the patterns given:
sed '/I love windows/,/New to shell scripting as well/ {/^[[:blank:]]*#/!d}' infile

standard-Complaint sed solution would be:
sed -e '2,7{' -e '/^[[:space:]]*#/!d' -e '}' infile

to read the line number from a variable, just double-quote your variables like "$line" (related: How do I use variables in a sed command?.)
line=2; sed -e "$line"',7{' -e '/^[[:space:]]*#/!d' -e '}' infile

The output is:
Windows user
# I like it
# I want to keep these two lines
New to Mac
Please help!

#EOF


text:
Q: How to save changes created by "user" for each user separately using Java/JSF/Hibernate H2 DB I have a following problem and I am not sure how to solve it.
I am writing a basic newsfeed agregator webapp, where the "publisher" can make new topics with news and the reader can subscribe topics and so read the news from those topics he subscribes. He can then mark them as read.
I am writing this with Hibernate H2 database, JSF/Java  and I have a problem. My code looks like this:
This is the entity of Person:
@Entity
@NamedQuery(name = "findPerson", query = "SELECT e FROM Person e")

public class Person implements Serializable {

private static final long serialVersionUID = 1L;

private static final String TemporalType = null;
@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private Long id;

private String name;
private String pw;
private String checkPw;
private String type;
private String topic;
private ArrayList<String> myTopics;

public Person(String name, String pw) {
    this.name = name;
    this.pw = pw;
}

//setters and getters

This is my personcontroller class, where I have my login and register method, they should save the user in session (i hope).
@Named(value = "personController")
@RequestScoped
@ManagedBean
@SessionScoped
public class PersonController {

@EJB
private PersonEJB personEJB;
private Person person = new Person();
private List<Person> personList = new ArrayList<>();
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
NewsController nc = new NewsController();
private ArrayList<String> myTopics;

public Person login(String name, String pw) {
    Person akt = new Person();

    for (int i = 0; i < getPersonList().size(); ++i) {
        akt = getPersonList().get(i);
        if (akt.getName().equals(name)) {
            if (akt.getPw().equals(pw)) {
                return akt;
            }
        }
    }
    FacesContext context = FacesContext.getCurrentInstance();
    context.getExternalContext().getSessionMap().put("user", person);
    return null;
}

public boolean register(String name, String pw, String checkPw, String type) {

        for (int i = 0; i < getPersonList().size(); ++i) {
            if (getPersonList().get(i) instanceof Reader) {
                p = getPersonList().get(i);
                if (p.getName().equals(name))
                    return false;
            }

        }
        break;

    case "Provider":
        p = new Provider(null, null);

        for (int i = 0; i < getPersonList().size(); ++i) {
            if (getPersonList().get(i) instanceof Provider) {
                p = getPersonList().get(i);
                if (p.getName().equals(name))
                    return false;
            }
        }
        break;
    default:
        return false;

    }

    person.setName(name);
    person.setPw(pw);

    return true;
}

public void subscribeNew() throws IOException {
    if (subscribe(person.getTopic()) == true)
        context.redirect("indexReader.xhtml");
}

public List<Person> getPersonList() {
    personList = personEJB.findPerson();
    return personList;
}

public String addNewPerson() {
    person = personEJB.addPerson(person);
    personList = personEJB.findPerson();
    return "employeeList.xhtml";
}

public void registerNew() throws IOException {

    if (register(person.getName(), person.getPw(), person.getCheckPw(),
            person.getType()) == true) {
        person = personEJB.addPerson(person);
        personList = personEJB.findPerson();
        context.redirect("login.xhtml");
    }

    else {
        context.redirect("register.xhtml");
    }
}

public void loginNew() throws IOException {

    if (login(person.getName(), person.getPw()).getType().equals("Reader")) {
        if (login(person.getName(), person.getPw()) != null)
            context.redirect("indexReader.xhtml");
    } else if (login(person.getName(), person.getPw()).getType().equals(
            "Provider")) {
        if (login(person.getName(), person.getPw()) != null)
            context.redirect("indexProvider.xhtml");
    } else {
        context.redirect("login.xhtml");
    }
}

 public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "login?faces-redirect=true";
    }

//setters, getters

}

The EJB looks like this:
@Stateless
public class PersonEJB {
    @PersistenceContext(unitName = "user")
    private EntityManager entityManager;

    public List<Person> findPerson() {
        TypedQuery<Person> query = entityManager.createNamedQuery("findPerson",
                Person.class);
        return query.getResultList();
    }

    public Person addPerson(Person person) {
        entityManager.persist(person);
        return person;
    }
}

The similar I have for News.
@Entity
@NamedQuery(name = "findNews", query = "SELECT e FROM News e")

public class News implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String text;
private String category;
private String status;

@Temporal(TemporalType.TIMESTAMP)
private Date created = new Date();

@PrePersist
private void onCreate() {
    created = new Date();
}

public News(String text, String category, String status) {
    this.text = text;
    this.category = category;
    this.status = status;
}
//setters, getters

What I want to do is get the Topic, that a person wants to subscribe and then show to the person just the news from the topic. I wrote something like this.
@Named(value = "newsController")
@RequestScoped
@SessionScoped

@ManagedBean(name="news")
public class NewsController implements Serializable{

private static final long serialVersionUID = 1L;
@EJB
private NewsEJB newsEJB;
private News news = new News(null, null, null);
private List<News> newsList = new ArrayList<>();
private List<News> filteredNews = new ArrayList<>();

private List<String> myTopics = new ArrayList<>();

private String topic;
private Person person = new Person();

public boolean subscribe(String topic) {
    for (int i = 0; i < getNewsList().size(); i++)
        if (getNewsList().get(i).getCategory().contains(topic)) {
            person.getMyTopics().add(topic);
            return true;
        }

            return false;
        }

public List<News> getFilteredNews(){
    News e = new News();
    if(subscribe(topic)==true){
    for(int i =0;i < getNewsList().size(); i++){
        topic = getMyTopics().get(i);
        if (getNewsList().get(i).getCategory().equals(topic)){
            filteredNews = newsEJB.findNews();
            newsEJB.addNews(e);
            filteredNews.add(e);
        }
    }
    }

    return filteredNews;
}

public void subscribeNew() throws IOException{
        getFilteredNews();
        context.redirect("foundTopics.xhtml");
}

public List<News> getNewsList() {
    newsList = newsEJB.findNews();
    return newsList;
}

public void publishNews() throws IOException {
    News akt = new News(news.getText(), news.getCategory(),
            news.getStatus());
    newsList = newsEJB.findNews();
    newsEJB.addNews(akt);
    context.redirect("indexProvider.xhtml");
}

//setters and getters

And the EJB class for news similar as the above one
public class NewsEJB {
    @PersistenceContext(unitName = "user")
    private EntityManager entityManager;

    public List<News> findNews() {
        TypedQuery<News> query = entityManager.createNamedQuery("findNews",
                News.class);
        return query.getResultList();
    }

    public News addNews(News news) {
        entityManager.persist(news);
        return news;
    }
}

Where the boolean subscribe() should get the topic I subscribe in new arraylist. Then compare the topics from this arraylist in the getFilteredNews() and show just the news with these topics. And subscribeNew() get the filteredNews and return to foundtopics.xhtml. But this is always a nullpointerexception.
Do you have an idea what I am doing wrong? Do I have to join the 2 tables first? And how should I do, that this arraylist with the subscribes topics whould be saved for each person? I think for each person different.


text:
Q: Is there any way to get Savings info of spot instance by AWS CLI I googled but can't find it. Can we obtain the spot usage and savings info in Savings tab on Spot instance by AWS CLI?

A: Yes and No.
General pricing information is available via Using the AWS Price List API - AWS Billing and Cost Management
Current spot prices are available via DescribeSpotPriceHistory - Amazon Elastic Compute Cloud
You would need to calculate the difference yourself.


text:
Q: Help on VGA and putpixel intel x86 asm AT&T syntax I want to draw a colored line in asm. I have to use AT&T syntax, on an x86 intel linux unit.
I got pretty far already, but I'd like to know how to enter VGA-mode, or Mode-X, and how to put a pixel on the screen. Is there a function for that in a standard C library (like printf)?
Thanks a lot for your help. :)

.bss    # Declaring uninitialized variables
.data   # Declaring initialized variables
.text   # Actual assembly code and constants
intro:  .asciz "Draw a line in VGA\n\n"
clr:    .asciz "Give a color \n"
optns:  .asciz "red (1), blue (2), white (3)\n"
res     .asciz "%d"
    ent:    .asciz "\n"

.global main            # Tell kernel where to start (visible from outside)

main:   pushl %ebp          # Push base pointer
        movl %esp, %ebp             # Initialize base pointer
    pushl $intro                # Push the string address
    call printf         # Call the printf routine from C library
    addl $8, %esp
pushl $clr          # push color question on the stack
call printf         # Print it

subl $4, %esp               # Reserve stack space for variable
leal -4(%ebp), %eax             # Load address of stack var in eax
pushl %eax          # Push second argument of scanf
pushl $rets         # Push first argument of scanf
call scanf          # Call scanf

    movl 4(%ebp), %ecx              # mov the result in ecx
    cmpl $1, %ecx
    je red
    cmpl $2, %ecx
    je blue
    jne white

red:    #... still working on this
    movl 0013h, %eax                # enter 320x200x256 mode
    int 10h                         # IS THIS CORRECT?

    movl $0, %ebx                   # set X to 0
    movl $0, %ecx                   # set Y to 0

    call draw                   # Call line routine

    movl 0003h, %eax                # IS THIS CORRECT?
    int 10h                         # return to text mode

    movl $0, (%esp)             # Make esp 0, indicating succesful termination
    call exit                       # Exit the program

draw:
        call putpixel
        # pushl %ebp                # Push the base pointer
        # movl %esp, %ebp           # Initialize base pointer
        inc %ebx                        # increment X
        inc %ecx                        # increment Y
        cmpl $200, %ecx                 # check if Y => 200
        jge end                         # if Y=> 200, jump to end
        jmp draw                        # loop
putpxl: #has to put a pixel at (%ebx, %ecx) and return to draw
        # should use the color from the main routine
end:    movl %ebp, %esp                 # Remove local variables
        popl %ebp                       # Remove base pointer
        ret                             # return to main routine

A: You are not allowed to do direct video (graphic mode) output in linux (protected OS). it was possible only in a dos (real-mode OS).
You can use framebuffer device or SDL, or libX11. But there is no reason why to do work with high-level libraries from the asm.
Int 10 is not allowed in linux  directly (in user mode; the kernel must do low-level accesses).
e.g. this is 5 year old exact the same discussion http://www.gamedev.net/topic/368196-linux-assembler-int-10h/

A: Best thing you could do would be to use a higher-level library, like SDL or Allegro. This way, your program will work on top of X11 and on non-VGA framebuffers (e.g: displays on embedded ARM-based devices).
Svgalib allowed to program for VGA and so-called SVGA graphics cards. Its development stopped years ago.
There are two ways to access VGA hardware:

*

*Using registers

*Using the VGA BIOS: this is the one you've tried. VGA BIOSes are written to run in real mode. To invoke them from protected mode, you would need to switch to vm86 mode. which is what LRMI (Linux Real Mode Interface, the opposite of DPMI) did.


text:
Q: Calling a controller in Laravel 4 I have a controller prefixed with a namespace. How can I execute that controller? Without necessarily make a Request object on the fly. What should I do?
I have found this solution on the net:
$app = app();
            $controller = $app->make(ucfirst("MyNamespace")."\\".ucfirst($controller_name)."Controller");
            return $controller->callAction($controller, $parameters = array());
I get an error that says `callAction()`'s first parameter must be of type `Container`.

How should I execute a controller in Laravel from inside another controller?


text:
Q: Issues with solarized and Terminal.app I really apologize because I know that this question has been asked multiple times. I have gone through all of the previous questions, but I still have yet to have any luck setting up the Solarized colorscheme in my Terminal.app for OS X Mountain Lion. So far this is what I have:

My .vimrc currently is set up like the following:
set number
syntax enable
set background="dark"
colorscheme solarized

but for my MacVim I get this:

This is what I would like to have my Terminal.app display as well. The only thing that my .vimrc says for MacVim is
colorscheme solarized

Edit
After I had asked this question, I eventually moved to iTerm2, which proved to be much nicer.
I'm not 100% sure, but I think the newer versions of OS X terminal will support 256 colors out of the box.

A: Ensure that TERM is set to xterm-256color to let Vim know that the terminal supports 256 colors. This is the default for Terminal in Lion 10.7 and later†, so your preferences were customized at some point.
To tell Terminal to set TERM to a different value, go to

Terminal > Preferences > Settings > [profile] > Advanced

and change Declare terminal as: to xterm-256color.
[Note that all this preference does is set the value of the TERM environment variable. It does not alter the behavior of Terminal or affect what sort of terminal it emulates.]
† Prior to Lion, the default was xterm-color.

A: Add to your ~/.vimrc
" Solarized Dark
syntax enable
set t_Co=256
let g:solarized_termcolors=256
set background=dark
colorscheme solarized

This works on both ansi and xterm-256color versions of Solarized. Tested on Terminal 2.3 on a new OS X 10.8.5 VM installation.
NB This answer supersedes the previous one that proposed changes to the profile swatches. I recently realised I had these commands in my .vimrc file that actually configured Solarized.

A: I had the same issue, then I downloaded an alternate implementation of the Solarized theme for the Mountain Lion terminal, and this appears to have solved it.

A: Just add let g:solarized_termcolors=256 to your vimrc

A: To run vim with 256 colors you must use a 256 color terminal. You can set your terminal to xterm-256color, for example, with export TERM=xterm-256color and then start vim. You can export this $TERM setting in one of your terminal startup scripts (e.g. .bashrc, .zshrc, etc.).

A: It may seem counterintuitive, but use set g:solarized_termcolors=16. This is confirmed to be the correct setting with :h solarized.


text:
Q: Link not working after AJAX request I'm having a minor but rather annoying issue with a webpage I'm making. So I have a link that, when clicked, makes an AJAX request to a PHP script (the link sends a hidden input value, if that matters). It works fine and it works as I expect, but then if I try to click the link again, it doesn't do anything. I have to refresh the page in order for it to work again, and I prefer to not have to do this.
Link:
Delete
JavaScript:
    $("a[name='delete-link']").click(function(e){
        e.preventDefault();
        var ID = $(this).parents("ul").find("input[name='delete-identifier']").val();

        $.ajax({
            type: 'POST',
            url: '../ajax.php',
            data: {delete: 'true', delete_id: ID},
            success: function(response){
                $("#result").html(response).fadeIn(500).delay(5000).fadeOut(500);
                $("div[name='update']").load("test.php #update");
            }
        })
    })

The only code in the #update div is this PHP code which echoes a table displaying users:
<?php
    if ($rs){
        $user_table = "
Action	";
        $user_table .= "
Name	Privilege ID
";
        while ($user = $rs->fetch_array(MYSQL_ASSOC)){
            $user_table .= "". $rank['RankName'] ."	". $user['PrivilegeID'] ."	";
            $user_table .= "

                                  <button type='button' class='btn btn-default dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>
                                    Action
                                  </button>

                                    <input type='hidden' name='delete-identifier' value='". $user['ID'] ."'>

Delete

";
        }
        $user_table .= "
";
        echo($user_table);
    }
?>

Any ideas?

A: after ajax you are updating the div, .click() do not work on dynamic loaded html.
Use .on()
$(document).on("click","a[name='delete-link']",function(e){
    e.preventDefault();
    var ID = $(this).closest("ul").find("input[name='delete-identifier']").val();

    $.ajax({
        type: 'POST',
        url: '../ajax.php',
        data: {delete: 'true', delete_id: ID},
        success: function(response){
            $("#result").html(response).fadeIn(500).delay(5000).fadeOut(500);
            $("#update").load("test.php");
        }
    })
})

In place of $(document) you can use Id selector of parent of dynamic content as $('#updateDivParentId')


text:
Q: ASP.NET Identity Model First fails because of renamed AspNetUserRoles columns Like several others I have tried to implement ASP.NET Identity Model First. Everything works fine once you have tried, errored, fumed, searched and resolved.. I thought.
See also:

*

*ASP.NET Identity with EF Database First MVC5

*http://danieleagle.com/blog/2014/05/setting-up-asp-net-identity-framework-2-0-with-database-first-vs2013-update-2-spa-template/
Course of action, summarized:

*

*Created default project (MVC5)

*Create database

*Update connectionstring in the web.config

*Run website, register: tables get created

*Create EF Model (edmx)

*Import Identity tables (everything fine up to this point)

*Modified xxx.Context.tt to inherit from IdentityDbContext

*Generate database script (trouble starts here)

I have solved the issues that appeared (up to the latest step). For completeness I will describe them.
Using the default Identity context
Everything works fine: tables get created, I can Register and login. This is however not the situation I want: I want to use a Model First approach.
Using the custom, model first context using the EF connectionstring
Modifying the CreatePerOwinContext so that it uses my Model First context:
public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(CustomModelFirstDbContext.Create);

And the ApplicationUserManager so that it uses the Model First context:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<CustomModelFirstDbContext>()));

Results in:

Server Error in '/' Application.
The entity type ApplicationUser is not part of the model for the
  current context.
Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The entity type
  ApplicationUser is not part of the model for the current context.
Source Error:
An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.
Stack Trace:
  [InvalidOperationException: The entity type ApplicationUser is not
  part of the model for the current context.]

Using the "normal" connectionstring with the custom, Model First context

An exception of type
  'System.Data.Entity.Infrastructure.UnintentionalCodeFirstException'
  occurred in WebApplication1.dll but was not handled in user code
Additional information: Code generated using the T4 templates for
  Database First and Model First development may not work correctly if
  used in Code First mode. To continue using Database First or Model
  First ensure that the Entity Framework connection string is specified
  in the config file of executing application. To use these classes,
  that were generated from Database First or Model First, with Code
  First add any additional configuration using attributes or the
  DbModelBuilder API and then remove the code that throws this
  exception.

So, I figured I needed the default Identity context to use Identity, and use the custom Model First context for everything else. Not the preferred solution, but acceptable.

*

*Rolled everything back

*Import Identity tables from database

*(Optional) Created entities via the Model First approach

*Generated database script

Both the normal project and a quick sanity check test project have the same problem with the AspNetUserRoles table. That is a junction table, and when importing it in the EF designer, everything is OK. You won't see it since it is a many to many relationship, and when inspecting the association between AspNetRole and AspNetUser it looks good.
Designer and mapping details:

However, when generating the sql script, EF modifies the keys.
Designer and mapping details:

Generated SQL script:
-- Creating table 'AspNetUserRoles'
CREATE TABLE [dbo].[AspNetUserRoles] (
[AspNetRoles_Id] nvarchar(128) NOT NULL,
[AspNetUsers_Id] nvarchar(128) NOT NULL
);
GO

In EF, you can't change the names of the mappings in the designer (thread on social.msdn.microsoft.com).
Subsequently the creation of a new user wil fail, using the originally created context because the junction table contains the wrong columns:

Server Error in '/' Application.
Invalid column name 'UserId'.
Invalid column name 'UserId'.
Invalid column name 'UserId'.
Invalid column name 'RoleId'.
Invalid column name 'UserId'.
Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'UserId'. Invalid column name 'UserId'. Invalid column name 'UserId'. Invalid column name 'RoleId'. Invalid column name 'UserId'.
Source Error:
Line 89: {
Line 90: var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
Line 91: IdentityResult result = await UserManager.CreateAsync(user, model.Password);
Line 92: if (result.Succeeded)
Line 93: {

What is the solution? Are there any alternatives than trying to change the generated script, or moving to Code First?

A: If you in the begginning and db is still empty than
I believe the easiest workaround is:

*

*Create EF Model(edmx).

*Right click on model "Generate Database from model".

*It will create DDL file  (snippet below)

*Replace all wrong "AspNetUsers_Id" and "AspNetRoles_Id" for correct values.

*Right click "execute".
Works for me.

-- Creating non-clustered index for FOREIGN KEY 'FK_AspNetUserRoles_AspNetUser'
CREATE INDEX [IX_FK_AspNetUserRoles_AspNetUser]
ON [dbo].[AspNetUserRoles]
([AspNetUsers_Id]);   //replace for  UserId

Happy coding!


text:
Q: Is there a fundamental difference between INTERSECT and INNER JOIN? I understand, that INNER JOIN is made for referenced keys and INTERSECT is not. But afaik in some cases, both of them can do the same thing. So, is there a difference (in performance or anything) between the following two expressions? And if there is, which one is better?
Expression 1:
SELECT id FROM customers
INNER JOIN orders ON customers.id = orders.customerID;

Expression 2:
SELECT id FROM customers
INTERSECT
SELECT customerID FROM orders

A: They are very different, even in your case.
The INNER JOIN will return duplicates, if id is duplicated in either table.  INTERSECT removes duplicates.  The INNER JOIN will never return NULL, but INTERSECT will return NULL.
The two are very different; INNER JOIN is an operator that generally matches on a limited set of columns and can return zero rows or more rows from either table.  INTERSECT is a set-based operator that compares complete rows between two sets and can never return more rows than in the smaller table.

A: Try the following, for example:
CREATE TABLE #a (id INT)

CREATE TABLE #b (id INT)

INSERT INTO #a VALUES (1), (NULL), (2)
INSERT INTO #b VALUES (1), (NULL), (3), (1)

SELECT a.id FROM #a a
INNER JOIN #b b ON a.id = b.id

SELECT id FROM #a
INTERSECT
SELECT id FROM #b


text:
Q: Why does JSON parsing with jsonpath-plus throw a TypeError? When my code calls jsonpath-plus, it's getting TypeError: Cannot read property 'value' of null (where value is the name of a child that I want to check). This occurs whenever the object provided in the `json' parameter has a null property. My path includes a conditional selector:
JSONPath({json: {content: null}, path: "$..[?(@.value)]"}

This is a simple case that always causes TypeError to be thrown.

A: This is a changed behavior introduced in jsonpath-plus version 5.0.4 around April 1, 2021. In verions 5.0.2 & 5.0.3, the conditional selector simply does not match the object. This appears to be a breaking change, so one would hope it will be reverted back in the next patch release. In the mean time, I'm using 5.0.3.
The maintainer has indicated that the breaking change is a bug-fix, so it's unlikely that the change will be reverted.


text:
Q: Brownian Motion (Geometric, Fractional, Drift) I have been researching Brownian motion for a while and have come across terms/types of Brownian motion such as fractional, geometric, and Brownian motion with drift. I understand the physical meaning of normal BM of particles suspended in a liquid and behaving chaotically but I don't understand the difference between these types or their physical meaning. I have read that geometric is used in finance but that is all I have understood so far.
Can someone explain these types without using too much mathematics if possible please? Specifically the 3 different types above but if there are any other more significant/common types then feel free to explain those briefly as well. Also if there are any good websites or videos clearly explaining these that would be much appreciated too.


text:
Q: Unable to type INR sign in 18.10 I am not able to type symbol for Indian rupees using my 18.10. I have set Regional format as English ( India ) and in other areas where I can find English ( India ). But when I type ALT+4, I get 4 on gedit. Any fix available for this? Am I doing something wrong?

A: I managed to fix it ₹
First, you need to take " Language and Region " under " Input Sources " choose " English ( India with Rupees ) " and bring it to the top as seen in the image below.

Now you will hope that when you type Alt Gr + 4 ₹ sign will appear. No, you will have to choose it from the top bar as well as seen below


text:
Q: Linking Rcpp to interp2d (GSL-type library) I need some help with a linker error I get during installation of an Rcpp package on a linux system where I don't have admin rights. In a nutshell, I get this error:

relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC

I have a file solve.cpp that uses external library interp2d, which in turn has a GSL dependency. I specify my dependencies via [[Rcpp::depends(RcppArmadillo,RcppGSL)]] and in the DESCRIPTION.  My Makevars is like the one from the RcppGSL package, with the addition of the linterp2d flag:
PKG_CPPFLAGS = -W $(GSL_CFLAGS) $(LOCAL_INCLUDE)
PKG_LIBS += $(GSL_LIBS) $(LOCAL_LIBS) -linterp2d $(RCPP_LDFLAGS)

where I define the environement variables
export LOCAL_INCLUDE="-I/data/uctpfos/local/include/"
export LOCAL_LIBS="-L/data/uctpfos/local/lib/"

on the system.
I do R CMD INSTALL bkPackage and see:
g++ -I/cm/shared/apps/R/3.0.1/lib64/R/include -DNDEBUG -W -I/cm/shared/apps/gsl/1.15/include -I/data/uctpfos/local/include -fPIC -I/usr/local/include -I"/data/uctpfos/R/x86_64-unknown-linux-gnu-library/3.0/Rcpp/include" -I"/data/uctpfos/R/x86_64-unknown-linux-gnu-library/3.0/RcppArmadillo/include" -I"/data/uctpfos/R/x86_64-unknown-linux-gnu-library/3.0/RcppGSL/include"   -fpic  -O3 -fPIC -c RcppExports.cpp -o RcppExports.o

g++ -I/cm/shared/apps/R/3.0.1/lib64/R/include -DNDEBUG -W -I/cm/shared/apps/gsl/1.15/include -I/data/uctpfos/local/include -fPIC -I/usr/local/include -I"/data/uctpfos/R/x86_64-unknown-linux-gnu-library/3.0/Rcpp/include" -I"/data/uctpfos/R/x86_64-unknown-linux-gnu-library/3.0/RcppArmadillo/include" -I"/data/uctpfos/R/x86_64-unknown-linux-gnu-library/3.0/RcppGSL/include"   -fpic  -O3 -fPIC -c solve.cpp -o solve.o

The problems appears after that in the linking step:
g++ -shared -L/usr/local/lib64 -o bkPackage.so RcppExports.o solve.o -L/cm/shared/apps/gsl/1.15/lib -lgsl -lgslcblas -lm -L/data/uctpfos/local/lib -linterp2d -L/data/uctpfos/R/x86_64-unknown-linux-gnu-library/3.0/Rcpp/lib -lRcpp -Wl,-rpath,/data/uctpfos/R/x86_64-unknown-linux-gnu-library/3.0/Rcpp/lib

The error follows as:
/usr/bin/ld: /data/uctpfos/local/lib/libinterp2d.a(interp2d_spline.c.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
/data/uctpfos/local/lib/libinterp2d.a: could not read symbols: Bad value

As you can see I compiled this with -fPIC, so that can't be it.

A: It's complaining that libinterp2d.a was not compiled with -fPIC; are you sure that was also compiled with -fPIC on?
Also, it seems you both have -fpic and -fPIC in your flags; you probably just want -fPIC. I think R actually ensures that's on by default.


text:
Q: Add items to list and then print it (iOS) I'm currently working on a restaurant app on iOS and I'm kinda new to programming.
Now, in my app, I have items in a tableView, and I want the user to add the items to a list (Their Order) and they must be able to view that list with their items in it.
If they are satisfied, they must be able to print it to a printer connected on a network and if they print it, it must look more or less like this:

*

*item (with their price on the end)

*item

*item
Total (and then the total amount of all the items on the list)
If this is possible, can you please help me.
Thanks!

A: At a high level, your app creates a print job, providing either an array of ready-to-print images and PDF documents, a single image or PDF document, an instance of any of the built-in print formatter classes, or a custom page renderer.
In iOS 4.2 and later, apps can add support for printing content to local AirPrint-capable printers. Although not all apps need printing support, it is often a useful feature if your app is used for creating content (such as a word processor or a drawing program), making purchases (printing order confirmations), and other tasks where the user might reasonably want a permanent record.
This chapter explains how to add printing support to your app. Just go through the developer.apple - Drawing Printing


text:
Q: how we can i use google translator api in my website Well I want to use Google api translator in my website and when I am putting this api code in my html page it's working fine.
----------------------------------google translator code :-----------------------------

I want to put the code in  when I am putting this code in iframe then it shows everything.
But while changing the language it changes the language of elements in the iframe it doesn't affect outside the iframe.

A: I guess this is why the iframe tag is used to include an external document into an existing one.
Google Translator will translate the content of the iframe only, since it has no clue about the container document.
Please see also:
http://forums.macrumors.com/showthread.php?t=467248


text:
Q: Using SSRS Expressions to see which options a user has selected from a multivalued parameter? I'm trying to set up a filter against a "Totals" column in an SSRS report using an expression for the field.
I have a multivalued parameter setup with the values value1, value2, value3, and value4 as options.
Before the filter, this totals column just simply added the integer values from the different columns.  I want to add functionality to where you can check which of the values the user has selected.
Similar to below (Pseudo code, because I can't figure out the syntax):
=IIF(Parameters!<Parameter>.Label="value1",Fields!value1.Value,0)
+IIF(Parameters!<Parameter>.Label="value2",Fields!value2.Value,0)
+IIF(Parameters!<Parameter>.Label="value3",Fields!value3.Value,0)
+IIF(Parameters!<Parameter>.Label="value4",Fields!value4.Value,0)
All values in the fields being added are simple integers.  I'd appreciate any help anyone can provide.  Thanks!

A: Assuming a parameter called Include, you can use an expression like this:
=IIf(InStr(Join(Parameters!Include.Value, ","), "value1") > 0, Fields!value1.Value, 0)
    + IIf(InStr(Join(Parameters!Include.Value, ","), "value2") > 0, Fields!value2.Value, 0)
    + IIf(InStr(Join(Parameters!Include.Value, ","), "value3") > 0, Fields!value3.Value, 0)
    + IIf(InStr(Join(Parameters!Include.Value, ","), "value4") > 0, Fields!value4.Value, 0)

This uses the Join function to create a comma-delimited string of the selected parameters, checks for a particular parameter value being selected, then add either the corresponding value or 0 to the total.
Here's a simple report with the expression:

All values selected:

Two values selected:

A: You can acheive this in a simple way without stringing together a whole bunch of IIF functions and specifying each and every field to be used. What if you want to change the name of a field or add fields?
Using custom code we can have a simple and robust way of performing this calculation. Right-click on the non-design surface of your report, click Report Properties... and then click on the Code tab. Insert the following code:
Function CalcTotal (ByVal param As Parameter, flds AS Fields) AS Integer
  Dim Result As Integer
  Result = 0
  If param.IsMultiValue then
    For i as integer = 0 to param.Count-1
        Result = Result + flds(param.Value(i)).Value
    Next
  End If

  Return Result
End Function

This takes the parameter object (not value) and iterates through the values selected to perform the calculation using the fields in the Fields collection.
Now for your expression, just use:
=Code.CalcTotal(Parameters!Include, Fields)


text:
Q: Driver signing: how to get MakeCert test certificates to work on x64 I'm trying to load a kernel driver that's been signed with a certificate generated by MakeCert.exe.
I followed the instructions given in the Windows Driver Kit documentation:

*

*Sign the driver with MakeCert.exe

*Verify the signature with SignTool verify /v /pa DriverFileName.sys.

*Installing the cert into the test computer's Trusted Root Certification Authorities store and Trusted Publishers store, using CertMgr.exe
When I verify the signature with SignTool verify /v /pa DriverFileName.sys as described in WDK Microsoft Docs, SignTool reports that the signature is ok. I've done this on both the development computer and the test machine that is supposed to load the driver.
However, the driver doesn't actually load. The Windows CodeIntegrity log says 3004: Windows is unable to verify the image integrity of the file \Device\HarddiskVolume3\path\DriverFileName.sys because file hash could not be found on the system. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source.
I looked at this similar question. I get the same results as in that question, when I run SignTool verify /v /kp DriverFileName.sys. It says:  SignTool Error: Signing Cert does not chain to a Microsoft Root Cert.
The linked question's resolution involved using a real, non-test certificate, and changing the signing setup so that it correctly chained to the Microsoft Root Certificate. I'm not yet at that stage; I just want to get my test infrastructure working "properly".
I'm interested in having the kernel load my driver, and verify the signature using the certificates that I've manually installed on the test machine. I know I can use bcdedit -set testsigning yes to disable signature validation entirely, but that seems like overkill - it will allow any signed driver to run, even if it wasn't signed with the test certificate I've installed on the machines. Is it possible to leave "testsigning" mode turned off (so the driver signature is still actually validated against an installed cert), but still use my internal self-generated MakeCert.exe test certificate?

A: It looks the answer is no, it's not possible.
Can I install self-signed drivers on 64-bit Windows without test mode if the self-signed CA root certificate is imported to the machine store?
The WDK documentation seems quite misleading. Installing the certificate generated by MakeCert.exe on x64 test machines seems to be entirely pointless, since the kernel never pays any attention to it.
If TESTSIGNING mode is on, the signature isn't validated, so the cert doesn't need to be installed.
If TESTSIGNING mode is off, the self-signed certificate isn't cross-signed by anything the kernel trusts, so it's not considered valid, so installing the cert doesn't help.
I'm happy to accept corrections.


text:
Q: Sharing router props to components that are not wrapped in Router My route looks like this: (Main.js)
<BrowserRouter>
    <Switch>
      <Route name="login" exact path="/login" component={LoginPass} />
      <Route name="loginWithTripId" exact path="/login/:tripid" component={LoginPass} />
      <PrivateRoute path="/trips/:tripid" component={App} />
    </Switch>
  </BrowserRouter>

and in my App render method: (App.js)
render() {
    const { classes, ...other } = this.props;
    return (
  <div className={classes.root}>
    <Appbar
    />

    <LeftDrawer
    />

    <Switch>
      <Route
        path={'/trips/dashboard'}
        render={props => (
          <Dashboard
            {...other}
            {...props}
          />
        )}
      />
      <Route
        path={'/trips/:tripid/itinerary'}
        render={props => (
          <Itinerary
            {...other}
            {...props}
          />
        )}
      />
      <Route render={() => <Redirect to={'/trips/dashboard'} />} />
    </Switch>
  </div>
);
}

How do I share the router props passed in Dashboard and Itinerary without saving it in the App local state? I've tried using withRouter inside LeftDrawer and Appbar but it has the router props of its parent (Main.js). I get match.path="/trip/:tripid" instead of either "trip/:tripid/itinerary" or "trip/dashboard".

For context, I need to render certain elements in my appbar/leftdrawer components depending on the URL and I'd like to match using the match.path props being passed into Itinerary and Dashboard Components. For example, if I'm in the route '/trip/dashboard', the Dashboard gets loaded. So the appbar needs to have an ADD button to add trips. This button isn't present in the appbar in the Itinerary View.  In the past, I've had LeftDraewr and Appbar inside Dashboard and Itinerary Components, but I moved it up one level.

A: Well if you want the router props in AppBar (which is rendered on all pages) then you can just wrap it in a route that matches every path:
<Route path="*" component={AppBar}/>

With the '*' path it will render on every page just as it does now, and being wrapped in the <Route/> then it should have the router props available.


text:
Q: Pass array to method and return the array Here is the question I am working on
Use a for loop to generate an array of ten random integers, all in the range from 100 to 200, inclusive. Use the Arrays class to both sort and display the entire array. Next, pass the array as the sole argument to a method that doubles each element of the array and then returns the array. Use a foreach loop to show all elements in the returned array on one line separated by a single space. This latter loop should also determine the sum of all elements in the returned array. Display the sum with a "thousands" comma as in the sample output.
And here is my code:
package bryant7and8;

import java.util.Arrays;

public static void main(String[] args) {

    int[] myList = new int[10];

        for (int i = 0; i < myList.length; i++) {
            myList[i] = 100 + (int) (Math.random() * ((110 - 10) + 1));

    }
    Arrays.sort(myList);
    System.out.println(Arrays.toString(myList));

    doubleArray (myList);
    System.out.println(doubleArray(myList));
}

public static int[] doubleArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
        array[i] *= 2;
    }

    return array;
}

}
I cannot figure out how to pass the array, I have been at it for a few hours and my books explanation is not helping. Also I apologize for such horrible question formatting I'm still new to stackoverflow.

A: void doubleArray(int[] values){
    //change the value array, with doubling logic

}

Since arrays are passed by reference, the passed array will be changed. There is no need to return it.

A: You should write a method like this:
public static int[] doubleArray (int[] array) {
    //double the array... I think you know how to do this part.
    return array;
}

Now lets say you have an array called myArray and you can pass it into the method like this:
doubleArray (myArray);

And then the elements in myArray will be doubled. You can also use the return value of the method for some other uses.
Alternatively, you can return another brand new array:
public static int[] doubleArray (int[] array) {
    int[] newArray = new int[array.length];
    //put all the stuff in "array" in "newArray"
    //double the new array... I think you know how to do this part.
    return newArray;
}

Then when you called the method, the argument passed in will not be changed. But the return value has the doubled array.

A: You just need a method that takes an array as an argument, modifies that array, then returns the same array.
private int[] doubleArray(int[] arr) {

    for (int i = 0; i < arr.length; i++) {
        arr[i] *= 2;
    }

    return arr;
}

EDIT: As pointed out by other answers, you don't need to return the array.  You're modifying the original array anyway, so any changes you make will persist outside of this method's scope.

A: Just simply create a static method(as you will be calling it from static main() method), pass your array as an argument to it. Make some modifications to it.
public static void doubleTheArrayElements(myList){
//put your logic here
}

In your main method call it: doubleTheArrayElements(myList)
No need to return the array as in Java arguments are passed by reference.

A: You'd better have faith that java is passed by value. For more details ,refer to Is Java "pass-by-reference" or "pass-by-value"?
The entire code is like below, and just for your information. After calling public static int[] notByReference(int[] arr) method, myList doesn't point to the new object. Instead, the copied variable has been assigned a new reference to the new object.
import java.util.Arrays;

public class ArrayTenRandom {

    public static void main(String[] args) {

        int[] myList = new int[10];

        for (int i = 0; i < myList.length; i++) {
            myList[i] = 100 + (int) (Math.random() * ((110 - 10) + 1));

        }
        Arrays.sort(myList);
        System.out.println(Arrays.toString(myList));
        doubleArray(myList);
        System.out.println(Arrays.toString(myList));
        notByReference(myList);
        System.out.println(Arrays.toString(myList));

    }

    public static void doubleArray(int[] arr){
        for(int i = 0; i < arr.length; i++){
            arr[i] = arr[i] * 2;
        }
    }

    public static int[] notByReference(int[] arr){
        arr = new int[2];
        System.out.println(Arrays.toString(arr));
        return arr;
    }
}


text:
Q: Pymongo error connecting to mongodb via atlas I am trying to establish a connection to my mongodb database via atlas and pymongo. I am connecting my application using the connection string given from atlas page, and everything seems to be working fine. I can connect to my database but then I get an error message when I try to count how many entries are in my database/retrieve/send data to atlas.
import pymongo
import dns

client = pymongo.MongoClient("mongodb+srv://username:<password>@storedinputs-vc4cl.mongodb.net/test?retryWrites=true")
db = client.get_database("dbname")
records = db.collectiontable

count = records.count_documents({})
print(count)

Then I get the following error:
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issue
r certificate (_ssl.c:1056),storedinputs-shard-00-00-vc4cl.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] cer
tificate verify failed: unable to get local issuer certificate (_ssl.c:1056)

Again I've tried it line by line and everything works fine until I try and count the amount of documents in my collection. I appreciate all the help I can get.

A: Try with
client = pymongo.MongoClient("mongodb+srv://username:<password>@storedinputs-vc4cl.mongodb.net/test", ssl=True,ssl_cert_reqs='CERT_NONE')

It should work.

A: Just add '&ssl=true&ssl_cert_reqs=CERT_NONE' to the db string and it will work fine !

A: Take a look at the troubleshooting section in PyMongo documentation, it covers the issue you are experiencing together with possible solutions.


text:
Q: Unable to perform work on the background thread So, I'm following this tutorial to implement a Service in my app. I implemented the Service succesfully. The service is activated and the notification is shown normally. Everything is fine except that I was not able to do work on the background thread. Please see below.
My goal is to set a mock location.
This is my onStartCommand for my Service:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText("hi")
            .setSmallIcon(R.drawable.icon)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);

    //do work on a background thread
    new Thread(new Runnable() {
        @Override
        public void run() {

            startMockLocation(); // doesn't actually mock device's location!
        }
    }).start();

    return START_NOT_STICKY;
}

However, when I do this, it works fine but it's not efficient:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText("hi")
            .setSmallIcon(R.drawable.icon)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);

// works great
timer.schedule(new TimerTask() {
    @Override
    public void run() {

        startMockLocation();
        //other stuff
    }
}, 0, 1000);

    return START_NOT_STICKY;
}

Mock location method:
public void startMockLocation(){ // this code is fine, nothing to fix here, something is wrong with the thread though :(

    FusedLocationProviderClient locationProvider =  new FusedLocationProviderClient(getApplicationContext());
    locationProvider.setMockMode(true);

    Location loc = new Location("gps");

    Location mockLocation = new Location("gps"); // a string
    mockLocation.setLatitude(48.8566);
    mockLocation.setLongitude(2.3522);
    mockLocation.setAltitude(loc.getAltitude());
    mockLocation.setTime(System.currentTimeMillis());

    mockLocation.setAccuracy(1f);
    mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mockLocation.setBearingAccuracyDegrees(0.1f);
        mockLocation.setVerticalAccuracyMeters(0.1f);
        mockLocation.setSpeedAccuracyMetersPerSecond(0.01f);
    }
    locationProvider.setMockLocation(mockLocation);

}

A: If by not being able to do work from background thread you mean that you don't see the effect of startMockLocation(), it depends on if there is any computation that depends on startMockLocation(). If you don't join the thread or block somewhere and wait for your background thread to complete, your main thread might very well run til termination before your background thread finishes its work. That would look like your background thread has not done anything.


text:
Q: Struggled to find a cause of redirecting on the error page while requesting a token from Spring Cloud Authentication Server I've got a problem with a spring cloud auth server. I sent a request from spring cloud gateway service and auth server received and authenticated user but it's redirected me on the error page.
Here is a spring cloud gateway application.yaml file
server:
  port: 9090

spring:
  application:
    name: api-gateway
  jackson:
    deserialization:
      FAIL_ON_IGNORED_PROPERTIES: false
    serialization:
      INDENT_OUTPUT: false
      WRITE_DATES_AS_TIMESTAMPS: false
      WRITE_BIGDECIMAL_AS_PLAIN: true
  security:
    oauth2:
      client:
        registration:
          insta-client-oidc:
            client-id: insta-client
            client-secret: secret
            scope: openid
            authorization-grant-type: authorization_code
            redirect-uri-template: '{baseUrl}/login/oauth2/code/insta-client-oidc'
            client-authentication-method: client_secret_post
            client-name: insta-client-oidc
        provider:
          insta-client-oidc:
            issuer-uri: http://localhost:9000
            token-uri: http://localhost:9000/oauth2/token
            authorization-uri: http://localhost:9000/oauth2/authorize
            user-info-uri: http://localhost:9000/userinfo
            user-name-attribute: user_name
            user-info-authentication-method: form
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: user-service-route
          uri: http://localhost:8080 #${USERS_SERVICE_URL:lb://user-service}
          predicates:
            - Path=/public/v1/users
            - Path=/public/v1/users/{username}
            - Path=/public/v1/users/search
            - Path=/public/v1/users/{username}/followers/**
            - Path=/public/v1/users/{username}/followings/**
            - Path=/public/v1/users/{username}/password
            - Path=/public/v1/users/{username}/photo
            - Path=/public/v1/users/{username}/profile
      default-filters:
        - RemoveRequestHeader=Cookie
        - TokenRelay=

eureka:
  instance:
    instance-id: ${spring.application.name}:${instanceId:${random.value}}
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
    fetch-registry: true
    register-with-eureka: true
    enabled: false

management:
  endpoint:
    gateway:
      enabled: true
  endpoints:
    web:
      exposure:
        include: gateway

logging:
  level:
    com: TRACE
    org: TRACE

Here is a spring authentication server config:
@Configuration
@RequiredArgsConstructor
public class AuthorizationServerConfig {
    private final SecurityProperties securityProperties;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.formLogin(Customizer.withDefaults()).build();
    }

    @Bean
    public SecurityFilterChain nextSecurityFilterChain(HttpSecurity http) throws Exception {
         return http
            .csrf().disable()
            .authorizeRequests(authorizeRequests -> authorizeRequests.anyRequest().authenticated())
            .formLogin(Customizer.withDefaults())
            .build();
}

    @Bean
    static BeanFactoryPostProcessor removeErrorSecurityFilter() {
        return (beanFactory) ->
            ((DefaultListableBeanFactory)beanFactory).removeBeanDefinition("errorPageSecurityInterceptor");
}

    @Bean
    public RegisteredClientRepository registeredClientRepository(PasswordEncoder passwordEncoder) {
    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId(securityProperties.getClientId())
            .clientSecret(passwordEncoder.encode(securityProperties.getClientSecret()))
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
            .redirectUri("http://localhost:9090/login/oauth2/code/insta-client-oidc")
            .redirectUri("http://localhost:9090/authorized")
            .scope(OidcScopes.OPENID)
            .tokenSettings(tokenSettings())

//.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
            .build();

    return new InMemoryRegisteredClientRepository(registeredClient);
}

    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() throws NoSuchAlgorithmException {
        RSAKey rsaKey = generateRsa();
        JWKSet jwkSet = new JWKSet(rsaKey);

        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    private static RSAKey generateRsa() throws NoSuchAlgorithmException {
        KeyPair keyPair = generateRsaKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        return new RSAKey.Builder(publicKey)
            .privateKey(privateKey)
            .keyID(UUID.randomUUID().toString())
            .build();
    }

    private static KeyPair generateRsaKey() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);

        return keyPairGenerator.generateKeyPair();
    }

    @Bean
    public ProviderSettings providerSettings() {
        return ProviderSettings.builder().issuer("http://localhost:9000").build();
    }

    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return context -> {
        Authentication principal = context.getPrincipal();
        if (Objects.equals(context.getTokenType().getValue(), "access_token") && principal instanceof UsernamePasswordAuthenticationToken) {
            Set<String> authorities = principal.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
            context.getClaims().claim("authorities", authorities);
            }
        };
    }

    private TokenSettings tokenSettings() {
        return TokenSettings.builder()
            .accessTokenFormat(OAuth2TokenFormat.SELF_CONTAINED)
            .accessTokenTimeToLive(Duration.ofMinutes(securityProperties.getExpirationTimeInMinutes()))
            .idTokenSignatureAlgorithm(SignatureAlgorithm.RS256)
            .build();
    }
}

Whole project you can find here: https://github.com/ZhenyaShvyrkov/insta-copy
log file you also can find in github repository
Thank you for any help in advance. Have a good one!


text:
Q: How can I calculate how much processing power a piece of javascript code uses? I would like to calculate how much processing power (in percentage, ideally) a certain piece of javascript code code uses. What are some known approaches I can use to calculate this?

A: You can visualise the CPU performance using Google Chrome Devl Tools
https://developers.google.com/web/tools/chrome-devtools/profile/rendering-tools/js-execution?hl=en