text:
Q: How do you write HTML and JS to a page with Firefox Extension?

I can't figure out how to inject HTML and javascript onto a webpage with Firefox extensions.
This works with Chrome extension but does NOT work with Firefox. Notice I use chrome.extension.getURL which pulls in HTML and Javascript.
Here is my manifest - note I dont even use the background stuff
{
  "background": {
    "scripts": [ "js/background.js", "js/jquery.js"]
  },
  "content_scripts": [ {
      "js": [ "js/jquery.js", "js/chart-min.js", "js/chart-colors.js", "js/jquery-ui.min.js", "js/profiles/my_request.js", "js/options.js", "js/profiles/projects_builder.js", "js/profiles/board_builder.js", "js/profiles/my_api.js", "js/profiles/user_board_builder.js", "js/profiles/user_board.js","js/profiles/default_labels.js", "js/profiles/default_lists.js", "js/profiles/master_board.js", "js/profiles/projects.js",  "js/profiles/estimates.js", "js/profiles/new_todo_label.js","js/profiles/reports_dashboard.js",  "js/profiles/mutation_observer.js", "js/profiles/completion_chart.js", "js/profiles/cumulative_flow_chart.js"  ],
       "matches": [ "https://asana.com/*" ],
       "all_frames": true
    }],
  "permissions":[ "identity", "cookies", "storage", "activeTab", "https://asana.com/*"],
  "name": "Boards here",
  "short_name" : "boards",
  "version": "3.1.9.5",
  "manifest_version": 2,
  "icons"   : { "48":  "images/logo_thicker.png"},
  "description": "html for website",
  "browser_action":{
    "default_icon":"images/logo_thicker.png",
    "default_popup":"html/popup.html"
  },
  "web_accessible_resources": [ "images/*",  "html/*" ]
}

Example for default lists -- default_lists.js utilizing my_request which is just a jquery ajax wrapper
DefaultLists = (function() {
  function DefaultLists() {

     if (window.location.href.includes('#default_lists')) {
        this.show_form()
    }

   DefaultLists.prototype.show_form = function {
        my_request.ajax({
            url: chrome.extension.getURL("html/manage_default_lists.html"),
            type: 'get',
            success: function (data) {
              $('.panel.panel--project').remove()
              $('.panel.panel--perma').html(data)
            }
         });
    };
  }

  return DefaultLists;
})();
window.default_lists = new DefaultLists();

So now manage_default_lists.html looks something like

<bc-infinite-page page="1" reached-infinity="" direction="down" trigger="bottom">

            Loading...

              <input id="new_label_name" placeholder="List name" type="text" style="width:180px;font-size:15px;margin-left:42px;padding:5px;border-radius: 0.4rem;border: 1px solid #bfbfbf;" value="">
              cancel
              <input id="create_label" style="float:right;" type="submit" value="save" class="btn btn--small btn--primary primary small" data-behavior="loading_on_submit primary_submit" data-loading-text="saving…">

  </bc-infinite-page>

A: You're adding this HTML into the web page using your content script and web_accessible_resources. It's not related to the extension's CSP that forbids inline scripts in extension pages like the browser_action popup or the options page. In your case the CSP of the page applies to the stuff you add in it. The page may forbid inline scripts easily, sites often do that.
You can either rewrite the Content-Security-Policy HTTP header of the page using webRequest API or rework the code a bit, the latter being a better solution not only because it's more focused but also because the result of rewriting an HTTP header is random when several extensions are doing it in the same HTTP request.
So let's rework the code:

*

*store the scripts separately

*fetch and inject via browser.tabs.executeScript

*run the injected code when we want it

The important change of behavior is that the code will be running in the content script's context, using content script's jQuery and variables. Previously your code was running in the page context so it was using jQuery and other variables of the page.
I'm using Mozilla's browser WebExtension namespace polyfill and async/await syntax.
manifest.json:
"background": {
  "scripts": [
    "browser-polyfill.min.js",
    "background.js"
  ]
},
"content_scripts": [{
  "js": [
    "browser-polyfill.min.js",
    "content.js"
  ],
  "matches": ["........."]
}],

directory structure:

*

*html/manage_default_lists.html

*html/manage_default_lists.js

Since executeScript can only be used in an extension page, not in a content script, we'll send a message to the background script with an instruction.
content.js:
async function getResource(name) {
  const htmlUrl = browser.runtime.getURL(`html/${name}.html`);
  const [html, scriptId] = await Promise.all([
    fetch(htmlUrl).then(r => r.text()),
    browser.runtime.sendMessage({
      cmd: 'executeScript',
      path: `html/${name}.js`,
    }),
  ]);
  const js = window[scriptId];
  delete window[scriptId];
  return {html, js};
}

DefaultLists.prototype.show_form = async () => {
  const {html, js} = await getResource('manage_default_lists');
  $('.panel.panel--project').remove()
  $('.panel.panel--perma').html(html);
  js();
};

background.js:
browser.runtime.onMessage.addListener(async (message, sender) => {
  if (!message) return;
  switch (message.cmd) {
    case 'executeScript': {
      const js = await (await fetch(browser.runtime.getURL(message.path))).text();
      const id = `js.${performance.now()}${Math.random()}`;
      await browser.tabs.executeScript(sender.tab.id, {
        // 0 at the end is to prevent executeScript from additionally returning
        // the function's code as a string, which we don't need
        code: `window["${id}"] = () => { ${js} };0`,
        frameId: sender.frameId,
        matchAboutBlank: true,
        runAt: 'document_start',
      });
      return id;
    }
  }
});


text:
Q: How to generate Doctrine models/classes that extend a custom record class When I use Doctrine to generate classes from Yaml/db each Base class (which includes the table definition) extends the Doctrine_Record class.
Since my app uses a master and (multiple) slave db servers I need to be able to make the Base classes extend my custom record class to force writes to go to the master db server (as described here).
However if I change the base class manually I lose it again when I regenerate my classes from Yaml/db using Doctrine.
I need to find a way of telling Doctrine to extend my own Base class, or find a different solution to a master/slave db setup using Doctrine.
Example generated model:
abstract class My_Base_User extends Doctrine_Record
{

However I need it to be automatically generated as:
abstract class My_Base_User extends My_Record
{

I am using Doctrine 1.2.1 in a new Zend Framework 1.9.6 application if it makes any difference.

A: Typical, as soon as I ask the question I manage to find the answer. I'm recording it here in case anyone else has the same issue.
You can pass in the parameter 'baseClassName' into the generateModels* methods and Doctrine will use that as the Base record class.
Examples:
Doctrine_Core::generateModelsFromDb('models', array('master'), array('generateTableClasses' => true, 'baseClassName' => 'My_Record'));

or using Cli:
$options['generate_models_options'] = array(
'pearStyle'             => true,
'baseClassPrefix'       => 'My_',
'baseClassName'         => 'My_Record',
'classPrefix'           => '',
'classPrefixFiles'      => false,
'generateTableClasses'  => true,
);

$cli = new Doctrine_Cli($options);

A: Perfect, thanks! This is cool because I grab doctrine options from my application.ini in my Zend Framework project of a similar version (1.9.x). Now I can simply modify the ini to add the baseClassName like so:
doctrine.generate_models_options.baseClassName = "BaseRecord"

Thanks again for saving me time figuring this out on my own :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inconsistency: Achievements/Winter Bash icons are 2D but Inbox icon is 3D? Not quite the same question as this or this.

The Achievements and the Winter Bash icons are 2D and flat, so why is the Inbox icon supposed to be seen as a 3D one with perspective? It's obvious why the OPs of the above questions are confused. In 2D that icon could be an envelope, but it isn't, and instead represents a physical real-world inbox and is clearly a 3D icon.
Is there a reason behind this design decision?
UPDATE:
This should make the difference clear:

A: Generally, I am in favor of making UI/UX elements consistent when possible. In this case, however, I think the "problem" of 2-D versus 3-D elements is a bit of a red herring.
I haven't seen evidence that people are confused by the fact that the inbox icon is 3-D while the achievements graph is 2-D. Rather, the confusion is caused by the fact that the inbox tray is, at this point, a somewhat antiquated and therefore unfamiliar object. (If the only misinterpretation of the inbox tray was that people thought it was an envelope, we'd be fine, since that's another common metaphor for "inbox", but as the questions you linked to illustrate, some people can't figure it out at all and others have a wide variety of interpretations.)
Regardless of whether the issue is one of dimensions or one of a poorly chosen symbol, I actually don't think it's a pressing problem to fix. Even in those threads you linked, people clearly understand the function of the icon, even if they like to debate what the symbol actually is. Sure, we could make it prettier or a more obvious illustration, but since people know that it's their inbox, and that they go there to see replies, there isn't much of a real problem to solve.
As far as why this design decision was made...we needed an icon that was small and recognizable in black and white. Our designer decided to go with the inbox tray symbol (there was some discussion about using an envelope, but I can't recall if there was any reason other than personal preference for going with the inbox tray), and arrived at what you see on the page.


text:
Q: URL Testing Tools API - How to Get more Responses options i was trying to implement the URL Testing Tools API, to get the scores about the requested website,
everything works fine expect that i want to get as result more details, not only enum type saying : Friendly or Not
how can i get more informations as "Loading Time" or "Est. Visitor Loss"

A: I assume you are using this google API which gives you very small amount of information and details (just as its webiste version).
Google pagespeed
If you want to get more information I suggest you to use google pagespeed API with device set to "mobile".
To do this you need:
Get google pagespeed credentials to use pagespeed api
Go to google api console (need to have google account).
Create new or choose existing project (list on top of page).
When in project Dashboard tab click "Enable APIs and services".
In search type "pagespeed" and enable this API.
Now go to project Credentials tab click "Create credentials".
Type of credentials depends on how you want to use api, eg. I use it in php web app with google library, so i choose "OAuth client ID" -> Web application and use credentials in JSON format. You can choose "API key" to generate one simple key to access api.
Now you have your credentials!
Call pagespeed endpoint
cURL
Simpliest way to call this endpoint is by curl call:
@edit: change endpoint to newer version of api: v4
curl "https://www.googleapis.com/pagespeedonline/v4/runPagespeed?url={url}&strategy=mobile&key={key}"

Where {url} is website url to test, and {key} is your "Api key" from project credentials.
You will get big JSON analyse result which needs to be parsed. It contain a lot of information which investigating I will leave to yourself.
Google libraries
Other way is using google libraries - if they exist for technology you are using. You can search for them on github
PHP
For example I use google php api which allows to use pagespeed (and a lot other) api.
PHP snippet where $credentials are json credentials from google api console, and $url is examined url.
//Some initialization of google library instances.
$client = new Google_Client();
$client -> setAuthConfig( $credentials );
$pagespeedService = new Google_Service_Pagespeedonline($client);
$pagespeedApi = $pagespeedService->pagespeedapi;

//Get pagespeed results.
$results = $pagespeedApi->runpagespeed($url, ['strategy' => 'mobile', 'screenshot' => true]);

//We even got image in base64!
$image = str_replace(array('_', '-'), array('/', '+'), $results->screenshot->data);
$imgHtml = '<img src="data:image/jpeg;base64,' . $image . '"/>';

P.S.

In future I suggest you to create more specific questions with links and/or tags so other people will easily find and understand your question.


text:
Q: Guess if a time is AM or PM I'm currently in the process of writing a human date parser. By human date, I mean it should be able to interpret strings as "tomorrow at 2" and return a valid date depending on the current time.
The issue I'm facing is the automatic detection of missing AM/PM token. For example, if I receive an email that says "Lets meet tomorrow at 2", I know that 2 is likely to be, in fact, 2 PM. On the other hand, if the email said "Lets meet tomorrow at 11", 11 is more likely to be 11AM.
I guess most of the time, a simple comparison should do the trick. If the number is bigger than a certain limit n, we can suppose that the time is AM. If the number is smaller, then it is probably PM. In the sample above, 2 was more likely to be PM, and 11 was AM.
I know that a common work day is about 9AM-6PM, so numbers lower than 6 or bigger or greater than 9 are fine. We can easily guess for those. But what do I do with 7 and 8?
So the exact question I have is, where do I put this exact limit? When numbers approach 7~8, the limit becomes more ambiguous. I tried to search for previous documentation on this problem but couldn't find any. Is there any kind of convention about this? Also, in my opinion, the locale and/or timezone could influence this limit.
By the way, I'm not interested by non-definitive answers such as "In my opinion, 7 is afternoon" or "For me, 8 is morning". I'm really interested in documentation that could help me draw a definitive line.
Hope the description of the problem is understandable enough.

A: Very complicated. You won't successfully set a hard limit. Some thoughts:

*

*Take into account awake time. Most are awake anywhere from 6am to 12am. Times outside of that are unlikely.

*You'll have to use context. If the event is a meeting at 6, 6p is more likely than 6a unless the context is "breakfast", "wake-up", etc.

*You should ideally build the system to learn what is most likely by allowing users to correct the times, if wrong, and having the system analyze the conditions and context under which corrections were done.
Like I said, this is very complicated. Google calendars does a bit of this. Examine that solution for examples.
EDIT with addtional thoughts:
I'd collect a bunch of keywords, associate them with AM/PM, search in the context phrase and use them to help determine correct time of day:
PM:
afternoon, "after work/school", "from work/school", dinner, supper, evening, tonight, night, late, noon, "prime time", etc.
AM:
morning, "before work/school", "to work/school", breakfast, early, wake, midnight, etc.
For something like "lunch", you'll have to have a rule like, if time is 12 or less than 6 it's pm, else it's am.

A: In addition to Jonathan's answer (basically an extension of 2) you could create some sense of context. Try to look for phrases "before lunch", "after lunch" and narrow down likely times. You could tweak the heuristics here a bit to make it more accurate as well. I think your best bet is to make it context sensitive.
As it has been stated, natural language analysis is a tough problem to crack.


text:
Q: Can I target a specific form for commenting with jquery I have created a news system on my web page where I use while loop to echo my news on a page. With news I created a form for news where I target it by name and I want to use jquery to process the results. When I use php it works fine but I want to avoid reloading page with submitting form and immediate post comment to page.
my form looks like this:
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
    <textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
    <input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
    <input type="hidden" id="type" name="type" value="0">
    <input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'

my php code looks like this:
if (isset($_POST['comments' . $row['news_id'] . '']) === true && empty($_POST['comment']) === false) {

global $user_data;

$user_id    = $user_data['user_id'];
$connect_id = $_POST['news_id'];
$type       = $_POST['type'];
$time       = date('Y-m-d H:i:s');
$comment    = $_POST['comment'];
$comment    = sanitize($comment);

mysql_query("INSERT INTO `comments` (`user_id`, `connect_id`, `type`, `time`, `comment`) VALUES ('$user_id', '$connect_id', '$type', '$time', '$comment')");
}

If I try to do somethink like this:
$(".comment-btn").click(function(e) {
    e.preventDefault();

    var text = $('.comment-area').val();

    console.log(text);

    $('.comment-area').val('');
});

It targets only the form where is the first news and doesn't target all the forms.
Is there any way to do this differently???
Thanks for helping.

A: You could try something like the following:
$(".comment-btn").each(function(){
    $(this).click(function(e) {
        e.preventDefault();
        var commentArea = $(this).siblings(".comment-area");
        var text = commentArea.val();
        console.log(text);
        commentArea.val('');
    });
});

The problem is that while this $(".comment-btn") returns an array of all the button in the forms you mentioned, this $(".comment-btn").click(... attaches a click event handler only for the first item of the array.

$(function(){
    $(".comment-btn").each(function(){
        $(this).click(function(e){
            e.preventDefault();
            var commentArea = $(this).siblings(".comment-area");
            var text = commentArea.val();
            console.log(text);
            commentArea.val('');
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
    <textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
    <input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
    <input type="hidden" id="type" name="type" value="0">
    <input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'

<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
    <textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
    <input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
    <input type="hidden" id="type" name="type" value="0">
    <input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'

<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
    <textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
    <input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
    <input type="hidden" id="type" name="type" value="0">
    <input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'

A: You could use jQuery on function to bind "click" event to all buttons with comment-btn class. However, it'll be important to then identify which comment-area you want to refer to. If that is not done, it'll simply erase the values of all fields / textareas with class comment-area.
$(".comment-btn").on("click", function(e) {
    e.preventDefault();

    var text = $(this).parent().find('.comment-area').val();
    console.log(text);
    $(this).parent().find('.comment-area').val('');
});

Working example with the only change being that input type for buttons is changed from "submit" to "button":
https://jsfiddle.net/L87n4Ljo/
Likewise, if you'd like to submit a particular form when the button is clicked, you'll have to do so by specifically identifying that form by using parent() function.

A: Try this, here we are blocking the default form submit which i think you will need if you don't want to reload the page.

$(".comments").on("submit", function(e) {

        e.preventDefault();
        var text = $(this).find('.comment-area').val();
        console.log(text);
        $(this).find('.comment-area').val('');

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
    <textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
    <input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
    <input type="hidden" id="type" name="type" value="0">
    <input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'


text:
Q: Why would VirtualBox abort and take Ubuntu down with it I am running VirtualBox on Ubuntu 18.04 LTS had Windows 10 running in a guest machine, I had no problems with either Ubuntu or VirtualBox, I was also using Cairo dock and had no problems with that either, until today when VirtualBox crashed without warning, I could see that the guest machine which as running Windows 10 Pro 64b, was aborted and while I was trying to figure out what went wrong by looking in the VirtualBox logs, Ubuntu crashed.
When I restarted Ubuntu, the crash log reads:
-rw-r-----  1 me  whoopsie  2060878 Sep 17 17:41 _usr_bin_nautilus.1000.crash
-rw-r-----  1 root whoopsie 91135782 Sep 17 15:38 _usr_lib_virtualbox_VirtualBoxVM.0.crash

Also cairo-dock failed to load and not only did it fail to load, there is actually no trace of it on my system and when I listed all installed apps in the terminal with the following commands, there is no cairo dock in the results, so it appears to have disappeared, its as if it was never on my system I cant find any trace of it:
apt list --installed |grep cairo
dpkg --get-selections | awk '{print $1}' |grep cairo

Any ideas as to what could cause the crashes VirtualBox followed by Ubuntu and then cause an installed application to completely disappear off my Ubuntu system, apart from maybe a magician?

A: Although I never got to the bottom of these issues, I resolved them all by doing the following:

*

*cairo-dock - Reinstalled with the latest version (3.4.1-1.2)

*VirtualBox - Upgraded to Version 6.0.12 r133076 (Qt5.9.5)

*Nautilus - The Linux OS Kernel has been upgraded several times and Nautilus has not crashed since.  I went from Kernel version 4.18.0-22.23~18.04.1 through to the current kernel version:
Linux version 5.0.0-31-generic (buildd@lgw01-amd64-046) (gcc version
7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)) #33~18.04.1-Ubuntu SMP Tue Oct 1 10:20:39 UTC 2019

So I can only conclude that the problems I was having were all unrelated and merely coincidental and that each of these app versions were unstable and after upgrading them I had no more problems and the issues with Nautilus were taken care of in one or the several kernel updates and I have had no problems since :)


text:
Q: Trying to set the focus/hover Foreground color on all buttons in a XAML Win 10 UAP Been trying to find a way to set a default font color for buttons when the user hovers over them. At moment they all default to black. If I was doing this in HTML/CSS I would use a hover style, but can't seem to figure out how to do the same effect in XAML.
Any suggestions would be great.
Thanks,
Coop

A: You've got two avenues here.
You can either override the button's default style (which determines a button's hover color). You can find most XAML controls default styles on MSDN or on your computer in C:\Program Files (x86)\Windows Kits\10\DesignTime\CommonConfiguration\Neutral\UAP\10.0.<WindowsBuildNumber>.0\Generic by default. The files generic.xaml and themeresources.xaml have all the default style and theme definitions.
An easy way to generate a copy of an existing control's default style is to open your page (or whatever) up in Blend, right click on an instance of that control, and select "Edit Template" -> "Edit Copy". That'll create a copy of the style for that control. Note that if you use Blend to generate a copy of a Style for you, it'll automatically give it a name. If you want to override the style of EVERY button, you don't your Style to have a name, i.e.:
<Style TargetType="Button">
    <!--Your custom style goes here-->
</Style>

Then, the part of the style you'd be changing would be this section:
<VisualState x:Name="PointerOver">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                       Storyboard.TargetProperty="BorderBrush">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseMediumLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                       Storyboard.TargetProperty="Foreground">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
    </Storyboard>
</VisualState>

See the ObjectAnimationUsingKeyFrame with a Storyboard.TargetName of ContentPresenter, and a Storyboard.TargetProperty of Foreground? That's the part that changes the button's text color when it gets hovered over. So all you have to do is change its value from {ThemeResource SystemControlHighlightBaseHighBrush} into whatever you want it to be. Note that a Button's Foreground property expects a Brush, but hex color codes will be implicitly converted into a SolidColorBrush, so you can just use, for example, #FFFFFF as your value.
Or, you see how in the default style, the button just uses the value of {ThemeResource SystemControlHighlightBaseHighBrush} to determine the Foreground color? You can actually override that brush. Since it's a ThemeResource, you'd want to override it in a Theme Dictionary. So, in your App.xaml, you'd want to do something like this:
<ResourceDictionary.ThemeDictionaries>
    <ResourceDictionary x:Key="Light">
        <SolidColorBrush x:Key="SystemControlHighlightBaseHighBrush" Color="your light theme color here"/>
    </ResourceDictionary>
    <ResourceDictionary x:Key="Default"> <!--The dark theme is considered "default".-->
        <SolidColorBrush x:Key="SystemControlHighlightBaseHighBrush" Color="your dark theme color here"/>
    </ResourceDictionary>
    <!--And for extra bonus points....-->
    <ResourceDictionary x:Key="HighContrast">
        <SolidColorBrush x:Key="SystemControlHighlightBaseHighBrush" Color="your high contrast theme color here"/>
    </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>

Be mindful though, that lots of different styles rely on that Brush, so changing it will probably have lots of unintended side effects.
Hope that helps!


text:
Q: moving lists into other lists so i have some html like this. ive added some classes for some clarity but their names are irrelevant. on mobile i want "sub-nav" to be a child of the "mobile parent" li. ive got it to appear after the li but not within it in the DOM structure. what am i missing? ive been messing around with the js, hasnt worked.

link 1

link 2

link 3

link 1

link 2

</ul

let trigger = document.getElementById('trigger');
let nav = document.querySelector('.site-navigation');
let mobileChild = document.querySelector('.mobileChild');
let mobileParent = document.querySelector('.mobileParent');

trigger.addEventListener('click', function(){
    trigger.classList.toggle('active');
    if (trigger.classList.contains('active')) {
        nav.classList.add('active');
    } else {
        if (nav.classList.contains('active')) {
            nav.classList.remove('active');
        }
    }
});

if (window.innerWidth <  768) {
    mobileParent.appendChild(mobileChild);
}

A: You can use the media query to show and hide elements for different devices.
Please refer the below code. And also refer this post.

.mobile-child-outer{
  display:block;
}
.mobile-child{
  display:none
}
@media screen
and (device-width: 360px)
and (device-height: 640px) {
  .mobile-child-outer{
    display:none;
  }
  .mobile-child{
    display:block
  }
}

link 1

link 2

link 3

link 1

link 2

link 1

link 2

Update
If you want the JS solution try the below. But, I don't think JS is a best solution for this, as you can achieve it with CSS.
window.addEventListener("resize", addSubNav);
function addSubNav(){
  var width = document.body.clientWidth;
  if (width <  768) {
     document.querySelector('.mobileParent .mobile-child').remove();
     mobileParent.appendChild(mobileChild);
  }
}


text:
Q: how to print the latest date for every unique values of 1st column in Linux bash NY2001 May 11 2014
NY2001 May 9 2014
NY2011 Jun 12 2014
NY2019 Jun 19 2014
NY2019 Jun 21 2014

how to print the latest date for every unique values of 1st column in Linux bash.

A: You can use:
while read p q; do echo "$p "$(date -d "$q" '+%s'); done < file| awk '
   !($1 in a) || a[$1]<$2{a[$1]=$2} END{for (i in a) {
         printf "%s ", i; system("date \"+%d %b %Y\" -d @" a[i])}}'
NY2019 21 Jun 2014
NY2001 11 May 2014
NY2011 12 Jun 2014


text:
Q: Shell Script Disk Image Analysis I'm a beginner programmer and I'm try to learn how to successfully mount a disk image and analyse it but can't fine any guides online or any mention on web pages.
I've set myself the task as I'm thinking of joining a computer forensics course next year and believe these skills will give me a head start.
This is the code I've made so far but I've become stuck. I want the script to be able to extract command history data for all users, and also log successful and unsuccessful login attempts from log files such as /var/log/wtmp.
I'm not exactly looking for someone to complete the code (as that would be counterproductive) but to point me towards hints and tips, guides and tutorials to get over these early stage of programming.
#!/bin/bash
mount="/myfilesystem"

if grep -qs "$mount" /proc/mounts; then
  echo "It's mounted."
else
  echo "It's not mounted."
  mount "$mount"
  if [ $? -eq 0 ]; then
   echo "Mount success!"
  else
   echo "Something went wrong with the mount..."
  fi
fi

sudo fdisk -l | grep/bin /sbin

A: For mounting a filesystem, you need two arguments at least.

*

*The image file or block device to be mounted and

*The place where to mount it in your filesystem

So, if you want to mount some external USB drive, that e.g. shows as /dev/sda and has a single partition (sda1), you need to do the following:

*

*Find or create a directory to mount your device (easiest as root), say you created a directory /root/mountpoint

*Execute the mount command: mount /dev/sda1 /root/mountpoint
You then can step into the mounted filesystem cd /root/mountpoint and look around.
Just as a sidenote: For forensics, you should always draw an image from the device (e.g. dd if=/dev/sda1 of=/root/disk.img) to avoid destroying any evidence and then mount it through the loop driver (losetup /dev/loop1 /root/disk.img; mount /dev/loop1 /root/mountpoint).
Hope this gives you a hint to start over...


text:
Q: My VS Code cannot connect to internet, I can't download a extension So I just installed VS code on my new windows. then I try can't download the extension. I've tried changing the DNS and turning off the firewall but it's still the same. I tried downloading the extension manual and it worked.
This pict is my vscode went I open it
(

I've also tried downloading the insider version and it's the same.

A: Fix it with system installer. My Vscode now can install


text:
Q: I am facing issue to access android external storage using the new version of kivymd 1.1.1 I build kivy app which contain part for users to upload images into database using file manager kivymd 0.104.2
this is my old code :
def open_file_manager(self):
    path = "."
    if platform == 'android':
        from android.permissions import request_permissions,Permission
        request_permissions([Permission.READ_EXTERNAL_STORAGE,
        Permission.WRITE_EXTERNAL_STORAGE])
        app_folder = os.path.dirname(os.path.abspath(__file__))
        path = "/storage/emulated/0"
    self.file_manager.show(path)
    self.manager_open = True

i had no issue it was working fine
After i updated to kivmd 1.1.1 that fuction stops to open my external storage on android no errors occur,
Then i updated my function to the below code as i understand from the file manager documentation
      path = "."
        if platform == 'android':
            from android.permissions import request_permissions, Permission
            from android.storage import primary_external_storage_path,secondary_external_storage_path

            primary_ext_storage = primary_external_storage_path()
            request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE])

            path = os.path.expanduser(primary_ext_storage)

        self.file_manager.show(path)

        self.manager_open = True

and also not working i receive the permission message and i press allow but nothing happen it will not open my storage but no crash happen like that the path  is not correct
my buildozer here
requirements =  python3,kivy==2.1.0,kivymd==1.1.1,pillow,requests,android,docutils,mysql-connector-python,plyer
# (list) Permissions
android.permissions = INTERNET,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE,MANAGE_EXTERNAL_STORAGE

when i logcat i can't find errors messages i found this line
I Hicom_Monitor: mAppSwitchNotifierEx. uid: 10232, foreground app: com.google.android.permissioncontroller, foreground activity: com.android.packageinstaller.permission.ui.GrantPermissionsActivity
can any one suggest me what to do for access android external storage again


text:
Q: JButton, JLabel, JTextArea is flapping while the background color alpha value is set to less then 255 (200) I am trying to set the background of a JTextArea transparent with alpha value 200 and added to a LayerPan, which support Z index, the behind of the JTextArea is JPanel which is using for playing video, in the front is a JTextArea which is using to show some text, everything works well, but the JTextArea background is flapping. For better understanding the question please look at the image below:
Case 1: Normal

Case 2: Abnormal

In the second case, you will see that the background is not correct, it is something that I don't want. What can be the problem?

A:
I am trying to set the background of a JTextArea transparent with alpha value 200

I've never tried playing with video and transparent background before but in general Swing does not properly support transparent backgrounds. The transparency breaks the painting rules since the component is neither fully opaque or transparent.
So basically you need to make sure the background of the parent component is painted first. Then you need to paint the background of your component to get the transparency.
Check out Background With Transparency for more information and a simple class that does this painting for you.


text:
Q: Continue CSS3 Keyframes Animation on Hover / Stop Repeat on Hover I have a CSS3 animation set up and I just want to change the box-shadow color on hover. However, when I do it, the animation abruptly resets. Is there any way to continue the seamless animation on hover with no jumping? If I need to use javascript or jquery, that's fine, but I'd prefer if there was a CSS3 solution. Any help is appreciated.

table {
    max-width:1000px!important;
    padding:15px;
    word-wrap:
    break-word;
    background-color:#ffffff;
    border: 7px solid #454ce9;
    animation: glowing 5000ms infinite;
}

table:hover {
    animation: glowing2 5000ms infinite;
}

@keyframes glowing {
    0% { box-shadow: 0 0 -10px #e9458a; }
    40% { box-shadow: 0 0 20px #e9458a; }
    60% { box-shadow: 0 0 20px #e9458a;}
    100% { box-shadow: 0 0 -10px #e9458a;}
}

@-webkit-keyframes glowing {
    0% { box-shadow: 0 0 -10px #e9458a; }
    40% { box-shadow: 0 0 20px #e9458a; }
    60% { box-shadow: 0 0 20px #e9458a;}
    100% { box-shadow: 0 0 -10px #e9458a;}
}

@keyframes glowing2 {
    0% { box-shadow: 0 0 -10px #ad45e9; }
    40% { box-shadow: 0 0 20px #ad45e9; }
    60% { box-shadow: 0 0 20px #ad45e9;}
    100% { box-shadow: 0 0 -10px #ad45e9;}
}

@-webkit-keyframes glowing2 {
    0% { box-shadow: 0 0 -10px #ad45e9; }
    40% { box-shadow: 0 0 20px #ad45e9; }
    60% { box-shadow: 0 0 20px #ad45e9;}
    100% { box-shadow: 0 0 -10px #ad45e9;}
}

Hover over me

A: To do hover animations, transition is a great feature that reverse the animation when unhover.

table {
    max-width:1000px!important;
    padding:15px;
    word-wrap:
    break-word;
    background-color:#ffffff;
    border: 7px solid #454ce9;
    box-shadow: 0 0 -10px #e9458a;
    transition: box-shadow 2500ms;
}

table:hover {
    box-shadow: 0 0 20px #e9458a;
}

Hover over me

If to still use animation, use animation-play-state and animation-fill-mode: forwards to make it run when hovered and keep state when unhovered
In below sample I used their longhand properties, though they can be added to the shorthand, i.e. like this for the animation-fill-mode animation: glowing 5000ms infinite forwards;.
I would keep animation-play-state as longhand, as it won't work on IE (and, if I remember correct, on older versions of Edge).
Note, negative <blur-radius> values on box-shadow is not allowed (and I noticed it won't work on IE/Edge but it did on Chrome)

table {
    max-width:1000px!important;
    padding:15px;
    word-wrap:
    break-word;
    background-color:#ffffff;
    border: 7px solid #454ce9;
    animation: glowing 5000ms infinite;
    animation-fill-mode: forwards;          /*  persist state  */
    animation-play-state: paused;           /*  pause the animation  */
}

table:hover {
    animation-play-state: running;           /* play the animation  */
}

@keyframes glowing {
    0% { box-shadow: 0 0 0px #e9458a; }
    40% { box-shadow: 0 0 20px #e9458a; }
    60% { box-shadow: 0 0 20px #e9458a;}
    100% { box-shadow: 0 0 0px #e9458a;}
}

@-webkit-keyframes glowing {
    0% { box-shadow: 0 0 0px #e9458a; }
    40% { box-shadow: 0 0 20px #e9458a; }
    60% { box-shadow: 0 0 20px #e9458a;}
    100% { box-shadow: 0 0 0px #e9458a;}
}

Hover over me

Updated based on a comment
It is also possible to change color during the animation

table {
    max-width:1000px!important;
    padding:15px;
    word-wrap: break-word;
    background-color:#ffffff;
    border: 7px solid #454ce9;
    animation: glowing 5000ms infinite forwards;
    animation-play-state: paused;
}

table:hover {
    animation-play-state: running;
}

@keyframes glowing {
    0% { box-shadow: 0 0 0px red; }
    25% { box-shadow: 0 0 20px blue; }
    50% { box-shadow: 0 0 20px green;}
    75% { box-shadow: 0 0 20px yellow;}
    100% { box-shadow: 0 0 0px red;}
}

Hover over me

A: Sure, use this to stop it from jumping back once the animation is complete
    animation-fill-mode: forwards;

Also seems to have been answered here - CSS Keyframe Animations on Hover - Animation Resetting with Mouse Movement


text:
Q: iOS Navigation Controller Background Glitch OK, Ive looked everywhere for an answer, and I am unsure of what you may call this by a name - but I have detailed what my issue is below.
In my main.storyboard file, I have a view as a child from a navigation controller (i.e., allowing nav bar navigation) - being a MKMapView, which when you tap on a pin, it brings up the next scene.. This is all as it should be... (lets call it the "map" and the "detail" scene)
BUT!!!
When you hit the back button, the map view glitches and overlays the detail views background image over the mkmapview for about half a second. Would anyone be able to suggest what this problem is? Thanks soo much!
Due to stack overflow, I can't upload a picture just yet (reputation).. are you allowed to link externally?
Your help is very much appreciated.
EDIT: Ive uploaded a screenshot: http://tinypic.com/r/e19gtx/8

A: Try
self.view.backgroundColor = [UIColor whiteColor];

in ViewDidLoad.
Basically make sure your glitchy view has a background colour.

A: Did you use segue? Try manually pusing the "detail" view controller onto the map using
[self.navigationController pushViewController:#yourDetailViewController# animated:YES]

hope this works, i encountered this before.


text:
Q: Aggregate multiple columns into array Suppose I have a table like the following

user
score_1
score_2
score_3

1
100
80
100

1
80
null
80

2
95
90
65

I would like to aggregate the 3 scores columns into an array. The result will look like (the order does not matter)

user
scores

1
[100,80,100,80,null,80]

2
[95,90,65]

I know I can take union of (user, score1), (user, score2) and (user,score3) and then do array_agg on top of that. I am wondering if there is a more efficient way.

A: If for some reason preserving null is a must for you - you can use below trick - but note - the output is not an array and rather string
select user,
  translate(format('%t', array_agg(struct(score_1, score_2, score_3))), '()', '') scores
from your_table
group by user

or even simpler
select user,
  format('%t', array_concat_agg([score_1,score_2,score_3])) scores
from your_table
group by user

with same output for both above

A: Consider below
select user, array_agg(score) scores
from your_table
unpivot (score for col in (score_1, score_2, score_3))
group by user

if applied to sample data in your question - output is


text:
Q: Java StringBuilder: Newline after x Chars without splitting up words public class Ex7
    {
        //constructor
        public static String s = "1234567890123456789 In the output words on a line are separated by precisely one space verb+' '+,\nlines are separated by\n\nprecisely one newline (so no trailing spaces) and";
        public static int width = 20;

        public static void format(){
            StringBuilder sb = new StringBuilder();
            for(int start = 0; start < s.length(); start += width){
                int cursor = start + width - 1;
                boolean w = true;
                while(w){
                    if(cursor-1 < s.length()){
                        if((s.charAt(cursor) == ' ') || (s.charAt(cursor)== '\t')){
                            if(start + width -1 < s.length()){
                                sb.append(s.substring(start, cursor));
                                sb.append("\n");
                                w = false;
                            }
                            else{
                                sb.append("\n");
                                sb.append(s.substring(start));
                                w = false;
                            }
                        }
                        else{
                            cursor--;
                        }
                    }
                    else{
                       sb.append("\n");
                       sb.append(s.substring(start));
                       w = false;
                    }
                }
            }
            System.out.println(sb);
            }
    }

Hey guys,
my goal is, to format a given String s, so that there is a newline after every 20th character (in this case). Words may not be split up (if the 20th character is part of a word, newline has to be inserted before that word.)
my output with this example-string:
1234567890123456789
In the output words
on a line are
ted by precisely
 space verb+'
nes are separated

precisely one
ine (so no trailing

spaces) and

the wanted output by exercise:
01234567890123456789
In the output words
on a line are
separated by
precisely one space
\verb+' '+, lines
are separated by
precisely one
newline (so no
trailing spaces)
and

We may not use the Scanner class or thrid-party-libraries.
Any suggestions?
Sincerely,
FLiiX

A: for(int i=0; i<s.length(); )
{
   if(!(s.substring(i+21).equals(" ")))
   {
      int j = i+21;
      do
      {
         j--;
      }while(!(s.substring(j).equals(" ")));
      System.out.print(s.substring(i, j) + "\n");
      i += i - j;
   }else{
      System.out.print(s.substring(i, i+20) + "\n");
      i += 20;
   }
}

I haven't tested this yet but I believe it would serve your purposes.

A: What you are looking for is something like this.
public String splitString(String s, int maxWidth) {
    StringBuilder sb = new StringBuilder(s);
    int i = 0;
    while ((i = sb.indexOf(" ", i + maxWidth)) != -1) {
        sb.replace(i, i + 1, "\n");
    }
    return sb.toString();
}


text:
Q: Android RecyclerView - How to get items selected in Fragment class which calls CustomAdapter. I know how to use get(getAbsoluteAdapterPosition() Below recycler view  code is working fine and I can Toast message what recycler view position was selected in RecycleAdapter class. But I want to know how can I get what recycler position selected in HomeFragment class?. I tried to get position by setting onclick listener to Imageview and Textview but gives error as reference to Null. Basically I want to use get(getAbsoluteAdapterPosition() in HomeFragment class to know what item selected and navigate to another Fragment. get(getAbsoluteAdapterPosition() is working as expected inside RecycleAdapter.class
binding.recyclerview.setOnClickListener is not working in HomeFragment.class. no error but no when I click on recycler views this is not shooted.
txt.setOnClickListener is giving error as null refernce which makes sense. because this is inflated in Adapter class but trying to refer in HomeFragement class. So how can I get what selected in homefragment.class. Thanks in advance
HomeFragment.class
'''
public class HomeFragment extends Fragment {
    HomeFragmentBinding binding;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.id.home_fragment, container, false);
        return v;
    }

    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        %% some code here %%
        recycleAdapter = new RecycleAdapter(list);

        binding.recyclerview.setAdapter(recycleAdapter);

        TextView txt = (TextView) binding.getRoot().findViewById(R.id.recycler_text);
        txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "Clicked on Image", Toast.LENGTH_SHORT).show();
            }
        });

        binding.recyclerview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "RecyclerView clicked", Toast.LENGTH_SHORT).show();
                Log.d("RecyclerViewclicked", " --- ");
            }
        });

'''

RecycleAdapter.class
'''
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder>{
    RecyclerRowItemsBinding binding;
    List<IconsModel> iconsList;
    public RecycleAdapter(List<IconsModel> iconslist) {
        this.iconsList = iconslist;
    }
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflator = LayoutInflater.from(parent.getContext());
    View v = inflator.inflate(R.layout.recycler_row_items, parent, false);
    MyViewHolder myviewholder = new MyViewHolder(v);
    return myviewholder;
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    IconsModel iconModel = iconsList.get(position);
    holder.imageView.setImageResource(iconModel.getImageid());
    holder.recyclertext.setText(iconModel.getIconName());
}

@Override
public int getItemCount() {
    //return 20;
    return iconsList.size();
}

class MyViewHolder extends RecyclerView.ViewHolder{
    ImageView imageView;
    TextView recyclertext;
    public MyViewHolder(@NonNull View itemView) {
        super(itemView);

        imageView = itemView.findViewById(R.id.recycler_image);
        recyclertext = itemView.findViewById(R.id.recycler_text);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IconsModel iconModel = iconsList.get(getAbsoluteAdapterPosition());
                Toast.makeText(***itemView.getContext(), "Clicked on "+iconModel.getIconName()***, Toast.LENGTH_SHORT).show();

            }
        });

    }
}

;

}
'''
home_fragment.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"/>
</androidx.constraintlayout.widget.ConstraintLayout>

'''
recycler_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    android:orientation="horizontal"
    app:cardCornerRadius="5dp"
    app:cardElevation="5dp"
    app:cardBackgroundColor="@color/home_bg_cardview">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/selectableItemBackground"
        android:backgroundTint="@color/home_bg_cardview"
        android:weightSum="2">

        <ImageView
            android:id="@+id/recycler_image"
            android:layout_width="0dp"
            android:layout_height="120dp"
            android:layout_weight="0.5"
            app:srcCompat="?android:attr/actionModeWebSearchDrawable"
            tools:ignore="ContentDescription" />

        <TextView
            android:id="@+id/recycler_text"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginBottom="29dp"
            android:layout_weight="1.5"
            android:gravity="center"
            android:text="Browse Items"
            android:textAlignment="center"
            android:textSize="24sp" />

    </LinearLayout>
</androidx.cardview.widget.CardView>

A: If you want to get the click event of recyclerview item in HomeFragment ,
Interface It's a good choice
//RecycleAdapter

private RecyclerViewListener  recyclerViewListener

public void setRecyclerViewListener(RecyclerViewListener  recyclerViewListener){
this.RecyclerViewListener  recyclerViewListener ;
}

public Interface RecyclerViewListener{
void onClick(View  view);
}

class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView recyclertext;
public MyViewHolder(@NonNull View itemView) {
    super(itemView);

    recyclertext = itemView.findViewById(R.id.recycler_text);

    recyclertext .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          if(recyclerViewListener  !=null)recyclerViewListener.onClick(v)

        }
    });

}

//HomeFragment

recycleAdapter.setRecyclerViewListener(new RecyclerViewListener{
@Override
        public void onClick(View v) {
        //todo

        }
})

A: Create Interface Class in your Project
public interface ItemClick {
public void onClick(IconsModel IconsModel,int pos);
}

Interface class call your recyclerAdapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {

Context context;
List<IconsModel> iconsList;
ItemClick click;

public TokensListAdapter(Context context, List<IconsModel> iconsList, ItemClick click) {
    this.context = context;
    this.tokensModelList = tokensModelList;
    this.click = click;
}

@NonNull
@Override
public TokensListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater =  LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.R.layout.recycler_row_items,parent,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull TokensListAdapter.ViewHolder holder, int position) {

    IconsModel iconModel = iconsList.get(position);
    holder.imageView.setImageResource(iconModel.getImageid());
    holder.recyclertext.setText(iconModel.getIconName());

    holder.itemView.setOnClickListener(v -> {
        click.onClick(iconModel,position);
    });
}

@Override
public int getItemCount() {
    return iconsList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView recyclertext;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.recycler_image);
        recyclertext = itemView.findViewById(R.id.recycler_text);
    }
  }
}

Interface Class implement Your Fragment
public class HomeFragment  extends Fragment implements ItemClick {

//adapter assign
recycleAdapter = new RecycleAdapter(getContext,list,this);

override method import your fragment
@Override
public void onClick(ItemCLick click, int pos) {
 Toast.makeText(getContext(), "Clicked" + pos, Toast.LENGTH_SHORT).show();
}


text:
Q: How to find prev and next id record from table How to know prev id value and next id value  from a table where id is given ?
like ia have id=5 for a recod in table then i want to know the prev id value and next id value

A: If id is an auto-increment INT field,
SELECT * FROM tablename WHERE id < 5 ORDER by ID DESC LIMIT 0,1;

SELECT * FROM tablename WHERE id > 5 ORDER by ID ASC LIMIT 0,1;

should do the job.

A: Perhaps something like...
SELECT MAX(id) AS previous
    FROM my_table
    WHERE id < 5;

and
SELECT MIN(id) AS next
    FROM my_table
    WHERE id > 5;

would get what you want.

A: SELECT * FROM table WHERE id = ( SELECT min(id) FROM table WHERE id > id )
SELECT * FROM table WHERE id = ( SELECT max(id) FROM table WHERE id < id )


text:
Q: Asp.net skin file Dynamically change classes I need to change all classes dynamically in asp.net (visual basic) based on some condition. Using a skin file seems logical, but I am not sure how to assign it. Just to clarify, I need something like below(pseudo code):
if(button.clicked)
change class="makeRed makeBold"
to
class="makeBlue makeBold"

Thanks in advance!

A: All ASP.NET controls have a .CssClass property.  You should be able to set the CssClass property to "makeRed makeBold".

A: My understanding is you want to change theme at runtime which is a little bit tricky.
One solution can be:

*

*Create one session variable which will hold current theme value

*On button click event assign value to session variable.

*During Page_preInit Event assign this variable value to Page.Theme property.

*Stop page loading and reload same page again using server.transfer method
protected void Page_PreInit(object sender, EventArgs e)
{
    string thm;
    thm = (string)Session["MyTheme"];
    if (thm != null)
    {
       Page.Theme = thm;
    }
    else
    {
       Session["MyTheme"] = "makeRed";
       Page.Theme = "makeRed";
    }
}

protected void btnCalculate_Click(object sender, EventArgs e)
{
    Session["MyTheme"] = "makeBlue";
    Server.Transfer(Request.FilePath);
}

Please check this link (although it is written in c#).


text:
Q: Data Annotations in MC2 - Issue with base class validation I have an Entity Framework 4 model first layer, where I have a Product base class and then different classes that derive from the class. For each type of Product there is a Partial Class, and then each of the partial classes uses a buddy class for Data Annotations.
[MetadataType(typeof(Product_Validation))]
public partial class Product : EntityObject
{
    private List<RuleViolation> ruleViolations = new List<RuleViolation>();
}

and then
public  class Product_Validation
{

    [DisplayName("Model Name")]
    public string ModelName { get; set; }

    [Required(ErrorMessage = "A description is required")]
    [StringLength(2, ErrorMessage = "must be 2 or more")]
    public string Description { get; set; }
}

The issue I have run into is that the base class validation (for product) is not happening server side in my ASP.NET MVC2 application. I have not tried client side yet.
The classes that are derived from Product, such as CD, do have the validation working. I know the wiring of the buddy class is working for the base product class because the Display Names I am using are being utilized. When I do my binding for the model I am using the derived class (CD).
Any ideas?
I looked at this SO Post but it did not seem to get me going.
Thanks!

A: Are you model binding the base or derived class?
If I remember correctly from some experimentation months ago you need to bind as a Product.  You cannot use CD's in your action methods or UpdateModel calls.
You may have to do two sets of model binding to make this work right.  Once for Product validation and another for CD.


text:
Q: Moved repository. Do I use SVN switch, SVN relocate or something else all together I've been planning a migration of a Subversion repository from a Linux server to a Windows server. I've outlined the steps to the migration as such:

*

*Create a dump of the repository

*Transfer the dump file to the destination Windows server

*Upload the repository in the new subversion server

*Change all references to old repository to new repository

After some frustration I finally reached step 4 but have come to a dilemma...I'm not sure how to change all the references. I've seen that relocate can be used but I've also heard that switch should be used if the structure changes...this is project for work so I NEED to make sure the proper command is used on the last step to avoid fallout.
The current file structure looks like so:
svn://svn@servername/Source/Program Name/bin/Release
The new file structure is dictated by VisualSVN Server and looks like so:
https://ServerName.domain.local/svn/RepositoryName/Source/Program Name/bin/Release
Will relocate work for this or am I going in the wrong direction?

A: Previous answerers don't read docs
>svn help switch

  2. The '--relocate' option is deprecated. This syntax is equivalent to
     'svn relocate FROM-PREFIX TO-PREFIX [PATH]'.

You must

*

*to use svn relocate (because you rewrite more than prefix)

*Use second form of relocate syntax relocate TO-URL [PATH], see also example in svn help relocate

  2. TO-URL is the (complete) new repository URL to use for PATH.

Examples:

  ...

  svn relocate http://www.example.com/repo/project \

               svn://svn.example.com/repo/project

in example old references svn://svn.example.com/repo/project are replaced by http://www.example.com/repo/project

A: Yes, svn switch --relocate command should work. But please note that you have to relocate root of your working copy.

A: The most simplified answer is this:
You use relocate, when you have moved the same data directory to a new server (new base URI).
You use switch, when you want to change between branches (paths with common ancestry) within the same repository.
In both cases repository UUID stays the same.
If you dump complete repository and recover it into a new data directory, you are essentially using the same data directory, repository UUID stays the same. You may use relocate.
If you change UUID or recover into an existing repository, your only choice is to checkout the working copy anew.

A: Use svn switch --relocate I just did it on a repo and it works likes magic. If you are using TortoiseSVN, use the "Relocate" command, not the "Switch" command.


text:
Q: An adjunction between two preorders Let $\mathcal{C}$ and $\mathcal{D}$ be two preorders, $L: \mathcal{C} \to \mathcal{D}$, $R: \mathcal{D} \to \mathcal{C}$ a pair of functors such that for all objects $c \in \mathcal{C}$ and $d \in \mathcal{D}$ there are bijections
$$
\theta_{c,d}: \text{Hom}_{\mathcal{D}}(Lc,d) \to \text{Hom}_{\mathcal{C}}(c,Rd).
$$
Prove that the bijections are natural in $c$ and $d$ and hence $L$ and $R$ form an adjunction.
Hint: Suppose $\mathcal{A}$ is a category, $F,G: \mathcal{A} \to \mathbf{Set}$ is a pair of functors taking values in the full subcategory $\mathcal{B} \subset \mathbf{Set}$ whose objects are sets with one element and the empty set. Note that $\mathcal{B}$ is a preorder. Then show that any family of bijiections $\{\tau_a: F(a) \to G(a)\}_{a \in \mathcal{A}}$ form a natural isomorphism.

I'm very confused about the hint, so I don't even know where to start. The way I was taught to show the above bijections are natural in $c$ and $d$ is to show two corresponding diagrams commute:
$$\require{AMScd}
\begin{CD}
\text{Hom}_{\mathcal{D}}(Lc,d) @>{\theta_{c,d}}>> \text{Hom}_{\mathcal{C}}(c,Rd)\\
@V{(Lf)^*}VV @V{f^*}VV \\
\text{Hom}_{\mathcal{D}}(Lc^\prime,d) @>{\theta_{c^\prime,d}}>> \text{Hom}_{\mathcal{C}}(c^\prime,Rd)
\end{CD}$$
and
$$\require{AMScd}
\begin{CD}
\text{Hom}_{\mathcal{D}}(Lc,d) @>{\theta_{c,d}}>> \text{Hom}_{\mathcal{C}}(c,Rd)\\
@V{g_*}VV @V{(Rg)_*}VV \\
\text{Hom}_{\mathcal{D}}(Lc,d^\prime) @>{\theta_{c,d^\prime}}>> \text{Hom}_{\mathcal{C}}(c,Rd^\prime)
\end{CD}$$
for any $f:c' \to c$ in $\mathcal{C}$ and $g:d \to d'$ in $\mathcal{D}$.
Here why do we need to consider two arbitrary functors $F$ and $G$ and show that there is a natural isomorphism between them? How can we use this result to prove the existence of an adjunction?

A: The hint states a more general fact.
Once you prove the hint, the exercise follows easily: The formulas
$$\forall c \in \mathcal C,\, \forall d \in \mathcal D : \quad
\begin{split}
F(c,d) = \operatorname{Hom}_{\mathcal{D}}(Lc,d) \\
G(c,d) = \operatorname{Hom}_{\mathcal{C}}(c,Rd)
\end{split}$$
define a pair functors $F,G \colon \mathcal C \times \mathcal D^{\rm op} \to \mathsf{Set}$ that take values in $\mathcal B$ (because $\mathcal C$ and $\mathcal D$ are preorders), so that the family $$\{\theta_{c,d} \colon F(c,d) \to G(c,d)\}_{(c,d) \in \mathcal C \times \mathcal D^{\rm op}}$$ are the components of a natural isomorphism.


text:
Q: MongoDB secondary replica permanently in not reachable/healthy state I have a standard 3 node MongoDB replica set:

*

*10.0.2.35 - Primary

*10.0.3.169 - Secondary

*10.0.1.48 - Secondary

I'm currently not able to connect to them as a replica set, I can only connect through the primary. If I run rs.status() on the primary, I repeatedly get:
{
        "set" : "ecReplica",
        "date" : ISODate("2018-04-23T19:12:10.014Z"),
        "myState" : 1,
        "term" : NumberLong(-1),
        "heartbeatIntervalMillis" : NumberLong(2000),
        "members" : [
                {
                        "_id" : 0,
                        "name" : "ip-10-0-3-169:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 10717677,
                        "optime" : Timestamp(1524510722, 15),
                        "optimeDate" : ISODate("2018-04-23T19:12:02Z"),
                        "lastHeartbeat" : ISODate("2018-04-23T19:12:08.186Z"),
                        "lastHeartbeatRecv" : ISODate("2018-04-23T19:12:09.656Z"),
                        "pingMs" : NumberLong(1),
                        "syncingTo" : "ip-10-0-2-35:27017",
                        "configVersion" : 405240
                },
                {
                        "_id" : 1,
                        "name" : "ip-10-0-1-48:27017",
                        "health" : 0,
                        "state" : 6,
                        "stateStr" : "(not reachable/healthy)",
                        "uptime" : 0,
                        "optime" : Timestamp(0, 0),
                        "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2018-04-23T19:12:09.116Z"),
                        "lastHeartbeatRecv" : ISODate("2018-04-23T19:12:08.404Z"),
                        "pingMs" : NumberLong(0),
                        "authenticated" : false,
                        "configVersion" : -1
                },
                {
                        "_id" : 2,
                        "name" : "ip-10-0-2-35:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 10717680,
                        "optime" : Timestamp(1524510722, 15),
                        "optimeDate" : ISODate("2018-04-23T19:12:02Z"),
                        "electionTime" : Timestamp(1524486537, 1),
                        "electionDate" : ISODate("2018-04-23T12:28:57Z"),
                        "configVersion" : 405240,
                        "self" : true
                }
        ],
        "ok" : 1
}

When I ssh into the primary, I see the following error in /var/log/mongodb/mongod.log:

2018-04-23T19:23:54.326+0000 I REPL     [ReplicationExecutor] Error in heartbeat request to ip-10-0-1-48:27017; Unauthorized not authorized on admin to execute command { replSetHeartbeat: "ecReplica", pv: 1, v: 405240, from: "ip-10-0-2-35:27017", fromId: 2, checkEmpty: false }

Additional info
Connectivity
I can connect to all 3 nodes individually using Mongo Shell and Robo3T using SSH tunneling, but I can't connect to the 3 as a replica set.
Production servers apparently connects successfully to the replica set.
telnet
telnet 10.0.1.48 27017 from 10.0.2.35 works.
/etc/mongod.conf
The config files are almost exactly equal, the only difference is in the net section:
Node 10.0.1.48:
# network interfaces
net:
  port: 27017
  bindIp: [127.0.0.1,10.0.3.169,10.0.2.35]

Node 10.0.3.169:
# network interfaces
net:
  port: 27017
  bindIp: [10.0.1.48,10.0.2.35,127.0.0.1]

Node 10.0.2.35:
# network interfaces
net:
  port: 27017
  bindIp: [127.0.0.1,10.0.3.169,10.0.1.48]

NOTICE: the security section is empty, so this is not a key-file issue.
db.version()
3.2.0

Infrastructure
All nodes are running in the same AWS VPC, while they're in different Availability Zones, they belong to the same Security Group and use the same Network ACLs and Route Tables.

This is an inherited setup, it has been live for more than 2 years.
What am I missing?

A: It seems that your settings is still auth disabled in ReplicaSet.
To enable it, simply add a security.keyFile in settings or use --keyFile in command line option.
Here is an example showing how to generate such file:
openssl rand -base64 756 > <path-to-keyfile>
chmod 400 <path-to-keyfile>

then add to mongod.conf the path of the genreated keyfile:
security:
   authorization: enabled
   keyFile: /path/to/keyfile

restart the mongod service, right now your mongo should be auth enabled.
for more information about keyFile, refer to  Enforce Keyfile Access Control in a Replica Set

A: I was able to find the root of the problem thanks to the inputs from @Stennie.
I've changed the replica set configuration to use the actual IP addresses instead of the AWS internal DNS.
Also, I fixed the bindIp option for the hosts:
# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: [127.0.0.1,**INSTANCE PRIVATE IP**]

#processManagement:

#security:
#  authorization: enabled

#operationProfiling:

replication:
  replSetName: ecReplica
#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

Still, running rs.status() gave me:
{
    "set" : "ecReplica",
    "date" : ISODate("2018-04-25T16:03:27.277Z"),
    "myState" : 1,
    "term" : NumberLong(-1),
    "heartbeatIntervalMillis" : NumberLong(2000),
    "members" : [
        {
            "_id" : 0,
            "name" : "10.0.3.169:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 6153,
            "optime" : Timestamp(1524671340, 1),
            "optimeDate" : ISODate("2018-04-25T15:49:00Z"),
            "electionTime" : Timestamp(1524672170, 1),
            "electionDate" : ISODate("2018-04-25T16:02:50Z"),
            "configVersion" : 405245,
            "self" : true
        },
        {
            "_id" : 1,
            "name" : "10.0.1.48:27017",
            "health" : 0,
            "state" : 6,
            "stateStr" : "(not reachable/healthy)",
            "uptime" : 0,
            "optime" : Timestamp(0, 0),
            "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
            "lastHeartbeat" : ISODate("2018-04-25T16:03:26.532Z"),
            "lastHeartbeatRecv" : ISODate("2018-04-25T16:03:25.651Z"),
            "pingMs" : NumberLong(0),
            "authenticated" : false,
            "configVersion" : -1
        },
        {
            "_id" : 2,
            "name" : "10.0.2.35:27017",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 5916,
            "optime" : Timestamp(1524671340, 1),
            "optimeDate" : ISODate("2018-04-25T15:49:00Z"),
            "lastHeartbeat" : ISODate("2018-04-25T16:03:26.531Z"),
            "lastHeartbeatRecv" : ISODate("2018-04-25T16:03:25.760Z"),
            "pingMs" : NumberLong(1),
            "lastHeartbeatMessage" : "could not find member to sync from",
            "configVersion" : 405245
        }
    ],
    "ok" : 1
}

Also, I noticed that the following line was uncommented in /etc/mongod.conf at 10.0.1.48:
security:
  authorization: enabled

In the other 2 config files, such line was commented.
When I commented out the authorization line and restarted the service, the rogue node could finally sync'ing:
{
    "set" : "ecReplica",
    "date" : ISODate("2018-04-25T16:14:18.489Z"),
    "myState" : 1,
    "term" : NumberLong(-1),
    "heartbeatIntervalMillis" : NumberLong(2000),
    "members" : [
        {
            "_id" : 0,
            "name" : "10.0.3.169:27017",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 70,
            "optime" : Timestamp(1524672835, 2),
            "optimeDate" : ISODate("2018-04-25T16:13:55Z"),
            "lastHeartbeat" : ISODate("2018-04-25T16:14:18.248Z"),
            "lastHeartbeatRecv" : ISODate("2018-04-25T16:14:16.605Z"),
            "pingMs" : NumberLong(1),
            "lastHeartbeatMessage" : "syncing from: 10.0.2.35:27017",
            "syncingTo" : "10.0.2.35:27017",
            "configVersion" : 405245
        },
        {
            "_id" : 1,
            "name" : "10.0.1.48:27017",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 186,
            "optime" : Timestamp(1524672835, 2),
            "optimeDate" : ISODate("2018-04-25T16:13:55Z"),
            "lastHeartbeat" : ISODate("2018-04-25T16:14:18.313Z"),
            "lastHeartbeatRecv" : ISODate("2018-04-25T16:14:17.533Z"),
            "pingMs" : NumberLong(3),
            "lastHeartbeatMessage" : "syncing from: 10.0.3.169:27017",
            "syncingTo" : "10.0.3.169:27017",
            "configVersion" : 405245
        },
        {
            "_id" : 2,
            "name" : "10.0.2.35:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 186,
            "optime" : Timestamp(1524672835, 2),
            "optimeDate" : ISODate("2018-04-25T16:13:55Z"),
            "infoMessage" : "could not find member to sync from",
            "electionTime" : Timestamp(1524672748, 1),
            "electionDate" : ISODate("2018-04-25T16:12:28Z"),
            "configVersion" : 405245,
            "self" : true
        }
    ],
    "ok" : 1
}


text:
Q: InvalidSelectorException: invalid selector: Compound class names not permitted I try to click on the select menu and to choose the element:

        Currency:
        UAH ₴

            

                EUR €

                UAH ₴

                USD $

        <select class="link hidden-md-up">
            <option value="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=2">EUR €</option>
            <option value="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=1" selected="selected">UAH ₴</option>
            <option value="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=3">USD $</option>
        </select>

My way:
WebElement element1 = driver.findElement(By.className("link hidden-md-up"));
Select dropList = new Select(element1);
//    debug sysout
dropList.getOptions().forEach(p -> System.out.println(p.getText()));

In result I get this exception:

org.openqa.selenium.InvalidSelectorException: invalid selector:
  Compound class names not permitted

How to correctly click on an element, using selenium?

A: The exception is due to the multiple classes used in the selector. Change your selector to use single class or a cssSelector. See example below.
Check if these selectors return unique(required) element.
WebElement element1 = driver.findElement(By.className("hidden-md-up"));

OR
WebElement element1 = driver.findElement(By.cssSelector(".link.hidden-md-up"));

A: It will not work with select class because, its not pure drop-down, its un-ordered lists of currencies
you need to open drop down by clicking on it, do something like this
driver.driver.findElement(By.xpath(".//div[@class='currency-selector dropdown js-dropdown']/a[@data-toggle='dropdown']")).click();

with this drop down list will open, now get individual element from list using xpath-
.//a[@title='USD']   or  .//a[@title='USD']/parent::li


text:
Q: Classifying dataset with few positive results, how to handle false positive paradox? I'm working on a classification task with data that have only 2% of positive results and it's hard to get high true positive result with low false positive. Maybe you know how to handle such data, or any tips and tricks?
I tried Boosted Tree Forest, Logistic Regression, Random Forest and some others.


text:
Q: Python readability regex Python is about reading the code and understands what is happening. That is what I like about Python. Regex is in general hard to read. codinghorror explains this very well, and also made a suggestion to split up the regular expression in multiple line for readability.
Code
F.e I have the working regex :
vms_list = re.findall(r'"[^"]*"', vms)

I would like to do something like :
vms_list = re.findall(r'
    "     # find token "
    [^"]  # find any char which is no " token
    *     # repeat this until
    "     # token " is found again
    ', vms)

Solution  :
  vms_list = re.findall(r"""   # start
                        ["]     # find token double quote, surround with square brackets
                        [^"]    # find token which is not token double quote
                        *       # repeat this until
                        ["]     # # until token double quote is found again
                        """, vms, re.VERBOSE)  # close

Research
I have searched for multiline regex, with many response, but not about the readability of regex.
Composed Regular Expressions - breaking a regex down into a readable form from 2009 came close but without a solution.
IgnorePatternWhitespace is advised to used like in codehorror blog. But I can not find it, or something similar, for Python.
Readability
This would really improve the readability of my Python regex.
Is something like this possible in Python?


text:
Q: Multilanguage site name Is this possible without modifying the source code ?
If not, what is a recommended way to do it. One solution would be to implement it inside the site custom theme to dynamically display several hardcoded strings  depending on user locale. In that case how can I get current locale in the velocity template ?

A: It does not seem to be possible to achieve without code change.
You can use theme-settings in your custom theme to store several site name strings which you can display to user based on locale.
In velocity template, you can get user and current locale by code below.
$user.getLanguageId()
$theme_display.getLanguageId()

HTH


text:
Q: SpriteKit sometimes fails to load SKTexture I am currently having a weird intermittent issue with SpriteKit and SKTexture preloading. I have multiple arrays of images which I preload in the following format:
- (NSDictionary *)loadTexturesWithNames:(NSArray *)aNames
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSMutableArray *textureArray = [NSMutableArray array];

    for (NSString *textureName in aNames)
    {
        SKTexture *texture = [SKTexture textureWithImageNamed:textureName];
        if (texture)
        {
            [textureArray addObject:texture];
            [dict setObject:texture forKey:textureName];
        }
    }

    [SKTexture preloadTextures:textureArray withCompletionHandler:^{
        _iCounter++;
        [self loadTextures];
    }];

    return dict;
}

This works fine 90% of the time but occasionally I get the following error:

SKTexture: Error loading image resource:

This doesn't happen on any particular set of images, just randomly. So sometimes the player will load fine, and others it won't. Could this be a memory issue? I split the texture loading up using an _iCounter which makes sure the previous set of images loads before it starts the next to try and stop too much concurrent loading. This sped up the process but I still see this intermittent issue.
Has anyone else seen this, or have any idea what could cause this?

A: A common cause in my experience is when you don't wait for the completion handler to be called. For instance doing something like this where "image" is one of the images being preloaded would be possible source of error:
[self loadTexturesWithNames:names];
SKSpriteNode* sprite = [SKSpriteNode spriteNodeWithImageNamed:@"image"];

Of course if you create sprite nodes and texture only in the loadTexture method it should be fine. Unless you perform other background tasks or you run the loadTextureWithNames selector in the background (separate thread).


text:
Q: Why is the table view not coming? I am new to Oracle. The Oracle live SQL shorthand gave ready-made code on the departments and employees model.
I don't understand why the code is not viewing any table although I wrote a select statement. I don't understand the execution protocol.
link
create table departments (

    name                           varchar2(255) not null,
    location                       varchar2(4000),
    country                        varchar2(4000)
)
;

create table employees (
    department_id                  number
                                   constraint employees_department_id_fk
                                   references departments on delete cascade,
    name                           varchar2(50) not null,
    email                          varchar2(255),
    cost_center                    number,
    date_hired                     date,
    job                            varchar2(255)
)
;

insert into departments (
    name,
    location,
    country
) values (
    'Security',
    'Tanquecitos',
    'United States'
);

insert into departments (
    name,
    location,
    country
) values (
    'Travel',
    'Sugarloaf',
    'United States'
);

insert into departments (
    name,
    location,
    country
) values (
    'Office of the CEO',
    'Dale City',
    'United States'
);

insert into departments (
    name,
    location,
    country
) values (
    'Security',
    'Grosvenor',
    'United States'
);

commit;
-- load data

insert into employees (
    department_id,
    name,
    email,
    cost_center,
    date_hired,
    job
) values (
    1,
    'Gricelda Luebbers',
    'gricelda.luebbers@aaab.com',
    20,
    sysdate - 94,
    'Systems Designer'
);

insert into employees (
    department_id,
    name,
    email,
    cost_center,
    date_hired,
    job
) values (
    1,
    'Dean Bollich',
    'dean.bollich@aaac.com',
    11,
    sysdate - 74,
    'Legal Assistant'
);

insert into employees (
    department_id,
    name,
    email,
    cost_center,
    date_hired,
    job
) values (
    1,
    'Milo Manoni',
    'milo.manoni@aaad.com',
    21,
    sysdate - 68,
    'Systems Designer'
);

insert into employees (
    department_id,
    name,
    email,
    cost_center,
    date_hired,
    job
) values (
    1,
    'Laurice Karl',
    'laurice.karl@aaae.com',
    78,
    sysdate - 73,
    'Programmer'
);

select
    departments.name                                   department_name,
    departments.location                               location,
    departments.country                                country,
    employees.name                                     employee_name,
    employees.email                                    email,
    employees.cost_center                              cost_center,
    employees.date_hired                               date_hired,
    employees.job                                      job
from
    departments,
    employees;

This is the output they are showing after running:
Table created.

ORA-02268: referenced table does not have a primary key

1 row(s) inserted.

1 row(s) inserted.

1 row(s) inserted.

1 row(s) inserted.

Statement processed.

ORA-00942: table or view does not exist

ORA-00942: table or view does not exist

ORA-00942: table or view does not exist

ORA-00942: table or view does not exist

ORA-00942: table or view does not exist

A: Your table departments does not have a primary key, so the constraint in table employees produces an error, and the table employees is not created.
You should refactor your SQL code, adding a proper primary key to the table involved and manage the insert value properly:
create table departments (
id                             numeric(10) not null
name                           varchar2(255) not null,
location                       varchar2(4000),
country                        varchar2(4000),
CONSTRAINT id PRIMARY KEY (id)
)
;


text:
Q: How to Force domain users to change password now How can I force all domain users to change their password now? I want to do so before users next logon.
Thanks

A: If you are using PowerShell, this command will force all users in the current domain to choose a new password next time they log in.
Get-ADUser -Filter "*" | Set-ADUser -ChangePasswordAtLogon $true

If you want to be more precise about which users are affected, you can narrow it down to an organizational unit.
$users = Get-ADUser -Filter "*" -SearchScope Subtree -SearchBase 'DC=contoso,DC=com'
$users | Set-ADUser -ChangePasswordAtLogon $true

More options can be found here: Migrated Users Get Prompted To Change Password at First Logon (blogs.technet.com).

A: Use a combination of dsquery and dsmod
eg
dsquery user "OU=Sales,OU=New York,dc=internal,dc=AcmeCorp,dc=com" | dsmod user -pwd ChangeThisNow! -mustchpwd yes -u Admin -p APassword

This would change password of all users in Sales in New York to "ChangeThisNow!" and force them to change it on login.
Here's a reference on dsmod


text:
Q: Vue 3 TypeScript optional props object checking length - error I need props to be an object that is optional.
interface MyObject { id: string| number, name: string, namePlural: string}
interface Props { preloadInputs?: MyObject}

...
// check if preloadInputs is not empty:
onMounted(() => {if (!(Object.keys(props.preloadInputs).length === 0)) {...} })

VSCode's error for the props.preloadInputs is:
I get an error:

No overload matches this call
Overload 1 of 2, ' (o: {}): string[]', gave the following error.
Overload 2 of 2, ' (o: object): string[]', gave the following error.ts (2769)

I am new to Vue and TS, so there must be something I am missing.

A: You defined preloadInputs to be optional so it can have a value of undefined. Object.keys() does not accept undefined as the argument. That's why you get the error Type 'undefined' is not assignable to type '{}'.
We could use the nullish coalescing operator to solve this problem.
Object.keys(props.preloadInputs ?? {}).length === 0

If props.preloadInputs is undefined, an empty object gets passed to Object.keys().


text:
Q: Wicket 1.4.9 cannot use AjaxRequestTarget from modal after Feedback error! I create a simple wicket web app for using description this problem when i set require is true at TextField and submit with null value in  Textfield. i have got a feedback panel message (This sound good) but my use case  i want to get my data from modal windows and send back to this form but it can not AjaxRequestTarget update TextField data and cannot input anything on other textfield.i cannot solve with this problem.please help me.but when i run web app again and used modal windows i can setting my data on text field.
This is my sample Code
User Entity :
public class User implements Serializable {

private String username;
private String password;

public User(String username, String password){
    this.username = username;
    this.password = password;
}

public User() {
    // TODO Auto-generated constructor stub
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}
}

My Page
public class FormPage extends WebPage{

private User user;
private ModalWindow modal;
private TestForm form;

public FormPage() {
    user = new User();

    modal = new ModalWindow("modal");
    modal.setOutputMarkupId(true);
    modal.setInitialHeight(300);
    modal.setInitialWidth(300);
    add(modal);

    form = new TestForm("form");
    add(form);
}

private class TestForm extends Form {

    private FeedbackPanel feedback;
    private TextField<String> username;
    private AjaxLink popupButton;
    private AjaxButton submitButton;
    private TextField<String> password;

    public TestForm(String id) {
        super(id);

        feedback = new FeedbackPanel("feedback");
        feedback.setOutputMarkupId(true);
        add(feedback);

        username = new TextField<String>("username", new PropertyModel<String>(FormPage.this, "user.username"));
        username.setOutputMarkupId(true);
        username.setRequired(true);
        add(username);

        password = new TextField<String>("password", new PropertyModel<String>(FormPage.this, "user.password"));
        password.setOutputMarkupId(true);
        password.setRequired(true);
        add(password);

        popupButton = new AjaxLink("popupButton") {

            @Override
            public void onClick(AjaxRequestTarget target) {
                UserPopup popup = new UserPopup(modal.getContentId()) {

                    @Override
                    public void onSuccess(AjaxRequestTarget target, User user) {
                        FormPage.this.user = user;
                        target.addComponent(username);
                        target.addComponent(password);
                        modal.close(target);
                    }
                };
                modal.setContent(popup);
                modal.show(target);
            }
        };
        add(popupButton);

        submitButton = new AjaxButton("submitButton", this) {

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                // TODO Auto-generated method stub

            }

            @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                target.addComponent(feedback);
            }
        };
        add(submitButton);

    }

}

}
my popup :
public abstract class UserPopup extends Panel{

private User user;

public UserPopup(String id) {
    super(id);

    user = new User("name","pass");

    add(new AjaxLink("userLink"){

        @Override
        public void onClick(AjaxRequestTarget target) {
            onSuccess(target, user);
        }

    });
}

public abstract void onSuccess(AjaxRequestTarget target,User user);

}

A: try this. onSuccess method, set the model object of your username and password fields.
@Override
                public void onSuccess(AjaxRequestTarget target, User user) {
                    FormPage.this.user = user;
                    username.setModelObject(user.getUsername());
                    password.setModelObject(user.getPassword());
                    target.addComponent(username);
                    target.addComponent(password);
                    modal.close(target);
                }

I had a similar usecase and it worked. You seem to be struggling with your english and so i may not have understood your question well.
Below is my code on similar problem.
public class ReleaseDetailPanel extends Panel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private Form<Release> frmRelease ;

    private TextField<String> txtName ;

    private TextArea<String> txtDescription;

    private TextField<Project> txtProject;

    private AjaxLink<String> lnkLookupProject ;

    private ModalWindow mdProjectLookup ;

    @Inject
    private Dao dao ;

    public ReleaseDetailPanel(String id, Release release) {
        super(id);

        frmRelease = new Form<Release>("frmRelease", new Model<Release>(release)){
            /**
             *
             */
            private static final long serialVersionUID = 8075962334880413343L;

            protected void onSubmit() {
                Release r = this.getModelObject();
                dao.save(r);
            };
        };

        txtName = new TextField<String>("txtName", new PropertyModel<String>(release, "name"));
        frmRelease.add(txtName);

        txtDescription = new TextArea<String>("txtDescription", new PropertyModel<String>(release, "description"));
        frmRelease.add(txtDescription);

        txtProject = new TextField<Project>("lstProject", new PropertyModel<Project>(release, "project") );
        frmRelease.add(txtProject);
        txtProject.setEnabled(false);
        txtProject.setOutputMarkupId(true);

        lnkLookupProject = new AjaxLink<String>("lnkLookupProject"){
            /**
             *
             */
            private static final long serialVersionUID = -1014715631761886636L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                mdProjectLookup.show(target);
            }

        };
        frmRelease.add(lnkLookupProject);
        add(frmRelease);

        mdProjectLookup = new ModalWindow("mdProjectLookup");
        mdProjectLookup.setContent(new ProjectListPanel(mdProjectLookup.getContentId()){

            @Override
            public Component getGridMenu(String id) {

                return new Label(id);
            }

            @Override
            public Component getGridItemMenu(String componentId, final Project project) {
                return new LabeledAjaxFallbackLink(componentId, "Select"){

                    /**
                     *
                     */
                    private static final long serialVersionUID = 1L;

                    @Override
                    public void doClick(AjaxRequestTarget target) {
                        txtProject.setModelObject(project);
                        target.addComponent(txtProject);
                        mdProjectLookup.close(target);
                    }

                };

            }

        });

        add(mdProjectLookup);
    }


text:
Q: Understanding debugger output in VSCode I'm trying to debug some node-application but I don't know how to interprete the variables section. As shown in the screenshot, the VSCode shows a lot of "members" as childs under the variable 'cf' which seems to be a function. But I'm confused than, because

*

*Does that mean, that the childs are variables within the functions definition

*What is the meaning of the [[]] Brackets?

*What is the meaning of the __ __ Underscores?


text:
Q: Arc of curve of function - Find the minimum length
This is the arc of the curve:
$$y = x^3 + x^2 - \frac{29x}{2} + 1 \\ t > 0 \\ x \in [t,t+1]$$
Find $t$ for which the length of the arc of the curve is minimum.

Should I use $ \int {\sqrt{1 + [f'(x)]^2}} dx$ ?
Thank you very, but very much!

A: Yes, one should use the formula. Note that the integral is from $t$ to $t+1$.
Then differentiate, using the Fundamental Theorem of Calculus, and proceed as usual. After setting the derivative equal to $0$, be careful when finding square roots.

A: doing André Nicolas say, we have:
$$f'(x)=3x^2+2x-\frac{29}{2}$$
and
$$g(t)=\int_t^{t+1}{\sqrt{1 + \left(3x^2 + 2x - \frac{29}{2}\right)^2}} dx$$ $$g(t)=\int_0^{t+1}{\sqrt{1 + \left(3x^2 + 2x - \frac{29}{2}\right)^2}} dx-\int_0^{t}{\sqrt{1 + \left(3x^2 + 2x - \frac{29}{2}\right)^2}} dx$$
now we calculate $g'(t)$:
$$g'(t)=\sqrt{1 + \left(3(t+1)^2 + 2(t+1) - \frac{29}{2}\right)^2}-\sqrt{1 + \left(3t^2 + 2t - \frac{29}{2}\right)^2}=0$$
$$1 + \left(3(t+1)^2 + 2(t+1) - \frac{29}{2}\right)^2-1-\left(3t^2 + 2t - \frac{29}{2}\right)^2=0$$
$$\left(3t^2+2t-\frac{29}{2}+6t+5\right)^2-\left(3t^2+2t-\frac{29}{2}\right)^2=0$$
$$2(6t+5)(3t^2+2t-\frac{29}{2})+(6t+5)^2=0$$
if $t$ distinc to $-\frac{5}{6}$, we factorizing $(6t+5)$:
$$6t^2+4t-29+6t+5=0$$
finally we have:
$$6t^2+10t-24=0$$
wich have the solutions: $t=-\frac{16}{12}$ and $t=3$
Finally the result is:
$$t=3$$


text:
Q: Excel: matching value in table then returning value of specific column I have a table that looks like this:
userID                Payment
--------------------------------------
1                     5000
2                     2489
3                     2529
4                     7423
3                     4328
5                     6475
1                     5644
1                     8585
2                     3214
5                     9876

and I have already gathered all the distinct userIDs and copied them to a new area
1
2
3
4
5

I'd like a formula I can put next to the distinct user ids that will search the 1st table, match userIDs and gather a sum of the payment values... So my distinct userids table would end up looking like this
userID        Payment
1             19229
2             5703
3             6857
4             7423
5             16351

I'm guessing i'm looking for something with vlookup, but I just can't get it to work.

A: Use SUMIF, like this (userID in A:A, Payments in B:B)
=SUMIF(A:A,D1,B:B)


text:
Q: Assign value to missing data that isn't already in the array I have a simple array, a, containing nine values between 1 and 10. A missing data point in this array is given the value 0.
I need to replace this value in the array with a value 0<x>10, but crucially it cannot be a value that is already present in the input array.
import numpy as np
def Data(a):
    b = np.arange(1,10)
    a[a==0] = b[b != a]
    return a

I have tried this, but it seems to compare a[0] with b[0], then a[1] and b[1].
What I need it to do is compare b[0] with all values in the array a.
If the value of b[0] isn't found anywhere in a, then I need it to replace the value 0 (the missing data point in array a) with exactly b[0].
Any smart and simple way to do this?

A: Something like this would ensure you have unique elements in a, and also replace the 0 values with a unique value in range(1,11).
>>> a = [1,2,10,0,4,0,0,3,7]
>>> unique = set()
>>> a = [x if x not in unique and not unique.add(x) else 0 for x in a]
>>> new = list(set(range(1,11)) - unique)
>>> from random import shuffle
>>> shuffle(new)  # this step may be unnecessary...
>>> [new.pop() if x is 0 else x for x in a]
[1, 2, 10, 9, 4, 8, 6, 3, 7]

A: I think you're looking for numpy.in1d, something like:
a[a == 0] = b[~np.in1d(b, a)]

For boolean arrays, ~ acts as a not.


text:
Q: Will passing std::string via copying be optimized? In our project there are lots of functions where strings are passed via copy:
void f(std::string a);

As we all know it's more effective to pass it by reference, but my collegue says the compiler will optimize it anyway. Is this any close to truth for GCC?
G++ 4.8.2, -O2 enabled in Release build.
Thanks!

A: This is a somewhat controversial issue.
In theory, yes the compiler is more likely to apply certain optimizations when passing by value. Chandler Carruth explained how this works for LLVM in his BoostCon 2013 keynote Optimizing the Emergent Structures of C++ (video)/(slides).
The problem is that there are overheads to pass-by-value which the compiler is not able to get rid of. This is true even when you have a conformant C++11 compiler and a movable type like std::string. Herb Sutter discussed the issue of calling conventions in particular in his CppCon2014 talk Essentials of Modern C++ Style (slides). His conclusion is to do it like you learned in C++98-school: Use const& as a default for passing non-trivial arguments.
Another big arguments against the pass-by-value convention is that it becomes very hard to write efficient code that gives a strong exception-safety guarantee: To get efficiency, the user will have to move the string into the function. But in that case, if the function throws, the string is gone forever.
Of course the prime directive of optimization still applies: When in doubt, measure. Run a profiler on your real code to see which works better for you.