text:
Q: Short story about a pilot who is integral to a space ship that attacks planets I read it in an anthology book in 1975. When not attacking planets the pilot has more freedom to think and does not like what he does during the raids, but before the raids start he is injected with chemicals and drugs that make him forget his own thoughts and reinforce his feelings of aggression and victory and superiority. This may have been in a book edited by Roger Elwood, but I am not positive.

A: "City of Yesterday" by Terry Carr; first published in If, December 1967, available at the Internet Archive. You probably read it in the Silverberg-edited anthology Beyond Control whose contents also included Philip K. Dick's "Autofac". From the story:

As the destruction continued, he felt more and more the oneness, the wholeness of machine and man. Charles the other-thing was gone, merged into his own being, and now he was the machine, the beautiful complex mass of metals and sensors, relays and engines and weaponry. He was a destruction-machine, a death-flier, a superefficient killer. It was like coming out of the darkness of some prison, being freed to burst out with all his pent-up hatreds and frustrations and destroy, destroy . . .
It was the closest thing he had to being human again, to being . . . what was the name he had back on that planet where he'd been born? He couldn't remember now; there was no room for even an echo of that name in his mind.
He was Charles.
He was a war-machine destroying a city—that and only that. Flight and power occupied his whole being, and the screaming release of hatred and fear within him was so intense that it was love. The attack pattern became, somehow, a ritual of courtship, the pyrobombs and destruction and fire below a kind of lovemaking whose insensitivity gripped him more and more fiercely as the attack continued. It was a red hell, but it was the only kind of real life he had known since the machines had taken him.
When the battle was over, when the city was a flaming circle of red and even the beams had stopped firing from below, he was exhausted both physically and emotionally. He was able to note dimly, with some back part of his brain or perhaps through one of Charles' machine synapse-patterns, that they had lost three of the fliers. But that didn't interest him; nothing did.
When something clicked in him and Charles' voice said, "Remove your muscle contacts now," he did so dully, uncaring. And he became J-1001011 again.


text:
Q: Auto - Increment patch version on master while merging branches to master Given:
Bitbucket repo, and 2 developers, Steve and Bob who are working on 2 branches, feature/alpha & feature/beta. On master branch and feature branches we have a properties file with version - let say 8.3.0.
How to...
ensure that after Bob or Steve merges their pull request to the master the patch version on the master is incremented? I.e.:

*

*Steve finishes his feature/alpha first, his pull request is approved and while he merges it to master the version on master becomes 8.3.1. After Bob does the same - 8.3.2.

Looking for the less painful solution. Thx in advance!
UPDATE 2020-12-07:
mnestorov's answer with some modifications led to the desired result. The difference was that I had no rights to add pre-merge hooks on the server. In case someone is strugling with the same issue - here is a hackish recepie:

*

*create a pre-push hook and put incrementation logic there.

*use one of existing maven plugins for git hooks and make the created hook a part of your repo.

In this way you will ensure your incrementation script will run any time your teammates push without begging devops for help :)

A: One way is to create a pre-merge-commit hook and place it on your bitbucket server.
The hook can test a bunch of things, like check into what branch you are merging in, but it can also create or append files that specify the version. Basically, it can be as simple as:
Let's say that your version.txt looks like this:
version = 8.3.0

Then you can have something like:
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git merge" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message to
# stderr if it wants to stop the merge commit.
#
# To enable this hook, rename this file to "pre-merge-commit".

echo "Bumping Service version"

OLD_VERSION=$(cat version.txt | grep -o "=.*" | tr -d '= ')
NEW_NUM=$(( $(echo $OLD_VERSION | grep -o "\.[0-9]*$" | tr -d ".") + 1 ))
LAST_NUM=$(echo $OLD_VERSION | grep -o "\.[0-9]*$" | tr -d ".")
NEW_VERSION=$(echo $OLD_VERSION | tr $LAST_NUM $NEW_NUM)

# More conversions to bump the version if needed
# more code code code
# ...

sed -i 's/\(^version = \).*/\1'"$NEW_VERSION"'/' ~/service/version/file/txt

Of course, I'm just guessing what it might be and how it can possible be automated to bump the sub-sub version that you have. But it can definitely be automated and calculated how to bump a number up, whatever it is.
Note: that this hook does not take in any arguments, so you can't pass a version number to it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS 3D navigation in opera not working Live example:
http://www.script-tutorials.com/demos/298/index.html (move mouse on the blue bar on the top of page)
My problem:
This css 3d navigation menu (on the top) not work in Opera browser.
Why please? The css have this:

-o-transition: -o-transform 0.5s ease;

-o- is not opera?

A: Opera does not require a vendor prefix for transform, the vendor prefix -o- is only needed for transition and border-image.
Try using the normal transform as the transition property, instead of -o-transform, but keep the -o-transition: ...
-o-transition: transform 0.5s ease;


text:
Q: Loading scripts only if a particular shortcode or widget is present I needed a way to filter a page/posts content before it was loaded so I could add scripts to the header if a specific shortcode was present. After much searching I came across this on  http://wpengineer.com
function has_my_shortcode($posts) {
    if ( empty($posts) )
        return $posts;

    $found = false;

    foreach ($posts as $post) {
        if ( stripos($post->post_content, '[my_shortcode') )
            $found = true;
            break;
        }

    if ($found){
        $urljs = get_bloginfo( 'template_directory' ).IMP_JS;

    wp_register_script('my_script', $urljs.'myscript.js' );

    wp_print_scripts('my_script');
}
    return $posts;
}
add_action('the_posts', 'has_my_shortcode');

which is absolutely brilliant and did exactly what I needed.
Now I need to extend it a bit further and do the same for sidebars. It can be by a particular widget type, shortcode, code snippet or anything else that would work to identify when the script needs to be loaded.
The problem is I can't figure out how to access the sidebars content before the sidebar is loaded (the theme in question will have several sidebars)

A: Just wanted to share a solution I worked on which allowed me to be a bit more versatile with my implementation.  Rather than having the function check for a variety of shortcodes, I modified it to seek out a single shortcode that references a script/style function that needs to be enqueued.  This will work for both methods in other classes (such as plugins that may not do this themselves) and in-scope functions.  Just drop the below code in functions.php and add the following syntax to any page/post where you want specific CSS & JS.
Page/Post Syntax:  [loadCSSandJS function="(class->method/function name)"]
functions.php code:
function page_specific_CSSandJS( $posts ) {
  if ( empty( $posts ) )
    return $posts;

  foreach ($posts as $post) {

    $returnValue = preg_match_all('#\[loadCSSandJS function="([A-z\-\>]+)"\]#i', $post->post_content, $types);

    foreach($types[1] as $type) {
      $items = explode("->",$type);
      if (count($items) == 2) {
        global $$items[0];
        if( method_exists( $$items[0], $items[1] ))
          add_action( 'wp_enqueue_scripts', array(&$$items[0], $items[1]) );
      }
      else if( !empty( $type ) && function_exists( $type ))
        add_action( 'wp_enqueue_scripts', $type );
    }
  }

  return $posts;
}

This will also allow you to add as many as you want on a page.  Keep in mind that you do need a method/function to load.

A: You can use the function is_active_widget . E.g.:
function check_widget() {
    if( is_active_widget( '', '', 'search' ) ) { // check if search widget is used
        wp_enqueue_script('my-script');
    }
}

add_action( 'init', 'check_widget' );

To load the script in the page where the widget is loaded only, you will have to add the is_active_widget() code, in you widget class. E.g., see the default recent comments widget (wp-includes/default-widgets.php, line 602):
class WP_Widget_Recent_Comments extends WP_Widget {

    function WP_Widget_Recent_Comments() {
        $widget_ops = array('classname' => 'widget_recent_comments', 'description' => __( 'The most recent comments' ) );
        $this->WP_Widget('recent-comments', __('Recent Comments'), $widget_ops);
        $this->alt_option_name = 'widget_recent_comments';

        if ( is_active_widget(false, false, $this->id_base) )
            add_action( 'wp_head', array(&$this, 'recent_comments_style') );

        add_action( 'comment_post', array(&$this, 'flush_widget_cache') );
        add_action( 'transition_comment_status', array(&$this, 'flush_widget_cache') );
    }

A: with Wordpress 4.7 there is another way to achieve this in your functions.php file,
add_action( 'wp_enqueue_scripts', 'register_my_script');
function register_my_script(){
  wp_register_script('my-shortcode-js',$src, $dependency, $version, $inFooter);
}

first you register your script, which doesn't actually get printed on your page unless your enqueue it if your shortcode is called,
add_filter( 'do_shortcode_tag','enqueue_my_script',10,3);
function enqueue_my_script($output, $tag, $attr){
  if('myShortcode' != $tag){ //make sure it is the right shortcode
    return $output;
  }
  if(!isset($attr['id'])){ //you can even check for specific attributes
    return $output;
  }
  wp_enqueue_script('my-shortcode-js'); //enqueue your script for printing
  return $output;
}

the do_shortcode_tag was introduced in WP 4.7 and can be found in the new developers documentation pages.

A: Thank you for sharing this tip!
It gave me a little headache, because at first it wasn't working. I think there are a couple of mistakes (maybe typos) in the code above has_my_shortcode and I re-written the function as below:
function has_my_shortcode( $posts ) {

        if ( empty($posts) )
            return $posts;

        $shortcode_found = false;

        foreach ($posts as $post) {

            if ( !( stripos($post->post_content, '[my-shortcode') === false ) ) {
                $shortcode_found = true;
                break;
            }
        }

        if ( $shortcode_found ) {
            $this->add_scripts();
            $this->add_styles();
        }
        return $posts;
    }

I think there were two main issues: the break wasn't in the scope of the if statement, and that caused the loop to always break at the first iteration. The other problem was more subtle and difficult to discover. The code above doesn't work if the shortcode is the very first thing written in a post. I had to use the === operator to solve this.
Anyway, thank you so much for sharing this technique, it helped a lot.


text:
Q: how to fix elements display over the elements in react on hover over the specific product, it's displayed over the navbar
[!
images also scroll over the navbar

the technology used in this project is - react + tailwind CSS
suggest CSS for this

A: *

*Maybe you forgot to add z-index css for navbar .

*Or navbar's z-index is smaller than product's z-index
.navbar{
   ...
   z-index: 999; // Sure that it's greater than `product's z-index`
 }


text:
Q: Bitbucket not accepting EC2 ssh-key I've tried to import id_rsa.pub that I generate from my EC2 terminal to my bitbucket account so I don't need to input auth password over and over again when I doing git command. But it seems the Bitbucket still rejected it.

Also please suggest me the simplest webhook that I could create to pull the repository via php exec command so I can doing pull request with link on web browser.
Thanks,

A: Check your ssh user and key
ssh -v user@domain.com
This should list the private key your registered with BitBucket. If it does NOT, then a little extra configuration may get you there:
~/.ssh/config
host domain.com
user username
identityfile ~/.ssh/id_rsa # path to your private-key-file

Generate the key on another computer.
OS versions and configurations can use any number of encryption algorithms and encoding methods for creating and storing the key-pair. Sometimes these methods don't transfer well between OSs, or won't play nice in different environments.

*

*Check your SSH protocol and client. You may need a different or newer version.

*If all else fails, generate the key on a computer that you know works for keygen, then figure out how to get this key working.


text:
Q: AWS DynamoDDB + python: throughput is not being reached, how can I speed up? I have a python script that performs the following operations. It reads a text file line by line. Info about each line has to be recorded in a DynamoDDB table. I process each ingested line and then perform one write like this:
with open(fPath, 'r') as f:
   for line in f:
      # process line, extract data to be written into DDB into item_data
      # also extract key
      item = table.new_item(hash_key=key_from_line,attrs=item_data)
      item.put()

I have noticed that the effective throughput, i.e. the number of writes I make per second (on average) is much lower than the max throughput I set for the table on the AWS DDB console. Now, it's possible that there are major inefficiencies at the line processing step. But I am wondering if I can also speed things up by writing into the table differently. For instance, does it make sense to collect an array of items and then write them all at once? If so, is there a way to determine the optimal size of the array? Any other simple (and maybe not so simple ways) of making writing faster?

A: The reason that you are not getting the maximum throughput is that you are creating "hot zones". That is you have too many calls to the same partition of your Table.
The fastest fix is to reverse your keys or to hash them, as they are probably having the same prefix.
Provisioned throughput is dependent on the primary key selection, and the workload patterns on individual items. When storing data, Amazon DynamoDB divides a table's items into multiple partitions, and distributes the data primarily based on the hash key element. The provisioned throughput associated with a table is also divided evenly among the partitions, with no sharing of provisioned throughput across partitions.

Total provisioned throughput/partitions = throughput per partition.

Consequently, to achieve the full amount of request throughput you have provisioned for a table, keep your workload spread evenly across the hash key values. Distributing requests across hash key values distributes the requests across partitions.
You can see more information here: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html#GuidelinesForTables.DataUpload


text:
Q: From direction cosine matrix to Cardan angles - Two different Matlab codes, different results I have two Matlab codes to get the Cardan angles (ZXY sequence) starting from a given direction cosine matrix (dcm), but the results are different. Why?
The dcm is:
dcm = [0.5972   -0.7833   0.1729;
       0.7990   0.5987    -0.0553;
       -0.0592  0.1719    0.9832];

First code (alpha=angle around x, beta=angle around y, gamma=angle around z):
[gamma, alpha, beta] = dcm2angle(dcm,'ZXY');
% Result:
%   -0.9277   -0.0553   -0.1741

Second code:
if abs(dcm(3,2)) ~= 1
    alpha = asin(dcm(3,2));
    %
    if dcm(3,3) >= 0
        beta = asin(-dcm(3,1)/cos(alpha));
    else
        beta = pi - asin(-dcm(3,1)/cos(alpha));
    end
    %
    if dcm(2,2) >= 0
        gamma = asin(-dcm(1,2)/cos(alpha));
    else
        gamma = pi - asin(-dcm(1,2)/cos(alpha));
    end
end
% Result:
%   0.9192    0.1728    0.0601

The dcm for the sequence ZXY in terms of sin and cos is:

Thank you so much for your willingness.


text:
Q: Cannot get my service worker to initialize in react
*

*I have changed unregister to register in the index.js file.

*Without any changes to the service worker or the web manifest, I run a build, then host it with serve (serve -s build). However when i run an audit with chrome, it errors out. the errors are:
start_url does not respond with a 200 when offline
Does not use HTTPS
Does not register a service worker that controls page and start_url
Does not redirect HTTP traffic to HTTPS
So how do i get the pwa to work out of the box? switching unregister to register does not seem to work.
service worker:

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
  window.location.hostname === '[::1]' ||
  window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);

export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/#/service-worker.js`;

      if (isLocalhost) {
        checkValidServiceWorker(swUrl, config);
        navigator.serviceWorker.ready.then(() => {
          console.log('This web app is being served cache-first by a service ');
        });
      } else {
        registerValidSW(swUrl, config);
      }
    });
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              console.log('Content is cached for offline use.');
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl, config) {
  fetch(swUrl)
    .then(response => {
      const contentType = response.headers.get('content-type');
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf('javascript') === -1)
      ) {
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

Manifest:
{
    "name": "MEX Broadband",
    "short_name": "MEX Broadband",
    "icons": [
        {
            "src": "/android-chrome-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "/android-chrome-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ],
    "theme_color": "#ffffff",
    "background_color": "#ffffff",
  "display": "standalone",
  "start_url": "./index.html"
}


text:
Q: Table cell height bug in Chrome I made a CSS table with a CSS table inside it. When I use vertical-align at the inner one it doesn't rendering it correctly when I resize it (make it smaller, then bigger). It still as height as the highest point
Look at this codepen and resize the window. Make it really small. Wait for 1-2 seconds. Then Make the window larger. Notice that the height of the table-cell doesnt goes back.
Annoying! Anyone knows a fix?
http://codepen.io/iamrane/pen/hklxj
Here it is in fullscreen: http://cdpn.io/hklxj

A: I found a bug in chromes bug list:
https://code.google.com/p/chromium/issues/detail?id=241331&q=vertical-align&colspec=ID%20Pri%20M%20Iteration%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified

A: Very annoying!
If you are desperate to get this working you could force Chrome to redraw the element (on window resize, maybe?):
var elem = document.getElementsByClassName("table-list")[0];

elem.style.display = "none";

elem.style.display = "table";


text:
Q: npm behind not working behind cntml proxy due to proxy auth problems i use cntml to redirect our proxy over the cntml proxy.
An npm install is terribly slow (takes hours on quickstart project)
I set up npm proxy with this:
npm config set proxy http://localhost:1111
npm config set https-proxy http://localhost:1111
npm config set registry http://registry.npmjs.org

CNTML works for very fast e.g. for chrome.
What can cause npm to fail?

A: If you are working behind a corporate proxy, providing just the host:port may not be enough.  I have found success with the following steps:
npm config set strict-ssl false

npm config set registry "http://registry.npmjs.org/"

Below, the %5C is a replacement of the backslash, and is important
npm config set proxy http://<domain>%5C<username>:
<password>@<host>:<port>

npm config set https-proxy http://<domain>%5C<username>:
<password>@<host>:port

npm install <npm_package>

Here is an example of the proxy usage:
npm config set proxy http://MyDomain%5CMyUsername:
MyPassword@myproxy.mycorp.net:1234


text:
Q: How to get a PDO Fetch( ) to return as string How can I get a PDO to return the data as a string not an array? I am not sure this is possible so if not is there a way to convert the array to a string after it has been processed?
My code which is returning the string is:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);

I have tried different fetch types such as FETCH_CLASS FETCH_OBJ

A: You can do it like this:
echo $stmt->fetchColumn();

Or:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result[0];

A: $result = $statement->fetchColumn();

This work for me, the only thing I noticed here is that fetchColumn() always refer to first column on your table. You need to adjust / re-position the only column needed to the first-column on your table or make an Sql query i.e "SELECT" query to get the only column needed. Thanks


text:
Q: Finder Search (spotlight) not finding all relevant results I'm trying to remove an application manually by deleting it and any extras using the search function in Finder.
As a backup, I also ran the app through AppCleaner to see if it caught anything as well and I noticed that AppCleaner marked some files (.plist, plist.lockfile, and some actual folders) that no matter what keyword I use won't show up via finder search.
My settings are to search 'My Mac' and have made sure system files are included and used both 'name matches' & 'name contains' but I can't pull up these files. I have already rebuilt the spotlight index and don't know what else to do when a custom search that explicitly includes system files doesn't yield the expected results.
Did finder search change in os 10.9?

A: The Spotlight window does not include files treated as system files by default. Try setting "System files" to "are included":

Or use mdfind:
$ mdfind -name tweetbot
/Applications/Tweetbot.app
/Users/lauri/Library/Application Support/CrashReporter/Tweetbot_4C49445B-E14E-51E5-87DC-7CE59AE6A841.plist
/Users/lauri/Library/Containers/com.tapbots.TweetbotMac/Data/Library/Application Support/CrashReporter/Tweetbot_4C49445B-E14E-51E5-87DC-7CE59AE6A841.plist
/Users/lauri/Library/Containers/com.tapbots.TweetbotMac/Data/Library/Application Support/Tweetbot
/Users/lauri/Library/Containers/com.tapbots.TweetbotMac
/Users/lauri/Library/Speech/Speakable Items/Application Speakable Items/Tweetbot
/Users/lauri/Library/SyncedPreferences/com.tapbots.TweetbotMac.plist


text:
Q: AWS Cloudfront returns 403 when PUT request body is greater than 8kb I have an API behind AWS Cloudfront which has functioned fine with our front end application for years. Recently, after a feature release, I've noticed some users are reporting data not being saved and the app just hanging. After a lengthy investigation, I've discovered that our Cloudfront distribution will return a 403 Forbidden error when a PUT request's JSON body is greater than 8kb. Anything less works fine, anything more returns 403. I verified this by sending PUT requests with a decreasing body data size until I got the expected 201 Created response, and just checked the size of the body sent. The JSON is properly formatted.
The error returns in about 170ms and contains the header from Cloudfront X-Cache: Error from cloudfront
I have looked for settings on size limits, I've tried disabling the WAF rules, I've tried "Compress objects" to both on/off. Would having Real-time logs enabled have an impact on the max data accepted somehow? Seems crazy but I'm kind of bewildered by this issue.
I would love to show you all some kind of log from Cloudwatch to help, but requests that don't make it past Cloudfront are not logged in Cloudwatch, and I have not been able to setup any kind of logging to get better insight into why it's barfing.

A: As was the initial hunch, this turned out to be a WAF ACL rule issue.
The blocking ACL was applied to the application load balancer, so finding it in the Web ACL list either requires inspecting the region where your load balancer is (eg us-west-2), or by inspecting the load balancer's Integrate Services, where you can see any AWS WAF rules:

*

*AWS > EC2 > Load Balancers > {instance} > Integrated services (tab) > AWS WAF

The specific rule was in an AWS managed rule set called AWS-AWSManagedRulesCommonRuleSet. Just turn the SizeRestrictions_BODY rule to Count instead of "Use action defined in the rule"
This obviously has impacts on what requests get through to your application, so do with that what you will.


text:
Q: Can a macro be used when a user clicks the Insertpicture button in a picture placeholder in PowerPoint? I have developed a server-based image library for a client that is accessed from a Tender Word template.
They have now asked for a new PowerPoint template that can import images from this Library. I have put together macros that can import specific images, but I need the user to select the one they want each time. For example, on a team slide, where there are six placeholders, they click the button and a macro shows the image library folder, not the default folder.
I would like to get this macro to work whenever the user clicks an import button in a picture placeholder, but can find a way of doing it.
Any suggestions would be great.

A: How about this approach

*

*Prepare the PowerPoint template and add a tag to each placeholder shape

*Create a macro that traps WindowSelectionChange events

*When the event occurs check if the selected shape has the tag that you added before and bring up your import dialog if yes

A: I don't believe PPT has an Event that would trap this user behavior.  Looking over my Event Class module, I don't see anything that looks like an obvious solution.
One idea you might look in to is customize a Context Menu to include a command that will execute this macro:
http://msdn.microsoft.com/en-us/library/office/gg469862(v=office.14).aspx#odc_xl_ta_CustomExcelContextMenus_AddControlsUsingRibbonX
However, MS has limited the ability to manipulate Context Menus in 2007+ versions of Office applications. For example, they no longer allow you to manipulate certain context menus (the one that comes to mind from my experience is the Chart Context Menu in Excel), so maybe this idea will not work, either.


text:
Q: How to get Injectable to generate dependency injection for third party Abstract class thats using factory constructors I am trying to register the class below with the package Injectable.
import 'dart:io';

import 'package:injectable/injectable.dart';

@injectable
class IWantToBeRegistered {
  final File file;
  IWantToBeRegistered({
    required this.file,
  });
}

I get the response below:
[WARNING] injectable_generator:injectable_config_builder on bin/service_locator.dart:
Missing dependencies in your_project/bin/service_locator.dart

[MachineCodeWriter] depends on unregistered type [File] from dart:io

Did you forget to annotate the above class(s) or their implementation with @injectable?
or add the right environment keys?

I have attempted registering File as a third party type but with no luck.
In the documentation of Injectable it does say it's possible to register it manually in the configure function, but I was unable to find a working example and failed to implement it successfully by myself.
The project is a command line app in Dart and I am using the SDK and package versions below:
Dart SDK version: 2.15.1 (stable)
get_it: ^7.2.0
injectable: ^1.5.0
injectable_generator: ^1.5.0

Thanks for your help!

A: You can use a RegisterModule for this purpose.
you can check how you can use RegisterModule for injectable from here
@module
abstract class RegisterModule {
   YourThirdParty getThirdPartyObjectInstance(TypeOfThirdParty typedObject, @factoryParam String url) => YourThirdParty(obj, url);
}


text:
Q: Determinant of a particular matrix. What is the best way to find determinant of the following matrix?
$$A=\left(\begin{matrix}
1&ax&a^2+x^2\\1&ay&a^2+y^2\\ 1&az&a^2+z^2
\end{matrix}\right)$$
I thought it looks like a Vandermonde matrix, but not exactly. I can't use  $|A+B|=|A|+|B|$ to form a Vandermonde matrix. Please suggest. Thanks.

A: I think the best way it's the following:
$$\Delta=\sum_{cyc}(ay(a^2+z^2)-ay(a^2+x^2))=a\sum_{cyc}(x^2z-x^2y)=a(x-y)(y-z)(z-x).$$

A: \begin{align}
&|A|\\
&=\det\left(\begin{matrix}
1&ax&a^2+x^2\\1&ay&a^2+y^2\\ 1&az&a^2+z^2
\end{matrix}\right) \\
&=\begin{vmatrix}
1&ax&a^2\\1&ay&a^2\\ 1&az&a^2
\end{vmatrix}+\begin{vmatrix}
1&ax&x^2\\1&ay&y^2\\ 1&az&z^2
\end{vmatrix} \tag{multilinearity on 3rd column} \\
&=0+a\begin{vmatrix}
1&x&x^2\\1&y&y^2\\ 1&z&z^2
\end{vmatrix} \\
&= a (x-y)(y-z)(z-x)
\end{align}

A: Note that
$$
\det\left(\begin{matrix}
1&ax&a^2+x^2\\1&ay&a^2+y^2\\ 1&az&a^2+z^2
\end{matrix}\right) =\det \left(\begin{matrix}
1&ax&x^2\\1&ay&y^2\\ 1&az&z^2
\end{matrix}\right)=a\cdot\det \left(\begin{matrix}
1&x&x^2\\1&y&y^2\\ 1&z&z^2
\end{matrix}\right)
$$ which boils down to Vandermonde determinant
$$
a(x-y)(y-z)(z-x).
$$


text:
Q: XmlTextReader for XDocument source Given an XDocument, how can I obtain an XmlTextReader to its contents?  XDocument.CreateReader() returns a XmlNodeReader, I need an XmlTextReader.
var xDoc = new XDocument(...);
var nodeReader = xDoc.CreateReader(); // I need a XmlTextReader
var textReader = new XmlTextReader(????xDoc???);

A: This seems to work, not sure why I didn't think of it sooner...
var xDoc = new XDocument(...);
var textReader = new XmlTextReader(new System.IO.StringReader(xDoc.ToString()));

A: I don't know if this is best way, but if you got XDocument and cant read xml file to anything else, you could change XDocument to MemoryStream and create `XmlTextReader' from this stream:
        var xmlFile = XDocument.Load(uri);
        Stream stream = new MemoryStream();
        xmlFile.Save(stream);
        stream.Position = 0;
        XmlTextReader reader = new XmlTextReader(stream);
        while (reader.Read())
        {
            //do your stuff with file
        }


text:
Q: Git clone from private github repository with Github Actions token I need to do some directory grooming before my app is ready to be tested or deployed. I would like to utilize a Makefile target which calls a shell script in the repo to make this CI/CD-agnostic. One can call this target with make prepare_directory
The CI platform I am using is Github Actions. Here are the relevant parts of the workflow which is being run on new Pull Requests:
name: PR Tests
env:
  GIT_TOKEN: ${{ secrets.GITHUB_TOKEN }}
jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 1
      - name: Prep directoy
        run: make prepare_directory

Here is the relevant part of the Makefile (which works exactly as expected locally):
...
prepare_directory:
    ./scripts/prepare_directory.sh

clean:
    @rm -Rf ./$(BUILDPREFIX)

.PHONY: all clean docker lint prep_avro $(dockerbuilds)

Here is the relevant part of the ./scripts/prepare-directory.sh script:
#!/bin/bash -e
# ...
# clone repo using https and GITHUB_TOKEN
git clone https://$GIT_TOKEN@github.com:USERNAME/REPO.git

When I try to clone using that URL, from the shell script, the script fails (along with the Github workflow pipeline) with the following error: fatal: unable to access 'https://github.com:USERNAME/REPO.git/': URL using bad/illegal format or missing URL
Does anybody know what I'm doing wrong?

A: You can add this action after your checkout step and GitHub can access your private repo dependancy.
Note:- Make sure to add a server's private key as a secret, public key to GitHub SSH keys and Please replace your private repo URL from https+auth_token to SSH. ssh://git@github.com/your_group/your_project.git
Below is the example
      - uses: webfactory/ssh-agent@v0.4.1
        with:
          ssh-private-key: ${{ secrets.SSH_KEY }}

SSH_KEY is the private key secret which you created.

A: I've created a GitHub App and Github Action to workaround these limitations GitHub Actions Access Manager. Feel free to drop some feedback.
Workflow

*

*This GitHub action will request an access token for a Target Repository from the App Server, authorize by the GitHub Action ID Token (JWT signed by GitHub).

*The App Server requests a GitHub App Installation Token to read .github/access.yaml file in Target Repository.

*The App Server reads .github/access.yaml file from Target Repository and determine which permissions should be granted to Requesting Repository, authorized by the GitHub App Installation Token from step 2..

*The App Server requests a GitHub App Installation Token with granted permissions for Source Directory and send it back in response to the GitHub action from step 1..

*The GitHub action sets the token as environment variable $GITHUB_ACCESS_TOKEN and as step output value ${{ steps.github-actions-access.outputs.token }}.

*Further steps can then utilize this token to access resources of the Target Repository.

A: The URL in your prepare-directory.sh script's git clone call has a typo in it:
# clone repo using https and GITHUB_TOKEN
git clone https://$GIT_TOKEN@github.com:USERNAME/REPO.git

The URL there is halfway between an HTTPS git URL and an SSH one. The : should be a /. Assuming your $GIT_TOKEN contains just the token and nothing else, you'd also need a : before the @:
git clone https://$GIT_TOKEN:@github.com/USERNAME/REPO.git

If your $GIT_TOKEN contained the complete auth string, which for a Github App installation access token would be something like "x-access-token:ghs_..." then you wouldn't need the : following $GIT_TOKEN, you'd just have $GIT_TOKEN@github.com.


text:
Q: Sleep thread until another thread completes for iOS I'm very new to backend programming and iOS programming. I'm currently integrating DynamoDB into my iOS application. I'm doing a signup function that queries the database to check whether the username is taken.
Here's the main idea of my code:
__block BOOL isPlayerTaken = NO;

//Block of code that queries the database
//Mutates value of isPlayerTaken if player exists

    [[dynamoDBObjectMapper query:[DDBRunnerTableRow class]
                  expression:queryExpression]
 continueWithExecutor:[BFExecutor mainThreadExecutor] withSuccessBlock:^id(BFTask *task) {
     AWSDynamoDBPaginatedOutput *paginatedOutput = task.result;
     DDBRunnerTableRow *queriedRunner = paginatedOutput.items[0];
     if (queriedRunner) {
         isPlayerTaken = YES;
         NSLog(@"%@", queriedRunner.runnerName);
     }

     return nil;
 }];

return isPlayerTaken;

However, the function returns before the query result is completed and hence the output is always NO.
How can I ensure that the function doesn't return until the query block completes?
Thank you so much for your help. I believe I would need this in many functions of my code that requires querying and inserting of data and I didn't want to come up with a hackish solution for it.

A: Try something like this:
[[dynamoDBObjectMapper query:[DDBRunnerTableRow class]
                  expression:queryExpression]
 continueWithExecutor:[BFExecutor mainThreadExecutor] withSuccessBlock:^id(BFTask *task) {
     AWSDynamoDBPaginatedOutput *paginatedOutput = task.result;
     DDBRunnerTableRow *queriedRunner = paginatedOutput.items[0];
     if (queriedRunner)
     {
         NSLog(@"%@", queriedRunner.runnerName);
         [self loginSuccessfull:queriedRunner];
     }
     else
     {
         [self loginFailed];
     }
 }];

then
- (void)loginSuccessfull:(DDBRunnerTableRow *)queriedRunner
{
    //whatever
}

- (void)loginFailed
{
    //whatever
}


text:
Q: Create a list like array when echoed in php I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,
i would want my final result  to look like
[10,200,235,390,290,250,250]
When i try the code below:
$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);

echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {

   $list =  $row['column'];
   $listwithcoma = "$list,";
   echo ltrim($listwithcoma,',');
}
echo ']'

The result is :
[10,200,235,390,290,250,250,]

A: You are doing it wrong. ltrim($listwithcoma,',') has no effect.

ltrim — Strip whitespace (or other characters) from the beginning of a string

You can try a simple way with implode.
$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
   $list[] =  $row['column'];
}

echo '[' . implode(',', $list) . ']';

A: Just use GROUP_CONCAT in query as
$query_rg = mysqli_query($link, "SELECT GROUP_CONCAT(`column` SEPARATOR ', ') as data
    FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
print_r($row_rg['data']);

A: Try like this
$list = array(); //define a array.
while ($row = mysqli_fetch_assoc($query_rg)) {
  $list[] =  $row['column']; //store column value in array.
}
$lists = "[".implode(",",$list)."]";
echo $lists; //will echo your results.

A: You should be using rtrim() function instead, that too outside the loop.
$listwithcoma = '';
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {

   $list =  $row['column'];
   $listwithcoma .= "$list,";
   // echo ltrim($listwithcoma,',');   Remove this
}

echo rtrim($listwithcoma,',');  // Add this
echo ']';


text:
Q: EXC-BAD-ACCESS when setting a relationship between two objects Can anyone explain why given the following MagicalRecord import code
__block NSManagedObject *importedObject = nil;

[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
  id entityClass = NSClassFromString( name );
  importedObject = [entityClass importFromObject:dictionary inContext:localContext];
}];

NSManagedObjectID *importedObjectID = importedObject.objectID;

NSManagedObject *relatedObject = ( (CustomRelatedExampleObject *) [[NSManagedObjectContext defaultContext] objectWithID:importedObjectID] ).relatedObject;

This works fine, setting the relationship and saving as expected
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
        someObjectInDefaultContext.alsoRelated = relatedObject;
}];

But this causes exec bad access, when I expected that this is technically more correct because I am using the local context for saving my data. (Note: I left out the code that gets objectIDs from both objects for brevity)
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
        AnotherCustomExampleObject *localSomeOtherObjectInDefaultContext = (AnotherCustomExampleObject *) [localContext objectWithID:someOtherObjectInDefaultContextObjectID];
        CustomRelatedExampleObject *localRelatedObject = (CustomRelatedExampleObject *) [localContext objectWithID:localRelatedObjectID];
        localSomeOtherObjectInDefaultContext.alsoRelated = localRelatedObject;
}];

I get exec bad access on the last line when I try to assign the object to the relationship in the other object.
UPDATE 1
This problem was caused by using temporary object ids when getting local copies of the objects in another managed object context.
UPDATE 2
I have discovered that simply changing the method used to retrieve the object removes the error.
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
    AnotherCustomExampleObject *localSomeOtherObjectInDefaultContext = (AnotherCustomExampleObject *) [localContext existingObjectWithID:someOtherObjectInDefaultContextObjectID];
    CustomRelatedExampleObject *localRelatedObject = (CustomRelatedExampleObject *) [localContext existingObjectWithID:localRelatedObjectID];
    localSomeOtherObjectInDefaultContext.alsoRelated = localRelatedObject;
}];

using existingObjectWithID instead of objectWithID returns and object with a permanent id instead of a temporary one.

A: Check your object ids. If one or both are temporary, core data will not like that. But, in general, the crash you describe is because you are trying to relate two objects from a different context. I know you're going through the proper steps here, but perhaps double check in the debugger to make sure the context on those objects are the same.


text:
Q: Can you, and if so how do you get the default cursor as an Image? Is there anyway I can get the users default cursor texture in JavaScript as an Image object?

A: Not really. Each browser is free to display whatever they want as cursor and there is no API to query what image they use. You could check the browser name and version and download the image from the source when it's an OSS project but ... yeah.
That said, you can define your own cursors:
cursor: url('some-cursor.ico'), default;

That way, you could try to make the browser use a known image.
Related:

*

*CSS Custom Cursors


text:
Q: Connect to a different database in django shell How can I connect to a different database when in a Django shell?
Something like:
python manage.py shell --database=slave

I tried googling all around, but couldn't find anything useful on this.
This is what my settings looks like:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db1',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': '10.10.10.10',
        'PORT': '',
        'CONN_MAX_AGE': 1000,
    },
    'slave':{
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db2',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': '10.10.10.10',
        'PORT': '',
        'CONN_MAX_AGE': 1000,
    },
}

A: You could select database in your query with using() ORM's method:
# This will hit a model in your default DB:
Model.objects.using('default').all()

# And this will hit a model in your slave DB:
Model.objects.using('slave').all()

A: You can split your settings module into submodules. For instance:
project/
    settings/
        __init__.py
        base.py
        dev.py
        prod.py
        shell.py

Your main/common settings are located in project/settings/base.py
In development, set DJANGO_SETTINGS_MODULE environment variable to project.settings.dev.
project/settings/dev.py may look like:
from .base import *

DEBUG = True

project/settings/shell.py may look like:
from .dev import *

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db2',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': '10.10.10.10',
        'PORT': '',
        'CONN_MAX_AGE': 1000,
    },
}

# OR
#
# DATABASES['master'] = DATABASES['default']
# DATABASES['default'] = DATABASES['slave']

Then run python manage.py shell --settings=project.settings.shell.

Or, alternatively, just create a second settings module:
project/
    settings.py
    shell_settings.py

project/shell_settings.py would look like:
from .settings import *

DATABASES['master'] = DATABASES['default']
DATABASES['default'] = DATABASES['slave']

and run python manage.py shell --settings=project.shell_settings

A: You can also use the connection module from django.db to create/connect to a brand new test database.
from django.db import connection
db = connection.creation.create_test_db()

I know it's not quite what was asked, but it's helpful and quick when testing. It will create a new test database and connect you to it. I haven't figured out how to connect to an existing database with it yet, but stay tuned.


text:
Q: Linq-to-entities, Generics and Precompiled Queries I'm experimenting with linq and generics. For now, I just implemented a GetAll method which returns all records of the given type.
class BaseBL<T> where T : class
{
    public IList<T> GetAll()
    {
        using (TestObjectContext entities = new TestObjectContext(...))
        {
            var result = from obj in entities.CreateObjectSet<T>() select obj;
            return result.ToList();
        }
    }
}

This works fine. Next, I would like to precompile the query:
class BaseBL<T> where T : class
{
    private readonly Func<ObjectContext, IQueryable<T>> cqGetAll =
    CompiledQuery.Compile<ObjectContext, IQueryable<T>>(
      (ctx) => from obj in ctx.CreateObjectSet<T>() select obj);

    public IList<T> GetAll()
    {
        using (TestObjectContext entities = new TestObjectContext(...))
        {
            var result = cqGetAll.Invoke(entities);
            return result.ToList();
        }
    }
}

Here, i get the following:
 base {System.Exception} = {"LINQ to Entities does not recognize the method
'System.Data.Objects.ObjectSet`1[admin_model.TestEntity] CreateObjectSet[TestEntity]()'
 method, and this method cannot be translated into a store expression."}

What is the problem with this? I guess the problem is with the result of the execution of the precompiled query, but I am unable to fanthom why.

A: I had this exception when I used methods inside the LINQ query that are not part of the entity model. The problem is that the precompiled query can't invoke the CreateObjectSet for the type TestEntity because the precompiled query is not part of the context that is used to invoke it.


text:
Q: Google analytics tracking outbound events I have setup outbound event tracking for Google analytics as per instructed by Google:
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
}

I am trying to determine if it is working properly eg if the event is being tracked.
When I view the click in my developer tools, it says the 'collect' request sent to google analytics was cancelled.
However, if I set the link to open in a new tab, the 'collect' request does not get cancelled.
I am wondering if it matters that collect was cancelled, eg even though my network tools are saying it was cancelled, was it really sent to google and my browser thinks it was cancelled because it did not register a response - which in this case we do not need we are redirecting away from the page anyway?
I know it is accessing 'hitcallback' as the code inside executes -  so I assume this means the call back has happend as intended?
The reason I ask is because for iphone, I cant get the link to open in a new window, and I will to wait 1+ days to see if the iphone event is tracked

A: There is an "events" item in the realtime reports menu, so you do not have to wait.
As far as your transport method is concerned, according to this site mobile Safari does not support navigator.sendBeacon, so this setting will do nothing for that specific use case and simply fall back to image or xhr respectively. Since that requires a server response I would assume that your events are not being tracked if the request is cancelled. But do go and check the realtime report to be certain.


text:
Q: nvidia driver-510 issue related to nvidia-515 A couple of weeks ago apt upgrade on my desktop computer running Ubuntu 20.04 started telling me I had kept-back packages. They were nvidia-510 packages, and one  nvidia-515 package. It seemed odd nvidia-driver-510 should have a dependency on nvidia-driver-515.
At the same time I started having issues with video, like movies not playing smoothly, and typing in an editor not being smooth. I decided to revert to nvidia-driver-470 which is working well on my laptop, but this caused graphics to stop working altogether, taking me back to VGA resolution and disabling additonal displays.
I tried the nvidia-driver-515, no luck. I tried Nouveau, didn't work. After about an hour I managed to fix the issue, I'll post what I did as an answer.

A: I did sudo apt remove nvidia-driver-515. Then I did sudo apt update and sudo apt upgrade. This made the kept-back messages go away. Then I did  sudo ubuntu-drivers autoinstall and I checked the additional drivers. I selected 510 and rebooted, and all is well now.
I don't know what exactly caused the issue, I may have mishandled the kept-back packages. I do know the issue started when nvidia-driver-515 started showing up on my computer.


text:
Q: Why do we need our set to be simple (connected) for a vector field to be gradient? We do know that

For a vector field $f=(f_1, f_2)\in C^1$ on simply connected set $S
 \in \mathbb{R}^n$ satisfying  $$D_1 f_2 = D_2 f_1$$ is a gradient of
  some potential function $\phi$.

, and I have also seen examples when the set is not simply connected, but only connected, the above theorem is not sufficient for $f$ to be a gradient.
However, I do not understand why do we need the set to be simply connected. In other words, when the set is only connected, what might cause a problem for sufficiency, and when it is simply connected, how does simpleness solve that problem.
Edit:
I mean I have read the proof, (from the book Multivariable Calculus by Apostle), but the author assumes a convex set instead of a simply connected set, and uses the convexity to construct a potential function while taking the line integral along the direct line segment joining the fixed point $a$ and the point $x$, but this theorem holds even when the set is only simply connected, and with Apostol's sketch of the proof, we do not need simpleness, but only path connectedness, so I do not understand why do we need simpleness in here ?
Further:
Is this condition (simply connecteness) is the "smallest" condition that this theorem holds ?

A: You can find $\phi$ by integrating along a path. However, in order for this to be well-defined, the result must not depend on the path taken. Simply put, if $S$ is simply connected then any tow different paths from $a$ to $b$ can be transformed into one another continuously, and the condition on $f$ guarantees that infinitesimal changes to the path do not change the integral.


text:
Q: what the java command's -jar option really does Does the -jar option of the java command also compile the sources before running the main method?
I believe so but i would like to have a better understanding of the internal process, from the man page you can clearly see a small workflow sequence:
-jar
             Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a  line  of
             the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. See the Jar tool reference page and
             the Jar trail of the Java Tutorial @

But it does not mention that it compiles the sources.

A:
Does the -jar option of the java command also compile the sources before running the main method?

No, absolutely not. It just specifies the jar file in which to find the manifest specifying the main class, and (usually) the class file for that class. It definitely doesn't compile anything.

A: The description you posted itself says everything
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a  line  of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. See the Jar tool reference page and the Jar trail of the Java

Jar files contain a manifest file which has a line of form Main-Class: classname. Here the class that contains the main method is given. Its important because standalone application in java begin execution at main method.
Command to run the application packaged in jar looks like :-
java -jar jar-file

jar-file is name of the jar.
Edit:- And to explicitly answer your question, NO , it does not compile the source code. The jar itself contains compiled class files. You can create jar by addin class files as
jar cvf Count.jar Count.class Sum.class

jar-command
cvf-options check details here http://docs.oracle.com/javase/tutorial/deployment/jar/build.html
Count.class Sum.class - name of class files(compiled source code) space separated to add in the jar.


text:
Q: Close pop up by clicking on body I have put javascript and css pop up in my magento application. I can close the pop up by clicking on close button on pop up, but if user clicks elsewhere(out of pop up window) on the page pop up should be closed.

A: See this question:
Use jQuery to hide a DIV when the user clicks outside of it
var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){
        mouse_is_inside=true;
    }, function(){
        mouse_is_inside=false;
    });

    $("body").mouseup(function(){
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});

So you check if the mouse is inside your popup div, and when it is not, you will close it onclick. If you provide some more code we can help you get that set up

A: maybe this helps you. I would recommend jQuery but as far as you can't use it maybe thats the solution for you.
 <script type="text/javascript">
    document.onclick=check;
    function check(e){
    var target = (e && e.target) || (event && event.srcElement);
    var obj = document.getElementById('body');
    if(target!=obj){obj.style.display='none'}
    }
  </script>

And if you have to "toggle" it maybe this helps you:
<script type="text/javascript">
  document.onclick=check;
  function check(e){
    var target = (e && e.target) || (event && event.srcElement);
    var obj = document.getElementById('mydiv');
    var obj2 = document.getElementById('sho');
    if(target!=obj&&target!=obj2){
      obj.style.display='none'
    }
    else if(target==obj2){
      obj.style.display='block'
    }
    }
    </script>


text:
Q: Ruby Binary Search Code is Not Returning Expected Results I'm trying to write a binary search method in Ruby and have found a strange situation in which my code doesn't return what I expect it to when I add two numbers together and divide them by two in the elsif statement.
When I give the method a target of 1-3 and an array of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] then the method works and I get the index of the target I want.
When I give the method a target of 4, I get an infinite loop because the middle = first + last / 2 code is returning 5 rather than the expected 3. I even tried to print a 7/2 result and I got 3, but when it's pulling in the values, it returns 5.
When I give the method a target of 7-10, it breaks and says there's an undefined method '<' for nil:NilClass on line 12 (which is the line that the elsif is on).

def binary_search(target, array)
  middle = array.length / 2
  first = 0
  last = array.length - 1

  while first < last
    if array[middle] == target
      puts "we've found the target! middle is #{middle}"
      return true
    elsif array[middle] < target
      first = middle + 1
      middle = first + last / 2
      puts "we're in the elsif and middle is #{middle}"
    else
      last = middle - 1
      middle = first + last / 2
      puts "we're in the else and middle is now #{middle}"
    end
  end
  false
end

binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

A: A prerequisite :

*

*4 + 4 / 2 will give us 6. It's the equivalent of 4 + (4 / 2 ).

*(4 + 4) / 2 will give us 4.

The two statements are not equivalent.
On the two middle computation :
middle = first + last / 2

We do not have what we expect.
You are looking to divide first AND last by two.
So you will want to have :
middle = (first + last) / 2

If you replace first + last / 2 by (first + last) / 2, your script will give us :
binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
we're in the else and middle is now 2
we're in the elsif and middle is 3
we've found the target! middle is 3
 => true


text:
Q: Restore plan cache and buffer pool after database restore? When restoring a database, is there a way to restore the plan cache so it doesn't have to be re-created during production use?
Similar question: is there a way to pro-actively restore the buffer cache during or after a database restore?,…. other than to create and run select statements on the tables previously in the buffer cache, a solution which would be time-consuming to create, and inevitably inaccurate.
This is a followup to this question:  "Does restoring database clear buffer cache and stored proc cache".  edit:  This question is a follow-up because I want to know if there is a workaround to get the plan cache and buffer pool back to their source state.

A:
When restoring a database, is there a way to restore the plan cache so it doesn't have to be re-created during production use?

No.  The caches will have to warm up based on use.  You can force plans using the Query Store for particular queries if you want, as the Query Store is part of the database, and will be present after Restore.


text:
Q: Serialize a decimal to a human readable currency format I am using json.net library to serialize an object which has a decimal value that represents a cost. When serializing, I want the json to look something like '$400,000' instead of '400000.0'.
Is there a way that I can accomplish this in an easy and efficient way? This object contains many other secondary objects and subsequent properties.
The application will be used locally and the specs say that the output should be in human readable format. Culture variance isn't of any importance in this context.

A: There's no easy way to perform this since you can't work around a fact that serializer is directly accessing your properties.
If you need a formatted JSON output I would recommend writing a helper class that wraps the class you want to expose. Unfortunately I've done this once for some XML report and really the easiest way went something like this:
class PersonXml
{
   Person _person;

   void PersonXml(Person person) { _person = person; }

   string Age { get { return _person.Age + " years"; } }
}

This is just a simple example I wrote on the fly but the principle is always the same. Even if some advanced JSON serializer offered me ways to format my output, I'd really keep this concept out of my main objects in a separate file with separate helper classes.
Again this isn't quite the solution, in my opinion it should never come to this but if it does, this is the lesser of the evils in my experience.
Also, just note that if you reference the class in your property getters there's a danger of null reference.

A: As D Stanley suggested, I changed the field type to string from decimal as data in it was only being read and not used for data manipulation.


text:
Q: Inserting Data into Many to many table Symfony I am trying to insert data into a database table using a sfWidgetFormDoctrineChoiceMany Symfony widget. For some unknown reason the data will insert if 2 values are selected from each field, but will not if 3 are selected in one field and only 1 or 2 in the other, like so :

However I get an error when I try to do this:

I am using Doctrine to generate my tables in the database. This is my schema:
#Article tables

SteerCmsArticle:
  columns:
    title:                 string(255)
    content:               string
    file:                  string(255)
    date_created:          string(255)
    active:                boolean
  relations:
    Tags:
      class:                SteerCmsArticleTags
      local:                a_id
      foreign:              a_tag_id
      refClass:             SteerCmsTaggedArticles
    Categories:
      class:                SteerCmsArticleCat
      local:                a_id
      foreign:              a_cat_id
      refClass:             SteerCmsCategorisedArticles

SteerCmsArticleCat:
  columns:
    name:             string(255)

SteerCmsArticleTags:
  columns:
    name:             string(255)

SteerCmsTaggedArticles:
  columns:
    a_id:                   integer(20)
    a_tag_id:               integer(20)
  relations:
    SteerCmsArticle:
      onDelete:               CASCADE
      local:                  a_id
      foreign:                id
    SteerCmsArticleTags:
      onDelete:               CASCADE
      local:                  a_tag_id
      foreign:                id

SteerCmsCategorisedArticles:
  columns:
    a_id:                   integer(20)
    a_cat_id:               integer(20)
  relations:
    SteerCmsArticle:
      onDelete:               CASCADE
      local:                  a_id
      foreign:                id
    SteerCmsArticleCat:
      onDelete:               CASCADE
      local:                  a_cat_id
      foreign:                id

A: I cant believe how silly I am was literally about to rebuild my model from scratch a simple spelling mistake when generating the form and validators. Make sure your validators correspond correctly with the forms triple check spelling!
'categories_list'      => new sfValidatorDoctrineChoiceMany(array('model' => 'SteerCmsArticle**Tags**', 'required' => false)),

Was ment to be...
'categories_list'      => new sfValidatorDoctrineChoiceMany(array('model' => 'SteerCmsArticle**Cats**, 'required' => false)),


text:
Q: Setting up filtering for server-side tracing I'm trying to set up a server-side trace in SQL Server 2008 R2. While I have no trouble selecting events and data columns, the filtering seems a bit odd...
I was trying to set up a filtering on both the duration of the SQL batch or stored procedure (filter anything >= 1000 ms), but I also wanted to filter on the database name involved.
When I export the trace definition from SQL Profiler to a *.sql file, I however don't seem to find any filtering on the database name:
-- lots of other stuff up here - setting up trace events and so on...

-- Set the Filters
declare @intfilter int
declare @bigintfilter bigint

exec sp_trace_setfilter @TraceID, 10, 0, 7, N'SQL Server Profiler - 100479e4-6eeb-4608-af17-64141f1631ec'
set @bigintfilter = 1000000
exec sp_trace_setfilter @TraceID, 13, 0, 4, @bigintfilter

....

So what's up with that? Why can I specify a database name to filter on - but the trace definition doesn't contain it, in the end?

*

*Does that mean the server-side trace is always only checking the database it's been creating in?

*But then why can I specify a filter by database name?

*Does this also mean there's no way to do cross-database server-wide tracing on e.g. deadlocks?

Update: after some more toying around, I came to the following conclusion:

*

*the filter on the database name was not applied to the Create Trace script in my case since I ended up selecting only the Locks / Deadlock Graph event - and that event doesn't expose a Database Name as an event column

*if I pick other events, like RPC completed that do expose the Database Name as an event column, I can filter on the Database Name and that filter is also properly added to the Create Trace script.
I can't figure out how I was able to actually define a filter on Database Name, since normally, if an event doesn't expose a column, that column is also not available in the Column filter dialog....
Anyway - for whatever reasons that are beyond me (for now, at least), Deadlock Graph doesn't expose the Database Name and thus I cannot filter on that property, either....
Thanks all that helped and provided insightful comments!

A:
Does that mean the server-side trace is always only checking the database it's been creating in?

No, the server-side trace has the scope of just that:  the server.  When I create (what I think is) the exact trace definition and export it, I get the following snippet:
-- Set the Filters
declare @intfilter int
declare @bigintfilter bigint

set @bigintfilter = 1000000
exec sp_trace_setfilter @TraceID, 13, 0, 4, @bigintfilter

exec sp_trace_setfilter @TraceID, 35, 0, 6, N'AdventureWorks'
-- Set the trace status to start
exec sp_trace_setstatus @TraceID, 1

I am using SQL Server Profiler 2008 R2 as well.  If you do not filter on the database name, then you will be capturing trace events for all of the instance databases.  As to why your export didn't seem to include that portion of the filter, I can't say for sure.  I know this goes without saying, but I'd check your trace definition within Profiler before you export to ensure the database name is in fact included as a filter (again, I know you've probably double and tripple checked this, but I had to say it).

A: I'm not sure what's going on with your Profiler because I was able to do this before. Sometimes the GUI to set up the filtering goes a bit haywire, and if you change certain things in the trace dialog box, all the filters are reset to defaults. All that said, I honestly don't remember if I used the 2008 R2 or 2012 management tools to generate my script.
In any event, here is the code to do the filtering you want:
exec sp_trace_setfilter @TraceID, 35, 0, 6, N'<database name 1>'
exec sp_trace_setfilter @TraceID, 35, 1, 6, N'<database name 2>'
exec sp_trace_setfilter @TraceID, 35, 1, 6, N'<database name 3>'

MSDN: sp_trace_setfilter


text:
Q: Changes between Mysql version 5.1 TO 5.7 I have recently migrated Mysql 5.1 to Mysql 5.7. DB Migration was successful but when the application started firing few selected queries, Mysql started taking hours to execute them for which previously execution times wherein 4-5 seconds. That's  why wanted to know changes between this two versions.
 One of the query creating issue:
select count(*) COUNT_PRODUCTS
from (select d.ID,
             d.EAN,
             d.NAME,
             d.SAP_CATEGORY_ID,
             d.SAP_VENDOR_ID,
             d.RELEASE_DATE,
             d.REMOVED_DATE,
             d.IS_DRAFT,
             d.DATA_STATE,
             d.gc,
             ATTRIBUTE_CODE AS ATTRIB_NAME,
             ATTRIBUTE_VALUE AS APP_STATUS
      from (select b.ID,
                   b.EAN,
                   b.NAME,
                   b.SAP_CATEGORY_ID,
                   b.SAP_VENDOR_ID,
                   b.RELEASE_DATE,
                   b.REMOVED_DATE,
                   b.IS_DRAFT,
                   b.DATA_STATE,
                   group_concat(pl.LIFECYCLE_VALUE) gc
            from  (select a.ID,
                          a.EAN,
                          a.NAME,
                          a.SAP_CATEGORY_ID,
                          a.SAP_VENDOR_ID,
                          a.RELEASE_DATE,
                          a.REMOVED_DATE,
                          a.IS_DRAFT,
                          a.DATA_STATE
                   from (select p.ID,
                                p.EAN,
                                p.NAME,
                                p.SAP_CATEGORY_ID,
                                p.SAP_VENDOR_ID,
                                p.RELEASE_DATE,
                                p.REMOVED_DATE,
                                p.IS_DRAFT,
                                p.DATA_STATE
                          from PRODUCTS as p
                          order by p.EAN, p.IS_DRAFT) as a
                   group by a.EAN ) as b
            left join PRODUCT_LIFECYCLE_STATES pl
               on pl.PRODUCT_ID = b.ID  group by b.ID ) as d
       left join PRODUCT_ATTRIBUTE_VALUES AS PRODAV
          ON ID=PRODAV.PRODUCT_ID
         AND PRODAV.ATTRIBUTE_VALUE_ID IN (select ID
                                           from ATTRIBUTE_VALUES
                                           where ATTRIBUTE_CODE='APPROVED_ATTRIBUTES')
       left join ATTRIBUTE_VALUES AS ATVALS
          ON PRODAV.ATTRIBUTE_VALUE_ID = ATVALS.ID
         AND ATVALS.ATTRIBUTE_CODE ='APPROVED_ATTRIBUTES'
       ORDER BY d.SAP_CATEGORY_ID, d.NAME ) f

I did one change in my.cnf file to  suppress GROUP BY error by changing FULL_GROUP_BY.
This is my first quesion , so please let me know if any further information or rectification is required.
I am not able to reply to comments. Even after removing ORDER BY clause it is taking same time of hours. Actually, this query is also used without the COUNT in some places. If I keep FULL_GROUP_BY it is ending up with an error.
After running EXPLAIN on this query I am getting the different result in the old and new server.
New Server

Old Server

A: Do a JOIN instead of AND PRODAV.ATTRIBUTE_VALUE_ID IN (select ID ...
FULL_GROUP_BY needs to be heeded.
p:   INDEX(EAN, IS_DRAFT)  -- in this order
pl:  INDEX(PRODUCT_ID)
PRODAV:  INDEX(PRODUCT_ID, ATTRIBUTE_VALUE_ID)  -- in this order (after doing the JOIN)
ATVALS:  INDEX(ID, ATTRIBUTE_CODE)  -- in either order

PRODAV.ATTRIBUTE_VALUE_ID = ATVALS.ID -- If this is a key-value store, do not normalize the key or the value; it will make for terrible performance.
As for why the performance changed between revisions, I can only guess that things like FULL_GROUP_BY messed up the optimization.  Some of my suggestions may uncork it.


text:
Q: Runtime change of AppBarLayout color How does Android Google Play app change color dynamically on user clicks on AppBarlayout?

I have tried the following
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
    @Override
    public void onTabSelected(TabLayout.Tab tab)
    {
        setTheme(R.style.AppTheme_2);
    }
}

<style name="AppTheme_2" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary_2</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark_2</item>
    <item name="colorAccent">@color/colorAccent_2</item>
</style>

A: You need to get the tab position in order to manipulate the color.
Here is the example.
 mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Log.e(TAG, String.valueOf(tab.getPosition()));

            switch (tab.getPosition()){
                case 0:
                    mAppBar.setBackgroundResource(R.color.colorPrimary);
                    break;
                case 1:
                    mAppBar.setBackgroundResource(R.color.colorPrimary);
                    break;
                case 2:
                    mAppBar.setBackgroundColor(Color.BLACK);
                    break;
            }
        }


text:
Q: Eclipse Oxygen fails to run - org.eclipse.swt.SWTException: Invalid thread access I have following problem: my eclipse Oxygen fails to run(error attached).
Everything is fine on fresh instalation, when I run it just after downloading (tested on 1a september and 2 december). However, when i restart my computer, eclipse won't start again unless i will reinstall it.
I have cleared both eclipse cache as same as my project (even fetched fresh version from repo), workspace and eclipse instalation place is also fresh.
I have read e.g. https://bugs.eclipse.org/bugs/show_bug.cgi?id=475392, https://bugs.eclipse.org/bugs/show_bug.cgi?id=514895 and other related posts, didn't help though.
Any idea? I am working on windows 10 64 bit, and JDK 9.0.1+11. My only plugin is BndTools 3.5, latest, project requires java 8 (current runtime jdk is 152).
Problem started on friday, 15 dec after running my project and resolving dependencies at example bnd project (http://enroute.osgi.org/tutorial_base/600-testing.html) at the same time. Couldn't run eclipse after that.
However, i did it before and didn't meet any problems (i mean opening example and running it). Also, I have cleared p2, mvn and bnd cache.
Below mentioned stack from eclipse .log:
!SESSION 2017-12-18 16:47:57.660 -----------------------------------------------
eclipse.buildId=4.7.2.M20171123-0800
java.version=9.0.1
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=pl_PL
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.osgi 4 0 2017-12-18 16:47:59.711
!MESSAGE Application error
!STACK 1
org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(SWT.java:4533)
    at org.eclipse.swt.SWT.error(SWT.java:4448)
    at org.eclipse.swt.SWT.error(SWT.java:4419)
    at org.eclipse.swt.widgets.Display.error(Display.java:1263)
    at org.eclipse.swt.widgets.Display.checkDevice(Display.java:767)
    at org.eclipse.swt.widgets.Display.addListener(Display.java:628)
    at org.eclipse.ui.internal.ide.application.IDEWorkbenchAdvisor.<init>(IDEWorkbenchAdvisor.java:187)
    at org.eclipse.ui.internal.ide.application.IDEWorkbenchAdvisor.<init>(IDEWorkbenchAdvisor.java:195)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:152)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)

Diff between fresh and dirty instalation

Update
After flushing whole system, problem gone for a while, however came back again, so it eliminates OS influence in my opinion.
As Struarf mentioned in his answer, deletion of configuration/org.eclipse.osgi templorary solves problem.
Nevertheless, when i have installed oxygen 2, I noticed that this problem is much more rarer than before (actually now 2nd time for 2 weeks, whether before was with each possible occasion), so maybe it comes in a good way...

A: I've just commented on bug 477247. I'm getting a similar exception (on OSX).  What allows me to start Eclipse without reinstalling is to delete the configuration/org.eclipse.osgi folder.  It looked like a bundle cache, and deleting such caches has worked elsewhere for me.  Hopefully this might also provide a clue for the devs.

A: You seem to hit bug 477247. Until now, Eclipse developers were not able to reproduce the issue, maybe you can help them by adding steps to reproduce to the bug, or any other useful details.


text:
Q: a WD external hard drive keeps connecting and reconnecting randomly please i'd appreciate an advice regarding the following issue :
i am using Ubuntu 16.04 on a DELL machine that is connected to an external WD hard drive 4TB (Wedter Digital) using a SABRENT docking station.
The external hard drive keeps connecting and reconnecting randomly, and i can not do any work ... Please would you advise how i shall fix the issue ?
is there an OS issue or a USB connection issue ? With DMESG, the message is :
 dmesg | tail -50
[ 1743.012026] sd 11:0:0:0: [sde] Mode Sense: 67 00 10 08
[ 1743.012388] sd 11:0:0:0: [sde] Write cache: enabled, read cache: enabled, supports DPO and FUA
[ 1743.036059] sd 11:0:0:0: [sde] Attached SCSI disk
[ 1743.970166] EXT4-fs (sde): recovery complete
[ 1743.970375] EXT4-fs (sde): mounted filesystem with ordered data mode. Opts: (null)
[ 1853.292280] usb 2-2: USB disconnect, device number 11
[ 1853.292510] sd 11:0:0:0: [sde] tag#0 uas_zap_pending 0 uas-tag 1 inflight: CMD
[ 1853.292518] sd 11:0:0:0: [sde] tag#0 CDB: Read(16) 88 00 00 00 00 01 7a 81 61 68 00 00 00 40 00 00
[ 1853.292527] sd 11:0:0:0: [sde] tag#1 uas_zap_pending 0 uas-tag 2 inflight: CMD
[ 1853.292533] sd 11:0:0:0: [sde] tag#1 CDB: Read(16) 88 00 00 00 00 01 7a 81 61 a8 00 00 00 80 00 00
[ 1853.292539] sd 11:0:0:0: [sde] tag#2 uas_zap_pending 0 uas-tag 3 inflight: CMD
[ 1853.292544] sd 11:0:0:0: [sde] tag#2 CDB: Write(16) 8a 00 00 00 00 01 7d 45 ff b8 00 00 00 08 00 00
[ 1853.292579] sd 11:0:0:0: [sde] tag#0 FAILED Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
[ 1853.292584] sd 11:0:0:0: [sde] tag#0 CDB: Read(16) 88 00 00 00 00 01 7a 81 61 68 00 00 00 40 00 00
[ 1853.292589] blk_update_request: I/O error, dev sde, sector 6350266728
[ 1853.292614] sd 11:0:0:0: [sde] tag#1 FAILED Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
[ 1853.292619] sd 11:0:0:0: [sde] tag#1 CDB: Read(16) 88 00 00 00 00 01 7a 81 61 a8 00 00 00 80 00 00
[ 1853.292623] blk_update_request: I/O error, dev sde, sector 6350266792
[ 1853.292635] sd 11:0:0:0: [sde] tag#2 FAILED Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
[ 1853.292640] sd 11:0:0:0: [sde] tag#2 CDB: Write(16) 8a 00 00 00 00 01 7d 45 ff b8 00 00 00 08 00 00
[ 1853.292644] blk_update_request: I/O error, dev sde, sector 6396706744
[ 1853.292704] EXT4-fs (sde): Delayed block allocation failed for inode 199884811 at logical offset 0 with max blocks 1 with error 5
[ 1853.292711] EXT4-fs (sde): This should not happen!! Data will be lost

[ 1853.292862] Aborting journal on device sde-8.
[ 1853.292875] JBD2: Error -5 detected when updating journal superblock for sde-8.
[ 1853.292918] EXT4-fs error (device sde): ext4_journal_check_start:56: Detected aborted journal
[ 1853.292926] EXT4-fs (sde): Remounting filesystem read-only
[ 1853.292931] EXT4-fs (sde): previous I/O error to superblock detected
[ 1853.292961] EXT4-fs (sde): ext4_writepages: jbd2_start: 1024 pages, ino 199884812; err -30
[ 1853.309837] EXT4-fs warning (device sde): ext4_dx_find_entry:1525: inode #194871302: lblock 1: comm pool: error -5 reading directory block
[ 1853.309931] EXT4-fs warning (device sde): ext4_dx_find_entry:1525: inode #194871302: lblock 6: comm pool: error -5 reading directory block
[ 1853.310108] sd 11:0:0:0: [sde] Synchronizing SCSI cache
[ 1853.436169] sd 11:0:0:0: [sde] Synchronize Cache(10) failed: Result: hostbyte=DID_ERROR driverbyte=DRIVER_OK
[ 1858.532374] usb 2-2: new SuperSpeed USB device number 12 using xhci_hcd
[ 1858.549351] usb 2-2: New USB device found, idVendor=152d, idProduct=1561
[ 1858.549358] usb 2-2: New USB device strings: Mfr=1, Product=2, SerialNumber=5
[ 1858.549364] usb 2-2: Product: SABRENT
[ 1858.549368] usb 2-2: Manufacturer: SABRENT
[ 1858.549372] usb 2-2: SerialNumber: DB98765432232
[ 1858.552345] scsi host12: uas
[ 1858.554204] scsi 12:0:0:0: Direct-Access     SABRENT                   0109 PQ: 0 ANSI: 6
[ 1858.555355] sd 12:0:0:0: Attached scsi generic sg2 type 0
[ 1858.555524] sd 12:0:0:0: [sde] 7814037168 512-byte logical blocks: (4.00 TB/3.64 TiB)
[ 1858.556473] sd 12:0:0:0: [sde] Write Protect is off
[ 1858.556481] sd 12:0:0:0: [sde] Mode Sense: 67 00 10 08
[ 1858.556856] sd 12:0:0:0: [sde] Write cache: enabled, read cache: enabled, supports DPO and FUA
[ 1858.583994] sd 12:0:0:0: [sde] Attached SCSI disk
[ 1859.542905] EXT4-fs (sde): recovery complete
[ 1859.543087] EXT4-fs (sde): mounted filesystem with ordered data mode. Opts: (null)

A: *

*The USB port does not supply enough power for a 4T drive. You should be using an external AC power adapter for the external drive case or SABRENT docking station, or use a POWERED USB hub.

*The drive may be having a problem reallocating bad blocks. To do a manual bad block scan...
Note: do NOT abort a bad block scan!
Note: do NOT bad block a SSD
Note: backup your important files FIRST!
Note: this will take many hours
Note: you may have a pending HDD failure
sudo e2fsck -fcky /dev/sdXX # read-only test
or
sudo e2fsck -fccky /dev/sdXX # non-destructive read/write test (recommended)
The -k is important, because it saves the previous bad block table, and adds any new bad blocks to that table. Without -k, you loose all of the prior bad block information.
The -fccky parameter...
   -f     Force checking even if the file system seems clean.

   -c     This option causes e2fsck to use badblocks(8) program  to  do  a
          read-only  scan  of  the device in order to find any bad blocks.
          If any bad blocks are found, they are added  to  the  bad  block
          inode  to  prevent them from being allocated to a file or direc‐
          tory.  If this option is specified twice,  then  the  bad  block
          scan will be done using a non-destructive read-write test.

   -k     When combined with the -c option, any existing bad blocks in the
          bad blocks list are preserved, and any new bad blocks  found  by
          running  badblocks(8)  will  be added to the existing bad blocks
          list.

   -y     Assume  an answer of `yes' to all questions; allows e2fsck to be
          used non-interactively.  This option may not be specified at the
          same time as the -n or -p options.

A: I had the same issue today with my 5TB disk. I thought that the disk is dead but it was power issue. Just unplugged from connected port (USBC through converter) and directly plugged it into traditional USB3 port and it perfectly works since then.


text:
Q: Trying to unset state-property's value not working using delete In my React-component there is a optional property. Depending om whether this is set or not, a modal dialog is shown.
Therefore, when the modal should be closed/hidden, the property should not be set.
My state (simplified):
interface IRequestNewState {
    pendingPlayer?: PlayerDataViewModel;
}

As it can be seen, the property pendingPlayer is optional inside the state.
In my submitclick-handler of the modal's inner form I want to reset the property and update the state.
This is done like so:
    ev.preventDefault();
    ev.stopPropagation();

    var theForm = ev.target as HTMLFormElement;

    if (theForm.checkValidity() === false) {
        theForm.classList.add("was-validated");
        this.setState(this.state);
        return;
    }

    const playerToAdd: PlayerResource = {};

    var formData = new FormData(theForm);
    for (let pair of formData.entries()) {
        pathval.setPathValue(playerToAdd, pair[0], pair[1]);
    }

    var newState = { ...this.state } as IRequestNewState;

    newState.theTeam.validatedTeamPlayers.push({ player: playerToAdd });
    delete newState.pendingPlayer;
    this.setState(newState);

Note: The spread-operator is used as I am changing more on the state than what is shown here (as it does not belong to the problem).
This will remove the pendingPlayer property from newState. However, when the next render is called, the property is still set.
What am I doing wrong here?
On the other hand I also tried to set newState.pendingPlayer = null; which gaves me (at least ReSharper does) the following error:

Cannot convert type 'any' to type 'PlayerDataViewModel': Type 'any' has no properties in common with type 'PlayerDataViewModel'

This still gets compiled but I don't understand the error here. And I want a solution showing me green light without hiding any warnings.
So what is the issue with the delete newState.pendingPlayer statement?

A: setStates can be batched and not necessarily run when they are called. @Rick Jolly stating that you don't need to do this.setState(this.state); could be why you're having this issue. If you're just trying to get a re-render and not making state changes (as it appears where you're using this.setState(this.state)) just use this.forceUpdate();


text:
Q: Kubernetes Endpoints IPs not in range I have a K8s cluster installed in several RHEL 7.2 VMs.
Seems that the installation form yum repository comes without addons.
Currently I am facing the following problem almost with any service I am trying to deploy: Jenkins, Kube-ui,  influxdb-grafana
Endpoints IPs are not in the range that is defined for Flannel and obviously the services are not available.
Any ideas on how to debug\resolve the problem?
System details:
# lsb_release -i -r
Distributor ID: RedHatEnterpriseServer
Release:        7.2

Packages installed:
kubernetes.x86_64               1.2.0-0.9.alpha1.gitb57e8bd.el7
etcd.x86_64                     2.2.5-1.el7
flannel.x86_64                  0.5.3-9.el7
docker.x86_64                   1.9.1-25.el7.centos

ETCD network configuration
# etcdctl get /atomic.io/network/config
{"Network":"10.0.0.0/16"}

Service gets proper IP but wrong Endpoints
# kubectl describe svc jenkinsmaster
Name:                   jenkinsmaster
Namespace:              default
Labels:                 kubernetes.io/cluster-service=true,kubernetes.io/name=JenkinsMaster
Selector:               name=jenkinsmaster
Type:                   NodePort
IP:                     10.254.113.89
Port:                   http    8080/TCP
NodePort:               http    30996/TCP
Endpoints:              172.17.0.2:8080
Port:                   slave   50000/TCP
NodePort:               slave   31412/TCP
Endpoints:              172.17.0.2:50000
Session Affinity:       None
No events.

Thank you.

A: I think the flannel network subnet and the kubernetes internal network subnet seems to be conflicting here.
With the amount of information as I see now all I can say is that there is a conflict here. To verify that flannel is working just start contianer in two different machines connected with flannel and see if they can talk and what IP address they get. If they are being assigned IP of range 10.0.0.0/16 and they can talk then flannel is doing good. And something is wrong with the integration with kubernetes.
If you are not getting the IP addresses of some other range flannel is not doing good.

A: kubernetes 1.12...docker 1.9... They are ancient version now. So you don't have CNI or kubeadm. I can barely remember how to setup a kubernetes cluster with flannel that time.
Anyway, you need to know Endpoint IP is same as target Pod IP, that is IP of docker container. So your docker container IP is not the same range as your flannel IP, and 172.17.0.x is the default docker IP range. So I think you need to change docker start parameter like --bip=${FLANNEL_SUBNET} --mtu=${FLANNEL_MTU}, you can use 10.0.0.0/16 as FLANNEL_SUBNET is you want a basic setup.


text:
Q: ARGB not working properly in Android app I am trying to apply a transparent background to my row when it is pressed in my ListView. I create the file list_selector.xml like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/argb80804040" />
</selector>

and in my news_item.xml, I define the back ground as follow:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/list_selector">

<ImageView
   android:id = "@+id/img"
   android:layout_width="95dip"
   android:layout_height="75dip"
   android:layout_alignParentLeft = "true"
   android:paddingTop="10dip"
   android:layout_marginLeft="10dip"
   android:paddingBottom="10dip"
   android:src="@drawable/no_news_image_small" />

<TextView android:id="@+id/title"
    android:layout_gravity="center_vertical"
    android:layout_width="fill_parent"
    android:layout_weight="1.0"
    android:layout_height="wrap_content"
    android:textSize="12sp"
    android:textStyle="bold"
    android:paddingTop="5dip"
    android:layout_marginLeft="110dip"
    android:textColor="#21B6EF"
    android:singleLine="true" />

<TextView android:layout_gravity="center_vertical"
    android:layout_width="fill_parent"
    android:layout_weight="1.0"
    android:layout_height="wrap_content"
    android:layout_marginLeft="110dip"
    android:textSize="10sp"
    android:id="@+id/description"
    android:layout_below="@id/title"
    android:paddingBottom="10dip"
    android:layout_marginBottom="5dip"
    android:textColor="#fff"/>

</RelativeLayout>

However, it displays as solid color instead of ARGB color. My drawable is define as follow:
<resources>
    <item type="drawable" name="transparent_orange">#64ff7b00</item>
    <item type="drawable" name="argb80804040">#80804040</item>
    <item type="drawable" name="argb40000000">#40000000</item>
    <item type="drawable" name="argb80408040">#80408040</item>
</resources>

Do I need to do something else to get aplha color working? I am trying on my own device (motorola defy), and i am also using another application that uses the same alpha color and the color appears ok in this application, but in mine, it doesnt.
Many thanks for any response
T

A: I don't really understand what do you want to achieve but my proposal will be
Define your colors in res/values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="transparent_orange">#64ff7b00</color>
  ...
</resources>

Then you can define a drawable to be used as a background like this in res/drawable/test.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <solid android:color="@color/transparent_orange" />
</shape>

Finally, you can use the resulting drawable as an attribute of the target container with
android:background="@drawable/blue_linear_gradient"


text:
Q: Testing for multiple flag values I have this flag enumeration:
public enum AssignmentType
{
    None = 0,
    Attendant = 1,
    ConductorCBS = 2,
    ReaderCBS = 4,
    Chairman = 8,
    Mike = 16,
    PlatformAttendant = 32,
    Prayer = 64,
    OCLM = 128,
    Sound = 256,
    Student = 512,
    Custom = 1024,
    Demonstration = 2048,
    Assistant = 4096
}

I am now wanting to test my variable for a certain flag condition.
I want to identify my variable is only any combination of:

*

*None

*Student

*Assistant

*Demonstration
So if it has any of the other enumeration values the variable would not satisfy the test.
At first I started with this:
bool bIsPersonnel = true;

if (_Assignments == AssignmentType.None ||
    _Assignments == AssignmentType.Demonstration ||
    _Assignments == AssignmentType.Student ||
    _Assignments == AssignmentType.Assistant ||
    _Assignments == (AssignmentType.Demonstration | AssignmentType.Student))
{
    bIsPersonnel = false;
}

But I quickly realised the multiple choices there are.
Is there a simpler way?
I can't see how to suggested answer helps. I guess it is easiest to do my test in reverse. Just test if it has any of the other flags then I know it is personnel!

A: You can apply a mask with the ~ bitwise negation operator to find all the invalid flags, and check whether any have been applied.
var valid = AssignmentType.Student | AssignmentType.Assistant | AssignmentType.Demonstration;
var invalid = ~valid; // Everything that isn't valid

if ((_Assignments & invalid) != 0)
{
    // There was at least one invalid flag, handle it appropriately
}

Or to check whether it's valid:
if ((_Assignment & invalid) == 0)
{
    // There are no invalid flags, handle it appropriately
}

Or if you're just after setting a single boolean flag, you don't need an if statement at all:
bool isPersonnel = ((assignment & invalid) != 0);

A: (Incorrect answer)
if ((_Assignments & AssignmentType.None) > 0
    || (_Assignments & AssignmentType.Student) > 0
    || (_Assignments & AssignmentType.Assistant) > 0
    || (_Assignments & AssignmentType.Demonstration) > 0
){
    bIsPersonnel = false;
}

Corrected answer:
var NonPersonnel = AssignmentType.None | AssignmentType.Student | AssignmentType.Assistant | Demonstration;
bool bIsPersonnel = (_Assignments | NonPersonnel) != NonPersonnel;

A: I think this works as expected:
var flags =
    AssignmentType.None
    | AssignmentType.Student
    | AssignmentType.Assistant
    | AssignmentType.Demonstration;

bool bIsPersonnel =
    !(_Assignments == AssignmentType.None
        || (flags & _Assignments) == _Assignments);

Here is some sample output:
_Assignments = AssignmentType.Demonstration | AssignmentType.Assistant; // False
_Assignments = AssignmentType.None; // False
_Assignments = AssignmentType.Demonstration | AssignmentType.Mike; // True

A: At the moment I have come up with doing the reverse test:
bool bIsPersonnel = false;

if(_Assignments.HasFlag(AssignmentType.Attendant | AssignmentType.ConductorCBS |
    AssignmentType.ReaderCBS | AssignmentType.Chairman |
    AssignmentType.Mike | AssignmentType.PlatformAttendant |
    AssignmentType.Prayer | AssignmentType.OCLM |
    AssignmentType.Sound | AssignmentType.Custom))
{
    bIsPersonnel = true;
}

This is easiest because we know that if any one of those flags are set the person is "Personnel". The other flags are out of the picture and we don't have to test for multiple flag configurations.

A: Just make a mask of values to check and and the mask with the value, that's how flags are checked, regardless of only the number of flags
if (0 != _Assignments &
     (AssignmentType.Demonstration | AssignmentType.Student | AssignmentType.Assistant))

No need to check AssignmentType.None because it's not a flag itself, just a reserved value that's equal to 0, used for checking that none of the flag is set. If the combination contains both "no flag" and "some other flag" then it doesn't make sense, right? If you do need to check the "no flag" condition then check it separately
if (_Assignments == AssignmentType.None || (0 != _Assignments &
         (AssignmentType.Demonstration | AssignmentType.Student | AssignmentType.Assistant)))

That's also how Enum.HasFlag() checks the flags

public static void Main()
{
   DinnerItems myOrder = DinnerItems.Appetizer | DinnerItems.Entree |
                        DinnerItems.Beverage | DinnerItems.Dessert;
   DinnerItems flagValue = DinnerItems.Entree | DinnerItems.Beverage;
   Console.WriteLine("{0} includes {1}: {2}",
                     myOrder, flagValue, myOrder.HasFlag(flagValue));
}


text:
Q: RRDtool update and modify rrd data source at timestamp I would to modify my rrd file. In particular I would modify one or more datasource data at precise timestamp.
I tried to do this with rrdtool update command but without success
Can you help me?

A: RRD is an INSERT-ONLY database ... it has no built in capabilities for modifying data after inserting ... you can use rrdtool dump to convert the rrd file to xml format, modify the data and then use rrdtool restore to recreate the rrd file.

A: RRDTool databases do not support update.  This is because they progressively summarise the data into the RRA, and so, as time moves on, no longer have the original raw data but only the summarised data.
In addition - and more importantly - RRD data are subject to Normalisation.  This converts the original time/value pair to an adjusted value on the precise time interval boundary.  In other words, if your interval is 5min, then a sample submitted for 12:01 will be adjusted proportionately into the 12:00 and 12:05 intervals.  So, you cannot store an exact time.
If you are looking to store a series of events with precise times and values, with the original data available and updateable indefinitely, then RRDTool is not an appropriate choice of database.  Lok at MySQL, Postgres, and other RDBMS.


text:
Q: While Refering to the Account field why it will give error that variable dosenot exist please help public class LeadHandler {
    public static void callme(List<Account>acc){
        for (Account a:acc){
            if(a.Type=='prospect'){//While refering Type it give an error
                                   that Varialble doesnot exist
                a.Rating='Hot';
                else {
                    a.Rating='Cold';
                }
            }
   }     }

}
    }

A: Your curly braces are unbalanced.
        if(a.Type=='prospect'){
            a.Rating='Hot';
            else {  // <---- missing close bracket before `else`
                a.Rating='Cold';
            }

This is likely to cause weird syntax and parsing errors, and the errors may not make sense. When your code is structurally broken, the parser sometimes is unable to understand elements that make sense to you.