Q: Open documents(pdf,doc,docx,txt) in browser page using php (without using google docs viewer) My question is that i want to open documents(pdf,doc,docx,txt) in browser page using php (without using google docs viewer) can any one help me?

A: Some of these are doable.  Some, not so much.  Let's tackle the low-hanging fruit first.
Text files
You can just wrap the content in <pre> tags after running it through htmlspecialchars.
PDF
There is no native way for PHP to turn a PDF document into HTML and images.  Your best bet is probably ImageMagick, a common image manipulation program.  You can basically call convert file.pdf file.png and it will convert the PDF file into a PNG image that you can then serve to the user.  ImageMagick is installed on many Linux servers.  If it's not available on your host's machine, please ask them to install it, most quality hosts shouldn't have a problem with this.
DOC & DOCX
We're getting a bit more tricky.  Again, there's no way to do this in pure PHP.  The Docvert extension looks like a possible choice, though it requires OpenOffice be installed as well.  I was actually going to recommend plain vanilla OpenOffice/LibreOffice as well, because it can do the job directly from the command line.  It's very unlikely that a shared host will want to install this.  You'll probably need your own dedicated or virtual private server.
In the end, while these options can be made to work, the output quality is not guaranteeable.  Overall, this is kind of a bad idea that you should not seriously consider implementing.

A: I am sure libraries and such exist that can do this. Google could probably help you there more than I can.
For txt files I would suggest breaking lines after a certain number of characters and putting them inside pre tags.
I know people will not be happy about this response, but if you are on a Linux environment and have pdf2html installed you could use shell_exec and call pdf2html.
Note: If you use shell_exec be wary of what you pass to it since it will be executed on the server outside of PHP.

A: I thought I'd just add that pdfs generally view well in a simple embed tag.
Or use an object so you can have fall backs if it cannot be displayed on the client.


Q: How to process an array of task asynchronously with swift combine I have a publisher which takes a network call and returns an array of IDs. I now need to call another network call for each ID to get all my data. And I want the final publisher to have the resulting object.
First network result:
"user": {
   "id": 0,
   "items": [1, 2, 3, 4, 5]
}

Final object:
struct User {
    let id: Int
    let items: [Item]
    ... other fields ...
}
struct Item {
    let id: Int
    ... other fields ...
}

Handling multiple network calls:
userPublisher.flatMap { user in
    let itemIDs = user.items
    return Future<[Item], Never>() { fulfill in
        ... OperationQueue of network requests ...
    }
}

I would like to perform the network requests in parallel, since they are not dependent on each other. I'm not sure if Future is right here, but I'd imagine I would then have code to do a
DispatchGroup or OperationQueue and fulfill when they're all done. Is there more of a Combine way of doing this?
Doe Combine have a concept of splitting one stream into many parallel streams and joining the streams together?

A: Combine offers extensions around URLSession to handle network requests unless you really need to integrate with OperationQueue based networking, then Future is a fine candidate. You can run multiple Futures and collect them at some point, but I'd really suggest looking at URLSession extensions for Combine.
struct User: Codable {
   var username: String
}

let requestURL = URL(string: "https://example.com/")!
let publisher = URLSession.shared.dataTaskPublisher(for: requestURL)
    .map { $0.data }
    .decode(type: User.self, decoder: JSONDecoder())

Regarding running a batch of requests, it's possible to use Publishers.MergeMany, i.e:
struct User: Codable {
   var username: String
}

let userIds = [1, 2, 3]

let subscriber = Just(userIds)
    .setFailureType(to: Error.self)
    .flatMap { (values) -> Publishers.MergeMany<AnyPublisher<User, Error>> in
    let tasks = values.map { (userId) -> AnyPublisher<User, Error> in
            let requestURL = URL(string: "https://jsonplaceholder.typicode.com/users/\(userId)")!

            return URLSession.shared.dataTaskPublisher(for: requestURL)
                .map { $0.data }
                .decode(type: User.self, decoder: JSONDecoder())
                .eraseToAnyPublisher()
    }
    return Publishers.MergeMany(tasks)
}.collect().sink(receiveCompletion: { (completion) in
    if case .failure(let error) = completion {
        print("Got error: \(error.localizedDescription)")
    }
}) { (allUsers) in
    print("Got users:")
    allUsers.map { print("\($0)") }
}

In the example above I use collect to collect all results, which postpones emitting the value to the Sink until all of the network requests successfully finished, however you can get rid of the collect and receive each User in the example above one by one as network requests complete.


Q: Use binding file to set the package on a namespace? I'm working on two large 3rd party schemas, one includes the other and generates a large number of type name collisions. If I could set the package on a namespace this problem would go away.
I hoped something like
<jaxb:bindings namespace="http://www.openapplications.org/oagis/9" >
    <jaxb:schemaBindings>
        <jaxb:package name="org.oagis" />
    </jaxb:schemaBindings>
</jaxb:bindings>

would work, or perhaps
<jaxb:bindings node="/xsd:schema[@targetNamespace='http://www.openapplications.org/oagis/9']">
    <jaxb:schemaBindings>
        <jaxb:package name="org.oagis" />
    </jaxb:schemaBindings>
</jaxb:bindings>

But no joy.
Trying to set on the individual xsd files in that namespace left me with the dread
[ERROR] Multiple <schemaBindings> are defined for the target namespace "http://www.openapplications.org/oagis/9"

Pointers/suggestions are appreciated.

A: This is a bit hard to answer without seeing the whole compilation. However I often got this error when compiling third-party schemas in the case when the same schema was included via different URLs.
I.e. I've implemented a project which compiled an extensive set of OGC Schemas. The problem was that these schemas referenced each other via relative and absolute URLs. So when I customized one of the schemas there were other schemas for the same namespace URI. Since JAXB processes imports and includes, it is not quite transparent what exactly gets compiled. Try to check your XJC logs for cues or - if you compile schemas directly via URLs (which is not recommended) - go through a logging proxy and see what actually gets accessed.


Q: Does Kafka broker server take into account updates to it's configuration file? Does Kafka broker server take into account updates to it's configuration file?
Its cumbersome having to restart all the servers in the cluster simply to update a configuration.

A: No, it's currently not possible to do dynamic configuration updates.
There's a Jira ticket for that exact issue here, and the accompanying KIP (Kafka Improvement Proposal).


Q: In what circumstances is uri passed to Android's ContentObserver.onChange() callback? The onChange() method of Android's ContentObserver class says, "Includes the changed content Uri when available." In what circumstances is the URI available? In what circumstances is it not available?
The uri parameter was added in API level 16 (Android 4.1) and so I would expect it to be set in Android 4.1 and newer. However I'm seeing a case on Android 4.3 where uri is not set.
Method 1: Works
MyContentObserver.onChange() is called and is passed a valid uri:
contentResolver.registerContentObserver(myUri, true, new MyContentObserver());

Method 2: Doesn't work--why not?
MyContentObserver.onChange() is called but the uri parameter is null:
contentResolver.query();
cursor.registerContentObserver(new MyContentObserver);

Is this expected? Is one of these preferred over the other? I've tested this using "content://com.google.android.gm/me@example.com/labels" and using my own custom ContentProvider.

A: This is an old question, but still unanswered. So I will add my answer in case people is still curious about it.
When your content provider notifies the registered observer using getContext().getContentResolver().notifyChange(URI, "your_uri");, it asks the ContentResponder for it. The return value from that method is the ContentObserver that you registered with the registerContentObserver() method of the content responder, which is what you did in the first case. However, in the second case, you registered the observer in the Cursor using the registerContentObserver() method of the Cursor, so the ContentResponder doesn't know about it.

A: If you are setting ContentObserver upon common tables(e.g people, mediaprovider etc) then unfortunately you might not receive any Uri as an argument, it might be blank as it depends upon underneath content provider implementation. To receive an valid Uri upon change, respective ContentProvider has to be modified to notify change along with URI.
e.g getContext().getContentResolver().notifyChange(Uri, "your_uri"); // this notifies all the  registered ContentObserver with Uri of modified concerned dataset.
If you are writing your own ContentProvider then use above mentioned line whenever you perform update, delete or insert operation on your database.


Q: Swift tableView with 3 Prototype Cells and auto-height I have a concept which I want to realize in Xcode. Its a default  TableViewController with 3 Prototype cells.
Cell 1 = name (Prototype Pages)
Cell 2 = seperator (Prototype Seperator)
Cell 3 = only ImageView (Prototype Seperator-with-only-image)

Cell 1 and cell 2 is OK. I need to set the height of all "Prototype Seperator-with-only-image" cells to auto. The height should be calculated based on added image dimensions.
Here my mockup

Addional info: The "Prototype Seperator-with-only-image" can occur multiple times and the dimensions of the images can vary.
Any ideas how I can achieve this?

A: You can set the tableview's rowHeight equal to UITableViewAutomaticDimension in your viewDidLoad method:
    self.yourTableView.rowHeight = UITableViewAutomaticDimension
    self.yourTableView.estimatedRowHeight = 42.0

Here you are telling your tableview to calculate the dimension of the row.
Then you are saying that you estimate that the row will have a height of 42, basically setting a minimum height.
I think this is a great example using a demo app.


Q: Storing Multiple Changes in Entity Framework I'm trying to achieve a form of two phase commit  using Entity Framework 1.0.
What I would like to achieve at a high level is:

*

*get all the data from the database and store this in a cache.

*modify individual entities

*Commit all changes into the database

The problem's i've encountered so far is that caching an IQueryable is a bit pointless as it's going to go back to the database regardless. So the other option is to use IEnumberable for storing the results of a query, but that stops me inheriting one query and refining it into another (I can live with that however). The other problem is that as soon as the EntityContext expires (which i've managed to persist in the current httprequest) that's it, no changes can be tracked.
Has anyone tried to do something similar to this in the past or got any pointers?
Many thanks,
Matt
jumpingmattflash.co.uk

A: The IQueryable is just that a queryable object not the actual data.
You need to run the ToList to get the data out.
You can do what you are trying to do if you can keep the Context open and use transactionscope. In most cases however this is not possible. This would also lock the database leading to other probelms.
A better way to do it would be:

*

*Read the data from the database

*Dispose of the context

*Client makes any changes needed

*Open new context

*Read the data again.

*make changes by copying data from changed data to second set

*commit the changes

*dispose of the context

A: Call .ToList() on your IQueryable results from the database. To then start refining into other queries use .AsQueryable(). This should solve your first problem.
As for your second problem, I'm also searching for a solution. As I understand the underlying implementation of the relationship parts of Entity Framework revolves around the ObjectStateManager in the System.Data.Objects namespace of the System.Data.Entity assembly. This in turn uses the MetadataWorkspace class in the System.Data.Metadata.Edm namespace to lookup the relationship mappings. These might be able to be used without an underlying database connection, and if so, would provide some very groovy tools to update complex object graphs.
It would be nice if the context had a Detach and Attach in a similar way to individual Entities. It looks like the next version of the Entity Framework is going to focus on these specific type of issues; more freedom when dealing with Entities and Contexts.


Q: How to unit test HttpClient GetAsync I have the following in my controller:
public async Task<IActionResult> IndexAsync()
{
    string baseUrl = "https://apilink.com";

    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync(baseUrl))
    using (HttpContent content = response.Content)
    {
        string data = await content.ReadAsStringAsync();
        if (data != null)
        {
            var recipeList = JsonConvert.DeserializeObject<Recipe[]>(data);
            return View();
        }
    }

    return View();
}

I want to unit test this but cannot work out how to test the HttpClient.
I have tried:
[Test]
public void Index_OnPageLoad_AllRecipesLoaded()
{
    var testController = new HomeController();
    mockHttpClient.Setup(m => m.GetAsync(It.IsAny<string>())).Returns(
        () => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
    mockHttpContent.Setup(m => m.ReadAsStringAsync()).Returns(() => Task.FromResult(LoadJson()));
    var result = testController.IndexAsync();
    Assert.IsNotNull(result);
}

// Loads the Json data as I don't actually want to make the API call in the test.
public string LoadJson()
{
    using (StreamReader r = new StreamReader("testJsonData.json"))
    {
        string json = r.ReadToEnd();
        return json;
    }
}

Is there a way to mock this effectively/simply? Or should I maybe inject my own IHttpClient interface? (I am not sure if that is good practice?)
Thanks

A: There are several ways to unit test HttpClient, but none are straightforward because HttpClient does not implement a straightforward abstraction.
1) Write an abstraction
Here is a straightforward abstraction and you can use this instead of HttpClient. This is my recommended approach. You can inject this into your services and mock the abstraction with Moq as you have done above.
public interface IClient
{
    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns>The response as the strong type specified by TResponseBody /></returns>
    /// <typeparam name="TRequestBody"></typeparam>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(IRequest<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    AbsoluteUrl BaseUri { get; }
}

Full code reference here. The Client class implements the abstraction.
2) Create a Fake Http Server and Verify the Calls on the Server-Side
This code sets up a fake server, and your tests can verify the Http calls.
    using var server = ServerExtensions
        .GetLocalhostAddress()
        .GetSingleRequestServer(async (context) =>
    {
Assert.AreEqual("seg1/", context?.Request?.Url?.Segments?[1]);
Assert.AreEqual("seg2", context?.Request?.Url?.Segments?[2]);
Assert.AreEqual("?Id=1", context?.Request?.Url?.Query);
Assert.AreEqual(headerValue, context?.Request?.Headers[headerKey]);

if (hasRequestBody)
{
    var length = context?.Request?.ContentLength64;
    if (!length.HasValue) throw new InvalidOperationException();
    var buffer = new byte[length.Value];
    _ = (context?.Request?.InputStream.ReadAsync(buffer, 0, (int)length.Value));
    Assert.AreEqual(requestJson, Encoding.UTF8.GetString(buffer));
}

if (context == null) throw new InvalidOperationException();

await context.WriteContentAndCloseAsync(responseJson).ConfigureAwait(false);
});

Full code reference here.
3) Mock the HttpHandler
You can inject a Mock HttpHandler into the HttpClient. Here is an example:
private static void GetHttpClientMoq(out Mock<HttpMessageHandler> handlerMock, out HttpClient httpClient, HttpResponseMessage value)
{
    handlerMock = new Mock<HttpMessageHandler>();

    handlerMock
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
    "SendAsync",
    ItExpr.IsAny<HttpRequestMessage>(),
    ItExpr.IsAny<CancellationToken>())
    .ReturnsAsync(value)
    .Verifiable();

    httpClient = new HttpClient(handlerMock.Object);
}

Full code reference. You can then verify the calls from the mock itself.


Q: Can't Print the RDLC report when I deploy onto another computer? When i run this on VS it works fine but when i run it on another computer it cant find the RDLC path.
  private void button1_Click(object sender, EventArgs e)
    {
        LocalReport localReport = new LocalReport();
        ReportParameterCollection reportParameters = new ReportParameterCollection();
        reportParameters.Add(new ReportParameter("Pallet_label", lb_pallet_name.Text));
        reportParameters.Add(new ReportParameter("Par_PalNum", LB_Number.Text));

        localReport.ReportPath = Application.StartupPath + "\\pallet_label.rdlc";

        localReport.SetParameters(reportParameters);

        localReport.PrintToPrinter();

       }


Q: upload_err_partial error when uploading files of size greater than 3GB I want to upload upto 10GB files using a normal php form. But even after increasing the below values,
upload_max_filesize
post_max_size
php_value upload_max_filesize
php_value post_max_size
request_terminate_timeout
FcgidMaxRequestLen

am able to upload a file upto 3.5gb without any problem. But above that am getting an error as "upload_err_partial". I also reffered a lot of site but the answer I thought releavant was adding "header(connection:close)". I added the line but still I did not get any result. Could anyone guide me in this.

A: This error usually means that the uploading is cancelled by the user , and some times it can be server problem also which can cause this. Try to contact to your hosting provider and see what can he do


Q: How to calculate averages for a 3D matrix for the same day of data over multiple years in Matlab? I am interested in calculating GPH anomalies in Matlab. I have a 3D matrix of lat, lon, and data. Where the data (3rd dimension) is a daily GPH value spaced in one-day increments for 32 years (from Jan. 1st 1979 to Jan. 1st 2011). The matrix is 95x38x11689. How do I compute a daily average across all years for each day of data, when the matrix is 3D?
In other words, how do I compute the average of Jan. 1st dates for all years to compute the climatological mean of all Jan. 1st's from 1979-2010 (where I don't have time information, but a GPH value for each day)? And so forth for each day after. The data also includes leap years. How do I handle that?
Example: Sort, and average all Jan. 1st GPH values for indices 1, 365, 730, etc. And for each day of all years after that in the same manner.

A: First let's take out all the Feb 29th, because these days are in the middle of the data and not appear in every year, and will bother the averaging:
Feb29=60+365*[1:4:32];
mean_Feb29=mean(GPH(:,:,Feb29),3);    % A matrix of 95x38 with the mean of all February 29th

GPH(:,:,Feb29)=[];           % omit Feb 29th from the data
Last_Jan_1=GPH(:,:,end);     % for Jan 1st you have additional data set, of year 2011
GPH(:,:,end)=[];            % omit Jan 1st 2011

re_GPH=reshape(GPH,95,38,365,[]);
av_GPH=mean(re_GPH,4);

Now re_GPH is a matrix of 95x38x365, where each slice in 3rd dimension is an average of a day in the year, starting Jan 1st, etc.
If you want the to include the last Jan 1st (Jen 1st 2011), run this line at after the previous code:
av_GPH(:,:,1)=mean(cat(3,av_GPH(:,:,1),Last_Jan_1),3);

For the ease of knowing which slice nubmer corresponds to each date, you can make an array of all the dates in the year:
t1 = datetime(2011,1,1,'format','MMMMd')
t2 = datetime(2011,12,31,'format','MMMMd')
t3=t1:t2;

Now, for example :
t3(156)=

  datetime

   June5

So av_GPH(:,:,156) is the average of June 5th.

For your comment, if you want to subtract each day from its average:
sub_GPH=GPH-repmat(av_GPH,1,1,32);

And for February 29th, you will need to do that BEFORE you erase them from the data (line 3 up there):
sub_GPH_Feb_29=GPH(:,:,Feb29)-repmat(mean_Feb29,1,1,8);


Q: PHP+Ubuntu Send email using gmail form localhost I have searched several posts on this but no luck. Everyone is using postfix. But when I gone through the text on
https://help.ubuntu.com/community/Postfix

What is a Mail Transfer Agent
  In other words, it's a mail server not a
  mail client like Thunderbird, Evolution, Outlook, Eudora, or a
  web-based email service like Yahoo, GMail, Hotmail, Earthlink,
  Comcast, SBCGlobal.net, ATT.net etc.... If you worked for a company
  named Acme and owned acme.com, you could provide your employees with
  email addresses @acme.com. Employees could send and receive email
  through your computer, but not without your computer running all the
  time. If all your email addresses are at a domain (@gmail.com,
  @yahoo.com) you do not own (you don't own Google) or do not host
  (acme.com) then you do not need this at all.

As the last line says You cannot us it for gmail or yahoo to make it work from localhost..!
Can anyone tell me how can I configure mail server on localhost using gmail SMTP? I am using Ubuntu 14.
Links I have tried before NONE of them worked for me. No error or warnings during testing of below listed links
https://askubuntu.com/questions/314664/sending-php-mail-from-localhost
https://askubuntu.com/questions/228938/how-can-i-configure-postfix-to-send-all-email-through-my-gmail-account
https://easyengine.io/tutorials/linux/ubuntu-postfix-gmail-smtp/
https://easyengine.io/tutorials/mail/postfix-debugging/

A: Please do following steps to send mail from localhost on Ubuntu/Linux through gmail :-
For that you need to install msmtp on Linux/Ubuntu server.
Gmail uses https:// (it's hyper text secure) so you need install ca-certificates
~$ sudo apt-get install msmtp ca-certificates

It will take few seconds to install msmtp package.
Now you have to create configuration file(msmtprc) using , gedit editor.
~$ sudo gedit /etc/msmtprc

Now you have to copy and paste following code in gedit (file you created with above command)
defaults
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

account default
host smtp.gmail.com
port 587
auth on
user MY_GMAIL_ID@gmail.com
password MY_GMAIL_PASSSWORD
from MY_GMAIL_ID@gmail.com
logfile /var/log/msmtp.log

Don't forget to replace MY_GMAIL_ID with your "gmail id" and MY_GMAIL_PASSSWORD with your "gmail password" in above lines of code.
Now create msmtp.log as
~$ sudo touch /var/log/msmtp.log

You have to make this file readable by anyone with
~$ sudo chmod 0644 /etc/msmtprc

Now Enable sendmail log file as writable with
~$ sudo chmod 0777 /var/log/msmtp.log

Your configuration for gmail's SMTP is now ready. Now send one test email as
~$ echo -e "Subject: Test Mail\r\n\r\nThis is my first test email." |msmtp --debug --from=default -t MY_GMAIL_ID@gmail.com

Please check your Gmail inbox.

Now if you want to send email with php from localhost please follow below instructions:-
Open and edit php.ini file
~$ sudo gedit /etc/php/7.0/apache2/php.ini

You have to set sendmail_path in your php.ini file.
Check your SMTP path with
~$ which msmtp

and you will get /usr/bin/msmtp like that.
Search sendmail_path in php.ini and edit as below
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = /usr/bin/msmtp -t

Please check 3rd line carefully there is no semicolon before sendmail_path.
Now save and exit from gedit. Now it's time to restart your apache
~$ sudo /etc/init.d/apache2 restart

Now create one php file with mail function from http://in2.php.net/manual/en/function.mail.php.
Do test and enjoy !!

A: This article explains exactly how to do what you want:
https://www.howtoforge.com/tutorial/configure-postfix-to-use-gmail-as-a-mail-relay/


Q: Filters with dynamic fields in elasticsearch I am switching a very old version of ElasticSearch to version 6.5.
...
  "text_mined_entities": {
            "nlp": {
                "abbreviations": [],
                "chunks": [],
                "recurring_chunks": [],
                "tagged_entities_grouped": {
                    "NEURO|SCICRUNCH": [
                        {
                            "category": "NEURO",
                            "end": 41,
                            "label": "Infant",
                            "match": "infant",
                            "original_value": "Infant",
                            "reference": "BIRNLEX695",
                            "reference_db": "SCICRUNCH",
                            "sentence": 0,
                            "start": 35
                        },
...

I am wanting to filter on the text_mined_entities.nlp.tagged_entities_grouped.*.reference fields ( which are stored as 'keyword' ), but haven't had much luck. Something like:
GET _search
{
  "query": {
    "bool": {
      "filter": { "term": {
        "text_mined_entities.nlp.tagged_entities_grouped.*.reference": "BIRNLEX695"

      }}

    }
  }
}

Any suggestions? Thanks.

A: Wildcard on fields can't be applied on term query. Instead you can use query_string which supports wildcard on field as well. So following will work:
Assuming text_mined_entities and nlp are of type nested
{
  "query": {
    "nested": {
      "path": "text_mined_entities.nlp",
      "query": {
        "query_string": {
          "query": "BIRNLEX695",
          "fields": [
            "text_mined_entities.nlp.tagged_entities_grouped.*.reference"
          ]
        }
      }
    }
  }
}

Update (if text_mined_entities & nlp are object type and not nested):
{
  "query": {
    "query_string": {
      "query": "BIRNLEX695",
      "fields": [
        "text_mined_entities.nlp.tagged_entities_grouped.*.reference"
      ]
    }
  }
}


Q: Make the animation faster when there are thousands of components I am trying to hide a JSplitPane with animation. By hide, I mean to setDividerLocation(0) so its left component is invisible (technically it is visible, but with zero width):
public class SplitPaneTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel(new BorderLayout());

            leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));

            JPanel rightPanel = new JPanel(new GridLayout(60, 60));
            for (int i = 0; i < 60 * 60; i++) {
//              rightPanel.add(new JLabel("s"));
            }
            rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));

            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
            frame.add(splitPane);

            JButton button = new JButton("Press me to hide");
            button.addActionListener(e -> hideWithAnimation(splitPane));
            leftPanel.add(button, BorderLayout.PAGE_START);

            frame.setMaximumSize(new Dimension(800, 800));
            frame.setSize(800, 800);
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        });
    }

    private static void hideWithAnimation(JSplitPane splitPane) {
        final Timer timer = new Timer(10, null);
        timer.addActionListener(e -> {
            splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
            if (splitPane.getDividerLocation() == 0)
                timer.stop();
        });
        timer.start();
    }

}

If you run it, will see that everything seems good, and the animation runs smooth.
However, in the real application the right of the JSplitPane is a JPanel with CardLayout and each card has a lot of components.
If you uncomment this line in order to simulate the number of components:
// rightPanel.add(new JLabel("s"));

and re-run the above example, you will see that the animation no longer runs smoothly. So, the question is, is is possible to make it smooth(-ier)?
I have no idea how to approach a solution - if any exists.
Based on my research, I registered a global ComponentListener:
Toolkit.getDefaultToolkit()
    .addAWTEventListener(System.out::println, AWTEvent.COMPONENT_EVENT_MASK);

and saw the tons of events that are being fired. So, I think the source of the problem is the tons of component events that are being fired for each component. Also, it seems that components with custom renderers (like JList - ListCellRenderer and JTable - TableCellRenderer), component events are firing for all of the renderers. For example, if a JList has 30 elements, 30 events (component) will be fired only for it. It also seems (and that's why I mentioned it) that for CardLayout, events are taking place for the "invisible" components as well.
I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.

A:
I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.

The layout manager is invoked every time the divider location is changed which would add a lot of overhead.
One solution might be to stop invoking the layout manager as the divider is animating. This can be done by overriding the doLayout() method of the right panel:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class SplitPaneTest2 {

        public static boolean doLayout = true;

        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());

                JPanel leftPanel = new JPanel(new BorderLayout());

                leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));

                JPanel rightPanel = new JPanel(new GridLayout(60, 60))
                {
                    @Override
                    public void doLayout()
                    {
                        if (SplitPaneTest2.doLayout)
                            super.doLayout();
                    }
                };
                for (int i = 0; i < 60 * 60; i++) {
                  rightPanel.add(new JLabel("s"));
                }
                rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));

                JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
                frame.add(splitPane);

                JButton button = new JButton("Press me to hide");
                button.addActionListener(e -> hideWithAnimation(splitPane));
                leftPanel.add(button, BorderLayout.PAGE_START);

                frame.setMaximumSize(new Dimension(800, 800));
                frame.setSize(800, 800);
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            });
        }

        private static void hideWithAnimation(JSplitPane splitPane) {
            SplitPaneTest2.doLayout = false;
            final Timer timer = new Timer(10, null);
            timer.addActionListener(e -> {
                splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
                if (splitPane.getDividerLocation() == 0)
                {
                    timer.stop();
                    SplitPaneTest2.doLayout = true;
                    splitPane.getRightComponent().revalidate();
                }
            });
            timer.start();
        }

    }

Edit:
I was not going to include my test on swapping out the panel full of components with a panel that uses an image of components since I fell the animation is the same, but since it was suggested by someone else here is my attempt for your evaluation:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;

public class SplitPaneTest2 {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel(new BorderLayout());

            leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));

            JPanel rightPanel = new JPanel(new GridLayout(60, 60));
            for (int i = 0; i < 60 * 60; i++) {
              rightPanel.add(new JLabel("s"));
            }
            rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));

            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
            frame.add(splitPane);

            JButton button = new JButton("Press me to hide");
            button.addActionListener(e -> hideWithAnimation(splitPane));
            leftPanel.add(button, BorderLayout.PAGE_START);

            frame.setMaximumSize(new Dimension(800, 800));
            frame.setSize(800, 800);
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        });
    }

    private static void hideWithAnimation(JSplitPane splitPane) {

        Component right = splitPane.getRightComponent();
        Dimension size = right.getSize();

        BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bi.createGraphics();
        right.paint( g );
        g.dispose();

        JLabel label = new JLabel( new ImageIcon( bi ) );
        label.setHorizontalAlignment(JLabel.LEFT);

        splitPane.setRightComponent( label );
        splitPane.setDividerLocation( splitPane.getDividerLocation() );

        final Timer timer = new Timer(10, null);
        timer.addActionListener(e -> {

            splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
            if (splitPane.getDividerLocation() == 0)
            {
                timer.stop();
                splitPane.setRightComponent( right );
            }
        });
        timer.start();
    }

}

A: @GeorgeZ. I think the concept presented by @camickr has to do with when you actually do the layout. As an alternative to overriding doLayout, I would suggest subclassing the GridLayout to only lay out the components at the end of the animation (without overriding doLayout). But this is the same concept as camickr's.
Although if the contents of your components in the right panel (ie the text of the labels) remain unchanged during the animation of the divider, you can also create an Image of the right panel when the user clicks the button and display that instead of the actual panel. This solution, I would imagine, involves:

*

*A CardLayout for the right panel. One card has the actual rightPanel contents (ie the JLabels). The second card has only one JLabel which will be loaded with the Image (as an ImageIcon) of the first card.

*As far as I know, by looking at the CardLayout's implementation, the bounds of all the child components of the Container are set during layoutContainer method. That would probably mean that the labels would be layed out inspite being invisible while the second card would be shown. So you should probably combine this with the subclassed GridLayout to lay out only at the end of the animation.

*To draw the Image of the first card, one should first create a BufferedImage, then createGraphics on it, then call rightPanel.paint on the created Graphics2D object and finally dispose the Graphics2D object after that.

*Create the second card such that the JLabel would be centered in it. To do this, you just have to provide the second card with a GridBagLayout and add only one Component in it (the JLabel) which should be the only. GridBagLayout always centers the contents.

Let me know if such a solution could be useful for you. It might not be useful because you could maybe want to actually see the labels change their lay out profile while the animation is in progress, or you may even want the user to be able to interact with the Components of the rightPanel while the animation is in progress. In both cases, taking a picture of the rightPanel and displaying it instead of the real labels while the animation takes place, should not suffice. So it really depends, in this case, on how dynamic will be the content of the rightPanel. Please let me know in the comments.
If the contents are always the same for every program run, then you could probably pre-create that Image and store it. Or even, a multitude of Images and store them and just display them one after another when the animation turns on.
Similarly, if the contents are not always the same for every program run, then you could also subclass GridLayout and precalculate the bounds of each component at startup. Then that would make GridLayout a bit faster in laying out the components (it would be like encoding a video with the location of each object), but as I am testing it, GridLayout is already fast: it just calculates about 10 variables at the start of laying out, and then imediately passes over to setting the bounds of each Component.
Edit 1:
And here is my attempt of my idea (with the Image):
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class SplitPaneTest {

    //Just a Timer which plays the animation of the split pane's divider going from side to side...
    public static class SplitPaneAnimationTimer extends Timer {
        private final JSplitPane splitPane;
        private int speed, newDivLoc;
        private IntBinaryOperator directionf;
        private Consumer<SplitPaneAnimationTimer> onFinish;

        public SplitPaneAnimationTimer(final int delay, final JSplitPane splitPane) {
            super(delay, null);
            this.splitPane = Objects.requireNonNull(splitPane);
            super.setRepeats(true);
            super.setCoalesce(false);
            super.addActionListener(e -> {
                splitPane.setDividerLocation(directionf.applyAsInt(newDivLoc, splitPane.getDividerLocation() + speed));
                if (newDivLoc == splitPane.getDividerLocation()) {
                    stop();
                    if (onFinish != null)
                        onFinish.accept(this);
                }
            });
            speed = 0;
            newDivLoc = 0;
            directionf = null;
            onFinish = null;
        }

        public int getSpeed() {
            return speed;
        }

        public JSplitPane getSplitPane() {
            return splitPane;
        }

        public void play(final int newDividerLocation, final int speed, final IntBinaryOperator directionf, final Consumer<SplitPaneAnimationTimer> onFinish) {
            if (newDividerLocation != splitPane.getDividerLocation() && Math.signum(speed) != Math.signum(newDividerLocation - splitPane.getDividerLocation()))
                throw new IllegalArgumentException("Speed needs to be in the direction towards the newDividerLocation (from the current position).");
            this.directionf = Objects.requireNonNull(directionf);
            newDivLoc = newDividerLocation;
            this.speed = speed;
            this.onFinish = onFinish;
            restart();
        }
    }

    //Just a GridLayout subclassed to only allow laying out the components only if it is enabled.
    public static class ToggleGridLayout extends GridLayout {
        private boolean enabled;

        public ToggleGridLayout(final int rows, final int cols) {
            super(rows, cols);
            enabled = true;
        }

        @Override
        public void layoutContainer(final Container parent) {
            if (enabled)
                super.layoutContainer(parent);
        }

        public void setEnabled(final boolean enabled) {
            this.enabled = enabled;
        }
    }

    //How to create a BufferedImage (instead of using the constructor):
    private static BufferedImage createBufferedImage(final int width, final int height, final boolean transparent) {
        final GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
        final GraphicsDevice gdev = genv.getDefaultScreenDevice();
        final GraphicsConfiguration gcnf = gdev.getDefaultConfiguration();
        return transparent
               ? gcnf.createCompatibleImage(width, height, Transparency.TRANSLUCENT)
               : gcnf.createCompatibleImage(width, height);
    }

    //This is the right panel... It is composed by two cards: one for the labels and one for the image.
    public static class RightPanel extends JPanel {
        private static final String CARD_IMAGE = "IMAGE",
                                    CARD_LABELS = "LABELS";

        private final JPanel labels, imagePanel; //The two cards.
        private final JLabel imageLabel; //The label in the second card.
        private final int speed; //The speed to animate the motion of the divider.
        private final SplitPaneAnimationTimer spat; //The Timer which animates the motion of the divider.
        private String currentCard; //Which card are we currently showing?...

        public RightPanel(final JSplitPane splitPane, final int delay, final int speed, final int rows, final int cols) {
            super(new CardLayout());
            super.setBorder(BorderFactory.createLineBorder(Color.red));

            spat = new SplitPaneAnimationTimer(delay, splitPane);
            this.speed = Math.abs(speed); //We only need a positive (absolute) value.

            //Label and panel of second card:
            imageLabel = new JLabel();
            imageLabel.setHorizontalAlignment(JLabel.CENTER);
            imageLabel.setVerticalAlignment(JLabel.CENTER);
            imagePanel = new JPanel(new GridBagLayout());
            imagePanel.add(imageLabel);

            //First card:
            labels = new JPanel(new ToggleGridLayout(rows, cols));
            for (int i = 0; i < rows * cols; ++i)
                labels.add(new JLabel("|"));

            //Adding cards...
            final CardLayout clay = (CardLayout) super.getLayout();
            super.add(imagePanel, CARD_IMAGE);
            super.add(labels, CARD_LABELS);
            clay.show(this, currentCard = CARD_LABELS);
        }

        //Will flip the cards.
        private void flip() {
            final CardLayout clay = (CardLayout) getLayout();
            final ToggleGridLayout labelsLayout = (ToggleGridLayout) labels.getLayout();
            if (CARD_LABELS.equals(currentCard)) { //If we are showing the labels:

                //Disable the laying out...
                labelsLayout.setEnabled(false);

                //Take a picture of the current panel state:
                final BufferedImage pic = createBufferedImage(labels.getWidth(), labels.getHeight(), true);
                final Graphics2D g2d = pic.createGraphics();
                labels.paint(g2d);
                g2d.dispose();
                imageLabel.setIcon(new ImageIcon(pic));
                imagePanel.revalidate();
                imagePanel.repaint();

                //Flip the cards:
                clay.show(this, currentCard = CARD_IMAGE);
            }
            else { //Else if we are showing the image:

                //Enable the laying out...
                labelsLayout.setEnabled(true);

                //Revalidate and repaint so as to utilize the laying out of the labels...
                labels.revalidate();
                labels.repaint();

                //Flip the cards:
                clay.show(this, currentCard = CARD_LABELS);
            }
        }

        //Called when we need to animate fully left motion (ie until reaching left side):
        public void goLeft() {
            final JSplitPane splitPane = spat.getSplitPane();
            final int currDivLoc = splitPane.getDividerLocation(),
                      minDivLoc = splitPane.getMinimumDividerLocation();
            if (CARD_LABELS.equals(currentCard) && currDivLoc > minDivLoc) { //If the animation is stopped:
                flip(); //Show the image label.
                spat.play(minDivLoc, -speed, Math::max, ignore -> flip()); //Start the animation to the left.
            }
        }

        //Called when we need to animate fully right motion (ie until reaching right side):
        public void goRight() {
            final JSplitPane splitPane = spat.getSplitPane();
            final int currDivLoc = splitPane.getDividerLocation(),
                      maxDivLoc = splitPane.getMaximumDividerLocation();
            if (CARD_LABELS.equals(currentCard) && currDivLoc < maxDivLoc) { //If the animation is stopped:
                flip(); //Show the image label.
                spat.play(maxDivLoc, speed, Math::min, ignore -> flip()); //Start the animation to the right.
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel(new BorderLayout());

            leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));

            int rows, cols;

            rows = cols = 60;

            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

            final RightPanel rightPanel = new RightPanel(splitPane, 10, 3, rows, cols);

            splitPane.setLeftComponent(leftPanel);
            splitPane.setRightComponent(rightPanel);

            JButton left = new JButton("Go left"),
                    right = new JButton("Go right");

            left.addActionListener(e -> rightPanel.goLeft());
            right.addActionListener(e -> rightPanel.goRight());

            final JPanel buttons = new JPanel(new GridLayout(1, 0));
            buttons.add(left);
            buttons.add(right);

            frame.add(splitPane, BorderLayout.CENTER);
            frame.add(buttons, BorderLayout.PAGE_START);
            frame.setSize(1000, 800);
            frame.setMaximumSize(frame.getSize());
            frame.setLocationByPlatform(true);
            frame.setVisible(true);

            splitPane.setDividerLocation(0.5);
        });
    }
}


Q: Django REST Framework: nested serializers and deserializing I'm again stuck with Django REST Framework and its serializers.
Basically, what I want to be able to do is stick the following incoming data into a serializers.Serializer instance:
data = {
    "thing_id": 715,
    "sub_things": [
        {
            "id": 1,
            "name": "bob"
        },

        {
             "id": 2,
             "name": "mike"
        }
    ]
}

sub_things are handled by a serializers.ModelSerializer called SubThingSerializer. This is how it looks like.
class SubThingSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubThing
        fields = ('id', 'name')
        read_only_fields = ('id', 'name')

Serialization of Thing is handled by a ThingSerializer, which I've for now handled as below:
class ThingSerializer(serializers.Serializer):
    thing_id = serializers.IntegerField()
    sub_things= SubThingSerializer(many=True)

Now, when I do
serializer = ThingSerializer(data=data)

I get empty OrderedDicts like:
{'sub_things': [OrderedDict(), OrderedDict()], 'thing_id': 715}

I guess it's wise to say that ThingSerializer will not need to get stored into a database, but it does use sub_things from database. These will not be written into db either. This is just to keep track of what sub_things the thing contains, pass this data back and forth between a browser client and a Python object for some calcualtions. And maybe store it in the session.
edit 1:
Most likely there's something I need to add to the create method of my ThingSerializer. So, I guess the ultimate question is: what's the correct syntax to pass sub_thing data to SubThingSerializers?
edit 2:
I dug a bit more. Seems that empty OrderedDicts get passed in validated_data to ThingSerializer.create() for some reason. Serializer validates alright with serializer.is_valid(). I could access the necessary data from initial_data, but that doesn't seem very solid.
edit 3:
Also tested around with serializers.ListField() for sub_things. Still seeing empty OrderedDicts in validated_data inside the create method.

A: Finally figured this out. read_only_fields on my SubThingSerializer prevented the data from getting through the validation resulting in empty dicts being created. I used read_only_fiels to prevent non-existent sub_thing data from being passed to my code, but I guess I'll need to find another way.


Q: Reading values from a text file to a linked list (no array of structs) to use for a stack; advice? I have a question. I am trying to read integer values from a file into a linked list, which will then be used for push and pop functions. I've done my push and pop functions, but I am trying to figure out if I have done the reading correctly. With my code so far, I used fscanf to read the file and printed it and it's printing all values. When I do my push function, it's not printing that correctly. Any advice on what I may be doing wrong.
4
2
1
6
1
5
2
3
3
1
6
1
\\values to be read from file

code below:
//linked list with place to store values and nodes
struct stack_list {
    int list_values;
    struct stack_list *node;
};

struct stack_list *head_node = NULL; //empty list

void stack_print(struct stack_list *);  //prototype to print list
struct stack_list * push(struct stack_list * n, struct stack_list * c); //prototype to push values

int main(int argc, char* argv[]) {

    FILE * fp;  //opening file
    fp = fopen("filename", "r");  //gives name of file to open
    struct stack_list * mock = (struct stack_list *)malloc(sizeof(struct stack_list));
    //int values[12];  //array to be used to collect values to pass to my list
    //int n, t;

    if (fp == NULL){

        printf("File not provided.");
    }
    else if (fp != NULL) {

        printf("Printing values first: \n");

        while (fscanf(fp,"%d", &mock->list_values) == 1) {
            mock->node = head_node;
            printf("%d\n", mock->list_values);
        }
    }
    push(mock, constructor_stack(mock));
    stack_print(mock);
}

struct stack_list * constructor_stack(int j){
    struct stack_list * my_node = (struct stack_list *)malloc(sizeof(struct stack_list));
    my_node->list_values = j;
    my_node->node = NULL;
    return my_node;
}

struct stack_list * push(struct stack_list * num_list, struct stack_list * check_nodes) {

    printf("Added values to stack:\n");
    printf("Push: %d\n", check_nodes->list_values);
    check_nodes->list_values = num_list;
    return check_nodes;
}

This is part of what I have so far. I did attempt to use an array to just store the values and pass to my list, but that didn't work either.
int values[12];  //array to be used to collect values to pass to my list
int n, t;

while (fscanf(fp,"%d", &values[n]) == 1) {
            n++;
        }
    }
    for (t = 0; t < 12; ++t) { //iterating over array where values are stored
        head_node = values[t]; //inputting values into the empty list
        printf("%d\n", head_node); //printing values passed to empty list for reference
    }

This is the output that I receive.
Printing values first:
4
2
1
6
1
5
2
3
3
1
6
1
Added values to stack:
Push: 136352
Printing stack:
1111111111111111111111

This printed the values but did not work in my push function either. I appreciate any advice!


Q: Why ARM Process IPI at the end of ISR I am studying IRQ handling on Linux.
I have a question, why we need to handle IPI at the end of each ISR[for SMP].
Is there something special with IPI? why not we process in do_asm_IRQ with other interrupts.
Any suggestion would be appreciated.
  6         .macro  arch_irq_handler_default
  7         get_irqnr_preamble r6, lr
  8 1:      get_irqnr_and_base r0, r2, r6, lr
  9         movne   r1, sp
 10         @
 11         @ routine called with r0 = irq number, r1 = struct pt_regs *
 12         @
 13         adrne   lr, BSYM(1b)
 14         bne     asm_do_IRQ
 15
 16 #ifdef CONFIG_SMP
 17         /*
 18          * XXX
 19          *
 20          * this macro assumes that irqstat (r2) and base (r6) are
 21          * preserved from get_irqnr_and_base above
 22          */
 23         ALT_SMP(test_for_ipi r0, r2, r6, lr)
 24         ALT_UP_B(9997f)
 25         movne   r1, sp
 26         adrne   lr, BSYM(1b)
 27         bne     do_IPI
 28 #endif

http://lxr.oss.org.cn/source/arch/arm/include/asm/entry-macro-multi.S?v=3.5.2;a=arm


Q: How to generate a random binary matrix where only one bit in each row has value 1? I want to use MATLAB to generate a random binary matrix A (n x m) which satisfies a condition:
Each row contains one position with value 1. Other positions are value 0. The position having 1 value is random position.
I tried this code
   n=5;m=10;
   %% A = randi([0 1], n,m);
   A=zeros(n,m);
   for i=1:n
       rand_pos=randperm(m);
       pos_one=rand_pos(1); % random possition of 1 value
       A(i,pos_one)=1;
   end

Is it correct?

A: The solution works, but it is inefficient.
You are using randperm to create a vector (array), and then use only the first element of the vector.
You can use randi to create a scalar (single element) instead:
n=5;m=10;
A=zeros(n,m);
for i=1:m
    %rand_pos gets a random number in range [1, n].
    rand_pos = randi([1, n]);
    A(rand_pos, i)=1;
end

You can also use the following "vectorized" solution:
rand_pos_vec = randi([1, n], 1, m);
A(sub2ind([n, m], rand_pos_vec, 1:m)) = 1;

The above solution:

*

*Creates a vector of random values in range [1, n].

*Use sub2ind to convert "row index" to "matrix index".

*Place 1 in "matrix index".

A: You can do it in one line using bsxfun and randi:
A = double(bsxfun(@eq, 1:m, randi(n, n, 1)));

This compares the row vector [1 2 ... m] with an n×1 random vector of values from 1 to n. The comparison is done element-wise with singleton expansion. For each row, exactly one of the values of [1 2 ... m] equals that in the random vector.


Q: Decode a string - Quote marks issue I am supposed to decode the string below in a script I have made (it is a task from a webpage). In order to ensure that the decoded word will be correct, I can not change the string in any way. Since the quote marks affects the string, parts like q90:;AI is not a string, which results in a syntax error.
q0Ø:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GØ""N6K086HB"Ø8CRHW"+LS79Ø""N29QCLN5WNEBS8GENBG4FØ47a

Is there a way I can decode the encrypted message without changing it? As of now I am just getting syntax error when I define the string in a variable.

A: You can surround the string with single quotes, since double quotes are used in the string already:
>>> print 'q0Ø:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GØ""N6K086HB"Ø8CRHW"+LS79Ø""N29QCLN5WNEBS8GENBG4FØ47a'
q0Ã:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GÃ""N6K086HB"Ã8CRHW"+LS79Ã""N29QCLN5WNEBS8GENBG4FÃ47a
>>>


Q: Foregin key constraint error but shouldn't be occuring I have a list table with 5 entries in it, the first column in the identity column (PK), within a parent table is a column that is related to this list table by ID (FK). I am using C# in a web app to run an ExecuteScalar with a stored procedure to insert the items into the parent table.
This is within a SQL database
LIST TABLE:
ID INT (PK),
SKILL_SET_NAME VARCHAR

PARENT TABLE:
ID INT,
SKILL_SET_ID INT (FK)

ITEMS WITHIN LIST TABLE:
1, SOMETHING
2, ANOTHER
3, ELSE

INSERT STATEMENT INTO PARENT TABLE
INSERT INTO PARENT TABLE
(ID, SKILL_SET_ID)
VALUES
([NUMBER], 1)

ACTUAL CODE (changed the ExecuteScalar to NonQuery, and the SkillSetID is the foreign key)
public static void SetRIPSSkillSetDetails(int HDR_ID, int SkillSetID, string SkillSetOptional, int SkillSetRating)
{
    ArrayList al = new ArrayList();

    al.Add(new DictionaryEntry("@HDR_ID", HDR_ID));
    al.Add(new DictionaryEntry("@SKILL_SET_ID", SkillSetID));
    al.Add(new DictionaryEntry("@SKILL_SET_OPTIONAL", SkillSetOptional));
    al.Add(new DictionaryEntry("@SKILL_SET_RATING", SkillSetRating));

    Core.RunNonQuery("web", "[IPAM_GLOBAL_INSERT_PARTICIPANT_RATING_DTL]", al);

When the code runs the ExecuteScalar I get the Foreign key constraint error, Please help

A: The stored procedure was bombing out, someone said you can step through sql storec procedures from VS, how do I do that?


Q: Color TdCalendarView rows I am using TdCalendarView code by Tinyfool in my project in which all calendar is designed using core graphics.I want to color rows of this calendar with two alternate colors.How can I do that?

A: You need to change  the stroke fill color here for either even value of i in for loop or odd value
-(void)drawDateWords
  {
CGContextRef ctx=UIGraphicsGetCurrentContext();

int width=self.frame.size.width;

int dayCount=[self getDayCountOfaMonth:currentMonthDate];
int day=0;
int x=0;
int y=0;
int s_width=width/7;
int curr_Weekday=[self getMonthWeekday:currentMonthDate];

// Normaly big Font
[array_Date addObject:@""];
[array_Month addObject:@""];
[array_Year addObject:@""];
[array_Desc addObject:@""];
[array_LastDate addObject:@""];
[self.array_Name addObject:@""];

UIFont *weekfont=[UIFont boldSystemFontOfSize:20];

for(int i=1;i<dayCount+1;i++)
{
    day=i+curr_Weekday-2;
    x=day % 7;
    y=day / 7;
    NSString *date=[[[NSString alloc] initWithFormat:@"%d",i] autorelease];

    for (int j=0; j<[array_Date count]; j++) {

        NSString *date1 = [array_Date objectAtIndex:j];
        int month1 = [[array_Month objectAtIndex:j] intValue];
        int year1 = [[array_Year objectAtIndex:j] intValue];

    if ([date isEqualToString:date1] && currentMonthDate.month == month1 && currentMonthDate.year == year1)
    {
        //[@"*" drawAtPoint:CGPointMake(x*s_width+18,y*itemHeight+headHeight+18) withFont:[UIFont boldSystemFontOfSize:25]];
        //[date drawAtPoint:CGPointMake(x*s_width+18,y*itemHeight+headHeight+18) withFont:[UIFont boldSystemFontOfSize:25]];
        [[UIColor redColor] set];

    }
    else{
        //[[UIColor redColor] set];
        [date drawAtPoint:CGPointMake(x*s_width+15,y*itemHeight+headHeight) withFont:weekfont];
    }

    }

if([self getDayFlag:i]==1)
    {
        CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
        [@"." drawAtPoint:CGPointMake(x*s_width+19,y*itemHeight+headHeight+6) withFont:[UIFont boldSystemFontOfSize:25]];
    }
    else if([self getDayFlag:i]==-1)
    {
        CGContextSetRGBFillColor(ctx, 0, 8.5, 0.3, 1);
        [@"." drawAtPoint:CGPointMake(x*s_width+19,y*itemHeight+headHeight+6) withFont:[UIFont boldSystemFontOfSize:25]];
    }

    CGContextSetRGBFillColor(ctx, 0, 0, 0, 1);
}
 }


Q: Istio 1.4.3 to 1.5.6 upgrade using istioctl and Istio operator Can I make an existing Istio open source installable compatible with the (Istioctl + Operator) ? I currently have Istio 1.4.3 installed via istioctl .. and need to make existing deployment Istio operator aware as well before I upgrade to Istio 1.5.6+ . Any specific steps to be followed here ?

A: There shouldn't be any problem with that, I have tried that on my test cluster and everything worked just fine.
I had a problem with upgrading immediately from 1.4.3 to 1.5.6, so with below steps you're first upgrading from 1.4.3 to 1.5.0, then from 1.5.0 to 1.5.6
Take a look at below steps to follow.

1.Follow istio documentation and install istioctl 1.4, 1.5 and 1.5.6 with:
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.4.0 sh -
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.5.0 sh -
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.5.6 sh -

2.Add the istioctl 1.4 to your path
cd istio-1.4.0
export PATH=$PWD/bin:$PATH

3.Install istio 1.4
istioctl manifest apply --set profile=demo

4.Check if everything works correct.
kubectl get pod -n istio-system
kubectl get svc -n istio-system
istioctl version

5.Add the istioctl 1.5 to your path
cd istio-1.5.0
export PATH=$PWD/bin:$PATH

6.Install istio operator for future upgrade.
istioctl operator init

7.Prepare IstioOperator.yaml
nano IstioOperator.yaml

apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
  namespace: istio-system
  name: example-istiocontrolplane
spec:
  profile: demo
  tag: 1.5.0

8.Before the upgrade use below commands
kubectl -n istio-system delete service/istio-galley deployment.apps/istio-galley
kubectl delete validatingwebhookconfiguration.admissionregistration.k8s.io/istio-galley

9.Upgrade from 1.4 to 1.5 with istioctl upgrade and prepared IstioOperator.yaml
istioctl upgrade -f IstioOperator.yaml

10.After the upgrade use below commands
kubectl -n istio-system delete deployment istio-citadel istio-galley istio-pilot istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete service istio-citadel istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete horizontalpodautoscaler.autoscaling/istio-pilot horizontalpodautoscaler.autoscaling/istio-telemetry
kubectl -n istio-system delete pdb istio-citadel istio-galley istio-pilot istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete deployment istiocoredns
kubectl -n istio-system delete service istiocoredns

11.Check if everything works correct.
kubectl get pod -n istio-system
kubectl get svc -n istio-system
istioctl version

12.Change istio IstioOperator.yaml tag value
nano IstioOperator.yaml

apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
  namespace: istio-system
  name: example-istiocontrolplane
spec:
  profile: demo
  tag: 1.5.6    <---

13.Upgrade from 1.5 to 1.5.6 with istioctl upgrade and prepared IstioOperator.yaml
istioctl upgrade -f IstioOperator.yaml

14.Add the istioctl 1.5.6 to your path
cd istio-1.5.6
export PATH=$PWD/bin:$PATH

15.I have deployed a bookinfo app to check if everything works correct.
kubectl label namespace default istio-injection=enabled
kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml
kubectl apply -f samples/bookinfo/networking/bookinfo-gateway.yaml

16.Results
curl -v xx.xx.xxx.xxx/productpage | grep HTTP
HTTP/1.1 200 OK

istioctl version
client version: 1.5.6
control plane version: 1.5.6
data plane version: 1.5.6 (9 proxies)

Let me know if have any more questions.


Q: Mac: Installing app from Internet has an exception I want to install Firefox in my MacBook, downloaded from Internet.
After a series of clicking, I can use it with an exception.
It is not in the LaunchPad. Looks like it is installed on an other disk.
Here is image:

How to fix it?

A: Drag it to the Applications folder (as the green arrow suggests), and then run it from that folder rather than from the disk image.


Q: AWS dynamodb with Ruby SDK I have tables in dynamodb. I am new to 'AWS'.now my site is getting very slow. I couldn't find the solution. I suspect DynamoDB. So I need to know some details about DynamoDB. What is Read and write capacity, latency, CPU utilization? How to handle these all? to get DB gets fast?

A: When you create a table, you specify the provisioned capacity for read and write. This will limit the number of records you can read per second and number of records you can write per second. Your use-case will determine your actual needs. You can modify the provisioned capacity of a table after you have created, while it is being used and it will not affect access. This hot upgrade is a powerful feature of DynamoDB.
If you are exceeding your provisioned capacity, then DynamoDB will throttle your API calls. The aws-sdk gem will automatically retry throttled DynamoDB calls up to 10 times, using an exponential backoff strategy, sleeping between attempts.
To configure the retry limit for DynamoDB:
Aws.config[:dynamodb] = { retry_limit: 5 }

You can tell if your request is getting retried by inspecting the response object:
ddb = Aws::DynamoDB::Client.new
resp = ddb.get_item(table_name: 'aws-sdk', key: { id: '123' })
resp.context.retires
#=> 0

Also, you can enable logging:
require 'logger'
ddb = Aws::DynamoDB::Client.new(logger: Rails.logger)
ddb.get_item(table_name: 'aws-sdk', key: { id: '123' })

# sent to the rails logger
[Aws::DynamoDB::Client 200 0.008879 0 retries] get_item(table_name:"aws-sdk",key:{"id"=>{s:"123"}})

The log message contains the service client call, the HTTP status code (200), the time spent waiting on the call, the number of retires and the operation name and params called. You can of course configure the :log_level and a :log_formatter to modify when and what things are logged.


Q: Is there a more straightforward way to search for a string while ignoring spaces? I am working on a function that searches a searches a string for one of a list of given words. The string being searched is generated by OCR software, that occasionally adds extra spaces between letters (depending on the font) which I need to ignore.
I currently have a function that looks like this:
function searchSomeText($searchTerms, $stringToBeSearched)
{
    $matches = array();
    for($i=0; $i < count($searchTerms); ++ $i)
    {
        $searchTerms[$i] = substr(chunk_split($searchTerms[$i],1,"\s*"), 0, -3);
    }
    $searchTermsString = implode("|", $searchTerms);

    if (preg_match("/\b($searchTermsString)\b/", $stringToBeSearched, $matches))
    {
        return $matches;
    }
    else { return false; }
}

*

*Is there any way to ignore spaces besides adding '\s*' between every character in the search terms?

*If there isn't, is there a more efficient method to add '\s*' after every character in the search terms but the last one other than using chunk_split() to add it after every character, and then chopping it off from the end?

Edit
I prefer not to just strip the spaces from the $stringToBeSearched because in the majority of cases, where the spacing is correct, I don't want a match where a search term is contained inside of another word (hence the '\b's)

A: Here is my recommended strategy for what I understand of your task:

*

*Do not mutate the haystack string.  Often the the string to be searched is much much longer than the needle(s) used in the search.  This potentially heavy lifting should be avoided when possible.

*Your search terms appear to be dynamic (and likely to be coming from user input), so the characters must be escaped to prevent regex pattern breakage.  Use preg_quote() for this process.

*Insert \s* between all non-whitespace characters in the escaped search terms (ignoring escaping slashes).

*Then convert all sequences of one or more whitespaces to \s+ in the search terms.

*Now that the terms are prepared, glue them together using pipes.  Wrap the piped expression in parentheses, then wrap that capture group in wordboundary markers (\b).

*Though not mentioned in your question, I recommend using case-insensitive matching.  If multibyte/unicode characters may be involved, add the u pattern modifier as well.

Recommended Code: (Demo)
function searchSomeText(array $searchTerms, string $stringToBeSearched): bool
{
    foreach ($searchTerms as &$searchTerm) {
        $searchTerm = preg_replace(
            ['/\\\\?\S\K(?=\S)/', '/\s+/'],
            ['\\s*', '\\s+'],
            preg_quote($searchTerm, '/')
        );
    }
    $pattern = '/\b(' . implode("|", $searchTerms) . ')\b/i';
    echo $pattern . "\n";
    return (bool)preg_match($pattern, $stringToBeSearched);
}

var_export(
    searchSomeText(
        ['at', 'cat ', 'the'],
        'The catheter in the hat'
    )
);

Output: (dynamic regex pattern & return value)
/\b(a\s*t|c\s*a\s*t\s+|t\s*h\s*e)\b/i
true


Q: deployment of persistence unit failed issue wHEN I AM DEPLOYING MY CRUDWEB web application it is throwing like below:
SEVERE:   Exception while deploying the app [CRUBWEB] : Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [CRUBWEBPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [SELECT e FROM custt e].
[14, 19] The abstract schema type 'custt' is unknown.

Please help Thanks.


Q: Rails AASM does not rollback when validation returns false I have a model Booking that changes the status using AASM
models/booking.rb
before_validation :item_availability, if: -> { pending? || approved? }

enum status: [:pending, :approved, :rejected, :on_loan, :returned]

aasm column: :status, enum: true, whiny_transitions: true do
  state :pending, initial: true
  state :approved

  event :approve do
    transitions from: :pending, to: :approved
  end
end

private
 def item_availability
    if quantity.to_f > item.quantity.to_f
      errors.add(:base, "Not enough quantity for #{item.name} only #{item.quantity} left")
      false
    end
  end

and I have a service that triggers the approve! event
  def run
    booking.transaction do
      booking.approve!
      booking.item.decrement!(:quantity, booking.quantity)
      BookingsMailer.send_approval(booking).deliver_now
    end
  rescue ActiveRecord::RecordInvalid => e
    errors.add(:base, e.message)
    false
  end

The problem here is the validation is being hit because the quantity is greater than the booking's quantity but the transaction in my service does not rollback.
According to documentation

Saving includes running all validations on the Job class. If
  whiny_persistence flag is set to true, exception is raised in case of
  failure.

I already set whiny_transitions to true but


Q: IClassFactory failed due to the following error: 800a0153 I'm trying to reference a com component and it is throwing the below error.
Creating an instance of the COM component with CLSID {xxx} from the IClassFactory failed due to the following error: 800a0153.
Specifically the error gets thrown when I try to instantiate an object. I checked that

*

*The project being built for x86 processors which it is

*The com object is registered using regsvr32, and is available in the registry.

I can also see the methods in the object browser, so I know .net is finding it.
Any ideas on what I'm missing?

A: This is an error code that's specific to the component.  If you don't have documentation that explains what the code might mean then you'll need support from the vendor.

A: As noted in my comment to Hans' answer, this error code is FACILITY_CONTROL, which is supposed to relate to OLE/ActiveX controls, and has an error code which lies in the standard range (i.e. for Microsoft use) defined in OleCtl.h, but is not documented in the Win32 header files so is probably internal to a Microsoft product such as Visual Basic.
Can you tell us anything else about the COM component you are trying to use?
If the COM component was written using Visual Basic, I think it's probable that what you are seeing is equivalent to the Runtime Error 339 which users of Visual Basic see if they try to reference an OCX control which has some of its dependencies missing. You might look at the dependencies of the COM server's DLL/EXE using Depends.exe and see whether you have them all present on your machine.

A: Back when I had to do a lot of COM work, I used COM Explorer quite a bit from these guys:
http://download.cnet.com/COM-Explorer/3000-2206_4-10022464.html?tag=mncol;lst
I had to install it last year to debug a bizarre COM registration issue with Office plugins.
Also, I have no affiliation with these guys whatsoever (and it looks like the company might be toast anyway).


Q: Why MySQL InnoDB can handle concurrent updates and PostgreSQL can't? Let's imagine you have a table with this definition:
CREATE TABLE public.positions
(
   id serial,
   latitude numeric(18,12),
   longitude numeric(18,12),
   updated_at timestamp without time zone
)

And you have 50,000 rows in such table. now for testing purposes you will run an update like this:
update positions
set  updated_at = now()
where latitude between 234.12 and 235.00;

that statement will update 1,000 rows from the 50,000 (in this specific dataset)
if you run such query in 30 different threads, MySQL innodb will succeed and postgres will fail with lots of deadlocks.
why?

A: Plain old luck, I would say.
If thirty threads go ahead and want to update the same 1000 rows, they can either access these rows in the same order (in which case they will lock out each other and do it sequentially) or in different orders (in which case they will deadlock).
That's the same for InnoDB and PostgreSQL.
To analyze why things work out different in your case, you should start by comparing the execution plans. Maybe then you get a clue why PostgreSQL does not access all rows in the same order.
Lacking this information, I'd guess that you are experiencing a feature introduced in version 8.3 that speeds up concurrent sequential scans:

*

*Concurrent large sequential scans can now share disk reads (Jeff Davis)
This is accomplished by starting the new sequential scan in the middle of the table (where another sequential scan is already in-progress) and wrapping around to the beginning to finish. This can affect the order of returned rows in a query that does not specify ORDER BY. The synchronize_seqscans configuration parameter can be used to disable this if necessary.

Check if your PostgreSQL execution plan uses sequential scans and see if changing synchronize_seqscans avoids the deadlocks.


Q: Correct usage of $.ajaxComplete and $.ajaxError? I've been using the following snippet on my ajax form submits:
$.ajax({
url: "",
data: ilmoittautumisdata,
type: "POST",
success:function(){

});
error:function(){

});
});

However, I remember that I was told to stop using success and error within it, as they're deprecated (?) and instead use  $.ajaxComplete(); and  $.ajaxError();.
However, reading the docs isn't helping me as I want to use both of them, and this isn't working for me.
$('#ilmoittuminen').submit(function(){
            var ilmoittautumisdata = $('#ilmoittuminen').serialize();
            $.ajax({
                //url: "",
                data: ilmoittautumisdata,
                type: "POST"
                });
            $.ajaxComplete(
            function(){
            $('#ilmoittuminen').slideUp();
            });
            $.ajaxError(
            function(){

            });
    return false;
    });

How I should do it?
http://jsfiddle.net/D7qgd/

A: Firstly, the word you're looking for is "deprecated". As far as I'm aware, the success and error properties are definitely not deprecated. You can (and should, in your case) continue to use them.
The problem with your attempt to use ajaxError and ajaxComplete is that they are implemented as instance methods, rather than static methods on the jQuery object itself. For that reason, you need to select some element and call the methods on that collection. The element itself doesn't matter at all:
$("#someElement").ajaxComplete(function () {
    // Do stuff
});

The next problem, which you haven't come across yet, is that the ajaxError and related methods register global AJAX event handlers. Each time you call one of those methods, you add a new event handler to the global set, and every time an AJAX event is fired, all of your registered handlers will be executed.

Update (Thanks @DCoder)
Looks like the success and error properties are deprecated as of jQuery 1.8. Instead, you can use the fail, done and always methods of the jQuery modified XHR object. Any objects that inherit from the deferred object can use these methods (the jqXHR object is one of these):
$.ajax(ajaxSetupObject).done(function () {
    // Handle success
}).error(function () {
    // Handle error
});

A: This code handles a success and error inside the ajax method.if there is a success it prints out success, with the object you receive, and vica versa.
$.ajax({
   type: 'json',
   url: 'foobar.com',
   success: function(s) {
     console.log('success' + s);
   },
   error: function(e) {
     console.log('error' + e);
   }
});


Q: Can c#/Razor work with DyGraph WITHOUT Javascript? In this question:
Previous DyGraph question
There is still the need to go to JavaScript to call DyGraph:
<script type="text/javascript">
g = new Dygraph(document.getElementById("readingGraph"), @data,{ labels: ["Sample Number", "Reading"] });
</script>

Is there anyway to remove JavaScript completely?
I would like a fully c# solution...

A: Ah, OBVIOUSSLY not. DyGraph is a javascript library. If you want to remove Javascript completely, you need to use a graph library that generates the graph on the server and sends the picture down to the client. Given that DyGraph is a javascript library - the obvious answer is no, it can not be used while at the same time totally disabling javascript.
Literally on the homepage it says: "dygraphs is a fast, flexible open source JavaScript charting library.".

A: If you want 100% C# and no Javascript, MudBlazor has some charting capabilities: https://mudblazor.com/components/barchart#api
As another answer states, "Given that DyGraph is a javascript library - the obvious answer is no, it can not be used while at the same time totally disabling javascript"


Q: localStorage.getItem retrieves 'null' I'm trying to get a counter for the number of times a button is pressed but when I try to retrieve it outside the function, it results in 'null' instead.
HTML:
<button class="signupbutton" onclick="counter()"> Yes I'm in!</button>

Number of people that have signed up for the newsletter:

0

Javascript:
function counter() {
    var elem = document.getElementById('counter1');
    var count = localStorage.getItem('count');
    if (count == null) {
        count = 0;
    }
    count++;
    localStorage.setItem('count', count);
    elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;

A: Make your code a bit more DRY would save you a bit of time, in validating that your counter has a "real" value. For the rest, the onclick inside an html element is not encouraged anymore, you can just update your code like
// wait until the page has loaded
window.addEventListener('load', function() {
  // get your elements once
  const counterElement = document.querySelector('#counter1');
  const signupButton = document.querySelector('.signupbutton');

  // assign a click event to your button
  signupButton.addEventListener('click', updateCounter);

  // function to retrieve the counter from your localStorage
  function getKeyOrDefault( key, defaultValue = 0 ) {
    return localStorage.getItem( key ) || defaultValue;
  }

  function updateCounter( e ) {
    let counter = parseInt( getKeyOrDefault( 'counter' ) );
    counter++;
    counterElement.innerHTML = counter;
    localStorage.setItem( 'counter', counter );
    e.preventDefault();
  }
  // set the initial value
  counterElement.innerHTML = getKeyOrDefault( 'counter' );
} );

Ofcourse, don't forget to change your html, to remove the counter function from the html element like
<button class="signupbutton"> Yes I'm in!</button>

Number of people that have signed up for the newsletter:

0

A sample of this code can be found on this jsfiddle (it is not here, as stackoverflow doesn't support localstorage)
Now, the only thing I am really worried about, is the text of your HTML, note that the localStorage will be a personal storage for all clients, so, if this is a website run from the internet, all persons who arrive there once will start with null (or 0) and just increase by 1 each time they click the button, you will be none the wiser, as it is localStorage.
Ofcourse, if you handle it on 1 computer, where people have to input their data, then you have at least some data stored locally, but still, this isn't a real storage you can do something with ;)

A: The code does work. However, you have to make sure, that the counter function is interpreted before the page has loaded. Put the JS at the end of the document head, or rewrite the onlick using addEventListener.

A: You should convert to integer ..
function counter() {
var elem = document.getElementById('counter1');
var count = localStorage.getItem('count');
if (count == null) {
    count = 0;
}
count = parseInt(count);
count++;
localStorage.setItem('count', count);
elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;

Please Try again

A: getItem/setItem are unavailable until didFinish will have executed unless
Read local storage data using WKWebView


Q: Can we create a custom wrapper for mock annotation of jmockit? Can we create a custom wrapper for mock annotation or MockUp class of jmockit ? If its possible can you explain how can we done it.

A: You can create a "custom wrapper" for JMockit's @Tested annotation (ie, use it as a meta-annotation), but not for any of the other annotations, @Mock included. So, the answer is no, it's not possible.


Q: Sync Azure AD users to SQL Server on vm or Sql Database Users Table How can we synchronize Azure AD users with a user table in the database?

A: To Sync Azure AD users to SQL make sure each property stored in the data source maps properly to an AD user's attribute.
This article by Adam Bertram has code and whole process to Sync Azure AD users to Sql Database.
As per official documentation
Azure role-based access control (Azure RBAC) applies only to the portal and is not propagated to SQL Server.

Note
Database users (with the exception of administrators) cannot be
created using the Azure portal. Azure roles are not propagated to the
database in SQL Database, the SQL Managed Instance, or Azure Synapse.
Azure roles are used for managing Azure Resources, and do not apply to
database permissions. For example, the SQL Server Contributor role
does not grant access to connect to the database in SQL Database, the
SQL Managed Instance, or Azure Synapse. The access permission must be
granted directly in the database using Transact-SQL statements.


Q: How do you serve a static website using Google Cloud CDN, Google Cloud Storage, and a custom domain? I'd like to set up a static website with files stored in a Google Storage bucket.  I already own a custom domain and have, at a minimum, some barebone files to see if the site is setup successfully.
Ideally, I'd like to serve the content via SSL when accessing that custom domain and have the content cached from Google Storage utilizing Google Cloud CDN so that end users are served content from the CDN as opposed to being served from Cloud Storage directly.
I haven't been able to find the perfect setup for this yet or even solidify if Google enables/supports this scenario at this point (I've read that there may be a need to leverage a load balancer to support SSL, but nothing conclusive).
So far I have created a Google Storage bucket and uploaded the desired files.  I then made the bucket publicly readable to ensure there aren't any permissions issues.  From there I set up a load balancer to leverage my custom domain with the checkbox of Google Cloud CDN checked, the storage bucket just created, set as the backend, and the host file mapping set to the default settings.
UPDATE:
It turned out just a few more steps were required.  First, I needed to turn "Requestor Pays" off for the Storage bucket being utilized.  Secondly, I needed to add permissions of "Storage Object Viewer" for "allUsers" (the legacy permission won't work here).  Lastly, I had to both set the "A" and "AAAA" records to the IPV4 and IPV6 addresses of my Load Balancer for the DNS config on my domain name (and clear all previous values so that they were only referring to the new ones).  After all of this was completed, everything is working as it should be :)
Thanks to both Cloud Ace (for leading me in the right direction) and a Google Customer Engineer that I met last week (for referring me to this article for reference: https://medium.com/@marco_37432/create-a-custom-domain-cdn-with-google-beta-7ad9531dfbae)!

A: When you create HTTP(S) Load Balancer, there should be a Certificate section in Frontend configuration if you set the protocol to HTTPS, also preserve a static IP. Then you can configure the DNS to point the domain to this IP.


Q: Controling the look and feel of JButtons on Mac For my assignment I need a 2 dimensional array of JButtons in a grid JPanel in a JFrame. The JButtons must change color when clicked. I cannot get them to hold any color.
I implemented the solutions proposed in a previous thread and found that the work around only produced border color:
JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);

unpainting the border:
button.setBorderPainted(false);

simply causes the entire JFrame to be red.
This issue is only with MAC computers and not the intended problem of the assignment.
Any thoughts?

A: Remember : The Swing toolkit is pretty good at getting the system look and feel "almost right".  If you really need the system feel, however, there are other options like SWT that are a little better suited.
If you want consistency then Swing can always default to the old school applet look which, although a little boring, is pretty reliable .  The upside of this is that, when we roll back to this more simplistic looking gui toolkit, platform specific quirks magically seem to disappear .
I think you might find your problem solved quite easily if you simply set the look and feel to the standard swing style look and feel.
The Solution
I would suggest a call to
    UIManager.setLookAndFeel(
        UIManager.getCrossPlatformLookAndFeelClassName());

In the static code block where you initialize your application.


Q: Getting the icon for an audio device In the Sound Control Panel in Windows, and in the Volume Mixer, all audio devices have a specific icon set.
Is it possible to get which icon is set for a device through the Windows API?
Sound Control Panel
Volume Mixer

A: As suggested by Simon Mourier in the comments above, there is a PKEY that can access that data.
You can follow along with most of this sample and just replace PKEY_Device_FriendlyNamewith PKEY_DeviceClass_IconPath.
In short, it's something like this:
    // [...]

    IMMDevice *pDevice; // the device you want to look up
    HRESULT hr = S_OK;
    IPropertyStore *pProps = NULL;
    PROPVARIANT varName;

    hr = pDevice->OpenPropertyStore(STGM_READ, &pProps);
    EXIT_ON_ERROR(hr);

    PropVariantInit(&varName);

    hr = pProps->GetValue(PKEY_DeviceClass_IconPath, &varName);
    EXIT_ON_ERROR(hr);

    // [...]


Q: How to display graph from database values using php? I want to create graph using php. I have tested jpgraph example. But it display error
like
> The image “http://localhost/test/jpgraphtest.php” cannot be displayed
> because it contains errors.

<?php
include('phpgraphlib.php');
$graph = new PHPGraphLib(500,350);
$data = array(12124, 5535, 43373, 22223, 90432, 23332, 15544, 24523,
 32778, 38878, 28787, 33243, 34832, 32302);
$graph->addData($data);
$graph->setTitle('Widgets Produced');
$graph->setGradient('red', 'maroon');
$graph->createGraph();
?>

A: check this link I think its perfect.
http://pchart.sourceforge.net/
(also you should configure php to enable image creating).
In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.
check these links.
http://www.php.net/manual/en/image.requirements.php
http://www.php.net/manual/en/image.installation.php
http://www.php.net/manual/en/image.configuration.php
examples:


Q: Prevent spring boot resolving properties to scientific notation I have a Spring Boot v2.1.0.RELEASE application with the following application.yml properties file:
example:
  aws:
    account: 845216416540
  sqs:
    endpoint: https://sqs.us-west-2.amazonaws.com/${example.aws.account}

Then I use the property like this:
@Component public class Example {

   @Value("${example.aws.sqs.endpoint}")
   private String endpoint;

   public void test()
   {
      System.out.println(endpoint);
      // prints -> https://sqs.us-west-2.amazonaws.com/8.4521641654E10
   }
}

*

*No that is not my actual aws account (spare me the lecture)

Here is what I can't seem to figure out...
1) Why does spring by default interpolate the the value of the account as scientific notation?
2) How can I configure or prevent this from happening?

A: Spring is inferring the value to be a number. You can force the value to be treated as a string in YAML config by quoting it ie "845216416540"
This answer covers YAML convention in detail: https://stackoverflow.com/a/22235064/13172778


Q: How to fixed header with in table? Hi all I want to fix (or) freezthead header on top and want to scroll tbody values only in table, as of now in table while scroll the page everything gets scrolled, but expecting to scroll only the tbody values ... My Demo
HTML

        {{$index+1}}
             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{dyedyarnreferencenumber.shade}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{dyedyarnreferencenumber.buyers_reference}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{dyedyarnreferencenumber.approved_supplier_ref}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{dyedyarnreferencenumber.category}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{sryarnorder.order_quantity}} {{sryarnorder.order_quantity_unit}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{sryarnorder.price_per_kg_currency}} {{sryarnorder.price_per_kg}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{sryarnorder.order_quantity * sryarnorder.price_per_kg}}

CSS
table tbody, table thead
{
    display: block!important;
}

table tbody
{
   overflow: auto!important;
   height: 100px!important;
}

table {
    width: 100%!important;
}
th
{
    width: auto!important;
}

Data
$scope.sryarnorders = [{"_id":"573d7fa0760ba711126d7de5","user":{"_id":"5721a378d33c0d6b0bb30416","displayName":"ms ms"},"__v":1,"colorshades":[{"_id":"573d7fc3760ba711126d7de6","price_per_kg_currency":"Inr","price_per_kg":"2","order_quantity_unit":"kg","order_quantity":"23","color":"56ffc46dab97a73d1066b792","quality":"Home Textiles","count":"yarn count"}],"created":"2016-05-19T08:56:00.997Z","remarks":"approved","actual_delivery_date":"2016-05-19","ex_india_date":"2016-05-19","ex_factory_date":"2016-05-19","lc_details_date":"2016-05-19","lc_details":"tooo much","po_delivery_date":"2016-05-19","sales_contract_date":"2016-05-19","sales_contract":"bioler","purchase_order_no_date":"2016-05-19","purchase_order_no":"1234","supplier_name":"Fsa","buyer_name":"e21"},{"_id":"56ffc6d5ab97a73d1066b798","user":{"_id":"56ff7bece2b9a1d10cd074a3","displayName":"saravana kumar"},"__v":1,"colorshades":[{"_id":"56ffc723ab97a73d1066b799","price_per_kg_currency":"Inr","price_per_kg":"120","order_quantity_unit":"kg","order_quantity":"25","color":"56ffc46dab97a73d1066b792","quality":"Home Textiles","count":"yarn count"}],"created":"2016-04-02T13:19:17.746Z","remarks":"pending","actual_delivery_date":"2016-04-02","ex_india_date":"2016-04-04","ex_factory_date":"2016-04-02","lc_details_date":"2016-04-02","lc_details":"lc","po_delivery_date":"2016-04-02","sales_contract_date":"2016-04-02","sales_contract":"required","purchase_order_no_date":"2016-04-02","purchase_order_no":"125","supplier_name":"Fsa","buyer_name":"Binary hand"},{"_id":"56ffc5e0ab97a73d1066b796","user":{"_id":"56ff7bece2b9a1d10cd074a3","displayName":"saravana kumar"},"__v":1,"colorshades":[{"_id":"56ffc608ab97a73d1066b797","price_per_kg_currency":"usd","price_per_kg":"5","order_quantity_unit":"kg","order_quantity":"20","color":"56ffc46dab97a73d1066b792","quality":"yarn quality","count":"yarn count"}],"created":"2016-04-02T13:15:12.876Z","remarks":"clear","actual_delivery_date":"2016-04-02","ex_india_date":"2016-04-02","ex_factory_date":"2016-04-02","lc_details_date":"2016-04-02","lc_details":"free","po_delivery_date":"2016-04-02","sales_contract_date":"2016-04-02","sales_contract":"required","purchase_order_no_date":"2016-04-02","purchase_order_no":"12345","supplier_name":"Fsa","buyer_name":"e21"}];
});

A: Try this: https://codepen.io/tjvantoll/pen/JEKIu
(you need to set fixed column widths)
HTML:

            Name
            Color
            Description

            Apple
            Red
            These are red.

CSS:
.fixed_headers {
  width: 750px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed_headers th {
  text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
  padding: 5px;
  text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
  min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
  min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
  width: 350px;
}
.fixed_headers thead {
  background-color: #333;
  color: #FDFDFD;
}
.fixed_headers thead tr {
  display: block;
  position: relative;
}
.fixed_headers tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
  background-color: #DDD;
}
.old_ie_wrapper {
  height: 300px;
  width: 750px;
  overflow-x: hidden;
  overflow-y: auto;
}
.old_ie_wrapper tbody {
  height: auto;
}


Q: Create Social Graph Dataset From Facebook I am doing a project at my college and I want to build a social graph from Facebook.
I want only the connections between users (friendship) so I can build a Graph.
I read the Facebook API documentation, from my understanding it doesn't allow to fetch my friends' friends, meaning that I'm stuck at first depth.
Does anyone have any suggestions on how to overcome this?

A: Without using a crawler, which is most likely against the TOS, this is not possible.
You could use the first depth to make only a first degree connection graph based on mutual friends within your friend network.
/userid1/friends/userid2

It would be easier to center your project around Twitter's data.


Q: What is a function signature? I was studying python and I ran into the concept of 'signature'. I looked things up but signature of a function seems to have different meaning for different languages. So, what does signature of a function refer to in python?

A: The signature indicates the names and types of the input arguments, and (with type annotations) the type of the returned result(s) of a function or method.
This is not particular to Python, though the concept is more central in some other languages (like C++, where the same method name can exist with multiple signatures, and the types of the input arguments determine which one will be called).

A: In general the signature of a function is defined by the number and type of input arguments the function takes and the type of the result the function returns.
As an example in C++ consider the following function:
int multiply(int x, int y){
    return x*y;
}

The signature of that function, described in an abstract way would be the set {int, int, int}.
As Python is a weakly typed language in general the signature is only given by the amount of parameters. But in newer Python versions type hints were introduced which clarify the signature:
def multiply(x: int, y: int) -> int:
    return x*y

A: A function signature is its declaration, parameters, and return type.
def func(params):
    #some stuff
    return modified_params

When you call it is an instance of that function.
var = func(parameters)