text:
Q: Least squares regression: assumptions on the corresponding data generating distribution? This question was inspired by this answer to the question: Linear regression: any non-normal distribution giving identity of OLS and MLE?
The setting is the following: assume the following regression model:
$$Y = f_{\beta}(X) + \epsilon,$$
where $\epsilon$ is a zero-mean random variable and $f_\beta$ a function of $x$ parametrized by $\beta$. We observe data $(x_i, y_i)_{i=1}^n$ and want to find an estimate for $\beta$ in the above model. This can be done with least squares regression:
$$\hat \beta = \arg \min_\beta \sum_{i=1}^n (y_i - f_\beta(x_i))^2. $$
Now, this corresponds to assuming a family of densities of the following form:
$$ p(y|x;\beta) =c g(x, y) \exp(-\kappa(y - f_\beta(x))^2),$$
where $g(x,y)$ does not depend on $\beta$ and $c$ is a constant, and performing MLE over $\beta$ with the above family: $\hat \beta = \arg \max_\beta \prod_{i=1}^n p(y_i|x_i;\beta) $.
Note that $g(x,y)$ above does not matter in maximizing the likelihood, so in principle it is unconstrained. However, I would like to understand if there is any condition $g(x,y)$ has to satisfy. Specifically, let us assume that the above model is valid for $\beta = \beta^\star$, ie the data were actually generated in that way for that value of $\beta$. This also means that the expected value $E[Y|X=x] = f_{\beta^\star} (x)$. Therefore, I believe the expectation of $Y$ under $p(y|x;\beta^\star)$ should be equal to $f_{\beta^\star} (x)$, ie:
$$ \int y\ p(y|x;\beta^\star) dy = c \int y\ g(x,y) e^{-\kappa(y - f_{\beta^\star}(x))^2} dy = f_{\beta^\star}(x), \ \forall\ x.$$
My question is: can we say anything about $g(x,y)$ given the latter expression? My intuition is that, as that holds for any $x$, if $f_{\beta^\star}(x)$ is not constant, there may be some constraints on how $g$ depends on both arguments, but I don't know how to go farther and am not sure about that.


text:
Q: Try-surrounded imports and catching KeyboardInterrupt I'm seeing a lot of the following pattern in a codebase I'm checking out at the moment:
try:
    import moduleA
    import moduleB
    from custom.module.A import AX
    from custom.module.A import AY
except KeyboardInterrupt:
    sys.exit()

Haven't seen it before. What's this guarding against?

A: The only way I can think of that makes sense is if some of those modules for some reason have input/raw_input that run inside of them, or otherwise deliberately raise KeyboardInterrupt for some reason.
Otherwise, really not quite sure what it's meant to do... (unless some of the imports take hours to run, and if you get fed up, can abandon it without seeing a traceback - but that doesn't make much sense either)

A: Whenever you press ctrl+C from your keyboard, a KeyboardInterrupt is sent to the python process. If not caught, it will cause an exception in the code so that the code exits wherever it is currently. In this case, there is no special action being taken, but, just a call to sys.exit(), which again causes the program to exit, but, without displaying the stack traceback
From the documentation:
http://docs.python.org/2/library/exceptions.html?highlight=keyboardinterrupt#exceptions.KeyboardInterrupt

A: It's not guarding against anything, at least not obviously. It's catching a KeyboardInterrupt:

Raised when the user hits the interrupt key (normally Control-C or
  Delete). During execution, a check for interrupts is made regularly.
  The exception inherits from BaseException so as to not be accidentally
  caught by code that catches Exception and thus prevent the interpreter
  from exiting.

Then simply exiting, which is what an interrupt would do anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I upload files to a folder in Google Team Drive with a service account credential? I'm trying to implement a new service to our application using Google Drive Java API v3 that is responsible for uploading files to a specific folder in Google Team Drive. I use the service account that my company has created specifically for this project and also generated a JSON file from Google Developer Console that contains a private key. I have also shared the folder to the service account using its email xxxxx@xxxx.iam.gserviceaccount.com and granted rights of Content Manager to the shared Team Drive. Furthermore, G Suite domain-wide of authority has not been granted to this service account for a few reasons.
What am I trying to achieve here:
I want to build and return an authorized Google Drive client service using the service account's generated private key and therefore be able to send the requests to upload files to the folder in Google Team Drive.
What I currently use:

*

*IntelliJ IDEA IntelliJ IDEA 2018.1.7 (Ultimate Edition)

*Spring Boot 2

*Java 10.0.1

What is the problem:
I'm unable to return the authorized Google Drive client service successfully and the requests to upload files are not being sent at all. What makes it more confusing is that there are no exceptions thrown. However, a credential is returned successfully with the access token and an expiration time.
What I have already read/found:
Using OAuth2.0 for Server to Server Application: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
Java Quickstart on creating simple requests to the Drive API:
https://developers.google.com/drive/api/v3/quickstart/java
JavaDoc reference for the Drive API:
https://developers.google.com/resources/api-libraries/documentation/drive/v3/java/latest/
How to upload file to google drive with service account credential:
How to upload file to google drive with service account credential
How to access Team Drive using service account with Google Drive .NET API v3:
How to access Team Drive using service account with Google Drive .NET API v3
Authentication to upload files in my drive using Google drive API client library for Java
Authentication to upload files in my drive using Google drive API client library for Java
What I have already tried:

*

*Using GoogleCredential-class to return the credential (that class appeared to be deprecated: https://googleapis.dev/java/google-api-client/latest/)

*Finding replacement for the deprecated class by looking into Github projects and tutorials

*Update and check all the missing dependencies in pom.xml

*Checked the settings of the shared Team Drive to make sure it is shared with the service account

*Added logs to make sure the problem is really what I described above

*Tried Java Quickstart on creating simple requests to the Drive API-tutorial (however, that turned out to be not completely suitable for our project's needs)
The relevant part of ContractStateUpdateService.java:
File fileMetadata = new File();
fileMetadata.setName(fileTitle);
// setting the id of folder to which the file must be inserted to
fileMetadata.setParents(Collections.singletonList("dumbFolderId"));
fileMetadata.setMimeType("application/pdf");

byte[] pdfBytes = Base64.getDecoder().decode(base64File.getBytes(StandardCharsets.UTF_8));
InputStream inputStream = new ByteArrayInputStream(pdfBytes);

// decoding base64 to PDF and its contents to a byte array without saving the file on the file system
InputStreamContent mediaContent = new InputStreamContent("application/pdf", inputStream);

logger.info("Starting to send the request to drive api");
File file = DriveUtils.getDriveService().files().create(fileMetadata, mediaContent).execute();
logger.info("Succesfully uploaded file: " + file.getDriveId());

DriveUtils.java:
public class DriveUtils {

    private static final String APPLICATION_NAME = "Google Drive Service";

    // setting the Drive scope since it is essential to access Team Drive
    private static List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);

    // private key is stored at the root of the project for now
    private static String PRIVATE_KEY_PATH = "/path/to/private_key.json";
    private static final Logger logger = LoggerFactory.getLogger(DriveUtils.class);

    // build and return an authorized drive client service
    public static Drive getDriveService() throws IOException, GeneralSecurityException {
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredentials credentials;

        try (FileInputStream inputStream = new FileInputStream(PRIVATE_KEY_PATH)){
            credentials = ServiceAccountCredentials.fromStream(inputStream).createScoped(SCOPES);
            credentials.refreshIfExpired();
            AccessToken token = credentials.getAccessToken();
            logger.info("credentials: " + token.getTokenValue());
        } catch (FileNotFoundException ex) {
            logger.error("File not found: {}", PRIVATE_KEY_PATH);
            throw new FileNotFoundException("File not found: " + ex.getMessage());
        }

        logger.info("Instantiating client next");
        // Instantiating a client: this is where the client should be built but nothing happens... no exceptions!
        Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, (HttpRequestInitializer) credentials)
                .setApplicationName(APPLICATION_NAME)
                .build();
        // this log should appear immediately after the client has been instantiated but still nothing happens
        logger.info("Client instantiated");

        return service;
    }

}

pom.xml:
<!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client -->
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>1.29.2</version>
        </dependency>

        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-drive</artifactId>
            <version>v3-rev165-1.25.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.auth/google-auth-library-oauth2-http -->
        <dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>0.16.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.6.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
        <dependency>
            <groupId>com.google.oauth-client</groupId>
            <artifactId>google-oauth-client-jetty</artifactId>
            <version>1.29.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

I'm sure I'm missing something here and I apologize for my English in advance. Any help will be appreciated.

A: Thank you for your comments, the advices here have been helpful and were worth to look into. However, the solution I'm going to present here isn't going to answer to my question directly on how or why my code didn't produce any error messages. So for now, this is my workaround solution to the problem:

*

*Enabling Drive API. After reading the good portion of articles and documentations on making requests from service account to Drive API, it became clear that my code wasn't going to work if we didn't have Drive API enabled from Google API Console.

*Downgrading the versions of three dependencies to 1.23.0.
pom.xml:
 <dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.23.0</version>
 </dependency>
 <dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v3-rev110-1.23.0</version>
 </dependency>
 <dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.23.0</version>
 </dependency>

*Setting the value of property setSupportsTeamDrive to true. Without the property we wouldn't have been able to save files to the shared folder in Team Drive at all.

ContractStateUpdateService.java:
File fileMetadata = new File();
fileMetadata.setName(fileTitle);

// setting the id of folder to which the file must be inserted to
fileMetadata.setParents(Collections.singletonList("dumbTeamDriveId"));
fileMetadata.setMimeType("application/pdf");

// decoding base64 to PDF and its contents to a byte array without saving the file on the file system
byte[] pdfBytes = Base64.getDecoder().decode(base64File.getBytes(StandardCharsets.UTF_8);
InputStream inputStream = new ByteArrayInputStream(pdfBytes);
InputStreamContent mediaContent = new InputStreamContent("application/pdf", inputStream);

try {
  // upload updated agreement as a PDF file to the Team Drive folder
  DriveUtils.getDriveService().files().create(fileMetadata, mediaContent)
                            .setSupportsTeamDrives(true) // remember to set this property to true!
                            .execute();
} catch (IOException ex) {
  logger.error("Exception: {}", ex.getMessage());
  throw new IOException("Exception: " + ex.getMessage());
} catch (GeneralSecurityException ex) {
  logger.error("Exception: {}", ex.getMessage());
  throw new GeneralSecurityException("Exception: " + ex.getMessage());
}

*Splitting the method to make logic more clearer.
Updated code from DriveUtils-class:
// create and return credential
private static Credential getCredentials() throws IOException {
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(PRIVATE_KEY_PATH))
                .createScoped(SCOPES);

    return credential;
}

// build and return an authorized drive client service
public static Drive getDriveService() throws IOException, GeneralSecurityException {
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    // Instantiating a client
    Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials())
                .setApplicationName(APPLICATION_NAME)
                .build();

    return service;
}


text:
Q: How to branch from n-4 commits, and set n-4 as master? I should have created a branch called develop n-4 commits ago, can I go back and set n-4 to be master and create a new branch from that point which includes the last n-4 commits?
I'm using GitExtensions on Windows but happy to do from commandline if easier.

A: You can do it using following commands:
git checkout -b develop HEAD
git branch -f master HEAD~4

First one creates a new branch develop. Next just reset the branch master

A: Stash all your changes, then:
 git branch develop
 git reset --hard HEAD~4


text:
Q: Decrypting AES and HMAC with PyCrypto Having a bit of trouble getting a AES cipher text to decrypt.
In this particular scenario, I am encrypting data on the client side with Crypto-JS and decrypting it back on a python server with PyCrypto.
encrypt.js:
  var password = 'BJhtfRjKnTDTtPXUBnErKDxfkiMCOLyP';
  var data = 'mytext';

  var masterKey = CryptoJS.SHA256(password).toString();

  // Derive keys for AES and HMAC
  var length = masterKey.toString().length / 2
  var encryptionKey = masterKey.substr(0, length);
  var hmacKey = masterKey.substr(length);

  var iv = CryptoJS.lib.WordArray.random(64/8);

  var encrypted = CryptoJS.AES.encrypt(
    data,
    encryptionKey,
    {
      iv: iv,
      mode: CryptoJS.mode.CFB
    }
  );

  var concat = iv + encrypted;

  // Calculate HMAC using iv and cipher text
  var hash = CryptoJS.HmacSHA256(concat, hmacKey);

  // Put it all together
  var registrationKey = iv + encrypted + hash;

  // Encode in Base64
  var basemessage = btoa(registrationKey);

decrypt.py:
class AESCipher:
    def __init__(self, key):
        key_hash = SHA256.new(key).hexdigest()
        # Derive keys
        encryption_key = key_hash[:len(key_hash)/2]
        self.key = encryption_key
        self.hmac_key = key_hash[len(key_hash)/2:]

    def verify_hmac(self, input_cipher, hmac_key):
        # Calculate hash using inputted key
        new_hash = HMAC.new(hmac_key, digestmod=SHA256)
        new_hash.update(input_cipher)
        digest = new_hash.hexdigest()

        # Calculate hash using derived key from local password
        local_hash = HMAC.new(self.hmac_key, digestmod=SHA256)
        local_hash.update(input_cipher)
        local_digest = local_hash.hexdigest()

        return True if digest == local_digest else False

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        hmac = enc[60:]
        cipher_text = enc[16:60]

        # Verify HMAC using concatenation of iv + cipher like in js
        verified_hmac = self.verify_hmac((iv+cipher_text), self.hmac_key)

        if verified_hmac:
            cipher = AES.new(self.key, AES.MODE_CFB, iv)
            return cipher.decrypt(cipher_text)

password = 'BJhtfRjKnTDTtPXUBnErKDxfkiMCOLyP'

input = 'long base64 registrationKey...'

cipher = AESCipher(password)
decrypted = cipher.decrypt(input)

I'm successful in re-calculating the HMAC but when I try and then decrypt the cipher I get something that seems encrypted with �'s in the result.
I was getting errors about input length of cipher text but when I switched to CFB mode that fixed it so I don't think it's a padding issue.

A: There are many problems with your code.
Client (JavaScript):

*

*AES has a block size of 128 bit and CFB mode expects a full block for the IV. Use
var iv = CryptoJS.lib.WordArray.random(128/8);

*The iv and hash variables are WordArray objects, but encrypted is not. When you force them to be converted to strings by concatenating them (+), iv and hash are Hex-encoded, but encrypted is formatted in an OpenSSL compatible format and Base64-encoded. You need to access the ciphertext property to get the encrypted WordArray:
var concat = iv + encrypted.ciphertext;

and
var registrationKey = iv + encrypted.ciphertext + hash;

*registrationKey is hex-encoded. There is no need to encode it again with Base64 and bloat it even more:
var basemessage = registrationKey;

If you want to convert the hex encoded registrationKey to base64 encoding, use:
var basemessage = CryptoJS.enc.Hex.parse(registrationKey).toString(CryptoJS.enc.Base64);

*concat is a hex-encoded string of the IV and ciphertext, because you forced the stringification by "adding" (+) iv and encrypted. The HmacSHA256() function takes either a WordArray object or a string. When you pass a string in, as you do, it will assume that the data is UTF-8 encoded and try to decode it as UTF-8. You need to parse the data yourself into a WordArray:
var hash = CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(concat), hmacKey);

*The CryptoJS.AES.encrypt() and CryptoJS.HmacSHA256() expect the key either as a WordArray object or as a string. As before, if the key is supplied as a string, a UTF-8 encoding is assumed which is not the case here. You better parse the strings into WordArrays yourself:
var encryptionKey = CryptoJS.enc.Hex.parse(masterKey.substr(0, length));
var hmacKey = CryptoJS.enc.Hex.parse(masterKey.substr(length));

Server (Python):

*

*You're not verifying anything in verify_hmac(). You hash the same data with the same key twice. What you need to do is hash the IV+ciphertext and compare the result with the hash (called tag or HMAC-tag) that you slice off the full ciphertext.
def verify_hmac(self, input_cipher, mac):
    # Calculate hash using derived key from local password
    local_hash = HMAC.new(self.hmac_key, digestmod=SHA256)
    local_hash.update(input_cipher)
    local_digest = local_hash.digest()

    return mac == local_digest

And later in decrypt():
verified_hmac = self.verify_hmac((iv+cipher_text), hmac)

*You need to correctly slice off the MAC. The 60 that is hardcoded is a bad idea. Since you're using SHA-256 the MAC is 32 bytes long, so you do this
hmac = enc[-32:]
cipher_text = enc[16:-32]

*The CFB mode is actually a set of similar modes. The actual mode is determined by the segment size. CryptoJS only supports segments of 128 bit. So you need tell pycrypto to use the same mode as in CryptoJS:
cipher = AES.new(self.key, AES.MODE_CFB, iv, segment_size=128)

If you want to use CFB mode with a segment size of 8 bit (default of pycrypto), you can use a modified version of CFB in CryptoJS from my project: Extension for CryptoJS
Full client code:
var password = 'BJhtfRjKnTDTtPXUBnErKDxfkiMCOLyP';
var data = 'mytext';

var masterKey = CryptoJS.SHA256(password).toString();
var length = masterKey.length / 2
var encryptionKey = CryptoJS.enc.Hex.parse(masterKey.substr(0, length));
var hmacKey = CryptoJS.enc.Hex.parse(masterKey.substr(length));

var iv = CryptoJS.lib.WordArray.random(128/8);

var encrypted = CryptoJS.AES.encrypt(
    data,
    encryptionKey,
    {
      iv: iv,
      mode: CryptoJS.mode.CFB
    }
);

var concat = iv + encrypted.ciphertext;
var hash = CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(concat), hmacKey);
var registrationKey = iv + encrypted.ciphertext + hash;
console.log(CryptoJS.enc.Hex.parse(registrationKey).toString(CryptoJS.enc.Base64));

Full server code:
from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA256
import base64
import binascii

class AESCipher:
    def __init__(self, key):
        key_hash = SHA256.new(key).hexdigest()
        self.hmac_key = binascii.unhexlify(key_hash[len(key_hash)/2:])
        self.key = binascii.unhexlify(key_hash[:len(key_hash)/2])

    def verify_hmac(self, input_cipher, mac):
        local_hash = HMAC.new(self.hmac_key, digestmod=SHA256)
        local_hash.update(input_cipher)
        local_digest = local_hash.digest()

        return SHA256.new(mac).digest() == SHA256.new(local_digest).digest() # more or less constant-time comparison

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        hmac = enc[-32:]
        cipher_text = enc[16:-32]

        verified_hmac = self.verify_hmac((iv+cipher_text), hmac)

        if verified_hmac:
            cipher = AES.new(self.key, AES.MODE_CFB, iv, segment_size=128)
            return cipher.decrypt(cipher_text)
        else:
            return 'Bad Verify'

password = 'BJhtfRjKnTDTtPXUBnErKDxfkiMCOLyP'

input = "btu0CCFbvdYV4B/j7hezAra6Q6u6KB8n5QcyA32JFLU8QRd+jLGW0GxMQsTqxaNaNkcU2I9r1ls4QUPUpaLPQg=="

obj = AESCipher(password)
decryption = obj.decrypt(input)

print 'Decrypted message:', decryption


text:
Q: Why kaminari pagination don't working? I want to create pagination with gem 'kaminari'.I have 2 models Post and Comment, Comment model belongs_to Post model.And I want to create pagination for model Comment, but what I do doesn't work.
This is my posts controller, method 'show'.
  def show
    @comment = @post.comments.page(params[:comments_page]).per(3)
    respond_with(@post)
  end

This is my view, action 'show'
%h2= @post.title
= @post.body
=image_tag @post.photo_url() if @post.photo?
= @post.photo_url.to_s
%h3 Комментарии
- @post.comments.each do |comment|
  %p= comment.name
  %p= comment.body
= paginate @comment
%h3 Оставить комментарий
= form_for ([@post, @post.comments.build]) do |f|
  = f.text_field :name, class: "form-control", placeholder: "Ваше имя"
  = f.text_area :body, class: "form-control", placeholder: "Комментарий"
  .pull-right
    = f.submit "Отправить", class: "btn btn-success"

How to fix?

A: You should pass @comments collection into your paginate method. Also, you use custom pagination param name, you should specify this:
= paginate @comments, param_name: :comments_page

What's more, you should iterate over your paginated comments, not all of them:
- @comments.each do |comment|

and in controller, name your instance variable properly:
@comments = @post.comments.page(params[:comments_page]).per(3)


text:
Q: Understanding WebPageTest waterfall I'm using WebPageTest and am struggling to understand the meaning of the different colors and why it takes so long for my images to be shown (almost 2s). Using the WebPageTest waterfall view I can see a lot of "wait". I just dunno how to read the waterfall correctly and understand what all of my content is waiting on to be downloaded.
You can see my test results on WebPageTest: http://webpagetest.org/video/compare.php?tests=190928_QX_41979a80ef721f72c65dba5363475192-r%3A1-c%3A0-l%3Awww.kaybojesen.dk%2F,
I did some research and found I have to fix the issue using preload attribute:
<link rel="preload" href="style.css" as="style">
<link rel="preload" href="main.js" as="script">
<link rel="preload" href="img.jpeg" as="image">

I have tried playing around with this preload attribute by preloading some of the js and also some of the images (requests 93-100) but neither of it have helped so far.
Which elements should I take a closer look on in order to fix this long waiting time before my content is showing?

A: The color key is at the top. It just tells you what type of asset is being loaded except for the DNS + connect + ssl which combined together make up the process of establishing the initial connection to a domain.
The Atelier theme doesn't seem to have been centered around performance, but you should still be able to get things loading faster. One thing that you could fix is you can make sure you're only loading the necessary scripts/css for each page. https://www.kaybojesen.dk/wp-content/plugins/instagram-feed/css/sb-instagram.min.css doesn't need to be loaded on the homepage. Some items such as the cookie notice, could be loaded after everything else. Fixing that should give you a big improvement. You can also load the CSS/JS from a CDN. Make sure you're using a good caching plugin if you're not already doing so.
It's easy to spot some of these problems such as the cookie notice loading too early. The tricky part is finding plugins or code snippets that you can use to fix these performance issues.
If you look at the "browser main thread" at the bottom it will tell you what is happening during the "wait" time. According to this, There is a bunch of layout happening. Chrome just needs some time after receiving all of the CSS to process it before it continues loading the page. I think webpagetest's server's are slower than your typical computer, so they spend more time in the wait stage, but it's probably a good idea to optimize for the worst case scenario. Anyhow, that's what the wait is all about.


text:
Q: Error while setting up OpenVPN I followed the instructions to set up OpenVPN, from here, now I am getting this error
$ sudo /etc/init.d/openvpn restart
Stopping virtual private network daemon(s)...
No VPN is  running.  * Starting virtual private network daemon(s)...
Autostarting VPN 'server'
/etc/openvpn/up.sh: 7: /sbin/brctl: not found

A: The message is saying that /sbin/brctl was not found. This file is found in the package bridge-utils.
sudo apt-get install bridge-utils will solve your problem.


text:
Q: React Router V4 - route with params failing With react router v4 i'm failing to create a route with params:
const Parent = () =>

    <Switch>
      <Route path="/places" component={PlacesView} />
      <Route path="/places/:placeId" component={PlacesDetailView} />
      <Route path="/callback" component={CallbackView }/>
    </Switch>

export const makeMainRoutes = () => {
    return (
      <Router>

           <Route path='/' component={Parent} />

      </Router>
);}

Everything that comes after /places simply fails to render the app.
Even if I add an extra subroute like /places/detail, it fails to render the app.
Edit: The Main component renders a navigation bar and the child components:

   <Progress />
   <Navigation location={this.props.location}/>

       <TopHeader />
       {this.props.children}

A: I faced exactly the same issue as OP. This tutorial helped me find the solution.
Adding the following lines into webpack.conf.js resolved the issue.
module.exports = {
  ...
  output: {
    ...
    filename: 'index.js',
    publicPath: '/'
  }
}


text:
Q: EMF dependence on certain variables (radius, loops and velocity) So imagine we had a solenoid with N loops and radius r, then we dropped a magnet through the solenoid from a height of of h above the solenoid. Now when the magnet goes through the coil an emf is produced.
Now I am trying to work out the relationship between emf and r, N and h
$$|\varepsilon| = N\frac{d\Phi_B }{dt} $$
Since we know the magnetic flux $\Phi_B=BA = B\pi r^2 $
$$|\varepsilon| =N \frac{d(B\pi r^2) }{dt}
 =N\pi r^2 \frac{dB }{dt} $$
Then using the chain rule $\frac{dB }{dt}=\frac{dB }{dx} \frac{dx }{dt}$. Hence
$$|\varepsilon|  =N\pi r^2 \frac{dB }{dx} \frac{dx }{dt}$$
But since the magnet was dropped from height h $\frac{dx }{dt}= v= \sqrt{2gh}$
Finally we can say
$$|\varepsilon|  =N\pi r^2 \sqrt{2gh} \frac{dB }{dx} $$
However I don't feel like this makes a lot of sense since it is kind of saying that the larger we make the radius of the solenoid the greater the emf but i feel like the opposite should happen (i.e. the bigger the radius the smaller the emf). Can some please explain what I have done wrong or explain how the emf is related to these variables?

A: The analysis you are attempting is much more complex because you have made some assumptions which are not realistic.
The first is that the magnet produces a magnetic field which is constant.
This is not true as by a simple experiment you can show the attractive power of a magnet for a piece of iron depends on the separation between the iron and the magnet.
So what happens is that the magnet is released and accelerated because of the gravitational attraction due to the Earth.
As the magnet gets closer to the solenoid the magnetic flux linked with the coil increases in a very non-linear way and thus an emf is induced in the solenoid.
The closer the magnet is to the solenoid the faster it is going and the greater is the magnetic field due to the magnet in the vicinity of the solenoid, so the emf increases.
AS the magnet enters the solenoid the rate of change flux linkage with the solenoid will start to decrease and so after passing through a maximum the induced emf will start to decrease even though the magnet is travelling faster.
Remember it is the rate of change of flux linkage which is important as the magnet passes though the solenoid less magnetic field lines are cut.
There will come a time when the magnet is at the centre of the solenoid when the rate of change of magnetic flux and hence the induced emf becomes zero.
Then the magnet start to "leave" the solenoid and the process described above is mirrored but with the emf now in the opposite direction becasue now the magnetic flux linked with the coil is decreasing.
The maximum emf during this phase will be larger that before because the magnet is travelling faster.
But that is not all you have to worry about in that the induced emf may induce a current if there is a complete conducting circuit.
So suppose the ends of the solenoid have a resistor connected across them and an induced current is produce.
Lenz tells you that that induced current will oppose the motion producing it and so the induced current will produce a magnetic field which will try and slow down the magnet.
This will mean that the acceleration of the magnet is no longer the acceleration of free fall but low and magnitude of the acceleration will depend on the position of the magnet within the solenoid.
A large induced emf will produce a large induced current and hence more opposition (force) to the downward fall of the magnet.
The slowing down effect will depend on the amount of resistance in the solenoid circuit.
If there ends of the solenoid did not have a resistor across them then there is still, albeit a very small, induced current in the copper windings of the solenoid which are called eddy currents.
However as these eddy currents are small the acceleration of the magnet as it falls though the magnet will be very close to the acceleration of free fall.
Graphically you might get something like this:

If eddy currents are significantly like this very strong neodymium magnet falling through a single turn "solenoid" the progress of the magnet through the solenoid is almost at constant speed as shown in this video.
So for a simple analysis you can probably only give an idea of how the emf changes as you variables, radius, loops and velocity, change rather that being able to evaluate the actual value of the induced emf.

A: The error you've made which led to the radius-squared in your answer is in assuming that the magnetic field from the falling magnet, $B$, is constant with $r$ in $\Phi_B=BA = B\pi r^2$. The magnetic field is not constant with $r$ but decreases with increasing $r$.
Lenz's law also tells us that the velocity is not determined by gravity alone, because the induced current in the solenoid produces a magnetic field which will slow the solenoid down.
There are some other things going wrong here too, but perhaps we can leave those for another opportunity.


text:
Q: Fetch array of url's I'm working with redux and I am trying to fetch Star War API.
Here is my code:
import { MOVIES_ERROR, MOVIE_CHARACTERS } from "./types";

// Get all characters

export const getCharacters = (userId) => async (dispatch) => {
  try {
    const res = await fetch(`https://swapi.dev/api/films/${userId}`);
    if (!res.ok) {
      throw new Error("sometheing went wrong");
    }
    const getData = await res.json();
    const characters = await getData.characters;
    let people = [];

    Promise.all(
      characters.map((url) =>
        fetch(url)
          .then((response) => response.json())
          .then((name) => people.push(name))
      )
    );
    dispatch({
      type: MOVIE_CHARACTERS,
      payload: people,
    });
  } catch (err) {
    dispatch({
      type: MOVIES_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

when I make a console log inside a promise. all I got people array filled with all the data, but when I dispatch it I got an empty array in the reducer. can anyone tell me what the mistake that i did?

A: I got the problem just now, I need to add await before Promise.all :)


text:
Q: do not start services i create an alarm service and call it in main activity, but get this error that: "unable to start service".............
i create table in db.java and set variable by InsertMagnt in alarmservice.
DB DataBase = new DB();
DataBase.InsertMagnt(Acce_x, Acce_y, Acce_z, "", "", 1);
    DataBase.InsertMagnt(Meg_x, Meg_y, Meg_z, datetime, "", 2);
    DataBase.InsertMagnt(Tilt_x, Tilt_y, Tilt_z, datetime, Direct, 3);
    DataBase.InsertMagnt(lon, lat, 0, datetime, "", 4);

and main activity is:
Intent AlarmIntent = new Intent(MainActivity.this, AlarmService.class);
    pending = PendingIntent.getService(MainActivity.this, 0, AlarmIntent, 0);
    alarm = (AlarmManager) getSystemService(ALARM_SERVICE);

    btnStart.setOnClickListener(new OnClickListener() {

        public void onClick(View view) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 5);
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10 * 1000, pending);
            Toast.makeText(MainActivity.this, "Service Start", Toast.LENGTH_SHORT).show();
        }
    });

i get this errors:
08-08 13:24:21.334: E/AndroidRuntime(9000): java.lang.RuntimeException: Unable to start service com.example.farzaneh.AlarmService@417c9cd8 with Intent { flg=0x4 cmp=com.example.farzaneh/.AlarmService (has extras) }: android.database.sqlite.SQLiteException: unrecognized token: "')" (code 1): , while compiling: INSERT INTO Acce_Log (X,Y,Z,Date) VALUES (0.0,0.0,0.0')

A: What's going on with this insert statement
INSERT INTO Acce_Log (X,Y,Z,Date) VALUES (0.0,0.0,0.0')//date is not inserted and the '

You have specified that four values will be inserted but inserting only three,and that '.Remove it,and pass the date as the last argument

A: Salam!
Your error is because of your mistakes about inserting a row into SQLite table (Look at your given error again!)
INSERT INTO Acce_Log (X, Y, Z, Date) VALUES (0.0, 0.0, 0.0 ')
                                    unrecognized token ----^

Please rectify your insert statement. Also note that SQLite does not provide any data type for storing date, you should store a date in either string or long format.
I recommend you to use long! use a Calendar object to convert your date into milliseconds since the epoch (in UTC timezone) and now its ready to be stored in  SQLite
UPDATE #1
Suppose I have the following table in the SQLite database
column name      type
-------------------------
   GID          INTEGER
  Name           TEXT
  Quan          INTEGER
 Surname         TEXT

Now, I want to populate this table with some sample data, For this purpose I'll use the following function.
public void addRow() {
    ContentValues contentValues = new ContentValues();
    contentValues.put("GID", 123);
    contentValues.put("Name", "Edward");
    contentValues.put("Quan", 12);
    contentValues.put("Surname", "Kenway");

    mDataBase.insert("Your table name", null, contentValues);
}


text:
Q: ERROR Error: No value accessor for form control with name: 'products' my project show this error:

ERROR Error: No value accessor for form control with name: 'products'.

I want to add an array Products in Myform component.
I have 2 problems:

*

*When I click button Register, I see this error.

*My products array come in order in the table, but when Register, this array is empty. My source code.

Html code:
<form [formGroup]="Myform" (ngSubmit)="onaddMyForm()">

        <select formControlName="client_id" id="client_id" materialize="material_select" [materializeSelectOptions]="client">
          <option value="" disabled selected>ClientName</option>
          <option *ngFor="let item of client" [value]="item.client_id">{{item.clientName}}</option>
        </select>

          total:
          <input formControlName="total" id="total" type="text" class="validate">

        Price
        Quantita
        Subtotale

        {{item.Price}}
        {{item.Quantita}}
        {{item.Subtotale}}

    <button id="add_client_button" type="submit" class="btn waves-effect waves-light">
      Register
    </button>

</form>

My ts code:
My constructors:
     constructor(
        private router: Router,
        private fb: FormBuilder,
        private ss: ws,

      ) {
// I create the formGroup
            this.Myform = new FormGroup({
              'client_id': new FormControl('', Validators.required),
              'products': this.fb.array([]),
              'total': new FormControl('', Validators.required)
            });
            }

//My function that post in ws My form Value
              onaddMyForm() {
            this.loading = true;
            let newprod = new Product(
              this.Myform.value
            );
            console.log(newprod)// in console my array is empty

            this.ss.prodcreate(newprod).subscribe(
              result => {
                if (result === true) {
                  Materialize.toast('Prod saved successfully', 4000);
                     } else {
                  this.loading = false;
                }
              },
              error => {
                this.loading = false;
              }
            );
          }

How should I do to fix it?
Img err

A: well, i was in a similar issue "ERROR Error: No value accessor for form control with unspecified "
i tried to solved it for 2 days, searched complete Stackoverflow,
at last what worked and what i did

*

*look for all the ngModel in your code and add name attribute to it.

*if name is specified add "ngDefaultControl" to it


text:
Q: Can i give to an attribute a complex name? In general if someone wants to set an attribute of an html element he has to write something like

However in my case I want the value of the src to be a combination of url and a string that i define.How can I achieve it? Ideally I would be happy if I could write

But it does not work.

A:

As identified in comments. Use single quotes.


text:
Q: How to get eigenvectors from PCA I'm using FactoMineR's PCA function to compute the PCA of my dataset.
I know I can get the eigenvalues with get_eigenvalue(res.pca) but how do I get the eigenvectors?

A: In Principal Components Analysis, you're decomposing the n-by-k variable matrix into three parts - U, D and V.  U are the left singular vectors that represent the rows of the decomposed matrix.  However, the U matrix is not itself the principal components.  All of the columns of U are mutually orthogonal (as you would expect), but they also all have the same variance.  The principal components are U scaled by the square root of the eigenvalues.  Here's an example:
library(FactoMineR)
data(decathlon)
dat <- decathlon[,1:10]
p <- PCA(dat)
#> Warning: ggrepel: 1 unlabeled data points (too many overlaps). Consider
#> increasing max.overlaps

comp1 <- predict(p, newdata=dat)$coord[,1:3]

U <- p$svd$U
e <- p$eig[,"eigenvalue"]

comp2 <- U[,1:3] %*% diag(sqrt(e[1:3]))

head(comp1[,1:3])
#>              Dim.1      Dim.2      Dim.3
#> SEBRLE   0.7916277  0.7716112  0.8268412
#> CLAY     1.2349906  0.5745781  2.1412470
#> KARPOV   1.3582149  0.4840209  1.9562580
#> BERNARD -0.6095151 -0.8746285  0.8899407
#> YURKOV  -0.5859683  2.1309542 -1.2251568
#> WARNERS  0.3568895 -1.6849567  0.7665531
head(comp2[,1:3])
#>            [,1]       [,2]       [,3]
#> [1,]  0.7916277  0.7716112  0.8268412
#> [2,]  1.2349906  0.5745781  2.1412470
#> [3,]  1.3582149  0.4840209  1.9562580
#> [4,] -0.6095151 -0.8746285  0.8899407
#> [5,] -0.5859683  2.1309542 -1.2251568
#> [6,]  0.3568895 -1.6849567  0.7665531

Created on 2022-02-16 by the reprex package (v2.0.1)


text:
Q: Convert XAML Storyboard to C#? I was wondering after some Googling if there is a tool roaming around to maybe convert Storyboard XAML code to C#, or if there is another way to reach my goal:
I need the code behind, because I need to have control over which value the "Wheel Of Fortune" will land on, but creating an animation with a timer and a spin event is too jittery and jerky.
Any advice on how to get the buttery smooth animation from XAML Blend Storyboards, but control of C# in one for this type of thing?
<Storyboard x:Key="OnMouseLeftButtonDown1">
        <PointAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransformOrigin)" Storyboard.TargetName="DailySpinColoursText_png">
            <EasingPointKeyFrame KeyTime="0" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:0.3" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:0.6" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:1" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:1.4" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:1.8" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:2.2" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:2.6" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:3" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:3.4" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:3.8" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:4.2" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:4.6" Value="0.5,0.5"/>
            <EasingPointKeyFrame KeyTime="0:0:5" Value="0.5,0.5"/>
        </PointAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)" Storyboard.TargetName="DailySpinColoursText_png">
            <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="100"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.6" Value="400"/>
            <EasingDoubleKeyFrame KeyTime="0:0:1" Value="1100"/>
            <EasingDoubleKeyFrame KeyTime="0:0:1.4" Value="2600"/>
            <EasingDoubleKeyFrame KeyTime="0:0:1.8" Value="4600"/>
            <EasingDoubleKeyFrame KeyTime="0:0:2.2" Value="6100"/>
            <EasingDoubleKeyFrame KeyTime="0:0:2.6" Value="7300"/>
            <EasingDoubleKeyFrame KeyTime="0:0:3" Value="8300"/>
            <EasingDoubleKeyFrame KeyTime="0:0:3.4" Value="8800"/>
            <EasingDoubleKeyFrame KeyTime="0:0:3.8" Value="9000"/>
            <EasingDoubleKeyFrame KeyTime="0:0:4.2" Value="9100"/>
            <EasingDoubleKeyFrame KeyTime="0:0:4.6" Value="9150"/>
            <EasingDoubleKeyFrame KeyTime="0:0:5" Value="9200"/>
            <EasingDoubleKeyFrame KeyTime="0:0:5.4" Value="9220"/>
            <EasingDoubleKeyFrame KeyTime="0:0:5.8" Value="9225"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>

Thank you in advance!
PS. I found a few examples online of rotation animation in C#, but I need it to spin up slowly, then in the middle of the animation start spinning really fast and then at the end come down to a slow and suspenseful end. With the things I have seen on the internet I would have no clue on how to do that.

A: You could animate the RotateTransform's Angle property in code behind like shown below. Instead of having a lot of EasingDoubleKeyFrames, you may probably also use a single EasingFunction:
element.RenderTransformOrigin = new Point(0.5, 0.5);
element.RenderTransform = new RotateTransform();

var animation = new DoubleAnimation
{
    To = 9225,
    Duration = TimeSpan.FromSeconds(5.8),
    EasingFunction = new CubicEase { EasingMode = EasingMode.EaseInOut }
};

element.RenderTransform.BeginAnimation(RotateTransform.AngleProperty, animation);


text:
Q: Good unit testing in Go I always thought that good unit test, are test that are independent. By 'independent' i mean that when function 'A' uses 'B', and we test function 'A', we mock/stub out 'B' in case when 'B' does not work correctly it will not fail 'A'.
But when we check sources of golang packages that principle is not respected.
For example  lets check url.go and url_test.go in url packages:
url.go:
func parseQuery(m Values, query string) (err error) {
    for query != "" {
    ...
    key, err1 := QueryUnescape(key)
    ...

url_test.go:
func TestParseQuery(t *testing.T) {
    for i, test := range parseTests {
        form, err := ParseQuery(test.query)
        ...

As we can see parseQuery use QueryUnescape. In test QueryUnescape is not stubbed in any way. So if QueryUnescape will work wrong, parseQuerytest will fail.
So authors of package not always meet requirement of 'independent' unit test. What was the reason to not bother about this principle in this case, is there some rule that allow programmer of accepting this form of unit tests?
After writing independent test in python, I'am little confused about balancing between writing perfect test(which much affects in golang about design of code) and results.

A: Your question is really about defining the scope of a "unit" when "unit testing", which can be tricky. A "unit" does not necessarily mean a function, or a struct. It might mean a few functions/structs working together. But it most certainly means that you will not cross process boundaries (like using the real file system or going over a network, hitting a database, etc...). The boundaries are tested with integration tests or simulated using test doubles (mocks, stubs, spies, etc...).
I'm the author of GoConvey, a testing tool that build on top of the built-in go "testing" package. GoConvey has a comprehensive suite of unit tests. In the tests for the core of the project I don't write tests that invoke every single exported and non-exported function. I wrote the tests with the public-facing API in mind (the exported functions/structs). The implementation of that API is not the concern of my unit tests but the outcome is. You can see what I mean just by reading a few tests. I only call a few public-facing methods and assert that the result is correct. There are actually lots of structs and functions being invoked but the test coverage in that package is very high (currently 92.8%--not as high as I'd like but it's pretty good).
In the case of the convey package within GoConvey the unit is the entire package and its components.  In the beginning I remember the tests being more granular, which allowed me to get into the red-green-refactor cycle more quickly. As the code grew, those smaller-scoped tests were superseded by broader tests that seemed more appropriate. So the suite will evolve with the production code. You'll feel a lot of friction and inertia if every single method is tested directly as you won't be able to change anything without breaking a bunch of tests.
Here's another interesting summary about how to discern the scope of a unit test:
http://blog.8thlight.com/uncle-bob/2014/01/27/TheChickenOrTheRoad.html


text:
Q: ASP.Net Open New Tab in Browser from CodeBehind I need to open a browser tab from a link that is given to me by an asp.net code behind.
Normally I would have a link and target="_blank", but the link that I need is dynamic, so I must have the behavior of a _blank link from code behind.
Any Ideas?

A: If you have the data needed to create the link when generating the initial HTML, you can do something like this in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
    Button1.OnClientClick="javascript:window.open('MyPage.aspx?Param=" + Param1.ToString() + "');";         }
}

If you're waiting for the PostBack to get the required data to build the link, you can send javascript down to the browser via the ScriptManager:
protected void Button1_Click(object sender, EventArgs e)
{
    //process whatever you need to to get Param1
    ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('MyPage.aspx?Param=" + Param1.ToString() + "');",true);
}

A: You're looking for the Target property.


text:
Q: CodeIgniter - Additional dbforge / migration fields Im having trouble figuring out this migrations business for CodeIgniter ... I cant find any decent documentation that explains additional field elements like current_timestamp, default datetime values etc etc
I was wondering if someone could help me out to translate the following into proper dbforge->add_field  arrays
I need the following 2
`last_login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

and
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'

I have copied these from the SQL insert statement from the tank_auth library.
But i want to put it into migrations now.
Cheers,

A: for number 1 you can use
$this->dbforge->add_field('last_login TIMESTAMP');

or
$data = array(
 'type' => 'TIMESTAMP'
);

This auto inserts ON UPDATE CURRENT_TIMESTAMP

A: I think you may be out of luck. These are the available options to dbforge:

Additionally, the following key/values can be used:
unsigned/true : to generate "UNSIGNED" in the field definition.
default/value : to generate a default value in the field definition.
null/true : to generate "NULL" in the field definition. Without this, the field will >     default to "NOT NULL".
auto_increment/true : generates an auto_increment flag on the field. Note that the >     field type must be a type that supports this,
such as integer

You may have to pass a standard query. $this->db->query('YOUR QUERY HERE'); may be what you need.


text:
Q: Oracle JRE 7 and 8 both will not install on previously Javaless win7 Simple question I thought I'd never have to ask, since I've done it hundreds of times before: How can I install JRE?
I have a Win7 x64 Pro box with no Java environment, running as an admin user.  I'm trying to install JRE8u45, but every time I try, the installer progresses a while and then ends with error 1603 with no additional detail.
The events in the Event Viewer for go like this:

Product: Java 8 Update 45 (64-bit) -- Error 1722. There is a problem
  with this Windows Installer package. A program run as part of the
  setup did not finish as expected. Contact your support personnel or
  package vendor. Action installexe, location: C:\Program
  Files\Java\jre1.8.0_45\installer.exe, command: /s
  INSTALLDIR="C:\Program Files\Java\jre1.8.0_45\" REPAIRMODE=0

That was an "error," and the next two are "information":

Product: Java 8 Update 45 (64-bit) -- Installation failed.

...and:

Windows Installer installed the product. Product Name: Java 8 Update
  45 (64-bit). Product Version: 8.0.450. Product Language: 1033.
  Manufacturer: Oracle Corporation. Installation success or error
  status: 1603.

Things I've tried

*

*This article linked to this hotfix.  I installed it and tried again, but got the same error trying to install JRE.

*I tried right-clicking the installer jre-8u45-windows-x64.exe and choosing "Run as administrator".  Same result.

*I tried Java 7 u79, and it also did not complete, and didn't even give an error code.  Interestingly, it seems to have finished (in that Java-related items are now on the Start Menu), even though it said that something (didn't say what) interrupted it, and Event Viewer shows this:

Windows Installer installed the product. Product Name: Java 7 Update
  79 (64-bit). Product Version: 7.0.790. Product Language: 1033.
  Manufacturer: Oracle. Installation success or error status: 1603.

Um...OK.  Another entry at the exact same time says:

Product: Java 7 Update 79 (64-bit) -- Installation operation failed.

At this point, the configuration applet works, but, my end goal was actually running Eclipse (for non-Java development, hence getting the JRE instead of the JDK), which now does not complain that there's no JRE, and instead complains:
---------------------------
Java Virtual Machine Launcher
---------------------------
Error: opening registry key 'Software\JavaSoft\Java Runtime Environment'
---------------------------
OK
---------------------------

So I guess it...half-installed.  When I OK that dialog, it then says:
---------------------------
Java Virtual Machine Launcher
---------------------------
Error: could not find java.dll
---------------------------
OK
---------------------------

And another OK gets me:
---------------------------
Java Virtual Machine Launcher
---------------------------
Error: Could not find Java SE Runtime Environment.
---------------------------
OK
---------------------------

After that, a popunder I didn't discover until later:
---------------------------
Eclipse
---------------------------
Java was started but returned exit code=2
C:\Windows\system32\javaw.exe
-Dosgi.requiredJavaVersion=1.7
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m
-jar H:\Downloads\eclipse-standard-luna-SR2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
-os win32
-ws win32
-arch x86_64
-showsplash H:\Downloads\eclipse-standard-luna-SR2-win32-x86_64\eclipse\\plugins\org.eclipse.platform_4.4.2.v20150204-1700\splash.bmp
-launcher H:\Downloads\eclipse-standard-luna-SR2-win32-x86_64\eclipse\eclipse.exe
-name Eclipse
--launcher.library H:\Downloads\eclipse-standard-luna-SR2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316\eclipse_1608.dll
-startup H:\Downloads\eclipse-standard-luna-SR2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.appendVmargs
-exitdata fa8_5c
-product org.eclipse.epp.package.standard.product
-vm C:\Windows\system32\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.7
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m
-jar H:\Downloads\eclipse-standard-luna-SR2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
---------------------------
OK
---------------------------

Rant: Really, on a fairly pristine--I'm just installing my development tools these last few days--fully patched, theoretically supported version of Windows, there's no way to install either the latest JRE, or the latest of the previous major version?

A: May 12 2015's new Windows Updates ran, then after a restart, I was able to install JRE 8 u45.  Not sure which exact update fixed it.

A: Simple solution worked for me.
Go to the installation folder and run the javacpl.exe click the Security Tab, untick "Enable Java content in the browser" Click Apply.
Then put the tick back in the box, Apply, OK and Open your browser, go to http://www.java.com click "Do I have Java?" and click on the Verify Java version button.
This sounds stupid, but it worked for me after 3 hours of messing about with installers, the registry, user accounts etcetera...


text:
Q: MediaPlayer issue in most android 6.0 devices in streaming In android 6.0 devices (not emulators api 23) I am receiving weird problem. Player starts playing song but after 1 or 2 seconds it again goes to 00:00 during this transition player skips the time required for transition and starts playing from that place eg(00:07).
But after 20+ seconds song starts playing normally for about 5 to 10 seconds and then player stops playing because the song is completed. Total time of this process is half than the duration of song.
What I think is there must be problem in preparing the music, but I am not sure what is the problem.
Here is the code what I have written so far
 public static MediaPlayer player = null;
 // above line is declared at start of class

// below code is written in a async task doInBackground
 if (player != null) {
        player.release();
        player = null;
    }
    durationOfSong = 0;
    String streamUrl = getSongsList.getStreamUrl(position);
    player = MediaPlayer.create(context, Uri.parse(streamUrl));
    try {
        Log.d(LOG_TAG, "end time: " + player.getDuration());
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mHandler.postDelayed(UpdateSong, 100);
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                loadingSongProgress.setMessage("Buffering song...");
            }
        });
        Manipulate manipulate = new Manipulate();
        endTimingOfSong = manipulate.MillisecondsToFormat(player.getDuration());

    } catch (NullPointerException e) {
        Log.e(LOG_TAG, "NP: error: " + e.toString());
        DialogWithNoSongError(view);
    }

 // and in post execute method
 loadingSongProgress.dismiss();
 player.start();
 createMediaDialog(view,position);
 // create media dialog is used to show image, song name and running time

Android devices running <6.0 OS and emulators (running 6.0) plays song in normal fashion.
If more code is needed I will edit the post, in case needed please suggest.
Thanks in advance!!

A: Remove the code the following code from the bottom

player.start();

and replace the following
    player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    loadingSongProgress.setMessage("Buffering song...");
                      mHandler.postDelayed(UpdateSong, 100)
                }
            });
player.prepareAsync();

Try to run this it might help you

A: Try this. It worked for me.
player.setDataSource(getSongsList.getStreamUrl(position));
player.prepareAsync();

Note: There are two methods to prepare the media player:
1. player.prepare(); this one returns after completing the prepare operation hence causes a delay in the UI thread.

*prepare.prepareAsync(); this one does all that works asynchronously. Hence does not cause any delay in UI thread.


text:
Q: Grammaticality of "who fell to earth, shattering the land" While watching Youtube videos, I recently came across this sentence

Their quarrel turned to rage and their violent struggle darkened the skies,          until the Dragon of the South Wind struck down his brother, who fell to earth, shattering the land.

"Who fell to earth, shattering the land." Is this a grammatically correct sentence? It appears like quite poetic language. What exact rule is this? and if so, do you have any additional examples?
Edit: Apparently this is a special adjective clause. Unfortunately, I am not familiar with this special chase. Any examples?

A: Yes, this sentence is correct.
To make grammar-checking easier, you should split the sentence in simpler sentences.

Their quarrel turned to rage and their violent struggle darkened the skies, until the Dragon of the South Wind struck down his brother, who fell to earth, shattering the land.

Becomes (replacing who by his brother) :

Their quarrel turned to rage and their violent struggle darkened the skies, until the Dragon of the South Wind struck down his brother.
His brother fell to earth, shattering the land.

Both of these sentences are correct, and the second is made an adjective clause correctly, so the final sentence is correct.


text:
Q: Karate - Get CSV Key Value from a particular section I want to get the value of a particular section in a csv file. A sample content is given below.
[Header]
data1,2
data1,name

[Header2]
headercount,3
headerName, test

I need to get the value of the 'headerName' key. So i am expecting 'test' as the return value.


text:
Q: C++ API to get the private and virtual bytes consumed by a process Is there an API provided by Microsoft to get the private and virtual bytes consumed by a process ?

A: GetProcessMemoryInfo could be of great use.

A: To complement the answer by DumbCoder which amongst others gives you physical memory usage, you should also take a look at GlobalMemoryStatusEx.
Here you can find the definition of virtual bytes  according to Microsoft and how you can derive it as a simple difference from two counters that GlobalMemoryStatusEx provides.
Notes of caution:

*

*The function GlobalMemoryStatusEx has mixed purpose since it provides information about the system as a whole and information specific to the calling process, e.g. virtual memory usage.

*Read/apply the API carefully otherwise you can end up with broken counters.


text:
Q: How can I get the same result using group by and summarize function using power bi DAX? I have written below code using summarize-columns function but I want to achieve this using GROUP BY function.
SUMMARIZECOLUMNS(
Mergetable[WeekDayName],FILTER(Mergetable,Mergetable[noShow]<>"true"),
          "TOTALDURATION", SUMX(Mergetable,Mergetable[MeetingDurationInHours]),
          "TOTALWEEKCOUNT", COUNTX(Mergetable,Mergetable[WeekDayName]),
          "DIVIDED",((SUMX(Mergetable,Mergetable[MeetingDurationInHours]))/(COUNTX(Mergetable,Mergetable[WeekDayName]))))

I have achieved so far using GROUP BY function but enable to divide the column totalduration and totalweekcount during run time.
GROUPBY(
    FILTER(Mergetable,Mergetable[noShow]<>"true"),
    Mergetable[WeekDayName],
    "TOTALDURATION", SUMX(CURRENTGROUP(),Mergetable[MeetingDurationInHours]),
    "TOTALWEEKCOUNT", COUNTX(CURRENTGROUP(),Mergetable[WeekDayName]))

Can anyone explain to me what needs to be done here to achieve same result as produced by summarize-columns function?

A: If you just want to add DIVIDED column to your groupby statement, then cover all with ADDCOLUMNS.
 ADDCOLUMNS( GROUPBY(
      FILTER(Mergetable,Mergetable[noShow]<>"true"),
      Mergetable[WeekDayName],
      "TOTALDURATION", SUMX(CURRENTGROUP(),Mergetable[MeetingDurationInHours]),
      "TOTALWEEKCOUNT", COUNTX(CURRENTGROUP(),Mergetable[WeekDayName]))
,  "DIVIDED", DIVIDE([TOTALDURATION], [TOTALWEEKCOUNT]) )


text:
Q: upgrade problem from 16.04 to 17.04 I did try to upgrade the ubuntu 16.04 LTS to 17.04 using information from this link :

After switching you'll need to run a quick update (it'll prompt you to do this anyway) and then you'll need to upgrade to Ubuntu 16.10 (yes, 16.10).
sudo do-release-upgrade -d
Once that upgrade has completed reboot, login and run the command again, this time to upgrade to Ubuntu 17.04.
sudo do-release-upgrade -d

When I tried to  upgrade 16.04 to 16.10 with sudo do-release-upgrade -d , the pc was turned off ( Mr X took off the battery ) so the upgrade was interrupted , but still everything working right and I continued upgrading to 17.04.
now I have a problem :

*

*when I run sudo apt-get update it  doesn't show all the dependencies

*when I run sudo apt-get upgrade it return this:

is there any way to fix these issues ?

A: I'm able to upgrade from 16.04 to 17.04 by following command sequence.
sudo apt update && sudo apt dist-upgrade

Then tried the following command as suggested in internet
sudo do-release-upgrade -d

result : System is up-to date, actually newer version available
Then tried to find which version available by issuing this command
thiru@ubuntu:~/work$ sudo do-release-upgrade -c
Checking for a new Ubuntu release
New release '17.04' available.
Run 'do-release-upgrade' to upgrade to it.

So, run this command to upgrade successfully as suggested by command output.
sudo do-release-upgrade

After this my Ubuntu updated to 17.04 successfully.

A: I don't now if it doomed something else on the system but it works out for my problem:
sudo -i                       # to be the superuser
dpkg --purge unity-plugin-scopes:amd64 url-dispatcher:amd64 url-dispatcher-tools unity8-common unity8 unity-greeter-session-broadcast unity8-desktop-session   # to remove the 7 last dependencies

then, remove libunity-scopes1.0:amd64 manually cause dpkg --dpkg had some issues with this one so with command line:
rm -r /usr/share/doc/libunity-scopes*
rm /var/lib/dpkg/info/libunity-scopes*
rm /usr/share/apport/package-hooks/libunity-scopes1.0.py
rm /var/crash/libunity-scopes*

then you can use:
dpkg --purge libunity-scopes1.0:amd64
apt-get install -f
apt autoremove


text:
Q: Seeking inexpensive GIS software that can export TIN files to AutoCAD? I'm an architect who would like to be able to download 3D terrain info and then bring it into AutoCAD 3D for use in renderings and animations using a couple of rendering/animation softwares called AccuRender and Lumion.
In the past, I was able to use an AutoCAD add-on software called EasySite (no longer available or supported) that could create TIN meshes from point files.
Is there an inexpensive way to download 3D terrain info that works in AutoCAD?


text:
Q: Checkpointing in high availability In Hadoop high availability, Check pointing is done by which node?
Is there a secondary name node in addition to the active and the stand-by nodes which does the check pointing?

A: The Standby NameNode maintains enough state to be a quick failover

[I]n an HA cluster, the Standby NameNode also performs checkpoints of the namespace state, and thus it is not necessary to run a Secondary NameNode, CheckpointNode, or BackupNode in an HA cluster. In fact, to do so would be an error

https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HDFSHighAvailabilityWithNFS.html#Architecture

Is there a secondary name node in addition to the active and the stand-by nodes

There is only one active and one standby, as mentioned also on that page.

Currently, only a maximum of two NameNodes may be configured per nameservice


text:
Q: Why would Neville be a candidate as the child of the first prophecy? Sybill Trelawney's prophecy said that the child to face Voldemort would be

"born as the seventh month dies."

Neville was born on July 30th, Harry on 31st. So isn't the 31st really the last day of the month, the day the month dies?
Since Harry fits the prophecy better (e.g. he was born on the last day of the month), why would Neville even be considered as the child of the prophecy?


text:
Q: Connecting to a particular machine in a server I am a beginner in this whole Ubuntu thing so I would appreciate to get some help, thanks !
I am trying to connect my Ubuntu machine (VirtualBox on Windows) to a distant server. After having done that connection, I wish to access a machine on that server.
Ex : I first enter "ssh mc@ssh.blablabla.com"
Then, I enter "ssh mc@machine1.blablabla.com" which connects me to the particular machine.
I was wondering how I could transfer files from my local repository to this particular machine. The problem is that the usual softwares (like WinSCP on Windows) only allow me to connect to the server but I cannot reach the particular machine on that server that interests me (the machines have many To of storage whereas simply connecting to the server only gives me 100 Mo).
It goes without saying that I cannot directly connect to the powerful machine without first connecting to the server.
Cheers !


text:
Q: ASP.NET Dirty in the context of ViewState What does "dirty" mean in the context of ViewState?
How does ViewState benefit from marking something as "dirty"?

A: Are you talking about the IsItemDirty-property of the StateBag class? This property is used to mark whether or not a particular item has been changed during the current request.
Here's a rather old article that explains some of it:
http://msdn.microsoft.com/en-us/magazine/cc188774.aspx


text:
Q: Unity [SerializeField] и инкапсуляция Когда в конце работы над проектом я хочу инкапсулировать код в своем проекте и убрать ненужные сериализуемые объекты т.е.
из [SerializeField] protected string name;  в  protected string name;

То все данные из этой переменной пропадают, (т.е. возвращает null).
Ключевое слово "protected" из-за того что данный код в "главном классе" или "классе-родитель" от которого наследуются другие классы.
Мой вопрос больше касается того, как делают при разработке игр разработчики, может эту переменную не нужно инкапсулировать а так и оставить?


text:
Q: How to call model methods in template I want to call the model method get_url() in the  tag in the template
models.py
class Department(Base):

  department_name = models.CharField(max_length=128)
  description = models.TextField(null=True, blank=True)

  def get_url(self):
      ct = ContentType.objects.get(model='department')
      url_name = ' %s:%s ' % (ct.app_label, ct.model)
      return reverse(url_name, args=(self.object_id))

template.html

A: Pass the model instance to template via context
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['instance'] = Department.objects.get(id=1)
    return context

A: I think you can do it like this:
class Department(Base):

  department_name = models.CharField(max_length=128)
  description = models.TextField(null=True, blank=True)

  def get_url(self):
      ct = ContentType.objects.get(model='department')
      url_name = ' %s:%s ' % (ct.app_label, ct.model)
      return reverse(url_name, args=(self.pk))  # <-- Changed to self.pk to access primary key of the object

Then you can use it in template like this:

Update
For accessing the instance of model in template, you need to send it to Template through context. In a function based view, you can try like this:
from django.shortcuts import render

def some_view(request):
   department = Department.objects.first()
   context = { 'object': department }  # Here you can use any key in dictionary, I am using object. This key is accessible in template
   return render(request, 'your_template.html', context)


text:
Q: @autowired field cannot not be resolved to a type I'm a newbie using Spring framework.
I want to use a class type  "BlaBla", of a different project BlablaProject, in my project "myProject" in Eclipse. Both projects uses Spring framework. To uses BlaBla I add the @autowired annotation in my classe :
@Autowired
private Blabla test;

I also add in application-context.xml of myProject
<context:component-scan base-package="test.domain" use-default-filters="true" />

Blabla is in the test.domain package defined in BlablaProject
But I receive the "cannot not be resolved to a type" error. What do I forget to configure, either in BlablaProject or in myProject?


text:
Q: detect the end of asynchronous recursion var checkduplicates = new Array();
drawOne(i);
//console.log(checkduplicates)

function drawOne(i)
{
    //randomly select one photo
    var picinfo = photos[Math.floor(Math.random()*photos.length)];
    //check duplicates pic, if duplicates exist, get another one
    while(checkduplicates.indexOf(picinfo)!=-1||picinfo.title.length>10)
    {
        picinfo = photos[Math.floor(Math.random()*photos.length)];
    }
    checkduplicates.push(picinfo);

    var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
    var img = new Image();
    //get the pic URL
    img.src = "http://farm" + picinfo.farm + ".static.flickr.com/"
    + picinfo.server + "/" + picinfo.id + "_" + picinfo.secret + "_m.jpg";

    img.onload = function()
    {
        // Draw pieces
        ctx.drawImage(img,0,0,132,150);
        ctx.drawImage(frame,0,0,133,152);
        if(picinfo.title=="")
            $("#"+i).append("Untitled");
        else
            $("#"+i).append(picinfo.title);

        i++;
        if (i != canvaslength)
        {
            drawOne(i);
        }
    }

What I am doing here is that I am dynamically generate pictures to fill out 16 canvas and some people said that I am using asynchronous recursion which I dont even notice. I have tried to use loop instead of recursion but somehow ended it up getting exception that i dont know how to fix. So I stick to recursion. However, my problem is that how I can detect the end of the recursion like the commented line shows there is only one item in the array.
//console.log(checkduplicates)

and the explanation I got is that as I understand, the commented console.log is executed before a bunch of recursion of drawOne function finished But what I wanted was that I wanted the full 16 images to be fully loaded and then select them so that I can do something with them. Therefore, the question is how I can detect the end of the recursion. Thank you. You are welcomed to ignore most of my codes and just look at the recursion part.

A: This is not 'asynchronous recursion'. That would imply that at least two of these loops are running at the same time, and they return asynchronously. Which is simply not the case.
Basically the only time you STOP recursion is when i == canvaslength.
So, just take that if statement.
if (i != canvaslength)
{
    drawOne(i);
}else{
    console.log('recursion is done')  // do what you want here.
}


text:
Q: How to fix error when trying to use batch_norm function from lasagne library? When i try to use batch_norm function from lasagne library:
lasagne.layers.batch_norm(...

this error appears:
AttributeError: module 'lasagne.layers' has no attribute 'batch_norm'

However I did all installs and updates which are necessary for that library. How to fix it?


text:
Q: specific type of SPARQL query assistance needed please I have a database of RDF triples that are along the lines of:
keyword002  isKeywordIn  doc0892
keyword002 phrase "thisIsATest"
I have a list of keywords that I want to find matches for in one query, For example, lets say I have 10 document, and I want to know (for each document) which, if any, of the keywords "testing3", "fubared","noob" are in the document.
what SPARQL query could I construct so that I can put specify a list of exact words (I tries a regex filter but did't seem to work. gave me partial matches too and didn't give me the document name) and Get back the name of the containing document and the keywords that matched?
I have been stuck on this for days and I get it to work but it is through a few recursive loops and takes forever, I need to speed things up drasticly.
**My server is down so I can't access my triplestore right now but thank you both for the reply! If I have any questions I will repost, thank you so much!

A: Untested, but one approach would be something like:
select distinct ?keyword ?document
where {
  ?keyword ns:isKeywordIn ?document;
           ns:phrase ?phrase.
  FILTER regex( ?phrase, "^(testing3|n00b|fubared)$", "i" )
}

This will give you pairs of document and keyword, where the keyword matches any one of the user input patterns. Note the use of ^ ... $ anchors so that you only get full word matches, not partial. However, this may be slow because there's not much distinctive information to index the query on, so the query engine will have to test each keyword in the corpus.
An alternative is to union the tests for multiple keywords:
select distinct ?keyword ?document
where {
  {?keyword ns:phrase "testing3" ; ns:isKeywordIn ?document}
  union
  {?keyword ns:phrase "n00b" ; ns:isKeywordIn ?document}
  union
  {?keyword ns:phrase "fubared" ; ns:isKeywordIn ?document}
}

A reasonable query optimizer should be able to use the more specific :phrase triples to index the query. However, it's slightly more complex to construct the query. Another drawback is that you don't have the equivalent of the ignore-case ("i") flag that you have in the regex example, so you user input must match your keyword text exactly.
A final alternative is to use a SPARQL extension to exploit a free-text index alongside the triple store. E.g. for Jena, see LARQ.

A: Generally, you should avoid using regex in a SPARQL query.  SPARQL engines are not typically designed to handle that very well.  The ones that do provide specific functionality for doing regex or keyword type searches over literal values, often based on a special Lucene index.  Normally regex is just going to end up doing lots of regexs over any relevant Literal values, which can be very expensive.
This should return the documents with the keyword "testing3"
select ?doc ?name where {
  ?doc :name ?name .
  ?keyword :isKeywordIn ?doc .
  ?keyword :phrase "testing3" .
}

If you want to get all documents which contain two specific keywords:
select ?doc ?name where {
  ?doc :name ?name .
  ?keyword :isKeywordIn ?doc .
  ?keyword :phrase "testing3" .
  ?kw :isKeywordIn ?doc .
  ?kw :phrase "noob" .
}

If you want to get all documents which either of the two specific keywords:
select distinct ?doc ?name where {
  ?doc :name ?name .
  {
    ?keyword :isKeywordIn ?doc .
    ?keyword :phrase "testing3" .
  } union {
    ?kw :isKeywordIn ?doc .
    ?kw :phrase "noob" .
  }
  }

I think this will get you want you're looking for, typo's and exact use of your domain ontology not withstanding.


text:
Q: Why do not inline-block elements occupy full width even on width 100%?

let lastSelectButton;

document.querySelectorAll('.primaryButton').forEach(button => {
  button.addEventListener('click', event => {
    if (lastSelectButton) document.querySelector(`#${lastSelectButton} + div`).classList.toggle('inlb');
    lastSelectButton = event.currentTarget.getAttribute('id');
    document.querySelector(`#${lastSelectButton} + div`).classList.toggle('inlb');
  }, false);
});
button {
  text-align: left;
}

.primaryButton {
  display: inline-block;
  background: #bfbfbf;
  border: none;
  width: 100%;
  padding: 5px;
}

.secondaryButton {
  background: #d4d4d4;
  border: none;
  width: 100%;
  text-indent: 1em;
}

.primaryButton:hover {
  background: #a1a1a1;
  cursor: pointer;
}

.secondaryButton:hover {
  background: #bfbfbf;
  cursor: pointer;
}

.none {
  display: none;
}

.inlb {
  display: inline-block !important;
}
<button class="primaryButton" id="p1">A</button>

  <button class="secondaryButton">1</button>
  <button class="secondaryButton">2</button>
  <button class="secondaryButton">3</button>

<button class="primaryButton" id="p2">B</button>

  <button class="secondaryButton">1</button>
  <button class="secondaryButton">2</button>

<button class="primaryButton" id="p3">C</button>

  <button class="secondaryButton">1</button>
  <button class="secondaryButton">2</button>

As seen, the secondary buttons do not occupy full width like the primary buttons. Why does this happen? How to correct it?
On the contrary, setting inline-blocks to blocks settles the matter:

let lastSelectButton;

document.querySelectorAll('.primaryButton').forEach(button => {
  button.addEventListener('click', event => {
    if (lastSelectButton) document.querySelector(`#${lastSelectButton} + div`).classList.toggle('inlb');
    lastSelectButton = event.currentTarget.getAttribute('id');
    document.querySelector(`#${lastSelectButton} + div`).classList.toggle('inlb');
  }, false);
});
button {
  text-align: left;
}

.primaryButton {
  display: block;
  background: #bfbfbf;
  border: none;
  width: 100%;
  padding: 5px;
}

.secondaryButton {
  background: #d4d4d4;
  border: none;
  width: 100%;
  text-indent: 1em;
}

.primaryButton:hover {
  background: #a1a1a1;
  cursor: pointer;
}

.secondaryButton:hover {
  background: #bfbfbf;
  cursor: pointer;
}

.none {
  display: none;
}

.inlb {
  display: block !important;
}
<button class="primaryButton" id="p1">A</button>

  <button class="secondaryButton">1</button>
  <button class="secondaryButton">2</button>
  <button class="secondaryButton">3</button>

<button class="primaryButton" id="p2">B</button>

  <button class="secondaryButton">1</button>
  <button class="secondaryButton">2</button>

<button class="primaryButton" id="p3">C</button>

  <button class="secondaryButton">1</button>
  <button class="secondaryButton">2</button>

What happens when I do this that solves the problem?
Edit: This question is not a duplicate of this question, the main issue of in my question is buttons taking full width, while the other question asks for a differences between display: inline-block and display: block .


text:
Q: Assign a function output prints to a variable in python I have a function (in some project) that it prints the result.when I call it from the command line or in another python project, it prints the output on the terminal. But I want to store all the print result in a variable, something like this:
output = function_name(function_args)

and instead of printing the results on the terminal I want to store them in the output variable.
also, the main function returns something(just a number as the status) as the result which i do not want that number.

A: You can do this by rebinding sys.stdout:
>>> def foo():
...     print('potato')
...
>>> import sys, io
>>> sys.stdout = io.StringIO()
>>> foo()
>>> val = sys.stdout.getvalue()
>>> sys.stdout = sys.__stdout__  # restores original stdout
>>> print(val)
potato

For a nicer way to do it, consider writing a context manager.  If you're on Python 3.4+, it's already been written for you.
>>> from contextlib import redirect_stdout
>>> f = io.StringIO()
>>> with redirect_stdout(f):
...     foo()
...
>>> print(f.getvalue())
potato

In the case that you are able to modify the function itself, it may be cleaner to allow a dependency injection of the output stream (this is just a fancy way of saying "passing arguments"):
def foo(file=sys.stdout):
    print('potato', file=file)

A: The sensible solution is simple and obvious: fix the function so that it returns the correct data instead of printing it. Else you can use the hack posted by wim but assuming you have the hand on the faulty function resorting to such a convoluted solution falls into the "WTF" category.
NB of course if you don't have the hand on the function's code or it's just for a 5 minutes one-shot script, capturing sys.stdout is a handy fallback.


text:
Q: передать url изображения при клике на него в input text поле Ребят подскажите пожалуйста как передать url изображения в поле input text при клике на изображение

A: <input type="text" id="inputId" />
<img onclick="document.getElementById('inputId').value=this.src" id="imgId" src="...

$("#imgId").click(function() { $("#inputId").val(this.src); });

A: Можете использовать событие click на картинке. Чтобы получить значение атрибутов, можете метод jquery  attr или prop

$("#my_image").on('click', function(e) {
  $("#my_input").val(e.target.src)
  console.log(e.target.src)
})

<input id="my_input" type="text"/>


text:
Q: CPU/Threads usage on M1 Pro (Apple Silicon) using openMP hope someone knows the answer to this...
I have a code that compiles perfectly well with openMP (it uses libsharp). However, I am finding it impossible to make the M1 Pro chip use all the 8 or 10 cores I have.
I am setting the threads variable correctly as export OMP_NUM_THREADS=10 such that the code correctly identifies it's supposed to be running with 10 threads (see image below showing a print-screen from my activity monitor):
Activity Monitor Print Screen
Print screen is showing that the code is compiled for Apple Silicon, uses 10 threads but not much of the CPU available.
Does anyone know how to properly compile/set the number of threads such that all the cores will be used?
This is trivial in x86 architectures.

A: Not really an answer, but long for a comment...
If both LLVM and GCC behave the same then it's not an OpenMP runtime issue. (And your monitor output shows that the correct number of threads have been created). I'm also not certain that it's really an Arm issue.
Are you comparing with an Apple x86 machine (so running the same operating system), or with a Linux x86 system?
The scheduling decisions of the two OSes are likely different, and (for instance) MacOS has no interface to bind threads to logicalCPUs.
As well as that, there's the issue of having some fast and some slow cores. That could mean that statically scheduled loops are inefficient.
I'm also confused by the fact that you arm to show multiple instances of your code running at the same time, so you are explicitly causing over-subscription of the logicalCPUs...


text:
Q: A monoid-structure on pairs of interlacing polynomials Let us call a pair of two real polynomials $(P,Q)$ interlacing if $\deg(P)=\deg(Q)+1$, both polynomials have strictly positive leading coefficients and $P,Q$ have only real roots which interlace weakly, ie.
$$\rho_1\leq \rho'_1\leq \rho_2\leq \dots\leq \rho'_{n-1}\leq \rho_n$$ where $\rho_1,\dots,\rho_n$ are all roots (including multiple roots which are repeated)
of $P$ and $\rho'_1,\dots,\rho'_{n-1}$ are all roots of $Q$. We admit the pair
$(\lambda,0)$ as interlacing for $\lambda>0$.
It is easy to show (use for example the fact that $(P,Q)$ is interlacing if and only if $Q/P$ has $n$ real poles and is decreasing on intervals without poles) that the set of all interlacing polynomials is a monoid
for the product given by
$$(P_1,Q_1)\cdot (P_2,Q_2)=(P_1P_2,P_1Q_2+P_2Q_1)\ .$$
The identity is of course the degenerate pair $(1,0)$.
I could find no mention of this structure in the literature on interlacing polynomials. Did it appear somewhere?
Remarks: The usual definition of interlacing pairs is slightly different:
positivity of leading coefficients is not required but roots have to
interlace strictly. The above definition is of course taylored for the monoid structure (which creates multiple roots by taking powers of pairs).
It is possible to work with equivalence classes of pairs by considering
$(P,Q)\sim (\lambda P,\lambda Q)$ for $\lambda >0$.
The mononoid structure does not extend to "triplets" of interlacing polynomials.


text:
Q: Angular 6 - Material Text box Floating placeholder not working I want to use Angular 6 Material UI componenet to give more advance look and feel, I am running below test program , but matInput is not giving that look and feel.
Reference: https://material.angular.io/components/input/overview
Code:
<form class="example-form">
  <md-form-field class="example-full-width">
    <input mdInput placeholder="Favorite food" value="Sushi">
  </md-form-field>

  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Leave a comment"></textarea>
  </mat-form-field>
</form>

and my pachage.json is
{
  "name": "employee-management-system",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "6.1.7",
    "@angular/common": "6.1.7",
    "@angular/compiler": "6.1.7",
    "@angular/core": "6.1.7",
    "@angular/forms": "6.1.7",
    "@angular/http": "6.1.7",
    "@angular/platform-browser": "6.1.7",
    "@angular/platform-browser-dynamic": "6.1.7",
    "@angular/router": "6.1.7",
    "core-js": "2.5.7",
    "rxjs": "6.3.2",
    "zone.js": "0.8.26",
    "moment": "2.22.2",
    "hammerjs": "2.0.8",
    "@angular/cdk": "6.4.7",
    "@angular/material": "6.4.7",
    "web-animations-js": "2.3.1",
    "angular-in-memory-web-api": "0.5.4",
    "@angular/material-moment-adapter": "6.4.7"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^6.0.0",
    "@angular-devkit/build-angular": "~0.6.0",
    "typescript": "~2.7.2",
    "@angular/cli": "~6.0.0",
    "@angular/language-service": "^6.0.0",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~1.4.2",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1"
  }
}

Output:
place holder is not floating

A: You have to include a theme in your angular material application. You can use one of the pre-built themes, to do that add in your styles.css:
@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';

You can change this theme for other of the prebuilt themes:
indigo-pink.css
pink-bluegrey.css
purple-green.css

or make your own theme.


text:
Q: android - how to avoid lag/freezes with Samsung RFS filesystem? The Samsung Galaxy S comes with a propietary filesystem called RFS.
This filesystem seems to underperform in some occasions. Some applications get laggy, and others just freeze when using it. This has reached a point on which an external team has created a tool that basically migrates the whole system to ext4.
But not everyone is technically-savy to apply it, or don't want to risk voiding their smartphone's warranty.
I realize that the ideal situation would be that the filesystem was transparent and performant in all cases. But since this doesn't seem to be the case, I'd like to know:

*

*Does anyone know how to work around RFS' rough edges?

*Is there any guide or a best-practices document that the devs should read?

Thanks a lot!

A: Don't do I/O on the UI thread. It's that simple.
That means don't load preferences, don't query a database, don't decode bitmaps, etc etc... use background threads for all those things. Use StrictMode to keep your code on the straight and narrow.
FWIW I am a Galaxy S owner and have long been appalled at how Samsung crippled its performance with one stupid choice. I run "Darky's ROM" on it now and that basically fixes everything permanently... can't recommend that ROM highly enough.

A: The only way around RFS is to change it to ext4. Look at the Nexus S (a Galaxy S device), Google changed the RFS to ext4.
RFS is R eally F ricken S low and Samsung needs to realize it and change these devices.
When I was running my Galaxy S with the RFS file system, I only "noticed" the lag sometimes (so i thought), mainly when twitter would sync the latest content. The device would completely lock up and I couldn't do anything. Now that I am running a kernel with voodoo, I realized how slow RFS is. I came from a G1, so the Galaxy S was lightening fast. When I went from RFS to EXT4, the change was like coming from my G1 to the Galaxy S again.
I have a few friends that also have the Galaxy S, and I recommended it to them. Even they complain about the lag of the device.
There is no work around for RFS. Every developer should contact Samsung and let them know just how bad RFS is.
As Reuben said, don't do I/O on the UI thread, but that's a good practice anyhow. But that still wont fix the short comings of RFS. If you do a lot of I/O, no matter what thread it's on, it is still going to lag the device.


text:
Q: Would like to know what I am doing wrong and where to go from here I'm trying to create something with what I have Learned. What I am doing is trying to take todays date, subtract to 91 days prior to todays date. Then compare to a list of individuals and their anniversary dates to see who needs something added. Example. If todays date is 8/12/2021 and I want to go back 91-97 days that would be 05/13/2021-05/06/2021. Then if Jerrys hire date was 05/13/2021 and Berry's hire date was 05/06/2021 and Jacks hire date was 05/17/2021. I want to run a code that would tell me that Jerry and Berry were hired 91-97 days prior. so far I have the code for the
require 'date'
now = Date.today
ninety_days_ago = (now - 90)

p ninety_days_ago

Then I was tinkering with trying to add the names and using IF statements and nothing would come out right. Like I would make a variable called names and then add jerry and berry and jack with their hire dates but it would not compare their dates to the 91-97 days prior but it would not include Jack because he isn't at 91-97 days yet.
How can I print out the names of the people?

A:
So I'm new to coding ..
I want to run a code that would tell me that Jerry and Berry were hired 91-97 days prior.

require 'date'

today = Date.new(2021, 8, 12)

# In most languages this is called an array of objects.
# In ruby, we say "an array of hashes".
hires = [
  { name: 'Jerry', date: Date.new(2021, 5, 13) },
  { name: 'Berry', date: Date.new(2021, 5, 6) },
  { name: 'Jack', date: Date.new(2021, 5, 17) }
]

# This is called a function in most languages.
# In ruby we call all functions like this, "methods"
def report(hires, today)
  hires.each do |hire|
    puts(
      format(
        '%s was hired on %s, which is %d days ago',
        hire[:name],
        hire[:date],
        today - hire[:date]
      )
    )
  end
end

report(hires, today)

You can save this to a file like hires.rb and run it with ruby hires.rb.


text:
Q: Product and sum of line bundles on circle Given nontrivial one-dimensional  vector bundle $E$ on circle (which is of course Möbius strip). I need to find out if $E \oplus E \oplus  ... \oplus E$ (n times) would be trivial or not (my guess is that it never happens) and the same question about $E \otimes E \otimes ... \otimes E$.
In the second case I can first of all notice that $E \otimes E$ is  also one-dimensional and then we can look at transition maps. Let it be just  multiplying by $-1$ (trivialization is considered in stereographic projections charts on circle). Well, then in $E \otimes E$ it will be $(-1) \otimes (-1) = 1 \otimes 1$ which makes this bundle into trivial one. For $E \otimes E \otimes E$ we obtain $-1 \otimes 1 \otimes 1= - id$ and so this bundle is not trivial and so on. We will obtain cylinder for even $n$ and Möbius strip for odd. Am I right?
I would appreciate some explanation regarding to first question and indication of mistakes (if there are) in my solution.

A: Real line bundles $L \to B$ are classified by their first Stiefel-Whitney class $w_1(L) \in H^1(L; \mathbb{Z}_2)$, in particular, $w_1(L) = 0$ if and only if $L$ is trivial. Therefore, if $E$ denotes the non-trivial line bundle on $S^1$, we see that $w_1(E)$ is the unique non-zero element of $H^1(S^1; \mathbb{Z}_2) \cong \mathbb{Z}_2$.
For line bundles $L_1$ and $L_2$, we have $w_1(L_1\oplus L_2) = w_1(L_1\otimes L_2) = w_1(L_1) + w_1(L_2)$, so for any line bundle $L$ we have
$$w_1(L^{\oplus n}) = w_1(L^{\otimes n}) = \begin{cases}
0 & n\ \text{even}\\
w_1(L) & n\ \text{odd}.
\end{cases}$$
There are two cases:

*

*if $L$ is trivial, then so is $L^{\oplus n}$ and $L^{\otimes n}$ for every $n$.

*if $L$ is non-trivial, then $L^{\oplus n}$ is trivial if and only if $n$ is even, and $L^{\otimes n}$ is trivial if and only if $n$ is even.

In particular, as $E \to S^1$ is non-trivial, we are in the second case.


text:
Q: How can I get multiple elements to work with JavaScript? So when I click the checkbox, the background colour changes. I want this function to work for all checkboxes, but it is currently only working for the first one.

function obtained() {
  var obt = document.getElementsByClassName("obtained")[0];
  var col = document.getElementsByClassName("entry")[0];
  if (obt.checked == true) {
    col.style.backgroundColor = "#2ab320";
  } else {
    col.style.backgroundColor = "#d3d5db";
  }
}

  title1
content1
  <input
    type="checkbox"
    class="obtained"
    onclick="obtained()"
    name="obtained"
  >

  title2
content2
  <input
    type="checkbox"
    class="obtained"
    onclick="obtained()"
    name="obtained"
  />

  title3
content3
  <input
    type="checkbox"
    class="obtained"
    onclick="obtained()"
    name="obtained"
  />

A: In cases like this one you should declare a helper function:
function makeTogglable(element) {
  const obt = element.querySelector(".obtained");
  obt.addEventListener("click", () => {
    if(obt.checked == true) {
      element.style.backgroundColor = "#2ab320";
    } else {
      element.style.backgroundColor = "#d3d5db";
    }
  });
}

Then you can apply it your HTML elements, for example:
document.querySelectorAll('.entry').forEach(e => makeTogglable(e));

Edit: forgot about listeners

A: You could pass an instance of the checkbox to the function like so:

function obtained(element) {
  var col = element.parentElement;
  if (element.checked == true) {
    col.style.backgroundColor = "#2ab320";
  } else {
    col.style.backgroundColor = "#d3d5db";
  }
}

  title1
content1
  <input
    type="checkbox"
    class="obtained"
    onclick="obtained(this)"
    name="obtained"
  >

  title2
content2
  <input
    type="checkbox"
    class="obtained"
    onclick="obtained(this)"
    name="obtained"
  />

  title3
content3
  <input
    type="checkbox"
    class="obtained"
    onclick="obtained(this)"
    name="obtained"
  />