text:
Q: creating a function or sproc to replace real data with pseudo random data I need to scrub data out of tables that can be classified as PHI.
Let's say the real data looks like this:
+-------------------+-----------+------+
|       Name        | Condition | Code |
+-------------------+-----------+------+
| Alex              | A         |   12 |
| Laura             | BB        |   32 |
| Bob               | AAA       |   55 |
| Gary              | C         |   32 |
+-------------------+-----------+------+

I will need to replace my Name column with the following fake names:
Names_Reference_Table:
+-------------+----+
|    Name     | ID |
+-------------+----+
| JOHN        |  1 |
| ROBERT      |  2 |
| MICHAEL     |  3 |
| WILLIAM     |  4 |
| DAVID       |  5 |
| RICHARD     |  6 |
| CHARLES     |  7 |
| JOSEPH      |  8 |
| THOMAS      |  9 |
| CHRISTOPHER | 10 |
| DANIEL      | 11 |
| PAUL        | 12 |
| MARK        | 13 |
| DONALD      | 14 |
| GEORGE      | 15 |
+-------------+----+

Though I have 10,000,000 real data records, I have only 10,000 fake data records. I am assuming that every fake name will be repeated 1000 times when replacing the real data.
The trick here is that this needs to be recreatable. After googling for hours, I did find some good sources, and I've created some kind of implementation that is deterministic, assuming that the seed does not change:
SELECT FLOOR(RAND(@seed * LOG([p].[patientid]) * 1000) * ( @count_names - 1 ) + 1)

As you can see from above, when you pass the same seed to RAND(), it will return the same value. However, this implementation is brittle.
Has anyone guidance on how to generate this deterministic behavior?

A: You could use the checksum or some other hashing function e.g.
SELECT Name
FROM Names_Reference_Table
WHERE ID = ABS(CHECKSUM('John')) % 10000

Assuming you have 10,000 fake names

A: If I understood it correctly actual names are more than dummy names. So you want to replace the actual names with dummy names by repeating dummy names by 1000 against the real name. This can be achieved by using Ntile function as follows -
declare @i int = (select max(id) from reference_table)
select b.name,a.condition,a.code from
(
select name,condition,code, Ntile(@i) over (order by code) as RefId
from actualTable
) as a
Left join Refrence_table as b
on b.id = a.refid

Let me know if this helps


text:
Q: RSpec: Testing logger messages for block syntax I currently use a logger in the following way:
def log_stuff
  logger.info { 'Info log message' }
  logger.debug { expesive_action }
end

But I would like to know if the logger receives the correct message with RSpec.
If I would just pass the logging line to the input this would have been easy:
# logger.info('Info log message')
expect(logger_mock).to receive(:info).with('Info log message')

But I couldn't figure out a way I could do something like this with the block syntax.
I specifically want to use this syntax, so that expensive_action only gets called when the log level is set to DEBUG.

A: It's not that difficult, though a tad trickier than vanilla expectations:
  expect(logger_mock).to receive(:info) do |&block|
    expect(block.call).to eq('Info log message')
  end

in this case, &block in your spec is simply the block you have in logger.info call. So you must explicitly call it, and then set another expectation on the return value. That's how I do it, at least.

A: Unfortunately it's quite tricky because the block is lazy evaluated.
Sometimes you can solve this by mocking at a lower level. For example, info internally calls add passing the type of log. However, even in this case, mocking add doesn't help you because the block is passed verbatim and it's not evaluated.
At this point, you may want to stub the execution of expensive_action and check if the action has been called or not. Of course, this solution would not work if you just return a string in the block, but only if you call another method you can mock.

A: TL;DR:
Based on @EdvardM's excellent answer:
The general case looks like this:
  expect(Rails.logger).to receive(:info) do |&block|
    expect(block.call).to match(/regex matching the log message/)
  end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Table in HTML using JavaScript I am not familiar with JavaScript and HTML. Just want to build a Table with JavaScript in HTML. I am following some instructions, part of code is as bellow. would you please let me know what is the problem that the table is not appearing?

    tb1= document.createElement('table');
    var tr = tb1.insertRow();
    var Cell1 = tr.insertCell(0),
    var Cell2 = tr.insertCell(1),
    var Cell3 = tr.insertCell(2),
    var Cell4 = tr.insertCell(3);
    cell1.innerHTML = "11";
    cell2.innerHTML = "11";
    cell3.innerHTML = "11";
    cell4.innerHTML = "11";
    tb1.appendChild(MyTable);

A: *

*You don't have to use document.createElement('table'); if the element is in your html, use getElementById("MyTable");

*You are using commas instead of semicolon in the end of lines;

There is an example that could make you understand better:

window.onload = function() {
   var table = document.getElementById("myTable");
   var row = table.insertRow(0);
   var cell1 = row.insertCell(0);
   cell1.innerHTML = "1";

   var row = table.insertRow(1);
   var cell1 = row.insertCell(0);
   cell1.innerHTML = "1";

   var row = table.insertRow(2);
   var cell1 = row.insertCell(0);
   cell1.innerHTML = "1";
};
table, td {
          border: 1px solid black;
        }

A:

var div= document.getElementById('MyTableContainer');
var tb1= document.createElement('table');
var tr = tb1.insertRow();
var cell1 = tr.insertCell(0);
var cell2 = tr.insertCell(1);
var cell3 = tr.insertCell(2);
var cell4 = tr.insertCell(3);
cell1.innerHTML = "11";
cell2.innerHTML = "11";
cell3.innerHTML = "11";
cell4.innerHTML = "11";
div.appendChild(tb1);
#MyTable > table {
  width: 100%;
}

td {
border: 1px solid;
}


text:
Q: Pointers in C, simple doubts I'm trying to understand some basic principles of pointers. Someone told me that assigning value to a pointer variable will change the actual variable value. Is that true? I wrote a piece of code and got this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int x=5;
    int *address_of_x = &x;
    int y = *address_of_x;
    *address_of_x = 9;
    printf("The value of x is: %d\n", x);
    printf("The X is at: %p\n", &address_of_x);
    printf("value of y = %d\n", y);
    return 0;
}

and got the output like this:
The value of x is: 9
The X is at: 0028FF04
value of y = 5

why the value of "y" stayed 5? Is that because of the ordering of commands?

A: Yes, it is.  address_of_x is assigned a pointer to x, but y is a completely independent int variable.  You assign it the same value as x (through a pointer), but x and y are different variables.
At this point, assigning to *address_of_x will change the value of x, but not y.

A: y isn't a pointer, it is an integer. This line:
int y = *address_of_x;

basically says "take the value pointed to by address_of_x and copy it into y.
If you had instead done this:
int *y = address_of_x;

Then *y would be 9.

A: Yes that was because of the ordering of the commands
when int y = *address_of_x; this executed the 'address_of_x' contained 5 and hence y got that value

A:  +--------------+
 |   5          |
 |*address_of_x |
 +--------------+
        ^
        |         y=*address_of_x =5
        |
 +--------------+
 | address_of_x |
 | 0028FF04     |
 +--------------+

Next time
 *address_of_x = 9

 +--------------+
 |   9          |
 |*address_of_x |
 +--------------+
        ^
        |         but y still 5
        |
 +--------------+
 | address_of_x |
 | 0028FF04     |
 +--------------+

A: You are right. Your pointer pointing to x not y. After pointer pointing to x *address_of_x will assigned to y. So y will get the value of 5.
Try to print value of x, It will changed to 9. Because *address_of_x pointing to x.
printf("value of x = %d\n", x); //output = 9

A: Statement
int y = *address_of_x;

assigns value at address_of_x to y and then after
  *address_of_x = 9;

is modifying the variable to which address_of_x points to (which is x here), not y.


text:
Q: The value of using string.find() is changed in while loop condition int main()
{
   int pos;
   string str = "asd\t123";
   pos = str.find('\t');
   cout << pos <<endl;
   while (pos =str.find('\t') != string::npos) {
      cout << pos <<endl;
      break;
   }
   cout << pos <<endl;
   return 0;
}

The output is 3 and 1. why would that happen if I put pos = str.find() in the while loop condition?

A: Try this:
while ( (pos = str.find('\t')) != string::npos)
{
...
}

The value is changed because while (pos = str.find('\t') != string::npos) is being interpreted as:
while (pos = (str.find('\t') != string::npos))

You are assigning the result of (str.find('\t') != string::npos), which is true to pos. Since pos is an int, true gets converted to 1.
As mentioned in the comments, you should turn on your wall warning flags, -Wall -Wextra -Wpedantic and you will immediately get a warning. Try it here: https://coliru.stacked-crooked.com/a/67c5d326f70b9bc1


text:
Q: Is it possible to filter Frequencies with AKEqualizerFilter? I use AKEqualizerFilter from amazing AudioKit framework in my project and everything works perfectly, except decrease of frequencies. On AudioKit GitHub-website is shown that Gain-reduction between -100 and 100 is possible, but when i go below 0, the frequencies are again louder.
How can I reduce gain below 0! of chosen frequencies with AKEqualiserFilter?
This is from AKEqualizerFilter branch:
https://github.com/AudioKit/AudioKit/blob/master/AudioKit/Common/Nodes/Effects/Filters/Equalizer%20Filter/AKEqualizerFilter.swift
/// A 2nd order tunable equalization filter that provides a peak/notch filter
/// for building parametric/graphic equalizers. With gain above 1, there will be
/// a peak at the center frequency with a width dependent on bandwidth. If gain
/// is less than 1, a notch is formed around the center frequency.
///

/// Lower and upper bounds for Gain
    public static let gainRange = -100.0 ... 100.

My Code:

        myEqualiserFilter1 = AKEqualizerFilter(myCompressor)
        myEqualiserFilter1.rampDuration = 0.3
        myEqualiserFilter1.centerFrequency = 50
        myEqualiserFilter1.bandwidth = 50
        kickEqualiserFilter1.gain = 0.0

//Slider action:
conductor.kickEqualiserFilter1.gain = Double(sender.value)

I would like to filter/reduce Frequencies from Audio Samples and I hope it is possible with AudioKit.

A: The range is incorrect in AudioKit, it should be a non-negative number. I've changed it on the develop branch.
https://github.com/AudioKit/AudioKit/commit/b811ac146e95d3666695dba59c6cd87593223066
A zero gain is the most reduction for that bandwidth.


text:
Q: This action could not be completed. Try Again (-22421) I am trying to upload an Apple TV App to the App Store for testing purposes, but I got the issue:

This Action could not be completed. Try Again (-22421)

as in the below image:

So what can I do?

A: For Xcode 8.3.2
i have resolved same issue

"This action could not be completed. Try Again (-22421)"

using following steps...

*

*Quit your xcode (if open)

*in Application Folder,
Xcode 8.3.2 -->Show Package Contents -->Contents -->Application -->Application Loader (Show package contents) -->Contents -->itms -->bin -->iTMSTransporter (right click and Open with Terminal, it will auto start updating...)
after updating
open your project, rebuild your archive and upload it again..

For Xcode 9
issue

"This action could not be completed. Try Again (-22421)"

has been Resolved in Xcode 9. Now, we can upload app through Xcode Organizer also.
https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW876

A: Open Terminal and run:
cd ~

mv .itmstransporter/ .old_itmstransporter/

"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"



A: The problem can not be solved with xCode Upload Process. I was facing same issues few days ago when submitting few of my apps and all apps showing same error. After many tries, I used Application Loader to upload app and it worked.

*

*First go to xcode -> product menu -> archive

*Select Export for Appstore

*Save IPA file

*Now Open Application loader by going to xCode -> xCode Menu -> Open Developer Tool -> Application Loader

*Login with the credentials of account, and select the IPA file.

Submit it! It works!

A: I've tried to load archive nearly 10 times (with all kinds of cleans and reloads, with different versions and provisioning files), still received the same error. Then suddenly on my next attempt it showed me: "cannot proceed with delivery an existing transporter instance is currently uploading this package", I did the following and it helped:
Basically, you need to clear out the transport tokens. This can happen if you were to close out of Xcode while in the middle of submitting an app to iTunes Connect.
/Users/<username>/.itmstransporter/UploadTokens/

Delete any .token files in this directory.
If you are unable to find the .token files, this is because they are hidden in Finder. To hide/show hidden files in Finder, use the following Terminal command (TRUE = UNHIDE, FALSE = HIDE):
defaults write com.apple.finder AppleShowAllFiles TRUE;killall Finder

A: I increased build number but the problem remained.
Then,

*

*I approved renewed licence agreement at itunesconnect.

*I opened App Store application on my MAC, and clicked update button for "Command Line Tools (OS X 10.11) for XCode, Version 7.3"

*I opened XCode. Clicked "Product" button on top bar. While tab content is open, I clicked "alt" key of keyboard to make "Clean Build Folder" option visible. I clicked this option.

*I rebuild my application for the same version that I received below error;

This action could not be completed. Try Again (-22421)

*This time I received below error when I want to upload new version;

This action could not be completed. Try again.

*I clicked Done and clicked blue "Upload to App Store" button again, and upload completed successfully.

I hope this helps.

A: This happens because Apple's servers may not be working correctly. Just wait and try later or next time. It will work for sure eventually.

A: There's another way to fix above error. Try this, it fixed it for me. Open Terminal and run:
cd ~
mv .itmstransporter/ .old_itmstransporter/
"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"

Three above code line will update iTMSTransporter, then you can try uploading in XCode again.
Refs for more details: https://forums.developer.apple.com/thread/76803

A: Tested in Xcode 7.3, 04142016

Instead of clicking the blue Upload to App Store… button from the Organizer or while Archiving, Xcode offers a better tool to do this, but it is a little hidden and the process is not clear how to use it.
Here is what I documented while submitting our latest iOS application to the App Store:
First, do NOT use the blue Upload to App Store… button.
From Xcode's Xcode: Developer Tools: menu, select Application Loader.
Sign in with appropriate credentials that allow you to upload to the App Store.
When Application Loader shows you its main screen, select the Choose button on the lower right of the main window and open your IPA that you exported for the App Store.
Proceed with the submission.
Why you want to do this:

*

*Detailed app submission error reporting. Exact explanations of submission errors. It tells you what's incorrect in your app that you are trying to submit.

*You don't have to deal with the insipid error that prompted this question in the first place.

*It works consistently in my tests where Xcode's Submit App to Store… from the Archive menu does not.

A: (As of May 23, 2018)
Step 1
Open Xcode --> Product tab --> Archive --> export and save to desktop
Step 2
Open Xcode --> Xcode tab --> Open Developer Tool --> Application Loader >> double-click Deliver YourApp and select the recently exported .ipa file from your desktop
Solved the issue every time =)

A: Just In case it is same my mistake.
Did you check both provisioning profile settings in "your Project" and "your Targets"?

A: In my case it was caused by lack of some of the app icons in the Images.xcassets

A: Both developers on our team experienced the same problem, from different machines on May 31st 2017.
I worked around the problem by:

*

*Setting up an app specific password on my Apple ID.

*Exporting the app from the organizer, as an IPA for app store distribution.

*Logging into application loader with that App Specific password and uploading the archive. It worked without any issues.

What a lovely waste of time. Hopefully these steps work for others and save some time.

A: As with all thing Xcode related. A simple reboot fixed the problem for me.

A: When you receive error "Action could not be completed. Try Again (-22421)",
Just try to resubmit same app on iTunes store using XCode again, and you will get the actual error messages next time.
Detailed error message which your received next time will help you what to do actually!!!
If you are receiving same error again and again, you can submit app using "App Loader" and it may success to submit.
[ Take care Point: ]
Please check your app version / build version number is greater than previously submitted version.
You can verify it in Xcode -> Project setting -> General section AND iTunes-Connect-Account -> App Package -> Activity tab

A: I had this problem over and over again. No descriptive description, just the error message that OP posted.
In fact, it was a problem with the build and so had nothing to do with Apple's servers at all, as you might think.
The solution was to go to Organizer and Export the build, then upload it via Application Loader. Here I got the correct error messages. In my case, it was a problem with CocoaPods breaking app extension validations. I solved this and then I could upload my build.
Hope this helps someone like me.

A: I had the same issue. It was related to the Build Settings -> Code Signing Identity -> Release which was set to iOS Developer. If has to be set to iOS Distribution in order for Xcode upload to work.

A: For June 1 2017
Certain combined steps from answer of this thread that worked for me. I am writing the process that worked fine for me.
1) Open terminal and run this
cd ~
mv .itmstransporter/ .old_itmstransporter/
"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"
iTMSTransporter will then update itself, wait till process completes.
2) Logout the apple account from Xcode preferences account and login again instead of creating new Id on iTunes and developer account.
3) Clean the project and archive then export the app from organiser as an IPA for app store distribution.
4) Logging into application loader with same account and upload the ipa.
5) Process will complete successfully.

A: You can try following solutions:
Use Application Loader to upload your app, as Xcode organizer can't upload file (rejects IPA) sometimes, without genuine reason and it's frequently occurring issue, with Xcode Organizer, that apple could not resolve permanently.
Solution for error code: 22421

*

*Apple app upload server is not working properly (not in
connection or lost connection during file upload). Just wait and try
again later (may be after a day).

*Fluctuation in your network
connection, during file upload.

*You may not have added privacy
statements in your info.plist file.

Cocoa Keys: Here, is list of keys (with privacy statements) that you should consider to add in your info.plist file, if you have used that service in your application.

Nowadays, you may also face, this error code: 90186 (with app loader)

*

*Outdated application loader can be reason of this error. Use latest Xcode tool and use application loader from Xcode Tool.

*Incorrect/invalid provisioning profile, associated with your build. Ensure, your have used correct provisioning profile (A provisioning
profile with Distribution/Production mode is require. A Development mode provisioning profile won't allow your to upload app on store.)

You can find latest Application Loader Tool from latest Xcode Tool: Xcode -> Open Developer Tool -> Application Loader

A: Hey i have same issue when i am trying to upload IPA on Appstore. I solved it when i checked that my Distribution provisioning profile was invalid. So just update provisioning profile,download then install and restart Xcode. Now archive and upload it on Appstore it will be done.
OR
Create IPA and upload via Application Loader.
Good luck.

A: The best solution is indeed Application Loader.
I can't comment on Naresh's note on this (I'm too much of a newbie to StackOverflow), but am warning you that if you are using Swift, don't the use Xcode ipa generation system. I prefer manual creation of the IPA by:
1) zipping 2 folders : a Payload folder that contain your .app and a SwiftSupport folder that you can copy from your Xarchive.
2) rename the zip to .ipa.

A: Validating the same archive that failed to upload worked for me. Or just Apple's servers came back up.

A: If you connect a device while the app is building/archiving, your generic device will change to your connected device automatically, and when you are trying to upload to the app store you will have that weird crash.
This:

will change to this automatically:

So to answer your question, I don't know if your issue have been caused because you plugged your iOs device while archiving, but you will be able to reproduce that issue if you plug your iOS device while archiving your app. Hope this helps somebody

A: My problem was with the provisional profiles.
So for me it worked:
Go to Xcode preferences -> Accounts -> In my ID Apple Account -> Select "Download All"
I checked too, in member center and delete all invalid provisionals profiles and:
1 - Close Xcode
2 - Open Xcode, do clean and build of my project.
3 - Archive my code again.

A: Check this list or just keep trying upload!

*

*Got to member center

*Check if there are any invalid provisioning profiles (for some reason, my app store distribution profile has become invalid)

*Delete invalid profiles

*Create new ones

*Download and drag on XCode

*Reboot Mac

*Archive => Upload to App Store

*Everything should be fine again

A: Just try exporting the iPA file and then upload that exported iPA file with application loader. It will solve your problem.

A: Will work for 100% sure. I had the same issue but its solved by below steps:

*

*Delete all profiles from: ~/Library/MobileDevice/Provisioning Profiles/

*Delete developer account from Xcode >> Preference >> Account >> Delete your Apple Id

*Delete derived data

*Restart machine

*Download your provisioning profiles which you require to submit app

*Open your project and clean it

*And try again for submit app.

I hope this will work for all.

A: I was experiencing the exact same error hence being here (failed about 6 times over an hour).
I just tried again now (without changing anything), it worked by itself.
I read on the Apple-forums that it's an issue with Apple servers, nothing to do with your Xcode.
I also read that others trying the upload via ApplicationLoader (Menu -> Xcode -> Open Developer Tool -> Application Loader), this will ask where your code is, you would then have to select your Archive (not the source code), you can upload your code this way if you need. I personally prefer the built-in Xcode instead.
Works either way.
For the record, I am copying the thread from Apple Forums.

A: Uncheck "Include bitcode" box, worked for me.

A: Update June5 ...
Apple appear to have fixed the current particular bug that was present for about the last week.
In short, you can upload with the blue "Upload to App Store..." button, rather than having to use the application loader.

For June 1, 2017
even more information, the seemingly failed uploads
do indeed seem to go to the app store...!

with each of the items there 208-231, I had tried to upload in the normal way, and it failed with the "Try Again (-22421)" code.
In fact, unnoticed by me, they were all going up to the app store, but it looks like they were just getting stuck on endless processing.
I then did I believe exactly what StevenOjo reported (yesterday) above:

*

*Setting up an A NEW account on iTunes with a NEW email address

*ALSO SET THAT UP ON DEVELOPER, remembering that, because Apple is the world's most idiotic organization, developer.apple is totally different from ituneconnect.apple

*From my actual normal account, and this is IN DEVELOPER, NOT ITUNES CONNECT, I invited that new alter ego as an admin

*Exporting the app from the organizer, as an IPA for app store distribution.

*Logging into application loader with that new email and uploading the archive. It worked without any issues.
It's possible it would actually work fine now with my usual account; I don't know.
To be clear, after a very short time (say, two minutes), the final build (ie, 233 above) did indeed become "ready to test" as normal on the app store ..

All the "dud" uploads seem to be stuck forever on processing.
The staggering incompetence of Apple has reached "conspiracy theory" levels....
It is literally not possible to hire programmers and sysadmins, who are this bad.
There must be some sort of conspiracy theory, behind the utter fiasco that is Apple's provisioning. Maybe it's some sort of reverse-psychology marketing plot or something ....... who knows.

Later the same day:
I TRIED UPDATING itmstransporter:
I then tried with a new build number using the normal "Upload to the App Store..." cheery blue button.
It did not work ...
I then tried using Application Loader as described above...
It DID work with ApplicationLoader.
Conclusion ...
Unfortunately, itmstransporter is probably not relevant.
:/  what a fiasco.

A: This occurred to me after I enabled two-factor authentication in my Apple ID. After I disable two-factor authentication, everything works as expected.

A: For me VPN caused that problem. After I disconnected from it upload was successful.

A: I think my issue was that I had previously attempted to upload the same version number of my application and it either failed for another reason, or I cancelled it myself.
I changed the version of my app to a version which had not been used before. Cleaned my project. Re-archived it, then uploaded with no issues.
......
You need to INCREASE your version number, you can't make it smaller...

A: Just close your Xcode and restart your mac.
Then try upload your app again.
It result from the networking problem,not your operation.

A: I also ran into this with my xCode 7.3.1, I did below and looks like 22421 is generic error code if Enable Bitcode is checked/selected:

*

*Removed and regenerated fresh certificates & profiles

*Cleaned project and restarted machine

*Made sure that I have all icons for my watch app and iOS app

*watch image asset/bundle is <5MB

*followed this to enable or disable Bitcode flag

And achieved.
- Still build gets uploaded only if I uncheck Enable Bitcode (which I don't understand why)

A: It is probably everything all right with your code/provisioning profiles/Xcode.
I did try once more, and it worked like a charm. I did not change anything.
Please take note that some actions of people replying earlier did take, could not have any effect on this problem but still, it might look like that actions did help. It would work with or without it anyway.

A: Close your xCode and Application Loader,
Reboot your Mac.
Now, launch Application Loader and send it.

A: I was too having this issues, I had uploaded my application and also updated it once but had no issues, but as i was uploading it for the 3rd time, i came across this issue, tried hell lot of things, scratched my head, googled it for hours, kept on trying the whole day, but nothing happened, but next day( a new light came) and my app uploaded on the first attempt.
Feel like there was some issue from apple side(be it there server, there software xCode or there mac).
So don not get dishearten if facing this problem, you can explore diff things with this problem but its just simple thing to correct this issue is to wait for some time take rest and try again.

A: I am quite sure that Xcode wants us to be logged in with our "normal" account to the App Store app when it tries to upload an app to the Mac App Store (MAS) via the Organizer window.
Usually, we developers all test our apps using our MAS test account. This seems to switch the logged App Store user, too. For me, this always works fine:

*

*Log in to the App Store app with your normal account.

*Retry the upload via the Xcode Organizer. Should then work like expected.

A: Just happened to us.
We were sure the cause is Apple's Christmas holoday (23-27 Dec 2016). But no - we've tried again 5 minutes later and the version passed.
However - the submission button is greyed out due to the holiday.

A: Make sure you have saved the prepare for submission page under itunesconnect.apple.com for the new version

A: Flaky network connection ...
I've had this in the past and it eventually just fixed itself.
But this weekend I tried for days consecutively without success.
However, on a hunch, I've just had success now by changing to a different network and then submitting.

A: The problem can not be solved with xCode Upload Process. I was facing same issues few days ago when submitting few of my apps and all apps showing same error. After many tries, I used Application Loader to upload app and it worked.
First go to xcode -> product menu -> archive
Select Export for Appstore
Save IPA file
Now Open Application loader by going to xCode -> xCode Menu -> Open Developer Tool -> Application Loader
Login with the credentials of account, and select the IPA file.
Submit it! It works!

A: After multiple days of waiting and the problem being persistent. I tried multiple solutions and the below worked for me:
Open your Terminal and put this command

sudo mkdir -p /Users/Shared
sudo chown root:wheel /Users/Shared
sudo chmod -R 1777 /Users/Shared

After I put this, everything works normally.
You can read more here http://www.cnet.com/news/itunes-crashing-with-access-privileges-error-in-10-6-7/

A: I had this problem too. My issue was that I had previously uploaded a build with the same build number.I just increased the build number in Unity and the problem was resolved. As a matter of fact I didn't realise this was the cause until I used Application Loader, which gave a much more informative error message.

A: When above problem exists and you have Two Factor Authentication enabled, just do the following:

*

*go to http://appleid.apple.com and then create your App-Specific Password

*Inside Application Loader login with your apple id and App Specific Password you just created.

*Upload your ipa to itunesconnect.


text:
Q: Vanishing constant term in powers of a Laurent polynomial This is motivated by idle curiosity. I recently learned a result of Duistermaat and Van Der Kallen in "Constant terms of powers of a Laurent polynomial" which says that:

If the constant term of $f^n$ vanishes for all $n\in \mathbb N$, where $f\in \mathbb C[x,x^{-1}]$ is a Laurent polynomial, then either $f\in \mathbb C [x]$ or $f\in \mathbb  C[x^{-1}]$.

Their proof uses complex analysis and I was wondering if one can prove the statement over an arbitrary field of characteristic zero using algebraic or combinatorial methods. Characteristic zero is of course necessary since $x^{p-1}+\frac{1}{x}$ satisfies the conditions in characteristic $p$.

A: I'll give an algebraic argument, which is I think essentially the same as Duistermatt's, but substitutes partial fractions and some valuation theory for complex analysis. K will be algebraically closed of characteristic 0; f will be in K[x,1/x]. We suppose f is not in K[x] or K[1/x]. Let r and -s be the largest and smallest exponent of x appearing in f; r and s are >0.
Lemma:---Let M be a finite extension of the field of fractions of K[[t]]. Extend the obvious valuation on the field of fractions to M. Then if a is in M with f(a)=t, ord f'(a) must be < 1. (To see this note that ord a is 0. Then a has a Newton-Puiseux expansion a0 +(a1)(t^p)+..., with a0 and a1 non-zero, and p a positive rational. The derivation D=d/dt extends to M, and 1=D(f(a)) is the product of f'(a) by (a1)(p)*(t^(p-1))+... So ord f'(a)=1-p which is < 1.)
Theorem 1:---Let S be a subset of the algebraic closure of K(z). Suppose that for each a in S, f(a)=1/z. Then the sum over S of the 1/(af'(a)) cannot be z. (To see this let t=1/z. Then K(z)= K(t) which imbeds in the field of fractions of K[[t]], and we may view S as a subset of a finite extension, M, of this field. By the lemma, each 1/(af'(a)) has ord > -1. But z=1/t has ord equal to -1.)
Now let c_n be the constant term in f^n, and W=1+... be the element sigma (c_n)(z^n) of K[[z]]. Combinatorialists know that a partial fraction argument shows that W is algebraic over L=K(z). Carrying out the partial fraction argument explicitly one finds:
Theorem 2:---There are a lying in a finite extension of L with each f(a) equal to 1/z,
such that zW is the sum of the 1/(af'a)). (So by Theorem 1, W is not 1, and c_1, c_2,... cannot all be 0.)
I'll sketch a proof of Theorem 2. Let U be the element (x^s)(1-zf) of L[x]. If a is a root of u, then f(a)=1/z. So by the lemma f'(a) is not 0. Then U'(a) is not 0, and U is separable. It follows that 1/(1-fz)=(x^s)/U is a sum of c/(x-a) where a runs over the roots of f(x)=1/z. It's easy to see that the c corresponding to a given a is -1/(zf'(a)). I now refer to Lemmas 3.6 and 3.7 of my article "Generating functions attached to some infinite matrices"---see arXiv 0906.1836 or Elec. J. of Comb, v.18 (1) 2011:
If we take U1=x^s and U2=U=(x^s)(1-zf) we are in the situation of Lemma 3.7. W is "the coefficient of x^0 in the element (U1)/(U2)". In the language of the lemma, W is the
sum of the l_0(c/(z-a)). The proof of Lemma 3.6 shows that l_0(1/(z-a)) is either 0 or -1/a.
So z l_0(c/(z-a)) is either 0 or 1/(af'(a)). This completes the proof.


text:
Q: Powershell Catch Exception I'm trying this to catch an exception but it just doesn't work rather just shows me error in the script editor I'm running the script from:-
Path I mentioned in the script "\server\abc" doesn't really exist, so it should catch it as an exception which it is not. HELP HELP
Try
{

Get-ChildItem -Path "\\server\abc"

}
Catch
{

 Write-Host "error"

}

A: You need to set the erroraction to STOP for the error to be terminating - only terminating errors are raised to a catch block.
Try
{

Get-ChildItem -Path "\\server\abc" -ErrorAction Stop

}
Catch
{

 Write-Host "error"

}


text:
Q: File permission problems with Apache, FastCGI, and Prestashop I am running a Prestashop installation on CentOS 6.5 and Apache 2.2.15. A while back I updated Apache and lost the ability to upload product images via Prestashop backoffice along with other problems, such as permission problems with the cache folder inside my Prestashop installation.
My Prestashop installation folders and files are set to user1:psacln, and I would imagine my Apache was set to run with this user and group before I updated it. Now, however, Apache is set to run with apache:apache, and I presume this is causing the problems. However, when I change Apache to run as user1:psacln I get these errors in /var/log/httpd/error_log:
[error] (13)Permission denied: mod_fcgid: couldn't bind unix domain socket /var/run/mod_fcgid/sock/20507.202
[warn] (13)Permission denied: mod_fcgid: spawn process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper error

I tried setting chown -R user1:psacln /var/run/mod_fcgid, but after this I just got Internal Server Error 500 when connecting to the site.
Thus, I suppose my real question is exactly where do I have to make changes besides httpd.conf (user, group) to make things tick properly with FastCGI?


text:
Q: Arc Lengths of Sine Curve I am dealing with the following problem:

In this sketch d and e are arc lengths.
Now I want to find the value of a for which:
$\dfrac{d}{2e}=0.05$
when the value of r is given.
I know that:
$a\sin(2\pi fb)=r$
$a\sin(2\pi fc)=r$
$b=\dfrac{1}{2f}-c$
$d=\int_b^c\sqrt{1+4\pi^2f^2a^2\cos^2(2\pi fx)}\mathrm{d}x$
$e=\int_0^\frac{1}{2f}\sqrt{1+4\pi^2f^2a^2\cos^2(2\pi fx)}\mathrm{d}x$
I have got Matlab installed on my computer, which can be helpful in this case I suppose...

A: Arc length integrals can't be calculated in terms of elementary functions. Result will need to use elliptic integrals.
Straight up calculation with computer shows that equation $\frac{d}{2e} = 0.05$ can be reduced to a form:
$$ \frac{E(\pi-\arcsin(\frac{r}{a}),z)-E(\arcsin(\frac{r}{a}),z)}{4E(z)} = 0.05$$,
where $z = 1- \frac{1}{1+(2af\pi)^2}$, $E(\phi,m)$ is elliptic integral of second kind (EllipticE in Mathematica) and $E(m) = E(\frac{\pi}{2},m)$ is complete elliptic integral.
I wasn't able to reduce this further, because I don't have any prior experience using elliptic integrals. Maybe someone else can continue on this.
Solving this equation agrees with my numerical calculations. For example if $f=1$ and $r=1$, solving the equation gives $a \approx 1.08713$, which is a correct answer.

A: To avoid confusion, let me call your function $g(x)=a\sin(2\pi fx)$. Then using standard arc length formulas from calculus,
\begin{align}
d=&\int_b^c \sqrt{1+[g'(x)]^2}dx\\
e=&\int_{1\over 2f}^{1\over f} \sqrt{1+[g'(x)]^2}dx,
\end{align}
so you want to solve ${d\over 2e}=0.05$.
Are you looking for a numerical answer? If so, we need to know the parameters $a$, $b$, $c$, and $f$.


text:
Q: update in pre save hook I have a user schema like this
const userSchema = new Schema({
  username: {
    type: String,
    unique: true,
    required: true,
  },
  cardIds: [{
    type: Schema.Types.ObjectId,
    ref: 'cards',
  }],
})
mongoose.model('users', userSchema)

I'm attempting to do two things in the pre save hook for user: first, saving each card with the user id and second, adding the cardIds to the User. My code:
const Card = mongoose.model('cards')

userSchema.pre('save', function (next) {
  if (this.cardIds.length === 0) {
    cardList.forEach(async card => {
      const newCard = await new Card({ ...card, user: this })
      this.cardIds.push(newCard) // this is not working
      newCard.save() // this is working
    })
  }
  next()
})

This will add each card into the cards collection with the correct user._id, however, each user will still have an empty array for cardIds.
The way I save the user is (omitting error handling/validation for convenience):
app.post('/users/new', async (req, res) => {
  const newUser = await new User({ username: req.body.username })
  await newUser.save()
  return res.json({ message: 'User created successfully' })
})

A: This is basically a javascript code this.cardIds.push(newCard) to push an element to an array but It doesn't do anything to your mongo database...
Therefore, In order to update an array in mongodb you need to use $push operator
userSchema.pre('save', function (next) {
  if (this.cardIds.length === 0) {
    cardList.forEach(async card => {
      const newCard = new Card({ ...card, user: this })
      const saveNewCard = await newCard.save() // this is working
      const updateUser = await User.update(
        { _id: this._id },
        { $push: { cardIds: saveNewCard._id }}
      )
    })
  }
  next()
})


text: Q: Draw/Simulate from Simplex with Interval Constraints without Rejection Sampling I need to draw an $n$ vector $x$ from the $(n-1)$-dimensional simplex ($x_i \ge 0, \sum_i x_i = 1$) where each dimension also satisfies a simple set of constraints $a_i \le x_i \le b_i$ with each $(a_i, b_i)$ known. My first thought was rejection sampling, but I worry that might be expensive for some configurations of $\{(a_i, b_i)\}$. Is there a shortcut that's faster? Ideally, I'd draw "uniformly" from this set to explore it (each $x$ will be a starting value for later optimization problems).


text:
Q: convert c# datatype to equivalent java datatype I have few datatypes used in C# that I need to translate to Java.
uint, Int16, UInt16, Nullable<Int16>
What will be the appropriate datatype for these in Java?

A: Although the link provided by x2 is good, it's not all that useful when dealing with unsigned primitives. For example: the range of an int is 2,147,483,648 to 2,147,483,647 (which is the same in both languages), but the range of C#s uint is 0 to 4,294,967,295.  Java doesn't have a similar primitive type, so you'd have to use something that contains that range (in this case, a long).
If you are only worried about 1-way compatibility (C# to Java) these should work:

*

*c# --> java

*uint --> long

*Int16 --> short

*UInt16 --> short

*Nullable --> look into the classes that wrap the primitive types (i.e. Integer wraps an int)

EDIT::
I just found this article on MSDN about the differences between the data types in the two languages.

A: Data type equivalents between Java and C#.  Hope you can find it out.

A: Chek it out


text:
Q: python excel synchronization Would just like to know what would be the best way to synchronize python and excel. Meaning: Python script would be running and excel sheet open. Excel would read values from python and python would read values from excel. Would appreciate your help.

A: xlwings allows you to interact with an open Excel workbook using Python. It also allows you to call Python code from within Excel macros.


text:
Q: How to use ABPeoplePickerNavigationController in MonoTouch to pick a specific email address or phone number of a contact? I have been using the ABPeoplePickerNavigationController in a project, written in MonoTouch, to pick a specific email address or phone number of a contact.
The code set a delegate, and in the delegate I implemented the ShouldContinue method, and retrieved the contact using the Handle property of all contacts. Unfortunately, it looks like something changed, or that I used undocumented features, or that I was simply lucky, because now when I'm in the process of updating the app for iPhone 5, the code no longer works.
Edit: Ok, my initial thoughts was that this was caused by changes in MonoTouch, since there has been quite a few updates since I last worked on this app. However, I now removed it from my device and downloaded the version I have on the app store, and it crashes in the same manner, null reference exception.
This means it is an iOS upgrade that made my code non-functional.
The goal of my code:

*

*Pick a person's specific email address, not just the person, but navigating into the details of the person, and selecting a specific email address or telephone number.

The below code deals with phone numbers only, the email code looks 95% similar.
Here is the code that constructs the picker:
var picker = new ABPeoplePickerNavigationController();
picker.Init();
picker.DisplayedProperties.Clear();
picker.DisplayedProperties.Add(ABPersonProperty.FirstName);
picker.DisplayedProperties.Add(ABPersonProperty.Phone);
var del = new PhonePickerDelegate();
picker.Delegate = del;

Here is the delegate class:
private class PhonePickerDelegate : ABPeoplePickerNavigationControllerDelegate
{
    public override bool ShouldContinue(ABPeoplePickerNavigationController peoplePicker, IntPtr selectedPerson, int propertyId, int identifier)
    {
        peoplePicker.DismissModalViewControllerAnimated(true);

        // THE NEXT LINE IS THE ONE THAT NO LONGER WORKS
        var contact = peoplePicker.AddressBook.SingleOrDefault(s => s.Handle == selectedPerson) as ABPerson;

        using (var phones = contact.GetPhones())
        {
            int index = phones.GetIndexForIdentifier(identifier);
            var phone = phones.GetValues()[index];
            var name = (contact.FirstName + " " + contact.MiddleName).Trim() + " " + contact.LastName;
            Selected(name + ": " + phone);
        }
        return false;
    }

    public override void Cancelled(ABPeoplePickerNavigationController peoplePicker)
    {
        peoplePicker.DismissModalViewControllerAnimated(true);
    }
}

Unfortunately this code no longer finds the correct contact, as none of the contacts has a Handle value that corresponds to the selectedPerson IntPtr value.
My questions are these:

*

*How can I fix the above code?

*Can I fix the above code?

*Is there some other class/method/delegate/event or whatnot I should be using instead?

A: You could do something like the following:
Note that AppDelegate.navigation would be your current NavigationController

using MonoTouch.AddressBookUI;
using MonoTouch.AddressBook;

ABPeoplePickerNavigationController _contactController = new ABPeoplePickerNavigationController ();
            AppDelegate.navigation.PresentViewController (_contactController, true, null);

            _contactController.Cancelled += delegate {
                AppDelegate.navigation.DismissViewController (true, null);
                return;
            };

            _contactController.SelectPerson += delegate(object sender, ABPeoplePickerSelectPersonEventArgs e) {
                _importedContact = e.Person;
                AppDelegate.navigation.DismissViewController (true, delegate {
                    // What to do when you dismiss the picker here.
                });
            };

e.Person is only going to give you the whole contact. You would want to do something like:
e.Person.GetEmails().FirstOrDefault

Hope this helps


text:
Q: Should I use # or #! I am doing some ajax page with jQuery, can you tell me which are the differences (especially for SEO point of view) between pages like:

*

*page.html#option1

*page.html#!option1

Edit: mh maybe the second options is google-friendly
Thanks

A: You should use #! if you want your site crawlable by Google. More information is found on their Getting Started guide. So yes, the second version is more SEO-friendly. Another post worth reading is Googles propsal for making ajax pages crawlable.
However, for a users point of view, there's no difference.
Just a tip, sammy.js is a great library for working with this. It allows you to define routes using hash fragments.


text:
Q: How to use FCM with Bazel in Android Studio? I have been trying to implement Firebase with Bazel in Android Studio and my Application is building successfully by running bazel build myapp but Firebase Services are not starting.I am getting FirebaseInitProvider: FirebaseApp initialization unsuccessful. Here is my WORKSPACE and BUILD files.

A: So, I was able to implement it successfully. Refer to my Github repository.


text:
Q: Macro to refer to struct member, homegrown complex type to standard C99 complex conversion I'm reworking the innards of a large scientific application, written in C, so that the homegrown MyComplex type and its associated routines are replaced with arithmetic that's using the C99 complex type.
Some of it is easy, like
#ifdef HAVE_COMPLEX_H
#include <complex.h>
#define double complex MyComplex
#define ComplexAddition(a, b) ((a) + (b))
#define ComplexConjugation(a) (conj(a))
#else
/* very old code, used everywhere in the project */
struct MyComplex { double re, double im };
typedef struct MyComplex MyComplex;
MyComplex ComplexAddition(MyComplex a, MyComplex b) { ... }
MyComplex ComplexConjugation(MyComplex a) { ... }
#endif

That bit works, and I'm happy with it, but some routines peek inside the MyComplex struct, so I thought I was being clever and replaced every occurrence of c.re with RealPart(c) where
#ifdef HAVE_COMPLEX_H
#define RealPart(c) creal(c)
#else
#define RealPart(c) c ## .re
#endif

(and analogous for ImagPart(c) and the im member).
This works splendidly if HAVE_COMPLEX_H is defined, but if I try to compile with HAVE_COMPLEX_H unset, the Clang compiler on my Mac (clang 7.3.0) says:
utils.c:13505:9: error: pasting formed '].', an invalid preprocessing token
        RealPart(m[row][dim - 1]), ImagPart(m[row][dim - 1]));
        ^
./utils.h:39:23: note: expanded from macro 'RealPart'
#define RealPart(c) c ## .re
                      ^
utils.c:13505:36: error: pasting formed '].', an invalid preprocessing token
        RealPart(m[row][dim - 1]), ImagPart(m[row][dim - 1]));
                                   ^
./utils.h:40:23: note: expanded from macro 'ImagPart'
#define ImagPart(c) c ## .im
                      ^

Similarly, the GNU 4.2.1 compiler (on OpenBSD) says
utils.c:9968:1: error: pasting "sum" and "." does not give a valid preprocessing token
utils.c:9968:1: error: pasting "sum" and "." does not give a valid preprocessing token
utils.c:10059:1: error: pasting "]" and "." does not give a valid preprocessing token

I can't seem to get the macro definition correct, and I'm starting to wonder if it's even possible to create a macro that expands to a member of a struct.
It's probably something simple that I have overlooked...

A: The problem was that ## concatenates string, and the arguments to RealPart() and ImagPart() aren't strings.
The correct macro definitions (for when HAVE_COMPLEX_H is not defined) are
#define RealPart(c) c.re
#define ImagPart(c) c.im

It was a bit too obvious for me.


text:
Q: Best and fastest way to use constants Here are the files I have for the moment:
main.py
functions.py
constants.py

I am working on a project in python which requires some constants and I decided to stock them in a python file called constants.py which looks like:
A = 5
B = 6
C = 7
# etc.

This file is both imported as a module in functions.py and main.py
However I would like to add some scripting and change these constants in main.py with parameters for examples, but if I change these constant in main.py they don't change anyway in functions.py which uses it a lot
And I didn't find any solution to that problem yet, so I am using a dictionary but dictionary takes 3 times longer to access a variable i.e:
timeit.timeit(stmt='b = a[5]; b = 0', setup="a = {5:5}", number=5000)
# 0.000302988540795468
timeit.timeit(stmt='b = a; b = 0', setup="a = 5", number=5000)
# 0.00013507954133143288

A: Putting aside the fact that these are not constants, you are probably changing the wrong thing when you're trying to change the values accross files. Use import constants and always refer to constants.A and changes to constants.A will be reflected everywhere. Do not do from constants import A and do not do A = constants.A; A = 10 and expect that to change A to 10 everywhere. Rather do constants.A = 10.


text:
Q: Is it acceptable to throw exceptions when not getting expected JSON data? Working on an android app which gathers data from the Open Weather API as a JSON. However the JSON does not always contain the same keys (ie. sometimes cloud data or a weather description is included, sometimes it isn't).
Right now my code looks like (with some extra getters/setters I didn't include here):
public class WeatherDescrip {

    private String weather;
    private String weather_Desc;
    private String icon;

    public WeatherDescrip(JSONObject weatherObj) {
        try {
            weather = weatherObj.getString("main");
        } catch (JSONException e) {
            weather = null;
            e.printStackTrace();
        }

        try {
            weather_Desc = weatherObj.getString("description");
        } catch (JSONException e) {
            weather_Desc = null;
            e.printStackTrace();
        }

        try {
            icon = weatherObj.getString("icon");
        } catch (JSONException e) {
            icon = null;
            e.printStackTrace();
        }
    }

}

Basically if the JSON I get from the API call doesn't have the necessary key I let the program throw an exception, which will usually happen with at least one piece of data each time the app is run (there is more done like this).
If anyone could please let me know whether this is an acceptable way to code, and possibly how to better implement this I would much appreciate it.
If you haven't noticed I'm also a total noob, sorry in advance if this is a terrible way of doing this.
Many Thanks

A: It's acceptable to throw exceptions whenever you decide. You just need to play how you want to handle it.
Is it acceptable to crash the program and boot your user back to the home screen? Absolutely not. Ever
Just read your data and handle the exceptions gracefully - no icon? Display a default. No data? Tell the user there is a problem right now so they aren't misled by the old data being displayed.
An alternate to avoid the majority of exceptions is to use GSON and Retrofit (I've linked a useful set of tutorials, not the home of GSON or Retrofit). With GSON you can create a model object, automatically map the data and then on your getters always return a value even if the JSON was incomplete
Example:
class MyObj {

    @SerializedName("main")
    private String weather;

    public String getWeather() {
        String weatherResult = weather;
        if (weatherResult == null || "".equals(weatherResult) {
            weatherResult = getString(R.strings.weather_unavailable);
        }
        return weatherResult;
    }

}

A: Throwing an exception is usually reserved for when an error occurs, rather than having it it being an expected result of running your code, since there is overhead in throwing an exception which can make your program execute (slightly) slower.
Realistically, it can be used whenever you like, however you like, but I might instead suggest using has() to check if the key exists before trying to access it. It's a more efficient way of achieving the same result, without having to throw or catch an exception.
if(weatherObj.has('description')) {
    weather_Desc = weatherObj.getString("description");
} else {
    weather_Desc = null;
}

A: This is generally not the correct forum for asking opinions, as you're asking for subjective opinions, there's technically no way to gauge a 'correct' answer, although you're free to select whatever answer you choose, if any ;-)
But in the nature of good will, I'll give you a few of my opinions.
Firstly, Exceptions are for just that, exceptions. If you have a scenario where you are in control of the code, and are aware of a potential for something not to occur in an 'ideal' way (e.g. like this, you're receiving dodgy data), then code for it, i.e.
if (data.contains("somethingOfInterest")) {
    consume(data);
} else {
    getDataFromSomewhereElse();
}

Rather than throw an exception, and force your program to handle it somewhere else (or not). Here's some additional information on why it's not a good idea to use exceptions for control flow.
Also, and this is advice from personal experience; in most scenarios, it's a good idea to do as little as makes sense within an Object's constructor, as it's more ugly to recover if exceptions do occur inside a constructor's method body. Instead, it may be better to encapsulate the logic you have there in some other factory-esque class or method, passing only the gathered data to the constructor. Something like:
public class WeatherDescrip {
    private String weather;
    private String weather_Desc;
    private String icon;

    public WeatherDescrip(String weather, String weather_Desc, String icon) {
        this.weather = weather;
        this.weather_Desc = weather_Desc;
        this.icon = icon;
    }
}

...

public static WeatherDescrip createWeatherDescrip(JSONObject weatherObj) {
    if (!weatherObj.containsKey("main")
        || !weatherObj.containsKey("description")
        || !weatherObj.containsKey("icon")) {
        throw SomeNewMeaningfulException("That I understand and can explicitly handle");
        or....
        return getMyDataFromSomeWhereElse();
    }

    return new WeatherDescrip(
        weatherObj.getString("main"),
        weatherObj.getString("description"),
        weatherObj.getString("icon")
    );
}

I hope this helps.


text:
Q: Testing a TCL package; Tuning it for efficiency I have written / rewritten a package and want to fully test it and do not know how to do so. Specifically when large amounts of data are loaded into the package it slows to a crawl.
I have posted the Code at wiki.tcl.tk
For the test assume that you have 12 columns & 10,000 rows.
where I run into an issue is Tcl2ExXML::outputXML.
How would you go about testing this and fixing where it is crawling at?
set Test_WB         "";
set Test_WS         "";
set ErrorHeadder    "";
set ErrorText       "";
set NormalHeadder   "";
set DateCol         "";

set Test_WB     [Tcl2ExXML::CreateWorkbook      "MassOrderLoad_[clock format [clock seconds] -format %Y%m%d%H%M%S]"]
set Test_WS     [Tcl2ExXML::CreateWorkSheet     $Test_WB "TestWS-[clock format [clock seconds] -format %Y-%m-%d]"]
set ErrorHeadder       [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -font {-nm "Calibri" -ff "Swiss" -sz 14 -fc #FF0000 -b 1} -border {{top bottom left} -ls "continuous" -lw 3} -interior {-ic #DCE6F1 -ip "Solid"}]
set ErrorText          [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -wrap 1 -font {-nm "Calibri" -ff "Swiss" -sz 11 -fc #FF0000}]
set NormalHeadder      [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -font {-nm "Calibri" -ff "Swiss" -sz 14 -fc #000000 -b 1} -border {-bp {top bottom} -ls "continuous" -lw 3 -bp {left right} -ls "continuous" -lw 1} -interior {-ic #DCE6F1 -ip "Solid"}]
set DateCol            [Tcl2ExXML::CreateStyle         $Test_WB -datafmt ymd]
                        Tcl2ExXML::setColumnAttributes $Test_WS 26 -s $DateCol
                        Tcl2ExXML::setColumnAttributes $Test_WS 27 -s $DateCol
set RowNum             [Tcl2ExXML::addRow $Test_WS -s $ErrorHeadder ERROR_MSG -s $NormalHeadder OPERATION  \
                                                   -s $NormalHeadder RowData_1 -s $NormalHeadder RowData_2 \
                                                   -s $NormalHeadder RowData_3 -s $NormalHeadder RowData_4 \
                                                   -s $NormalHeadder RowData_5 -s $NormalHeadder RowData_6 \
                                                   -s $NormalHeadder RowData_7 -s $NormalHeadder RowData_8 \
                                                   -s $NormalHeadder RowData_9 -s $NormalHeadder RowData_10]

foreach Row $DataList
    lassign $Row C1  C2  C3  C4  C5  C6  C7  C8  C9  C10 C11 C12
    set RowNum             [Tcl2ExXML::addRow $Test_WS -s $ErrorText $C1 $C2 $C3 $C4 $C5 $C6 $C7 $C8 $C9 $C10 $C11 $C12]
}

set XML [Tcl2ExXML::outputXML $Test_WB]
puts "XML Created, Cleaning up."
puts $Chan $XML
close $Chan

Tcl2ExXML::DeleteWorkbook $Test_WB

A: It's kind of a large thing you're asking for here and there's all sorts of things that could be issues. Could you split the problem up into smaller pieces and measure them on their own? Try to figure out where the critical problems are? (The time command will help you get some hard data.)
If the fundamental problem is just that the output is large, writing it to a temporary file might be the best option. But that's not necessarily going to help either.
Having scanned through, I see some potentially expensive operations. In particular, clock format and array names are not known for being cheap. Doesn't mean that they're the problem though. That drilling down step I mentioned above is critical.


text:
Q: How to use this fitted model to predict the annual flood data in the future year? Like in the 2030? In this paper: https://sci-hub.se/https://doi.org/10.1080/02664763.2021.1940109, if we have the following dataset: in page 18, Section 6 Application:

The second real data have 59 observations showing the consecutive annual maximum flood data discharge rates of the Feather River at Oroville, CA, for a period of 59 years [45]. This data set was also studied by Mudholkar and Hutson [42]

The authors make the inference of the Gumbel distribution. Consider the MLE of Gumbel distribution:

, the MLE of this real data is $\hat{\mu}=45,438.99$ and $\hat{\sigma}=37,472.34$.
Question: How to use this fitted model to predict the annual maximum flood data in the future year? Like in the 2030?


text:
Q: Probability formula related to distribution balls in boxes. Problem
Suppose there is a distribution of $N$ distinct balls in $n$ different boxes such that each ball has the same probability to be in any box. Let $A_i=\{\text{the i-th box is not empty}\}$.
(1) Show for all $k=1,...,n$, we have $$V_k=P(A_{i_1} \cap ... \cap A_{ik})=\sum_{j=0}^k {k \choose j}(-1)^j(1-\frac{j}{n})^N.$$
(2) Prove that if $\lim_{n,N \to \infty} \dfrac{N}{n}=\lambda$, then $\lim_{n,N \to \infty} V_k=(1-e^{-\alpha})^k$.
I am trying to show this formula by induction. For $n=2$, we have that $$P(A_{i_1} \cap A_{i_2})=1-P((A_{i_1} \cap A_{i_2})^c)=1-(P({A_{i_1}}^c)+P({A_{i_2}}^c)-P({A_{i_1}}^c \cap {A_{i_2}}^c)).$$
This last expression equals to $$1-2\frac{(n-1)^N}{n^N}+\frac{(n-2)^N}{n^N}.$$
By a simple calculation, one can verify $$\sum_{j=0}^k {k \choose j}(-1)^j(1-\frac{j}{n})^N=1-2\frac{(n-1)^N}{n^N}+\frac{(n-2)^N}{n^N}.$$
So the hypothesis is true for $n=2$. Now, I've supposed that the statement is true for $k \leq n$ and I've tried to prove it for $k=n+1$ but I couldn't. I would appreciate if someone could help me to finish the problem with an answer or with suggestions and also any hint to do part (2).

A: $(1)$ Rather than using induction, use the Inclusion-Exclusion Principle:
\begin{eqnarray*}
P\left(\bigcap A_{i_k} \right) &=& 1 - \sum_{r=1}^{k}{P\left(A_{i_r}^c\right)} + \sum_{r \lt s}{P\left(A_{i_r}^c \cap A_{i_s}^c\right)} - \ldots + (-1)^k P(A_{i_1}^c \cap \ldots \cap A_{i_k}^c)
\end{eqnarray*}
The general term on the RHS, with an intersection of $j$ sets, is a sum of $\binom{k}{j}$ terms of the form:
\begin{eqnarray*}
P\left(\bigcap_{r=1}^{j} A_{i_r}^c \right) &=& P(\mbox{all $N$ balls are in the other $n-j$ boxes}) \\
&=& \left(1 - \frac{j}{n}\right)^N
\end{eqnarray*}
This gives us the required answer:
\begin{eqnarray*}
P\left(\bigcap A_{i_k} \right) &=& \sum_{j=0}^k {k \choose j}(-1)^j(1-\frac{j}{n})^N
\end{eqnarray*}
$(2)$ Firstly,
$$\lim_{n,N \to \infty}{(1-\frac{j}{n})^N} = e^{-jN/n} = e^{-\lambda j}$$
using the known limit (with $k=-j, \,\,x=n, \,\,m=N/n$):
$$\lim_{x \to \infty}{(1+\frac{k}{x})^{mx}} = e^{mk}$$which is the first limit in "Notable special limits" section.
Therefore,
\begin{eqnarray*}
\lim_{n,N \to \infty}{V_k} &=& \lim_{n,N \to \infty}{\sum_{j=0}^k {k \choose j}(-1)^j(1-\frac{j}{n})^N} \\
&=& \sum_{j=0}^k {k \choose j}(-1)^j\lim_{n,N \to \infty}{(1-\frac{j}{n})^N} \\
&=& \sum_{j=0}^k {k \choose j}(-1)^j e^{-\lambda j} \\
&=& \sum_{j=0}^k {k \choose j}1^{k-j} \left(-e^{-\lambda}\right)^j \\
&=& (1 - e^{-\lambda})^k \qquad\mbox{(by the Binomial Thm)}
\end{eqnarray*}


text:
Q: Differences between "for ever" and "forever"
What are the differences between "forever" and "for ever" in the
  meaning and usages?

A: Both mean the same. When something is for ever, it's for all time in the future.
In AmE, it's a one word version. However, there's a very little difference. The one-word version refers persistency whereas the two-word term means eternally (though except in the US).
Good information here.

A: They are synonymous, however forever is far more common (at least in the US) than for ever.  I don't think I've ever seen it written as two words and I read quite a lot.

A: for ever - always
forever- continually,eternal

A: Forever is a measurement of time. And for ever is beyond time.


text:
Q: splitting a sas program into multiple programs and finally merging output I created a file (metadata.sas7bdat) which has 100 entries with two columns directory and sasdatasets.
Directory                filename

/home                    abc.sas7bdat

/home                    def.sas7bdat

/home/sub_dir            ghj.sas7bdat

Assume I have sample.sas which just gets the means of each dataset.
Proc means data=abc.sas out=x;

Run;

The above sample.sas should run on each dataset present in metadata file. Right now I have written it in very traditional way of it loops through all the files in metadata and runs proc means on each file and appends all the data. The final dataset has the means of all the files present in metadata.
I believe if I can split the metadata file into 4 parts each having (100/4=25 entries) and submit it as 4 programs and finally merge the output from all the 4 programs It would reduce the processing time by large amount. ( think of 10,000 entries and also assume there is more processing than proc means). Its just I am not well versed with what kind of options to use to submit it as 4 programs and how to sync the output from 4 different processes.
Can you provide me the skeleton of how I should construct this program , I have my vague thoughts but I am sure I can take away   some elegant answers .

A: This question appears to be very similar to Is it possible to loop over SAS datasets?
Breaking into four parts will not reduce the overall processing time.  For each part sure.  If you think the overall there will be reduced processing, what tests or evidence is there supporting that premise ?
When there is a very large set of processing, P, broken into steps, p(1), p(2), ... p(N), you will need to construct a data structure that can store intermediate results, and rules for not repeating past processing when restarting the process after some p(i) experiences an error, or prior attempt at P stops at p(i)
Consider your case, you will need to store, or accumulate intermediate means with a step-key. The natural key would be the directory and filename.
A top-level dispatcher invokes a step macro for each item in the metadata.  The step macro performs the process details when necessary and appends the results in an accumulating way.
Top-level: dispatch each step for the metadata items
%macro process_all (metadata=, results=);
  data _null_;
    set &metadata;

    invoke = cats('%process_step(libname=',libname,',memname=',memname,",results=&results)");
    put 'NOTE: ' _n_= invoke=;

    call execute ('%nrstr(' || trim(invoke) || ')');

    /* global parameter for checking testing 'restart' *

    %if %symexist(test_param_1) %then %do;
    if _n_ >= &test_param_1 then stop;
    %end;
  run;
%mend;

Step-level: core process for one metadata item.  Skip step if done before, otherwise do actions and accumulate results.
%macro process_step(libname=, memname=, results=);

  %local have_results;
  %local step_done;

  %let have_results = %sysfunc(exist(&results,data));
  %let step_done = 0;

  %if &have_results %then %do;
    data _null_;
      set &results; where libname="&libname" and memname="&memname";
      call symput ('step_done', '1'); stop;
    run;
  %end;

  %if &step_done %then %do;
    %put NOTE: This step already done. &=libname &=memname;
    %return;
  %end;

  proc delete data=_step_out;
  proc means data=&libname..&memname noprint;
    var height weight;
    output out=_step_out(label="step output for &libname. . &memname.");
  run;

  data _step_out;
    length libname $8 memname $32.;
    set _step_out;
    libname = symget('libname');
    memname = symget('memname');
  run;

  proc append base=&results data=_step_out force;
  run;
%mend;

Test the scheme for various configurations of metadata
data _1 _2 _3 _4 _5 _6 _7 _8;
  set sashelp.class;
run;

data configuration_1(keep=libname memname);
  length libname $8 memname $32.;
  libname = 'work';
  do index = 1,2,3,7,8; memname='_'||cats(index); output; end;
run;

options mprint;

/*
* reset results to start from scratch
proc delete data=results_1;run;
*/

%let test_param_1 = 3; %* force stoppage after first three items;
%process_all(metadata=configuration_1, results=results_1)

%symdel test_param_1; %* force rerun of all to ignore first three already done items;
%process_all(metadata=configuration_1, results=results_1)

However you actually program the scheme you should be aware of and account for intermediate settings or data sets that might be left over from a prior run or step.


text:
Q: removeEventListener for window.onstorage? The MDN docs describe two possible ways to listen to storage events, window.addEventListener('storage', () => { ... }) and window.onstorage = () => { ... }. In a React app, if I used addEventListener inside of a useEffect hook, I'd want to return the cleanup function window.removeEventListener('storage', ... ) to avoid a memory leak after the component unmounts.
However, window.onstorage = () => { ... } does not offer a way to remove the event listener. Does this mean that it's safe to listen to storage events this way without returning a cleanup function in a useEffect hook?

A: When you add a listener like
window.onstorage = () => { ... }

You are technically allowed to only have one listener in your application on storage. However if window.addEventListener you can have as many event listeners as you want and cleanup requires the same function reference that was passed to addEventListener to be passed on to removeEventListener
You can clean it up by setting the storage listener function to null
useEffect(() => {
    // other code
    return () => { window.onstorage = null };
}, []);


text:
Q: Why does my perl server stop working when i press 'enter'? I have created a server in perl that sends messages or commands to the client. I can send commands just fine, but when i am being prompted for the command on my server i have created, if i press 'enter', the server messes up. Why is this happening?
Here is part of my code:
print "\nConnection recieved from IP address $peer_address on port $peer_port ";
    $closed_message = "\n\tTerminated client session...";
 while (1)
 {

     print "\nCommand: ";

     $send_data = <STDIN>;
     chop($send_data);

     if ($send_data eq 'e' or $send_data eq 'E' or $send_data eq ' E' or $send_data eq ' E ' or $send_data eq 'E ' or $send_data eq ' e' or $send_data eq ' e ' or $send_data eq 'e')
        {

        $client_socket->send ($send_data);
        close $client_socket;
        print "$closed_message\n";
        &options;
        }

     else
        {
        $client_socket->send($send_data);
        }

        $client_socket->recv($recieved_data,8000);
        print "\nRecieved: $recieved_data";
}

}

A: Your server is blocking in the call to $client_socket->recv(...) -- server and client are deadlocked, each waiting for the other to speak.
Try putting this line after your chop():
next unless length $send_data;  # restart the loop if no command submitted

Now, reworking your example, here's what I speculate is happening:
$send_data = <STDIN>;            # $send_data := "\n"
                                 # you just input a blank line with [ENTER]

chop($send_data);                # $send_data := ""

$client_socket->send($send_data) # you send a zero-length buffer
                                 # On my system, this does generate a syscall for
                                 # the sender, but no data is transmitted

$client_socket->recv($buf, 8192) # Hang indefinitely.  Your client application
                                 # received no command, and so it has sent no
                                 # response.

This is just speculation.  As @DVK commented, we don't actually know your symptoms, and it is difficult from your description to guess what is going on.  It does, however, resemble a problem I've been bitten by in the past.


text:
Q: Как стать специалистом по информационной безопасности? Здравствуйте! Я очень интересуюсь темой информационной безопасности, но не знаю с чего начать изучение. Подскажите пожалуйста, с чего начать свой путь белового "хакера"?
P.S. Может быть, есть какие учебные пособия, книги, и т.п?
Заранее спасибо!

A: *

*тебе необходимо понимание низкоуровневой (нулей и еденичек) работы компьютера, для этого тебе нужна математика

*тебе нужно знать распостранённые стандарты (типа rfc-all all заменить на цифры), для этого тебе нужно знание английского

*тебе нужен выход в сеть tor, ибо там пишут что-либо более-менее рабочее


text:
Q: Error releasing structure pointer using free **Hi, technologists. I'm new here. This is my first time to ask questions here. Please forgive me if I have done something wrong. I hope you can be more patient with me. Thank you very much.
I've been studying PointersOnC. And then I had a little trouble writing exercises. The topic is to write a program to achieve matrix multiplication. I defined a structure and named it a matrix. There are variables x and y of type int in the matrix, x and y store the row and column values. The matrix also has a secondary pointer of type int to store the values in the matrix. I define a struct level pointer in the main function and allocate memory through the function. It then allocates the secondary pointer in the structure and stores the value in the secondary pointer. But I had a problem freeing memory. I first release the first level of the second level pointer, then release the second level pointer, and finally release the structure pointer. An error was reported while releasing the structure pointer. **
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct {
    int x, y;           // Rows and Columns
    int** values;       // Numbers in the matrix
} matrix;
// Initialization matrix
bool InitMatrix(matrix** m)
{
    *m = (matrix*)malloc(sizeof(matrix*));
    if (!*m)
        return false;

    (*m)->x = 0, (*m)->y = 0;
    (*m)->values = NULL;        // Secondary pointer

    return true;
}
// Dynamic memory allocation two-dimensional array
bool mallocTowAry(matrix* m)
{
    if (m->x == 0 || m->y == 0)
        return false;
    m->values = (int**)malloc(sizeof(int*) * m->x);
    if (!m->values)
        return false;
    for (int i = 0; i < m->x; i++)
    {
        m->values[i] = (int*)malloc(sizeof(int) * m->y);
        if (m->values[i] == NULL)
            return false;
    }
    return true;
}
// Store the number of the matrix in the array
void assginTow(matrix* m)
{
    for (int i = 0; i < m->x; i++)
    {
        printf("Please enter the elements in the i-th row, separated by spaces:\n");
        for (int j = 0; j < m->y; j++)
            scanf("%d", &m->values[i][j]);
    }
}
// Initialize the secondary pointer in the structure
bool assginMatrix(matrix* m, int x, int y)
{
    m->x = x, m->y = y;
    if (!mallocTowAry(m))
        return false;
    assginTow(m);

    return true;
}
// Print matrix
void showMatrix(matrix* m)
{
    for (int i = 0; i < m->x; i++)
    {
        for (int j = 0; j < m->y; j++)
            printf("%d ", m->values[i][j]);
        printf("\n");
    }
}
int main(int argc, char* args[])
{
    matrix* m_1;
    // Initialize the matrix, but without x and y
    if (!InitMatrix(&m_1))
        return 1;

    int x, y;
    printf("Please enter the row and column values, separated by spaces: \n");
    // Read in x and y
    scanf("%d %d", &x, &y);
    if (!assginMatrix(m_1, x, y))
        return 2;

    showMatrix(m_1);

    // Destroy the matrix
    DestoryMatrix(&m_1);

    return 0;
}


text:
Q: Google Bar Chart Annotation Prints Larger Font Than Browser Displays with Firefox Problem:
Google Bar Chart displays annotations correctly in the browser (Firefox 43.0.3) but during printing will enlarge the font of certain annotations making them unreadable.

*

*This problem does not occur using Chrome (ver 47.0.2526.106 - 64bit) or Safari (ver 9.0.2).

*Interestingly IE 11 (11.0.26) seems
to print the annotation fonts fine but doesn't handle other aspects
of Google Chart printing.

*All testing done on Mac OSX (10.11.2) and
Windows 7 Enterprise.

Question:
Is there a way to fix this problem in Firefox: printing annotations in correct font size?  The only solution I have is to not use annotations or create a separate 'print' page that is identical to the view except all annotations are turned off.  Not ideal solutions.  Curious that I could not find this specific 'annotation printing problem' discussed anywhere else.  Appreciate guidance, thoughts, brain-storming, work-arounds.
Research:
I assume this is a browser-specific rendering problem when printing SVG (format in which Google renders the charts). The only solution seems to be using the chart.getImageURI() method which returns a base-64 encoded PNG string (ref link). Doing this however will make your charts no longer interactive (because they will render as PNG) and it doesn't work on IE<9.0 (if that's an issue for you).  Perhaps another issue might be the typeface used by Google Chart annotations not being recognized when printing?
Possible related articles:

*

*@font-face font-size rendered larger in some browsers than others
Example:
The problem exists even on the Google API documentation page:
https://developers.google.com/chart/interactive/docs/gallery/barchart


text:
Q: Selenium Grid Proxy: how to get the response after a command get executed I created a Selenium Grid proxy, I want to log every command done, the problem is I can't find a way to get the response of the command for example after "GetTitle" command I want to get the "Title" returned.

A: Where do you want this logging to be done ? If you attempt at logging this at the Custom Proxy, then these logs would be available only on the machine that runs the hub. Is that what you want ? If yes, then here's how you should be doing it :
Within an overloaded variant of org.openqa.grid.internal.listeners.CommandListener#afterCommand (this method should be available in your DefaultRemoteProxy extension object that you are building), extract this information from within the javax.servlet.http.HttpServletRequest by reading its entity value and then translating that into a proper payload.
Here's how the afterCommand() (or) beforeCommand() method from your customized version of org.openqa.grid.selenium.proxy.DefaultRemoteProxy can look like:
org.openqa.grid.web.servlet.handler.SeleniumBasedResponse ar = new org.openqa.grid.web.servlet.handler.SeleniumBasedResponse(response);
if (ar.getForwardedContent() != null) {
    System.err.println("Content" + ar.getForwardedContent());
}

If that's not what you want, then you should be looking at leveraging the EventFiringWebDriver. Take a look at the below blogs to learn how to work with the EventFiringWebDriver. The EventFiringWebDriver does not require customization at the Grid side, it just needs you to make use of the EventFiringWebDriver which would wrap within it an existing RemoteWebDriver object and the listeners you inject to it will help you get this.

*

*http://darrellgrainger.blogspot.in/2011/02/generating-screen-capture-on-exception.html

*https://rationaleemotions.wordpress.com/2015/04/18/eavesdropping-into-webdriver/ (This is my blog) Here I talk about not even using EventFiringWebDriver but instead work with a decorated CommandExecutor which would log all these information for you.


text:
Q: New post - First argument in form cannot contain nil or be empty This is error I'm getting when I click on "New Post:

First argument in form cannot contain nil or be empty

My PostController:
class PostsController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]

def index
    @posts = Post.all
end

def show

end

def edit

end

def update
    @post.update(post_params)
    redirect_to posts_path
end

def new
    if user_signed_in?
        @post = Post.new
    else
        flash[:alert] = ":("
    end
end

def create
    @post = Post.new(post_params)
    @post.user_id = current_user.id
    @post.save
    redirect_to posts_path
end

def destroy
    if user_signed_in?
        @post.destroy!
    else
        flash[:alert] = ":("
    end
    redirect_to posts_path
end

private
def post_params
    params.require(:post).permit(:body)
end

def set_user
    @post = Post.find(params[:id])
end

end
and posts#index:
<% @posts.each do |post|  %>
<%= post.body %>
<%= link_to 'Show', post %>
<%= link_to 'Edit', edit_post_path(post) %>
<%= link_to 'Delete', post, method: :delete %>

_form.html.erb
<%= form_for(@post) do |f| %>

    <%= f.label :body %>

    <%= f.text_area :body %>

    <%= f.submit %>

<% end %>

A: you should check your "new.html.erb"  or "_form.html.erb" file. to see if the "form_for" method is correctly called.

A: If you are using devise, You can get this by adding a before action:
before_action :authenticate_user!, only: [:new]

and you new action as:
def new
  @post = Post.new
end


text:
Q: Yii2- Failed to create Mongodb models using Gii I can't create MongoDb models using Gii module code generator. Gets the below error :
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: common\components\MongoConnection::getTableSchema()

A: Gii should not be used to create MongoDB Models.
MongoDB documents may change from one to another and there is no "collection definiton", as oposed to "table schemas" where you can get all column names and types.
This is the reason why a model cannot be created automatically and should be created manually.

A: There is a Gii component to help you generate MongoDB ActiveRecords.
Here's a little YouTube video that shows you exactly how it modify Yii2 configuration, create an active record and generate a CRUD controller.
http://www.youtube.com/watch?v=1urmws7hz5Q


text:
Q: If List Items cross more than 5 remove items and show next 5 list items javascript html I m trying to dynamically generate a UL list, but the issue is list is generating list of 1000 items. so I want to limit the list,
Below is list which will keep on generating dynamically

aa
bb
cc
dd
ee
ff
gg
hh
ii
jj
kk
ll
mm
nn
.
.
.
nth

I want to divide the UL list in group so it should show 1st 5 list items and then remove it and show next 5 list items and again steps should repeat.
I m generating list in

I tried this

$(function () {
    $('span').click(function () {
        $('#datalist li:hidden').slice(0, 2).show();
        if ($('#datalist li').length == $('#datalist li:visible').length) {
            $('span ').hide();
        }
    });
});
ul li:nth-child(n+3) {
    display:none;
}
ul li {
    border: 1px solid #aaa;
}
span {
    cursor: pointer;
    color: #f00;
}

aa

bb

cc

dd

ee

ff

gg

hh

ii

jj

readmore

A: So if the goal is to only show the last 5 items, you can do this with just CSS using nth-last-of-type.
Note: ignore the javascript and the button, its just there to demonstrate the adding of an item to the list.

$('button').on('click',function(){
 var lastItem = $('#datalist li:last-child').html();
  var nextItem = parseInt(lastItem)+1;
  $('#datalist').append('
'+nextItem+'
')
});
ul#datalist > li {
  display: none;
}
ul#datalist > li:nth-last-of-type(-n+5) {
display: block;
}

01

02

03

04

05

06

07

08

09

10

<button>Add item</button>

A: Ok, here is a JS solution that will remove all but the last 5 items.
Again, please ignore the button thats adding the items, this is only here to demonstrate what happens when an item is added.

$('button').on('click', function() {
  var lastItem = $('#datalist li:last-child').html();
  var nextItem = parseInt(lastItem) + 1;
  $('#datalist').append('
' + nextItem + '
')
  filterList();
});

function filterList() {
  $("#datalist > li").not(":nth-last-of-type(-n+5)").remove();
}

filterList();

01

02

03

04

05

06

07

08

09

10

<button>Add item</button>


text: Q: Prove that there are infinitely many prime numbers that satisfy $ (p^2)+2p=-1 \pmod 6$, I have been struggling with this question. I don't know how to proceed. Would you be able to walk me through the steps to complete it?


text:
Q: Problem getting the actual width of control before rendering in wpf I have a wpf window that hosts a control.
The window's height and width are set to SizeToControl.
Now I need to position this Window relative to the position of its parent window.(basically the Top right position).
(So my windows Top = ParentWindow.Top, and Left = ParentWindow.Left + ParentWindow.ActualWidth - control.ActualWidth so that my window is positioned inside the parent window but to its right corner)
So i will need to set the Top and Left of the window. To do this I need the Actual Width of the control that is being hosted inside it....but I can only get this once I actually do,
Window.Show(control,parent)
Is there a way to get around this problem? How do I get the actual rendered width of the control before it is actually shown?
Thanks!

A: Have you tried this approach?
    public partial class ShellWindow : Window
    {
        public ShellWindow(IShellPresentationModel model)
        {
            InitializeComponent();
            this.Loaded += ShellWindow_Loaded;
        }

        void ShellWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var innerWindow = new InnerWindow();
            innerWindow.Owner = this;
            innerWindow.Loaded += InnerWindow_Loaded;
            innerWindow.Show();
        }

        void InnerWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var w = (InnerWindow)sender;
            w.Owner = this;
            w.Top = this.Top;
            w.Left = this.Left + this.ActualWidth - w.ActualWidth;
        }
}


text:
Q: Can I create a .NET 4.0 application in Visual Stduio 2008? I have a visual studio 2008.
I have downloaded and installed a .NET 4.0 package.
But I still can't create a .net 4.0 applications. VS 2008 shows it can only create 2.0, 3.0, 3.5 applications.

A: This is not possible. .NET 4.0 can only be used with Visual Studio 2010.
Visual Studio 2008 could target 2.0, 3.0 and 3.5 because there were all based on the same runtime and language (3.0 and 3.5 were essentially additional libraries and updated compilers). 4.0 however is a different runtime.

A: yes in VS 2008 you can't able to create .Net 4.0 applications.For that you need VS 2010

A: That's because VS2008 doesn't support .NET 4 as a target platform. For that you need either VS2010 or just use the compiler that ships with the framework (but then you will not have an IDE).


text:
Q: Databinding not observe LiveData in ViewModel I am trying to use Data binding with LiveData in ViewModel. But when using Transformations.map functions not trigged without adding observers explicitly. Data binding in XML not generate observers for LiveData in ViewModel.
LoginFragment.kt
class LoginFragment : Fragment() {

    var homeViewModel: HomeViewModel? = null

    companion object {
        val TAG : String = "LoginFragment"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val binding = DataBindingUtil.inflate<FragmentLoginBinding>(inflater, R.layout.fragment_login, container, false)
                .apply {
                    setLifecycleOwner(this@LoginFragment)
                    loginButton.setOnClickListener {
                        signInWithEmail()
                    }
        }

        return binding.root
    }

    /*private fun observeHomeFragmentUIDataLiveData() {
        homeViewModel?.homeFragmentUIDataLiveData?.observe(this, Observer {
            val email = it.email
            Toast.makeText(activity,email, Toast.LENGTH_SHORT).show()
        })
    }

    private fun observeLoginErrorEventLiveData() {
        homeViewModel?.loginErrorEventLiveData?.observe(this, Observer {
            Toast.makeText(activity,it, Toast.LENGTH_SHORT).show()
        })
    }*/

    /**
     * Sign In via Email
     */
    fun signInWithEmail(){
        val email = email_text_input_layout.editText?.text.toString()
        val password = password_text_input_layout.editText?.text.toString()

        var cancel : Boolean? = false
        var focusView : View? = null

        if(password.isEmpty()){
            password_text_input_layout.error = getString(R.string.this_field_is_required)
            focusView = password_text_input_layout
            cancel = true
        }

        if(email.isEmpty()){
            email_text_input_layout.error = getString(R.string.this_field_is_required)
            focusView = email_text_input_layout
            cancel = true
        }

        if(cancel!!){
            focusView?.requestFocus()
        }
        else{
            homeViewModel?.signInWithEmail(email,password)

            /*homeViewModel?.signInWithEmail(email,password)?.observe(this, Observer {
                val email = it
                Toast.makeText(activity,""+email, Toast.LENGTH_SHORT).show()
            })*/
        }
    }
}

fragment_login.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable name="homeViewModel" type="com.rramprasad.adminapp.HomeViewModel"/>
    </data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="LoginFragment">

<!-- Skipped some code for clarity -->

<androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/error_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{homeViewModel.loginErrorEventLiveData.value}"
        app:isGone="@{homeViewModel.isLoginSuccess}"
        android:textColor="@android:color/holo_orange_dark"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/password_text_input_layout"
        app:layout_constraintBottom_toBottomOf="@id/login_button"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

HomeViewModel.kt
class HomeViewModel(application: Application) : AndroidViewModel(application) {

    val homeRepository: HomeRepository?

    init {
        homeRepository = HomeRepository()
    }

    // UI Data for HomeFragment
    val homeFragmentUIDataLiveData : MutableLiveData<HomeFragmentUIData> = MutableLiveData()

    // UI Data for LoginFragment
    val loginErrorEventLiveData : MutableLiveData<String> = MutableLiveData()

    var isLoginSuccess: LiveData<Boolean>? = null

    fun signInWithEmail(email: String, password: String) : LiveData<Boolean>? {
        val signInResponseMutableLiveData : MutableLiveData<Any> = homeRepository?.signInWithEmail(email, password)!!

        isLoginSuccess = Transformations.map(signInResponseMutableLiveData) { signInResponse ->
            when (signInResponse) {
                (signInResponse is FirebaseUser) -> {
                    val firebaseUserEmail = (signInResponse as FirebaseUser).email
                    homeFragmentUIDataLiveData.value = HomeFragmentUIData(firebaseUserEmail ?: "")
                    return@map true
                }
                else -> {
                    loginErrorEventLiveData.value = signInResponse.toString()
                    return@map false
                }
            }
        }

        return isLoginSuccess
    }
}

BindingAdapters.kt
@BindingAdapter("isGone")
fun bindIsGone(view: View, isGone: Boolean) {
    view.visibility = if (isGone) {
        View.GONE
    } else {
        View.VISIBLE
    }
}

Android studio version:

Android Studio 3.2 RC 3
Build #AI-181.5540.7.32.4987877, built on August 31, 2018
JRE: 1.8.0_152-release-1136-b06 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.4

build.gradle:
android {
    compileSdkVersion 28
    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled = true
    }
}


text:
Q: Trading view strategy tester Is there a way to disable strategy tester from opening up automatically after adding a strategy to chart?
Also the properties inputs from the settings, to make it only accessible from the strategy tester.

A: Not possible I think, by default, a backtest strategy script always opens the strategy tester first. There is no way to change that
Maybe, create a ticket to the TradingView helpdesk team asking for this to change?


text:
Q: Attempting to use Mode Wrap in Cuda I'm attempting to use the cudaAddressModeWrap function in Cuda, however, I'm having some difficulties.
I have included my code below:
texture <float, 2, cudaReadModeElementType> tex;

__global__ void transformKernel( float* Btmp, int width, int height)
{
    unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;
    unsigned int y = blockIdx.y*blockDim.y + threadIdx.y;

  if ( (x < width) && (y < height) )
  {
    if( x == 0 || x == 1 )
      Btmp[y*width+x] = tex2D(tex, x, y);
    else
    {
      Btmp[y*width+x] = tex2D(tex, x, y) + \
        (0.15 * tex2D(tex, x - 2, y))    + \
        (0.65 * tex2D(tex, x - 1, y))    + \
        (1.35 * tex2D(tex, x + 1, y))    + \
        (1.85 * tex2D(tex, x + 2, y));
      Btmp[y * width + x] /= float(5);
    }
  }
}

I want periodic boundary conditions so Mode Wrap should be perfect for this. I think I am setting up the parameter incorrectly but I'm not sure. Here is the relevant code.
  int i, j;
  float **A;
  float *Atmp;

  A = (float **)malloc( ndim * sizeof(float *));
  Atmp = (float *)malloc ( ndim * mdim * sizeof(float));
  for(i=0;i<ndim;i++)
    A[i] = &Atmp[i * mdim];

  for(i=0;i<ndim;i++)
  {
    for(j=0;j<mdim;j++)
    {
      A[i][j] = 0;
    }
    A[i][0] = 0.85 * (float)((i+1)*(i+1))/(float)(ndim*ndim);
    A[i][1] = 1.00 * (float)((i+1)*(i+1))/(float)(ndim*ndim);
  }

  cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);

  cudaArray* cu_array;
  cudaMallocArray( &cu_array, &channelDesc, mdim, ndim );
  cudaMemcpyToArray( cu_array, 0, 0, Atmp, ndim * mdim *sizeof(float), cudaMemcpyHostToDevice);

  tex.addressMode[0] = cudaAddressModeWrap;
  tex.addressMode[1] = cudaAddressModeWrap;

  tex.filterMode = cudaFilterModePoint;

  tex.normalized = false;

  cudaBindTextureToArray(tex, cu_array, channelDesc);

  dim3 dimBlock(4, 4, 1);
  dim3 dimGrid(mdim / dimBlock.x, ndim / dimBlock.y, 1);

  float* d_data = NULL;
  cudaMalloc( (void**) &d_data, ndim * mdim *sizeof(float));

  transformKernel<<< dimGrid, dimBlock, 0 >>>(d_data, mdim, ndim);

  cudaMemcpy(Btmp, d_data, ndim*mdim*sizeof(float), cudaMemcpyDeviceToHost);

The desired output is:
1.33e-02 1.56e-02 2.43e-03 4.69e-04 0.00e+00 0.00e+00 4.91e-03 9.37e-03
5.31e-02 6.25e-02 9.72e-03 1.88e-03 0.00e+00 0.00e+00 1.97e-02 3.75e-02
1.20e-01 1.41e-01 2.19e-02 4.22e-03 0.00e+00 0.00e+00 4.42e-02 8.43e-02
2.13e-01 2.50e-01 3.89e-02 7.50e-03 0.00e+00 0.00e+00 7.86e-02 1.50e-01
3.32e-01 3.91e-01 6.07e-02 1.17e-02 0.00e+00 0.00e+00 1.23e-01 2.34e-01
4.78e-01 5.62e-01 8.75e-02 1.69e-02 0.00e+00 0.00e+00 1.77e-01 3.37e-01
6.51e-01 7.66e-01 1.19e-01 2.30e-02 0.00e+00 0.00e+00 2.41e-01 4.59e-01
8.50e-01 1.00e+00 1.56e-01 3.00e-02 0.00e+00 0.00e+00 3.15e-01 6.00e-01

And using the Texture memory I get:
1.33e-02 1.56e-02 2.43e-03 4.69e-04 0.00e+00 0.00e+00 0.00e+00 0.00e+00
5.31e-02 6.25e-02 9.72e-03 1.88e-03 0.00e+00 0.00e+00 0.00e+00 0.00e+00
1.20e-01 1.41e-01 2.19e-02 4.22e-03 0.00e+00 0.00e+00 0.00e+00 0.00e+00
2.13e-01 2.50e-01 3.89e-02 7.50e-03 0.00e+00 0.00e+00 0.00e+00 0.00e+00
3.32e-01 3.91e-01 6.07e-02 1.17e-02 0.00e+00 0.00e+00 0.00e+00 0.00e+00
4.78e-01 5.62e-01 8.75e-02 1.69e-02 0.00e+00 0.00e+00 0.00e+00 0.00e+00
6.51e-01 7.66e-01 1.19e-01 2.30e-02 0.00e+00 0.00e+00 0.00e+00 0.00e+00
8.50e-01 1.00e+00 1.56e-01 3.00e-02 0.00e+00 0.00e+00 0.00e+00 0.00e+00

A: According to the documentation for the addressing mode:

The addressing mode. It is valid to call the device functions of Section B.8 with coordinates that are out of range. The addressing mode defines what happens in that case. The default addressing mode is to clamp the coordinates to the valid range: [0, N) for non-normalized coordinates and [0.0, 1.0) for normalized coordinates. If the border mode is specified instead, texture fetches with out-of-range texture coordinates return zero. For normalized coordinates, the wrap mode and the mirror mode are also available. When using the wrap mode, each coordinate x is converted to frac(x)=x floor(x) where floor(x) is the largest integer not greater than x. When using the mirror mode, each coordinate x is converted to frac(x) if floor(x) is even and 1-frac(x) if floor(x) is odd. The addressing mode is specified as an array of size three whose first, second, and third elements specify the addressing mode for the first, second, and third texture coordinates, respectively; the addressing mode are cudaAddressModeBorder, cudaAddressModeClamp, cudaAddressModeWrap, and cudaAddressModeMirror; cudaAddressModeWrap and cudaAddressModeMirror are only supported for normalized texture coordinates

Since you are not using normalized coordinates:
tex.normalized = false;

the wrap mode is not available.


text:
Q: SharePoint Power Shell copy certain version of a document from one library to another I have a source document library, with varying versions for each document. let's say there is a document in the library that has versions 6.0, 5.0, 4.0. The current version of this document is 6.0.
I want to copy the document's 4.0 version to another target document library using a sharepoint PowerShell script

A: Please try the script below, change the required parameter to yours. And change the version number to the one you need.
#Variables for Processing
$WebURL="your site url"
$SourceFile="your file path"
$TargetLibrary="target library name"

#Get Objects
$Web = Get-SPWeb $WebURL
$File = $Web.GetFile($SourceFile)
$Version4=$File.versions.GetVersionFromLabel("1.0")
$TargetLibrary = $Web.GetFolder($TargetLibrary)

#Copy the file into the Target library
$TargetLibrary.Files.Add($File.Name, $Version4.OpenBinary(), $true)

A: If you open the version history of any document, you will find each older version have a URL like http://xxxxx/_vti_history/xxxxx . By providing the right URL your script can download specific version directly. Then upload to another library.
There is a good PowerShell sample script here please refer to this old thread.