text:
Q: Can someone clarify the notation of x $\equiv$ -8 $\equiv$ 6 ($\bmod$ 7) This is an example from Discrete Mathematics and its Applications

This is example 1 that this example references

And here's Theorem 1 that the example references

Example 1 makes sense. We have to determine if the inverse of 3 modulo 7 exists first of all. It will exist based on theorem 1 if m > 1, which it is in this case bc m = 7 and if gcd(3, 7) is 1 - definition of relatively prime.
To determine if gcd(3, 7) is 1, you can use Euclid's Algorithm,
7 = 3(2) + 1
3 = 1(3) + 0
In this case, 1 is the gcd because it is last remainder before the remainder goes to zero. $\equiv$
Now you know the inverse exists. To find the actual inverse, you want the inverse to be in the form
a'a $\equiv$  1 $\bmod$ m
where a' would be the inverse.
To do this, you would need to use Bezout's Theorem that gcd(a, b) = sa + tb, so from my work in Euclid's Theorem, you can see
7 = 3(2) + 1
-2(3) + 1(7) = 1
then
-2(3) - 1 = -1(7)
-2(3) $\equiv$ 1$\bmod$(7) which is in the form of a'a $\equiv$  1 $\bmod$ m, so a' or the inverse of a modulo m is -2.
Here's where I get lost. In example 3, the author uses the result he got from the inverse to solve the linear congruence of 3x $\equiv$ 4(mod 7).
I understand that -6 $\equiv$ 1 ($\bmod$ 7) and -8 $\equiv$ 6 ($\bmod$ 7), but how does that lead to x $\equiv$  -8 $\equiv$ 6 ($\bmod$ 7)? What does that even mean?

A: $\qquad\ \  3\,x\,\equiv\, 4 \pmod 7\ $ scaled by $\ {-2}\equiv 3^{-1}_{\phantom{I_{I_{I_I}}}} $ yields
$\smash[t]{\ \ \overbrace{-2\cdot 3}^{\Large\ \equiv\, \color{#c00}1}\,x\,\equiv\,\overbrace{-2\cdot 4}^{\Large\! \equiv\, \color{#0a0}6}\pmod 7}$
$\ \Rightarrow\ \color{#c00}1\cdot x\equiv \color{#0a0}6\pmod 7,\, $ where we've used the Congruence Product Rule to scale it.
Indeed $\ x\equiv 6\,\Rightarrow\, 3x \equiv 18\equiv 4\pmod 7$
Alternatively $\ x\,\equiv\ \dfrac{4}{3}\,\equiv\, \dfrac{-3}3\,\equiv\, {-}1\,\equiv\, 6 $
Beware $ $ Modular fraction arithmetic is well-defined only for fractions with denominator coprime to the modulus. See here for further discussion.

A: You are trying to find solutions to the equivalence $3x \equiv 4 \pmod{7}$.  What the author is saying is that both $-8$ and $6$ are solutions to the equivalence, which we can verify by direct substitution.
If we substitute $-8$ for $x$, we obtain
\begin{align*}
3(-8) & \equiv -24 \pmod{7}\\
      & \equiv -28 + 4 \pmod{7}\\
      & \equiv -4 \cdot 7 + 4 \pmod{7}\\
      & \equiv 4 \pmod{7}
\end{align*}
If we substitute $6$ for $x$, we obtain
\begin{align*}
3 \cdot 6 & \equiv 18 \pmod{7}\\
          & \equiv 14 + 4 \pmod{7}\\
          & \equiv 2 \cdot 7 + 4 \pmod{7}\\
          & \equiv 4 \pmod{7}
\end{align*}
Moreover,
\begin{align*}
-8 & \equiv -14 + 6 \pmod{7}\\
   & \equiv -2 \cdot 7 + 6 \pmod{7}\\
   & \equiv 6 \pmod{7}
\end{align*}
In fact, if $n \in \mathbb{Z}$, then $6 + 7n$ is a solution to the equivalence since
\begin{align*}
3(6 + 7n) & \equiv 18 + 21n \pmod{7}\\
          & \equiv 14 + 4 + 21n \pmod{7}\\
          & \equiv 7(2 + 3n) + 4 \pmod{7}\\
          & \equiv 4 \pmod{7}
\end{align*}
The author found the particular solution $-8$ (which corresponds to the choice $n = -2$).  However, we usually wish to express the solution of an equivalence modulo $n$ as one of the residues $0, 1, \ldots, n - 1$.  Since $n = 7$, the answer in the set of residues $\{0, 1, 2, 3, 4, 5, 6\}$ that is equivalent modulo $7$ to $-8$ is $6$.


text:
Q: How does the displacement current flow in a conductor at steady current? According to the concept of displacement current, time varying electric fields give rise to displacement currents. But in a capacitor, once steady current flows, there is no change in electric field. Now how does the displacement current flow? If it does not, it leads to a contradiction. Someone please answer me. Thank you very much.

A: Your problem is that you're confusing current with charge. In a capacitor the electric field is constant when the current flowing through it is zero. There may be currents flowing through other parts of the circuit in steady state, but the steady state capacitor has charge and no current flow.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count records based on a column with a part of the same value I have a table similar to this:
Table A22

Id
Item
Location

1
a
1234-01

2
a
1234-01

3
a
1234-01

4
a
1234-01

5
a
2345-01

6
b
1234-01

7
b
1234-01

8
b
1234-01

9
b
1234-01

10
b
2345-01

I would like to compare the first 4 values in Location and count all locations which have the same 4 values and the same item.
I try this query and similar ones but I can't get the correct count:
select
    a.item,
    a.location,
    sum(a.id) as 'count'
from
    a22 a,
    a22 b
where
    1 = 1
    and substring(a.location, 1, 4) = substring(b.LOCATION_NAME, 1, 4)
group by
    a.item, a.location

Edit: Desired output should be like this:

Item
Location
Count

a
1234-01
4

a
2345-01
1

b
1234-01
4

b
2345-01
1

Any suggestions?

A: Bryan Dellinger gave me the correct answer:
select count('dracula'),
       item,
       substring(location,1,4)
    from a22
    group by
        item,
        substring(location,1,4);


text:
Q: How to render v-for from particular index I want to loop in v-for from suppose from number 5 to 10 .
The loop want to be started at 5 and end at 10.
I have tried this

=5">

But I want more effective way of doing the loop  . Does anyone knows how to do so that loop starts at 5 ?

A: Also try this simple approach:

new Vue({
  el: '#test',
  data: {
    items: [
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
      '10'
    ]
  },
  methods: {
    sliceItems: function (start, end) {
      return this.items.slice(start, end);
    }
  }
})

{{ item }}

A: Another simple alternative is to just use basic +/-:

new Vue({
  el: '#app',
  data: {
    start: 5,
    end: 10
  }
})

{{ i+start }}

If you really need to use {{ i }} a lot of times and is bothered by adding start, you can use a little trick:

new Vue({
  el: '#app',
  data: {
    start: 5,
    end: 10
  }
})

    <template v-for="curr in end-start" >

        {{ i }}{{ i }}{{ i }}{{ i }}{{ i }}{{ i }}{{ i }}{{ i }}{{ i }}

    </template>

A: Its possible for your example:

... some code here

and mount range function:
var app = new Vue({
  el: '#app',
  methods:{
    range : function (start, end) {
      return Array(end - start + 1).fill().map((_, idx) => start + idx)
   }
  }
});

and sample in jsfidle.
If want know more than this github issue can help you.


text:
Q: WPF вставка изображения из файла ресурсов Всем привет. На главной форме у меня есть меню, и я пытаюсь сделать иконку для элемента.
<MenuItem Header="Добавить издательство" Width="auto" Command="local:WindowCommands.AddHouse" Height="33" Margin="0" HorizontalAlignment="Left" VerticalAlignment="Center">
  <MenuItem.Icon>
    <Image Source="Resources/ic_store_black_36dp_2x.png" Stretch="Uniform" StretchDirection="Both" />
  </MenuItem.Icon>
</MenuItem>

В конструкторе показывает картинку, но при запуске приложения она не отображается. Что я делаю не так ? Заранее спасибо за ответ.

A: Вы не должны использовать ресурсы из свойств проекта, это даст вам лишь нативные ресурсы, которые подходят для WinForms, но не WPF.
Делайте вот как:

*

*Создайте каталог Resources в проекте, и добавьте туда файл через Add → Existing Item.

*Убедитесь, что тип файла выбран как Resource (а не Embedded Resource)

*Укажите в XAML путь:
<Image Source="Resources/redsquare.png"/>

*Результат:


text:
Q: Ruby Rails preserve a variable used in one method for another method to access I have a method that sorts the index for a list of products.  Sorts them alphabetically, by rating, etc.  That works perfect.
When I got to the show page, I added next and previous buttons.  But they are working off the next ID in the table, not the next in the sort I made.  I think as a user, I want to cycle through my currently chosen sort.
So I changed the next/previous methods to get the index of the current show product, next will add +1, previous -1 to the index and check the length -1 to start it back to zero.
But here's the issue.  I need to preserve the current variable of the sort for the next/previous methods to access.
The approach I'm trying:
I think I need to use after_action on the controller to set the variable aside in a method. The index method contains the used sort variable something like:
after_action :set_product_sort, only: [:index]

  private
    def set_product_sort
      @current_product_sort = @products_sort
    end

From research, I keep seeing i have to involve the routes.  Something like this:
  resources :products_controller do
    collection do
      get :set_product_sort
    end
  end

So if that makes sense (I'm out of my depth here).  I am not clear on a few things.
If I do before_action on the index method, the variable will not be set to the sort.  So I think after_action is what I need.  But am I wrong?  Will the variable already be dropped at that point?
In that routes block, what is "collection".  I got that block from a blog post and trying to look up "collection" yields general info about collections.  I am thinking perhaps collection is supposed to be the variable name (ie @products_sort)?
And finally, how would I call upon this next/previous
Next/previous need to know the current product as well as the current sort.  The current product is already in the controller show method.  Does that routes.rb block set the sort variable up to just call it in method?  or does it need to be dot notation and maybe make the next/previous self.next and self.previous?

A: I'm guessing this is a pure Rails app? I would suggest using a different route for each of your sorted index pages, or maybe using nested routes. That way you could do localhost:3000/products/alpha/:id or localhost:3000/products/by_rating/:id, etc. That way the server can parse the request based on the URL and send the appropriate record.
Your routes would look something like:
get '/products/alpha/:id/', to: 'products#show_alpha', as: 'product_alpha_show'
get '/products/by_rating/:id', to: 'products#show_by_rating', as: 'product_rating_show'

Or something along those lines.
If you don't want different URL paths for the different index pages then I think you're looking at storing the sort method in localStorage, or some sort of token.
Fairly new to programming myself, but that's what I would do.


text:
Q: Zend\ServiceManager\Exception\ServiceNotFoundException zend framwork 3 I'm trying to follow this tutorial to add a login and a access filter to my project: https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/User_Management__Authentication_and_Access_Filtering.html
I've follow all the steps, but it's showing this error.
That's my module code: https://github.com/Nathipg/LoginZf3
I tryed to config the factory at module.config.php but it didn't work
Does anyone have a clue about how to fix it?

A: I found the problem
The namespace were wrong at AuthManagerFactory


text:
Q: Need to submit a form without the onsubmit and include the action Here is a form
<cfoutput>
<form name    = "xrefform"
    id        = "xrefform"
    action    = ""
    method    = "post"
    onsubmit  = "return submitx('#coltop#', '#col#')">
</cfoutput>

There are two different way to submit it:
1) when you want the data in the form to be placed in a MySql Table
2) when you want the data to be deleted from the Mysql Table
For the first case I have
<input type     = "Submit"
        name    = "SubmitXref"
        class   = "submitbut"
        value   = "Submit"
        onclick = "aasubmit('xref2.cfm')">

with corresponding javascript:
 function aasubmit(target) {
   document.xrefform.action = target;
 }//end function aasubmit

This works fine.
For the delete case I have
<input   type    = "Submit"
         id      = "delbut"
         class   = "onoffbut"
         value   = "delete"
         onclick = "aasubmit('repdel.cfm')">

This has a problem, which is that the submitx() javascript runs, and in this case I don't want it to.
I find references that say using the document.form.submit() method will avoid running the onsubmit function.  But I can't figure out how to indicate the action.
Can someone show me how to do this?

After fussing around some more I found the answer:
For the delete button --which needs to evade the onsubmit script --here is the HTML:
   <input type    = "button"
        id      = "delbut"
        value   = "Delete this item"
        onclick = "buttonsubmit('xrefdel.cfm', 'xrefform')">

And here is the javascript.
function buttonsubmit(target, source) {
var q = document.getElementById(source);
q.action = target;
q.submit();
}

This works perfectly.  The ordinary submit honors the onsubmit script, the delete button skips it.

A: Let's outline your requirements:

*

*One form

*Two submit buttons

*No JavaScript submit.

If you give each of the submit buttons a name, then you can have a single action page and check which button was clicked.
name="doUpdate" or name="doDelete"
The only name key that will exist in the form scope is whichever submit button was clicked. Use structKeyExists() to check and process accordingly.
Of course, you probably want to use onsubmit="return validateForm()" to call a validation function. If you click on "delete", you might want the user to confirm that was what they wanted to do before processing it. The function validateForm() just needs to return true or false, so you'll still avoid the JavaScript submit().

A: Do something like this in the form:
<input name="action" value="save" id="action" type="hidden">
<button type="submit" class="button button-basic-green" onclick="document.getElementById('action').value='save';"> Save</button>
<button type="submit" class="button button-basic" onclick="document.getElementById('action').value='reload';"> Save & Reload</button>
<button type="submit" class="button button-basic" onclick="document.location.href='./';return false;"> Cancel</button>

Note the default action of "save". Gets you something like:

Then in the singular form-action page, check to see what the form.action is and process accordingly.
<cfif form.action eq "reload">
    <cfset loc="page.cfm?id=#form.id#">
<cfelse>
    <cfset loc="./">
</cfif>


text:
Q: Checking if an user input is in array I want to write a small java program that asks the user for an input and checks if the input is in the array and redirects the user to a HTML page if the input is in the array.
package ticketnummercheck;
import java.util.Scanner;

public class TicketnummerCheck {

    public static void main(String[] args) {

        int ticketnummer = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Ticketnummer:");
        ticketnummer = input.nextInt();

        String [] ticketnummerDB = {"1234", "12345", "123456", "123456"};

    }

}

A: Use this
if(Arrays.asList(ticketnummerDB)
         .contains(String.valueOf(ticketnummer))) {
    // contains value
}
else {
    // does not contain value
}


text:
Q: Assembly: Which Value when using 'Load Immediate(li)' Helloo,
I'm learning MIPS Assembly righ know at University and I'm bit confused.
When using the command 'li' for example in li $v0, ()... when do I use which value for the brackets? I saw now 1s and 4s.
Please Help
I tried using different values but I dont understand it.


text:
Q: Cannot perform correct action after condition is met using Enumeration Flags Method:

*

*List of employees

*Each employee has a skill set, can contain several skills

*Skill set is derived from enumeration

*I want to be able to have a loop that reads the enumeration and if they contain the appropriate skill it comes out of the loop

Code
 bool success = false;
 foreach (Employee emp in employees)
 {
 while (emp.Busy != true || success == true)
 {
 if (emp.Busy == false && emp.Skills.ToString() == _skillRequired.ToString() && success == false)
 {
 emp.EmployeeWorkload = _jobName;
 emp.ShiftsLeft = _shiftsLeft;
 emp.Busy = true;
 success = true;
 }
 else if (emp.Busy == true)
 {
 MessageBox.Show("Sorry there is no one available for this job");
 }

Problem
[Flags]
public enum MemberSkills { None = 0, CSharp = 1 << 0, SQL = 1 << 1, PHP = 1 << 2, Javascript = 1 << 3, Web = 1 << 4, Python = 1 << 5, Oracle = 1 << 6, CPlus = 1 << 7, Perl = 1 << 8 };

Employee e1 = new Employee(MemberJob.Employee, "Name", MemberSkills.CPlus | MemberSkills.CSharp, false);
Employee e2 = new Employee(MemberJob.Employee, "Another Name", MemberSkills.CSharp, false);

Because the object contains one or more MemberSkills, the if statement reads the object as "CSharp | CPlus" and cannot correctly perform the method. Instead selecting an employee with CSharp in their skill set. See e2

A: There's a method called HasFlag on the Enum class that will do what you need:
var _skillRequired = MemberSkills.CSharp;

if (emp.Skills.HasFlag(_skillRequired))
{
    ...
}

If for some reason you can't change skillRequired, you'll need to parse the value to an enum:
var _skillRequiredAsEnum = (MemberSkills)Enum.Parse(typeof(MemberSkills), _skillRequired));

A: Since enum is Flags, you can use .HasFlag method of enum to check whether flags are set.
Or in old way; you can use (emp.Skills & _skillRequired) == _skillRequired to see if all required flags are set.


text:
Q: Highchart, Can we keep the data table on the side of the chart? I have a problem where the chart has so much data that a normal data table can't see all the data on one page, and highchart can't export 2 sheets of data. So I wanted to know if we could put the data table on the side of the chart. like this
This demo Link Demo


text:
Q: grabbing article id post For some reason, this isn't working, but not sure why. I'm trying to grab the comment id on how many comments are in the database, but it's showing "0". When clearly I see comments.
Visit live: http://www.krissales.me/#/media/articles
If you click on the article link, it'll show how many comments on that page, but not on the page I want it to show on.
I'm pretty sure it has something to do with the:

$amount_get = mysql_query("SELECT * FROM comment WHERE id='" .
  mysql_real_escape_string($_GET['id']) . "'");         $comments =
  mysql_num_rows($amount_get);

article.php:
<?php

        $amount_get = mysql_query("SELECT * FROM comment WHERE id='" . mysql_real_escape_string($_GET['id']) . "'");
        $comments = mysql_num_rows($amount_get);

        $grab = mysql_query("SELECT * FROM articles WHERE id='" . mysql_real_escape_string($_GET['id']) . "' LIMIT 1");
        $grab = mysql_query("SELECT id, news_title, news_content, news_author, news_day, news_month, news_year, news_date FROM articles ORDER BY id DESC limit 3");
        $news_day =$row['news_day'];
        $news_month =$row['news_month'];
        $news_year =$row['news_year'];

        if (mysql_num_rows($grab)==0) {
        echo "
Sorry, it looks like their are no articles posted!
";
    }
        while($row = mysql_fetch_array($grab)){

    ?>

<?php echo $row['news_day'] ?> <?php echo $row['news_month'] ?> <?php echo $row['news_year'] ?>

<a href="#/media/<?php echo $row['id'] ?>.<?php echo stripslashes(str_replace(" ", "-", $row['news_title'])); ?>"><?php echo stripslashes($row['news_title']); ?>

The content for this article will be posted here shortly, i need to edit some PHP that limits the chars for this section

Comments (<?php echo $comments ?>)

  <?php } ?>

A: You should have a look at the WHERE condition of this line:
$amount_get = mysql_query("SELECT * FROM comment WHERE id='" . mysql_real_escape_string($_GET['id']) . "'");

I guess that id should been changed to something like article_id - a foreign_key that points the an article.


text:
Q: Converting mac node script to windows I have a postinstall node script that copies previously run scripts into my npm-scripts folder.  However, this only works for Mac.  I need to have it work for Windows as well so I am creating a new file that will run 1 for windows or the one listed below for Mac.
`cp ../node_modules/some-components/npm-scripts/*.js ../npm_scripts`

I'm not seeing a clear way to convert the syntax to be usable by a windows machine as well as whether to use copy or robocopy.  Any suggestions would be greatly appreciated.

A: Create a copy.js file which performs the copy platform-independently via a Node.js API (i.e. do not rely on Windows or Unix-specific shell commands cp or copy). My suggestion: Use fs-extra, which also handles copying directories, in contrast to the included fs.
var fs = require('fs-extra'); // add to your dependencies via 'npm install fs-extra --save'
var path = require('path');

fs.copySync(
      path.resolve(__dirname, '../path/to/source',
      path.resolve(__dirname, '../path/to/destination'));


text:
Q: Derivative of delta distribution I'm reading  Reed & Simon's book on Functional Analysis. In the chapter of locally convex spaces they say:
"consider the tempered distribution $\delta'(f)=-f'(0)$, which doesn't come from a measure".
Why is that true? I've tried to prove that claim but it's been unsuccessful.

A: The support of the $\delta'$ is $\{0\}$; for any $f$ that is $0$ on a neighborhood of $\{0\}$, $\delta'(f)=0$.
If $\delta'$ were described by a measure, $\mu$, then that measure must also be supported on $\{0\}$. Then
$$
\mu(f)=\int f\,\mathrm{d}\mu\tag{1}
$$
and $(1)$ is dependent only on the value of $f$ on $\{0\}$.  Both $1+x$ and $1$ are functions which on $\{0\}$ have the same value, but $\delta'(1+x)=1$ and $\delta'(1)=0$.

A: Suppose that $\delta'$ is given by a mesure $\mu$. Then we have for any compact $\mathrm K$ $$ \int_{\mathrm K} d\mu = 0$$

A: According to Riesz's representation theorem, a measure is a continuous linear functional on the Fréchet space of continuous functions with compact support. The functional you have here is not even well-defined on that space.
A possible objection is that the definition should be considered on the subspace of sufficiently regular functions and then extended by density. But the assignment $$f\in C^1(\mathbb{R})\to f'(0)$$ is not continuous with respect to the topology of $C(\mathbb{R})$. For example, the sequence
$$f_n(x)=\frac{\sin(nx)}{n}\zeta(x), $$
where $\zeta$ is a smooth cutoff function, is such that $f_n \to 0$ in $C(\mathbb{R})$ (that is, uniformly on compact sets) but $f'_n(0)=1$ for all $n$.


text:
Q: How can I add my input text box to my link params? I have the following in my shop.gsp file:
<input type="text" class="inputTextBox" name="queryString"/>
<g:link action="shop" controller="item" params='[queryString:
"${document.getElementById('queryString').value}", queryType: "search"]'>
 Search
 </g:link>

But in my controller when I do a params.queryString it returns an empty string.I know I could be using a form for this but for my problem I need to use the link like it is. So how can I get the value of my input text in the link parameters?

A: Here is an example of how to do this with the use of some jQuery. Off the top of my head, so please forgive any typos.
<input id="field" name="field" type="text" value="" />
<g:link class="mylink" controller="somewhere" action="something">My link</g:link>

<script type="text/javascript">
jQuery(function(){
    $("a.mylink").on("click", function(e) {
        window.location.href = $(this).attr("href") + "?field=" + $("#field").val();
        return false;
    });
});
</script>


text:
Q: Bootstrap dynamic hours refreshing issue tl;dr : I want to refresh time inside the popover without having to toggle it again (by clicking). When it's opened, it update the time.
I'm trying to make my popover refresh but I can't find a way to do it. I have dynamic hours in it, it needs to change every seconds. It is the only content that will need to be refresh even when the page is active. The other will update if we toggle it, if I need to update it too. I tried to search many ways to do it but couldn't find any clues.

            <canvas class="canvas" id="canvas" width="650px" height="450px">Votre
                navigateur ne supporte pas le canevas.
            </canvas>

            <input type="image" src="images/plane.png" id="planeimg" data-container="body" data-toggle="popover" data-placement="top"
                title="Données du trajet" data-html="true"/>

                Départ :  Montreal

                Arrivée :  Toronto

                Prochaine ville :  Toronto

                Vitesse : 500 km/h

                Temps restant :  2 h

                Heure :

Here is my Javascript code :
$(function(){
    // Enables popover
    $("[data-toggle=popover]").popover({
        html: true,
        content: function() {
            return $('#popover-content').html();
        }
    });
});

// TIME FUNCTION
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('timeHours').innerHTML =
    h + ":" + m + ":" + s;

    var t = setTimeout(startTime, 500);
}

function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

Thanks for the help guys!

A: Here's simple solution for updating clock:

function startTime() {
    var currentTime = new Date();
    var h = currentTime.getHours();
    var m = currentTime.getMinutes();
    var s = currentTime.getSeconds();

    // Pad the minutes and seconds with leading zeros
    m = ( m < 10 ? "0" : "") + m;
    s = ( s < 10 ? "0" : "") + s;

    // AM or PM (for 24h delete this)
    var time = (h < 12) ? "AM" : "PM";

    // 12 hour format (for 24h delete this)
    h = (h > 12) ? h - 12 : h;

    // Conver an hours form 0 to 12
    h = (h == 0) ? 12 : h;

    // Visual compose
    var display = h + ":" + m + ":" + s + " " + time;
    // (for 24h )
    // var display = h + ":" + m + ":" + s;

    $("#timeHours").html(display);

}

$(document).ready(function(){
  setInterval('startTime()', 1000);
});

Hope it helps!


text:
Q: dis.readchar Chinese letters - wrongly interpreted Characters! I want to read a file into an ArrayList of Characters. At first I thought this might be a pretty slick way doing it:
ArrayList<Character> char_chain = new ArrayList<Character>();

try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            while (dis.available() != 0) {
                // UTF8 unnoetig, da 26 Lettern
                while (!EOF) {
                    try {
                        char_chain.add(dis.readChar());
                    } catch (EOFException e) {
                        EOF = true;
                    }
                }
            }
        if (debug) {
            while (char_chain.get(i) instanceof Character) {
                System.out.println(char_chain.get(i++));
            }
        }

If I do this I get Chinese letters:
噖
䝃
塘
䕅

Could someone tell me why that is? :) I should mention that the text contains regular upper-case letters like: ABCDE and so on.

A: DataInputStream.readChar() assumes that you are reading UTF-16 characters.
To read character data, use an InputStreamReader with the correct encoding ("US-ASCII" should be sufficient if the file only contains basic latin letters).


text:
Q: How to split different fixed rows into different formats? Sample Data: goo.gl/akWozD (Assume 1 million rows with 8 columns)
How to edit the VBA codes below to churn out different file format (CSV and Excel) with different fixed rows? For example: the InputBox will ask for CSV fixed rows size and also Excel fixed rows size simultaneously.
The desired output would be CSV 1, CSV 2, CSV 3, etc and Excel 1, Excel 2, Excel 3, etc where CSV has X fixed rows and Excel has Y fixed rows, in the same folder. The original workbook will not be changed/modified. X and Y will be asked when Macro is run.
Thank you.
Public Sub SplitFixedRows()
  Dim wbOrig As Workbook
  Dim wb As Workbook
  Dim ThisSheet As Worksheet
  Dim NumOfColumns As Integer
  Dim RangeToCopy As Range
  Dim RangeOfHeader As Range
  Dim WorkbookCounter As Integer
  Dim RowsInFile

  Application.ScreenUpdating = False
  RowsInFile = InputBox("Please enter data size +1 header (Example: 11, 101, 501): ")

  Set wbOrig = ActiveWorkbook
  Set ThisSheet = wbOrig.ActiveSheet
  NumOfColumns = ThisSheet.UsedRange.Columns.Count
  WorkbookCounter = 1

  Set RangeOfHeader = ThisSheet.Range(ThisSheet.Cells(1, 1), ThisSheet.Cells(1, NumOfColumns))
  For p = 2 To ThisSheet.UsedRange.Rows.Count Step RowsInFile - 1
    Set wb = Workbooks.Add

    RangeOfHeader.Copy wb.Sheets(1).Range("A1")

    Set RangeToCopy = ThisSheet.Range(ThisSheet.Cells(p, 1), ThisSheet.Cells(p + RowsInFile - 2, NumOfColumns))
    RangeToCopy.Copy wb.Sheets(1).Range("A2")

    wb.SaveAs wbOrig.Path & "\Data " & WorkbookCounter
    wb.Close

    WorkbookCounter = WorkbookCounter + 1
  Next p

  Application.ScreenUpdating = True
  Set wb = Nothing
End Sub

A: If I understood you correctly, you only lack producing CSV file. This can be done in in following steps:
Dim FSO, wfile As Object
Dim content As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set wfile = FSO.OpenTextFile("path to the file", 2) 'connection for writing

'here you prepare whole content of the file

wfile.Write content
wfile.Close

In order to prepare the content of the file, you just append to it values in consecutive cells separated by comma (or whatever you want). To  do that, you just need to loop through the range :)


text:
Q: Got "401 Client Error: Unauthorized" when execute st2 command with fabric 2 in fabric 1.14.0, below codes works well
from fabric.api import run, settings, hide
theCmd = 'st2 run core.http url="http://httpbin.org/get"'
user='<my account>'
ss_host='<stackstorm host>'
ss_bast='<stackstorm bastion>'
with settings(user=user, host_string=ss_host, gateway=ss_bast):
    ss_result = run(theCmd)

However, when I switched it to fabric2(2.5.0), below code doesn't work:
from fabric import Connection
theCmd = 'st2 run core.http url="http://httpbin.org/get"'
user='<my account>'
ss_host='<stackstorm host>'
ss_bast='<stackstorm bastion>'
with Connection(host=ss_host, user=user, gateway=Connection(host=ss_bast)) as ss_conn:
    response = ss_conn.run('ls -la', warn=True, hide=True)
    response = ss_conn.run(theCmd)

The first command(ls -la) succeeded, which means the connection was created successfully, but the second command failed with below error
ERROR: 401 Client Error: Unauthorized
MESSAGE: Unauthorized - One of Token or API key required. for url: http://127.0.0.1:9101/v1/actions/core.http

Traceback (most recent call last):
  File "test/test_ss.py", line 12, in <module>
    response = ss_conn.run(theCmd)
  File "<decorator-gen-3>", line 2, in run
  File "venv/lib/python3.7/site-packages/fabric/connection.py", line 30, in opens
    return method(self, *args, **kwargs)
  File "venv/lib/python3.7/site-packages/fabric/connection.py", line 721, in run
    return self._run(self._remote_runner(), command, **kwargs)
  File "venv/lib/python3.7/site-packages/invoke/context.py", line 101, in _run
    return runner.run(command, **kwargs)
  File "venv/lib/python3.7/site-packages/invoke/runners.py", line 363, in run
    return self._run_body(command, **kwargs)
  File "venv/lib/python3.7/site-packages/invoke/runners.py", line 422, in _run_body
    return self.make_promise() if self._asynchronous else self._finish()
  File "venv/lib/python3.7/site-packages/invoke/runners.py", line 489, in _finish
    raise UnexpectedExit(result)
invoke.exceptions.UnexpectedExit: Encountered a bad command exit code!

Command: 'st2 run core.http url="http://httpbin.org/get"'

Exit code: 1

Did I miss any setting?

A: in fabric 2, you have to generate token and set ST2_AUTH_TOKEN in env. Then execute the rest commands
with Connection(host=ss_host, user=user, gateway=Connection(host=ss_bast), inline_ssh_env=True) as ss_conn:
    token = ss_conn.run('st2 auth <username> -p <password> -t', hide=True).stdout.strip()
    ss_conn.config.run.env = {"ST2_AUTH_TOKEN": token}


text:
Q: Using awk for rows with different number of columns I have the following information printed in the terminal and as you can see the number of columns in the first and second rows
Strms  Blocks   Compressed Uncompressed  Ratio  Check   Filename
    1       1  2,526.9 MiB    317.1 GiB  0.008  CRC64   rar.stadium.trace.xz

So, if I use awk '{print $3 "\t" $4}', I will get
Compressed  Uncompressed
2,526.9 MiB

Which is not what I want. any idea?

A: Use FIELDWIDTHS parameter with gnu awk to set widths of each field like this:
xz -l t.xz | awk '{print $3"\t"$4}' FIELDWIDTHS="5 8 13 13 7 7 99"
   Compressed    Uncompressed
     79.7 MiB       553.9 MiB
  2,526.9 MiB       317.1 GiB

Edit: last filed set to 99 to handle long file name if its need
Edit2: to better handle space and length of field
Edit3: FIELDWIDTHS="5 8 13 13 7 7 *" can be used.

A: If you want to make use of GNU awk, you can parse the first line to determine FIELDWIDTHS:
awk '(NR==1){ for(i=1;i<=NF;++i) {match($0," *"$i); f=f" "RLENGTH};
              FIELDWIDTHS=f; $0=$0}
     {print $3,$4}'

See comment of EdMorton for improvements to the above and the reasoning why.
If you do not have access to GNU awk, you can make the output of xz easily parsable by using the robot mode:

The robot mode is activated with the --robot option.  It makes the output of xz easier to parse by other programs.  Currently --robot is supported only together with --version, --info-memory, and --list.  It will be supported for compression and decompression in the future.
xz  --robot --list uses tab-separated output.  The first column of every line has a string that indicates the type of information found on that line:

For a single file, you are interested in the file line:

The columns of the file lines:

*Number of streams in the file

*Total number of blocks in the stream(s)

*Compressed size of the file

*Uncompressed size of the file

*Compression ratio, for example 0.123.  If ratio is over 9.999, three dashes (---) are displayed instead of the ratio.

*Comma-separated list of integrity check names.  The following strings are used for the known check types: None, CRC32, CRC64, and SHA-256.  For unknown check types, Unknown-N is used,
                where N is the Check ID as a decimal number (one or two digits).

*Total size of stream padding in the file

So what you are interested in is:
xz --robot -l file.xz | awk 'BEGIN{FS=OFS="\t"; print "Compressed", "Uncompressed"}/file/{print $4,$5}'

If you want it in human-readable format, you can use this function in awk:
function tohuman(size, t,u,s) {
    split( "B KiB MiB GiB TiB PiB EiB ZiB YiB" , u, " ");
    t=size; s=1; while( t>1024 ){ t/=1024; s++ }
    return sprintf("%6.1f %s", t, u[s]) }


text:
Q: Pass CMD output to Powershell via pipeline Wondering the way to pass a console application output from cmd.exe to Powershell for further manipulation without a temp file.
Example:
cmd /c SET | powershell -command Write-Host -f Green $_

Expectation: the green-colored SET's output.

A: If you want to pipe the output from an executable from within powershell, simply pipe directly to a function:
cmd /c SET |Write-Host -ForegroundColor Green

If you want to pipe output to powershell.exe from cmd.exe:
SET |powershell -Command "$input |Write-Host -ForegroundColor Green"

Alternatively, grab the environment variables directly from PowerShell's env: drive, no need to invoke cmd:
Get-ChildItem env: |Out-String |Write-Host -ForegroundColor Green


text:
Q: Firebase cloud messaging not working in background I am trying to send push notifications to my app. But the app is not receiving notifications if it is in background. I am using Firebase cloud messaging service.
here is the onMessageReceived method:
 @Override
    public void onMessageReceived(@NonNull final RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Map<String, String> data = remoteMessage.getData();
        String body = data.get("body");
        String title = data.get("title");
        String id = data.get("android_channel_id");
        int priority = remoteMessage.getPriority();

        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

 Notification notification = new NotificationCompat.Builder(getApplicationContext(), id)
                        .setSmallIcon(R.drawable.notification)
                        .setContentTitle(title)
                        .setContentText(body)
                        .setPriority(priority)
                        .setContentIntent(pendingIntent)
                        .setStyle(new androidx.media.app.NotificationCompat.MediaStyle())
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.aajevan_logo))

                        .setAutoCancel(true)
                        .build();

                notificationManager.notify(200, notification);

 @Override
    public void onNewToken(@NonNull String s) {
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {

                        if (!task.isSuccessful()) {
                            Log.d("*******FAILED", task.getException().getMessage());
                            return;
                        }

                        String token = task.getResult().getToken();
                        Log.d("/**MY TOKEN", token);
                    }
                });
    }

When the app is in foreground or background there is no problem. But it does not work if I kill my app. If I open the app once then I am receiving all my notifications at once.

A: First of all, there are 2 types of messages(notifications and data). Firebase Console sends notification messages. When you send these type of messages the firebase will handle them automatically when your application is closed or in background (not killed). check this for more info about notification messages and data messages.
Also, a killed application is an application that a user force stopped it or it crashed due to a bug or the Operating System decided to kill it (battery management). A killed application will not receive any kind of notifications.


text:
Q: for loop not working as excpected I have a class, with a variable like this:
@tags = { 'tag-test': [ 'ZnVuY3Rpb24gcmFuZG9tKCkgeyBbbmF0aXZlIGNvZGVdIH0xNDcwODI4MzQ4Mzk3TmFO' ] }

Now I'm trying to go over all indexes, then remove one of their values IF they have it :
rmtag = (t) ->
    i = @tags[t].indexOf socket.uid
    console.log "Checking tag " + t + " index is " + i
    if i != -1
        console.log "Removing " + i
        @tags[t].splice i, 1

rmtag = rmtag.bind @

for d, i in @tags
    rmtag i

In this case, socket.uid has the value of ZnVuY3Rpb24gcmFuZG9tKCkgeyBbbmF0aXZlIGNvZGVdIH0xNDcwODI4MzQ4Mzk3TmFO.
Any ideas on why this isn't working ?

A: Well, for some reason the for loop didn't get executed. Anyway, by first listing the keys and then going over them works as expected:
tags = @tags

# Remove entry from all tags
rmtag = (t) ->
    @tags[t] = @tags[t].filter((tag) => tag != socket.uid)

rmtag = rmtag.bind @
keys = Object.keys tags
for k in keys
    rmtag k

A: for ... in is used to loop over arrays but @tags is an object. You use for ... of to loop over objects:
for k, v of @tags
    rmtag k

If you say for d, i in tags, CoffeeScript will produce JavaScript like this:
for (i = j = 0, len = tags.length; j < len; i = ++j) {
    d = tags[i];
    ...
}

But you don't have a length property in @tags so the j < len condition fails immediately and the loop never executes.


text:
Q: How to inject Service Layer into controller when service layer depends upon repository and UnitOfWork I am a little confused about how this would work with Unity.  Let's assume the following scenario, I have a controller called TestController that depends upon two Services ServiceA and ServiceB.  Now serviceA depends upon two Repositories, RepositoryA1 and RepositoryA2.  ServiceB depends upon one Repository, RepositoryB.  Let's further assume that ServiceA, RepositoryA1 and RepositoryA2 depends upon UnitOfWork, UnitOfWork1.  I am having trouble understanding how to implement this for MVC3 and the Unity Application Block.  Could someone provide an example of how this should be coded?

A: There's a lot opinions on this but this is how I worked it out for myself
UnitOfWork
public interface IUnitOfWork : IDisposable
{
    FooContext DbContext { get; }
    void Save();
}
public class UnitOfWork : IUnitOfWork
{
    protected string ConnectionString;
    private FooContext context;

    public UnitOfWork(string connectionString)
    {
        this.ConnectionString = connectionString;
    }

    public FooContext DbContext
    {
        get
        {
            if (context == null)
            {
                context = new FooContext(ConnectionString);
            }
            return context;
        }
    }
    ...
}

GenericRepository
public class GenericRepository<TEntity> :
    IGenericRepository<TEntity> where TEntity : class
{
    protected FooContext DbContext;

    public GenericRepository(IUnitOfWork unitOfWork)
    {
        this.DbContext = unitOfWork.DbContext;
    }

    ...
}

Generic repositories here but they could just as well be built to be specific.
Service
public class FooService : IFooService
{
    private IUnitOfWork unitOfWork;
    private IGenericRepository<Foo> fooRepository;
    private IGenericRepository<Bar> barRepository;

    public FooService(IUnitOfWork unitOfWork,
                      IGenericRepository<Foo> fooRepository,
                      IGenericRepository<Bar> barRepository)
    {
        this.unitOfWork = unitOfWork;
        this.fooRepository = fooRepository;
        this.barRepository = barRepository;
    }
}

You still need to pass the IUnitOfWork to get access to the Save method. I suppose I could have gotten it from one of the repositories.
UnityConfig
var container = new UnityContainer();
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager(),
    new InjectionConstructor(ConnectionString));
container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
container.RegisterType<IFooService, FooService>();
container.RegisterType<IBarService, BarService>();

Controller
private IFooService fooService;
private IBarSevice barService;

public HomeController(IFooService fooService, IBarService barService)
{
    this.fooService = fooService;
    this.barService = barService;
}


text:
Q: PHP DOM - counting child nodes? HTML snippet #1

headline

HTML snippet #2

headline

PHP code
$doc = new DOMDocument();
$doc->loadHTML($x);
$xpath = new DOMXpath($doc);
$divs = $xpath->query("//div");

foreach ($divs as $div) echo $div->childNodes->length,"
";

Output with $x = snippet #1
    1
    3
Output with $x = snippet #2
    0
    1
see working demo: http://codepad.viper-7.com/11BGge
My questions
  1. How can this be?
  2. How to count child nodes correctly with DOM?
EDIT:
as Silkfire said, empty space is considered a text node. I set
$doc->preserveWhiteSpace = false;

but the results are still the same: http://codepad.viper-7.com/bnG5io
Any ideas?

A: Just count non-text nodes in your loop:
$count = 0;
foreach($div->childNodes as $node)
  if(!($node instanceof \DomText))
    $count++;

print $count;

Using xpath:
$nodesFromDiv1 = $xpath->query("//div[1]/*")->length;
$nodesFromDiv2 = $xpath->query("//div[2]/*")->length;

To remove empty text nodes, when preserveWhiteSpace=false is not working (as I suggested in the chat):
$textNodes = $xpath->query('//text()');

foreach($textNodes as $node)
  if(trim($node->wholeText) === '')
    $node->parentNode->removeChild($node);

A: Whitespace is considered a node because it is a text() node (DOMText).
You can make this work by changing your foreach loop:
foreach ($divs as $div) {
    echo $div->childNodes->length - $xpath->query('./text()', $div)->length, '
';
}

A: Firefox,Chrome and most other browsers, will treat empty white-spaces or new lines as text nodes, Internet Explorer will not.Check
Here


text:
Q: Including ffmpeg library in AWS Lambda I'm trying to include the ffmpeg library with AWS.
drwxrwxrwx 2 root root        0 Dec 22 13:04 bin
    -rwxrwxrwx 1 root root 40166912 Dec 22 11:50 ffmpeg.exe
    -rwxrwxrwx 1 root root       30 Dec 22 13:04 version.sh

drwxrwxrwx 2 root root        0 Dec 22 16:35 node_modules
-rwxrwxrwx 1 root root      594 Dec 22 13:03 package.json
-rwxrwxrwx 1 root root      818 Dec 30 11:04 SplitFrames.js

Below is what's in the main js file, SplitFrames.js
var execute = require('lambduh-execute');
var validate = require('lambduh-validate');

process.env['PATH'] = process.env['PATH'] + ':/tmp/:' + process.env['LAMBDA_TASK_ROOT']

exports.handler = function(event, context, callback) {
    var exec = require('child_process').exec;
    var cmd = 'ffmpeg -version';

    exec(cmd, function(error, stdout, stderr) {
        console.log(stdout);
        callback(null, stdout);
    });
}

I test the function in lambda and it outputs nothing. Wondering how to include the ffmpeg library with AWS and node js. Any help is greatly appreciated.

A: It's unclear what problem are you trying to solve, could you please add it to your question?
From the extension it seems your are using wrong platforms binary there -rwxrwxrwx 1 root root 40166912 Dec 22 11:50 ffmpeg.exe, Lambda is using Linux kernel version – 4.4.35-33.55.amzn1.x86_64 (http://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html).
Instead of that you could use this node module https://github.com/eugeneware/ffmpeg-static which should contain all three big platforms, Linux, Windows included (installing binaries from 3rd party sites isn't good practice).
Make sure you get the execution path correct.


text:
Q: PHP / MYSQL Change button text on condition I have the following simple function
function getAllJobs($userType)
{
    if ($userType == 2) {
        $sql = "SELECT * FROM jobs";
        $stmnt = $db->prepare($sql);
        $stmnt->execute();
        return $stmnt->fetchAll();
    } else {
        return false;
    }
}

The above produces the following page, via a simple foreach() loop:

WHAT I AM TRYING TODO
When a user ALREADY applied for a job displayed, I want the blue "Apply" button to change to something like "Applied"
Now I believe this can / should be achieved by changing the mysql query in my function above.
Here is a look at my database:

WHAT I TRIED
I tried changing my db query in getAllJobs() function as follows:
SELECT jobs.*, bids.*
        FROM bids
        INNER JOIN jobs on jobs.jobID = bids.jobID
        WHERE bids.jobID = jobs.jobID

The problem with the above query is it only returns the jobs which the specific user applied for.
Again what I am trying to achieve is to display ALL jobs where the user Already applied for a job change button text to "Applied" or something similar. The below image serves as an example of what I am trying to achieve.

Any help or advice much appreciated. Kindly drop me a comment should you need more information or code.
EDIT:
I should probably add my foreach code here:
  <?php
    foreach ($jobs as $job){
    $description = $job['description'];
    $jobDescription = substrwords($description, 30);
    echo '
' . $job['headline'] . '
';
    echo '
' . $jobDescription . '
';
    echo '
' . $job['datePosted'] . '
';
    echo '
' . $job['amount'] . '
';
    echo '
' . $job['location'] . '
';?>
    <?php
    echo '
';
    ?>
    <input type="text" value="apply" name="action" style="display: none" />

    <button name="placeBid" type="submit" class="btn btn-primary" value="<?php echo $job['jobID']; ?>">Apply</button>
    <?php echo '

';
    echo '
';
    }//foreach

A: Try this:
SELECT jobs.*, bids.*
FROM jobs
LEFT JOIN bids
    ON jobs.jobID = bids.jobID

A: Give this a shot.
Using this query you will get an "appliedFor" column with each job. If this is 1, the user has applied for the job. If it is 0 then the user has not applied for the job.
SELECT
  jobs.*,
  (COALESCE(bids.bidId, 0) > 0) AS appliedFor
FROM jobs
LEFT JOIN bids ON bids.jobID = jobs.jobID AND bids.userID = 1;

Before the explanation, see the test here: http://sqlfiddle.com/#!9/eb5a4f/1/0
It's quite simple really...

*

*Just do a LEFT JOIN on the bids table using the jobID and the userID. This means that if there is a corresponding row in the bids table bids.bidID will be numeric, otherwise it will be NULL.

*I then did a COALESCE on that column meaning if the value is NULL it would be changed to 0.

*Wrap the above in brackets and ensure that the result is more than 0. This gives you a boolean which can be aliased for your use in the query result.

I tested using the following schema:
CREATE TABLE jobs (
  jobID int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (jobID)
);

CREATE TABLE bids (
  bidID int NOT NULL AUTO_INCREMENT,
  userID int,
  jobID int,
  PRIMARY KEY (bidID)
);

INSERT INTO jobs () VALUES();
INSERT INTO jobs () VALUES();
INSERT INTO jobs () VALUES();
INSERT INTO bids (userID, jobID) VALUES(1, 1);
INSERT INTO bids (userID, jobID) VALUES(2, 1);
INSERT INTO bids (userID, jobID) VALUES(1, 3);

The PHP code to match up with this will look something like the following:
<?php
foreach ($jobs as $job){
    $description = $job['description'];
    $jobDescription = substrwords($description, 30);
    $buttonText = "Apply";
    if ($job['appliedFor']) { // This is where we're using the new value we've selected
        $buttonText = "Applied";
    }
    ?>

<?php echo $job['headline']; ?>

<?php echo $jobDescription; ?>

<?php echo $job['datePosted']; ?>

<?php echo $job['amount']; ?>

<?php echo $job['location']; ?>

        <input type="text" value="apply" name="action" style="display: none" />
        <button name="placeBid" type="submit" class="btn btn-primary" value="<?php echo $job['jobID']; ?>"><?php echo $buttonText; ?></button>

    <?php
}//foreach

P.s. I looked at your schema and it looked to me as if the bids table contained all of the job applications for specific users. If this isn't correct my example above will be incorrect.

A: You are using inner join where you get records that are common on both table
LEFT JOIN gets all records from the LEFT linked table but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL
  SELECT jobs.*, bids.*
            FROM jobs
            LEFT JOIN bids on jobs.jobID = bids.jobID

After this you can make condition based on null.

A: for a particular user whose id is $userID.so yuo can get null if he has not applied for that job and check if it is null than 0 else 1.check condition and change text according to condition.
i am writing query only.you will get data in $job than run this code.i hope it may help.
<?php
    $sql="SELECT a.*,b.*,if(b.bidID is null,0,1) as applied from jobs a left join bids b on a.jobID=b.jobID AND b.userID=$userID";

    foreach ($jobs as $job){
        $description = $job['description'];
        $jobDescription = substrwords($description, 30);
        echo '
' . $job['headline'] . '
';
        echo '
' . $jobDescription . '
';
        echo '
' . $job['datePosted'] . '
';
        echo '
' . $job['amount'] . '
';
        echo '
' . $job['location'] . '
';?>
        <?php
        echo '
';
        ?>
        <input type="text" value="apply" name="action" style="display: none" />

        <button name="placeBid" type="submit" class="btn btn-primary" value="<?php echo $job['jobID']; ?>"><?=$job['applied']=='1'?'Applied':'Apply'?></button>
        <?php echo '

';
        echo '
';
    }


text:
Q: How to replace selected text with stored text with JavaScript/jQuery? Let's say I have a textarea and I select some text (with my cursor):

Text
Text <-- selected text
Text

And lets say I have a variable called storedText. How do I got about to replace the selected text with the content of storedText?

Text
Stored Text <-- selected text
Text


text:
Q: Powershell 2.0 Get users for a local group How can I get user list from a local group? I only have PS 2.0 and it does not have Get-ADGroup command.
I can get local groups:
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$groups = $adsi.Children | Where { $_.SchemaClassName -eq 'Group' }
$group | ft Name

What I need is to list all the members for each group.

A: You can try the following
$obj = [ADSI]"WinNT://$env:COMPUTERNAME"
$admingroup = $obj.Children | Where { $_.SchemaClassName -eq 'group'} |  where {$_.name -eq 'Administrators'}
$admingroup.Invoke('Members') | % {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}
$admingroup.Invoke('Members') | % {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}

Here are the common properties
String :
Description, FullName, HomeDirectory, HomeDirDrive, Profile, LoginScript, ObjectSID

Integer :
UserFlags, PasswordExpired, PrimaryGroupID

Time :
PasswordAge

You'll find more in Microsoft documentation.

A: Try this
$computer = [ADSI]"WinNT://$env:COMPUTERNAME"

$computer.psbase.children | where { $_.psbase.schemaClassName -eq 'group' } | foreach {
    write-host $_.name
    write-host "------"
    $group =[ADSI]$_.psbase.Path
    $group.psbase.Invoke("Members") | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
    write-host
}

This doesn't give the domain though, hence i had to look for other ways, like:
If you want to see members of a local group quickly:
PS C:\> net localgroup USERS
Alias name     USERS
Comment        Users are prevented from making accidental or intentional system-wide changes and can run most applications

Members

-------------------------------------------------------------------------------
NT AUTHORITY\Authenticated Users
NT AUTHORITY\INTERACTIVE
The command completed successfully.

Now you can manipulate this output a bit to get what you need:
$computer = [ADSI]"WinNT://$env:COMPUTERNAME"

$groups = $computer.psbase.children | where { $_.psbase.schemaClassName -eq 'group' } | select -ExpandProperty Name

Foreach($group in $groups)
 {
  write-host $group
  write-host "------"
  net localgroup $group | where {$_ -notmatch "command completed successfully"} | select -skip 6
  Write-host
 }


text:
Q: Why am I getting `ZeroDivisionError: float division by zero` error? I want to find a function's x value at y=0.
from pynverse import inversefunc
from math import pi,sqrt
R=20
C=5*10**-9
L=5*10**-4
Z= (lambda x: sqrt(R**2+(1/(2*pi*C*x)-2*pi*L*x)**2))
inversefunc(Z,y_values=0)

But I get following error code:
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
inversefunc(Z,y_values=0)
File "C:\Python27\lib\site-packages\pynverse\inverse.py", line 113, in inversefunc
trend = np.sign(func(ref2, *args) - func(ref1, *args))
File "<pyshell#15>", line 1, in <lambda>
Z= (lambda x: sqrt(R**2+(1/(2*pi*C*x)-2*pi*L*x)**2))
ZeroDivisionError: float division by zero

Please help me why! Thank you.

A: You can inform that the answer is undefined when the divisor is 0, and you should use normal functions, not named lambdas in python.
from pynverse import inversefunc
from math import pi,sqrt

def Z(x):
    # Can define these globally if necessary.
    R = 20
    C = 5 * 10**-9
    L = 5 * 10**-4

    return sqrt(R**2 + (1/(2*pi*C*x) - 2*pi*L*x)**2))

try:
    inversefunc(Z, y_values=0)
except ZeroDivisionError:
    print("answer is undefined")


text:
Q: NServiceBus Unit of Work For Multitenancy with Custom ORM Here are my parameters:

*

*Simple NServiceBus Saga implementation using the default builder

*In-house ORM on top of SQL Server

*Multitenancy - I have two ASP.NET MVC 4 domains running on the same website, each with their own databases

We configure our ORM using a static method like so:
public class EndpointConfig: IConfigureThisEndpoint, IWantCustomInitialization {
  public void Init() {
    var bus = Configure.With()
      .AutofacBuilder()
      .UnicastBus().LoadMessageHandlers().DoNotAutoSubscribe()
      .XmlSerializer()
      .MsmqTransport().IsTransactional(true).PurgeOnStartup(false)
      .MsmqSubscriptionStorage()
      .Sagas().RavenSagaPersister().InstallRavenIfNeeded()
      .UseInMemoryTimeoutPersister()
      .CreateBus()
      .Start();

     SlenderConfiguration.Init(bus);
  }
}

public class SlenderCofnigruation {
  private static ORMScope scope { get; set; }

  public static void Init(IBus bus)
  {
    ORMConfig.GetScope = () =>
    {
       var environment = "dev";
       if (bus.CurrentMessageContext.Headers.ContainsKey("Environment"))
         environment = bus.CurrentMessageContext.Headers["Environment"];

       if (scope == null)
         scope = new SlenderScope(ConfigurationManager.ConnectionStrings[environment].ConnectionString);
      return scope;
    };
  }
}

This works fine in our single-tenant Beta environment - it's fine for that static scope to get re-used because the environment header is always the same for a given deployment.
It's my understanding that this won't work for the multitenant situation described above, because NServiceBus will reuse threads across messages. The same scope would then be used, causing problems if the message was intended for a different environment.
What I think I want is a single scope per message, but I'm really not sure how to get there.
I've seen Unit Of Work Implementation for RavenDB, and the unit of work implementation in the full duplex sample, but I'm not sure that's the right path.
I've also seen the DependencyLifecycle enum, but I'm not sure how I can use that to resolve the scope given the way I have to set up the GetScope func.
Obviously I have no idea what's going on here. Any suggestions?

A: If you need to do something on a per-message basis, consider using message mutators (IMutateIncomingMessages) in addition to your unit-of-work management with some thread-static state.


text:
Q: Is there a python function that determines if a vector is in a convex hull of other vectors I am looking for a function in Python that would tell me if a given vector in 3D is in the convex hull of other vectors, i.e. if the vector can be represented as a convex combination of a set of vectors.
I have only found a function that solves the linear equation for a full rank matrix, using np.linalg.solve() function. In my case the vectors in the convex hull could be linearly dependent, so this approach doesn't work.
Here is random data example generated in 3D:
import numpy
mat = np.random.rand(15,3)
vec = np.random.rand(1,3)

I am looking for either a convex solution for the problem:
convex_sol(mat,vec) = [0.2,0.3,0.4]

or a boolean solution that returns True is vec is in the convex hull of mat, and False otherwise.


text:
Q: Qgis - Projection Problem with EPSG:2272 I work in both Qgis and ArcGIS.  Most of my data has been created using ArcGIS and all of my data should be in the EPSG:2272.  When I add my data to Qgis, it does not recognize my projection and gives it a user:100000 projection.  Below is a comparison from the first part of projection files from ArcGIS and Qgis.  As you can see the beginning section of each file is slightly different.  Is this causing Qgis to not recognize my projection correctly?  How can I fix it so my projections are recognized in both ArcGIS and Qgis?
from ArcGIS
PROJCS["NAD_1983_StatePlane_Pennsylvania_South_FIPS_3702_Feet",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],
from GIS
PROJCS["NAD83_Pennsylvania_South_ftUS",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137,298.257222101]],

A: This is an old quarrel between ESRI and GDAL about projection names.
If you create a project with layers in EPSG:2272, an additional .qpj file will be created that contains the EPSG code number. Once you have done this, QGIS will always look into that file and not into the .prj from ESRI (without EPSG number).
In QGIS, you can safely use Rightclick -> Set CRS for layer to assign EPSG:2272 to it. Once you save the layer, QGIS can rely on the .qpj file, even if you get a newer version of the file from the ARCGIS world.

A: *

*From ArcGIS is the crs ESRI WKT version (SpatialReference.org, EPSG.io)

*From QGIS is the official crs OGC WKT version (EPSG.io)

These ESRI WKT definitions are not all supported by other GIS or libraries (depending of your version of GDAL)


text:
Q: vue3 - Update state in onBeforeRouteUpdate() I'm a newbie and working with translation software, thanks for the guidance.
I have a routing component that updates count in onBeforeRouteUpdate() every time I navigate, it works fine, but the onUpdated() hook is called twice, I don't understand why, is there any way to avoid it
code:
<template>
  <div>{{count}}</div>
</template>

<script setup>
import { ref, onUpdated } from 'vue'
import { onBeforeRouteUpdate } from 'vue-router'

const count = ref(0)
onUpdated(() => console.log('updated'))

onBeforeRouteUpdate((to, from) => {
  count.value += 1
})
</script>

output twice in the console
[1]: https://i.stack.imgur.com/bfCEx.png


text:
Q: Passing functions which have multiple return values as arguments in Python So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.
a = [[1,2],[3,4]]

def cord():
    return 1, 1

def printa(y,x):
    print a[y][x]

printa(cord())

...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.
Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?

A: Try this:
>>> def cord():
...     return (1, 1)
...
>>> def printa(y, x):
...     print a[y][x]
...
>>> a=[[1,2],[3,4]]
>>> printa(*cord())
4

The star basically says "use the elements of this collection as positional arguments."  You can do the same with a dict for keyword arguments using two stars:
>>> a = {'a' : 2, 'b' : 3}
>>> def foo(a, b):
...    print a, b
...
>>> foo(**a)
2 3

A: printa(*cord())

The * here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.
It's basically the reverse of the * you might use to capture all non-keyword arguments in a function definition:
def fn(*args):
    # args is now a tuple of the non-keyworded arguments
    print args

fn(1, 2, 3, 4, 5)

prints (1, 2, 3, 4, 5)
fn(*[1, 2, 3, 4, 5])

does the same.

A: Actually, Python doesn't really return multiple values, it returns one value which can be multiple values packed into a tuple. Which means that you need to "unpack" the returned value in order to have multiples.
A statement like
x,y = cord()

does that, but directly using the return value as you did in
printa(cord())

doesn't, that's why you need to use the asterisk. Perhaps a nice term for it might be "implicit tuple unpacking" or "tuple unpacking without assignment".


text:
Q: Can't find GNU nano global config I install GNU nano 2.7.5 editor from source on my CentOS 6.5
./configure --prefix=/usr
make
make install

Now I try to locate global nanorc file but can't find any, then I create new /etc/nanorc but it seems that nano doesn't read it. How & Where shoud I create this file? Is there any nono command that can help me locate where this file should be? (Yes I know that I can create ~/.nanorc but I need it global not local)
I don't see any other problems with this fresh installed nano editor.
//EDIT//
I reinstal nano from source using, but /etc/nanorc still doesn't work
./configure --prefix=/usr     \
            --sysconfdir=/etc \
            --enable-utf8     \
            --docdir=/usr/share/doc/nano-2.7.5

A: It's unfortunate this relatively simple answer didn't receive a satisfactory answer for four years. Hopefully OP is still around to take a look.
The location of any program config file depends on its install path, or more accurately, its install prefix. The binary goes in <prefix>/bin, and it would look for <prefix>/etc/<name-of-config-file> on startup, unless otherwise configured.
Therefore if you installed with --prefix=/usr, then your nano binary would be /usr/bin/nano, and its global config file would be /usr/etc/nanorc.
Similarly, if you installed with --prefix=/usr/local (which I recommend for locally compiled programs; also default), your global config file would be /usr/local/etc/nanorc.
Tested with CentOS-7_5.4.72_aarch64 & nano-5.7 on Raspberry Pi-4.

A: normally when you install a program from source, its config file will be at the place where its installed ,somewhere like "/usr/src" or "/opt"
you can change that whene you run ./configure
take a look at the file named "INSTALL" in tar file of nano source

By default, make install' installs the package's commands under
  /usr/local/bin', include files under /usr/local/include', etc.  You
  can specify an installation prefix other than/usr/local' by giving
  configure' the option--prefix=PREFIX', where PREFIX must be an
  absolute file name.


text:
Q: What's the AWS SDK V2 class for Lambda S3Event? For the Java SDK V1, I have a lambda function like this:
public static void doSomethingLambda(S3Event s3Event) throws Exception {
    s3Event....

however in SDK V2, S3Event does not seem to exist. Unless I am using the wrong dependency? (The docs for V2 are pretty sparse)
Here is my SDK V1 Dependencies:
  <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-events</artifactId>
        <version>1.3.0</version>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-s3</artifactId>
        <version>1.11.534</version>
    </dependency>

and SDK V2:
 <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>s3</artifactId>
    </dependency>
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>lambda</artifactId>
    </dependency>

A: According to the resolution provided on 18 May for aws lambda java libs to aws sdk java v2
aws-lambda-java-events version 3.0.0 was just released with support for all events (including S3) without the inclusion of SDK v1 dependencies.
This should help you make use of the AWS SDK for Java v2 and reduce your function package size as the v1 SDK does not need to be bundled anymore if it's not explicitly needed.

Source code is here


text:
Q: Renaming a few columns in a data frame: Why doesn't ifelse with %in% operator preserve order? This is in reference to this question.
I'd like to rename a subset of columns in a large data frame. I'd expect the following code to rename columns X4,X5,X6 and X7 to gradek, grade1, grade2, and grade3 respectively:
set.seed(1)
in.df <- data.frame( matrix( rnorm(60), ncol=10) )
names(in.df) <- ifelse( names(in.df) %in% c('X4', 'X5', 'X6', 'X7'),
                         paste('grade', c('k',1:3), sep=''),
                         names(in.df) )

However,
> names(in.df)
 [1] "X1"     "X2"     "X3"     "grade3" "gradek" "grade1" "grade2" "X8"
 [9] "X9"     "X10"

even though
> paste('grade', c('k',1:3), sep='')
[1] "gradek" "grade1" "grade2" "grade3"

showing that the order isn't preserved. This thread, suggests that using match instead of %in% would work, but in this case it does not. ( Perhaps that was true in other versions of R. In my installed version (2.15.3), the help page on match suggests that %in% is defined via match so switching it up would be of no help. )
Any help would be appreciated!
Accepted answers
This answer fixes my renaming problem.
This answer explains the weird behavior is due to recycling.

A: %in% should work, but perhaps match is better.
Consider the following. "A" and "B" represent your names(in.df). We want to replace the values in "matchme" in that order using the results of paste('grade', c('k',1:3), sep='').
Compare the different output:
A <- B <- c("X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9", "X10")
matchme <- c('X4', 'X7', 'X6', 'X5')
A[A %in% matchme] <- paste('grade', c('k',1:3), sep='')
A
#  [1] "X1"     "X2"     "X3"     "gradek" "grade1" "grade2" "grade3" "X8"
#  [9] "X9"     "X10"
B[match(matchme, B)] <- paste('grade', c('k',1:3), sep='')
B
#  [1] "X1"     "X2"     "X3"     "gradek" "grade3" "grade2" "grade1" "X8"
#  [9] "X9"     "X10"

A: Ananda's answer gives a good approach of how to do what you want. I will instead answer the question as to why you got the results you did rather than the ones you expected.
The reason the names seem out of order is related to how ifelse works and argument recycling.  Let's look at the three arguments to ifelse:
> list(names(in.df) %in% c('X4', 'X5', 'X6', 'X7'),
+      paste('grade', c('k',1:3), sep=''),
+      names(in.df))
[[1]]
 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE

[[2]]
[1] "gradek" "grade1" "grade2" "grade3"

[[3]]
 [1] "X1"  "X2"  "X3"  "X4"  "X5"  "X6"  "X7"  "X8"  "X9"  "X10"

ifelse decides which corresponding element to pick based on whether the first argument is TRUE or FALSE. But the second argument is not as long as the first, so it is recycled to be the right length. Putting these into a data.frame so that looking at them side-by-side is easier, and manually expanding out the second set of names, gives:
> data.frame(test = names(in.df) %in% c('X4', 'X5', 'X6', 'X7'),
+            `TRUE` = rep(paste('grade', c('k',1:3), sep=''),length=10),
+            `FALSE` = names(in.df))
    test  TRUE. FALSE.
1  FALSE gradek     X1
2  FALSE grade1     X2
3  FALSE grade2     X3
4   TRUE grade3     X4
5   TRUE gradek     X5
6   TRUE grade1     X6
7   TRUE grade2     X7
8  FALSE grade3     X8
9  FALSE gradek     X9
10 FALSE grade1    X10

So the 4th, 5th, 6th, and 7th elements of the new names are used, which correspond, due to argument recycling, to the 4th, 1st, 2nd, and 3rd.


text:
Q: Adding code to Entity Framework 6 model that runs whenever a new model context is instantiated I'm using EF6 and the latest build of the SQLite EF6 provider.  There's a PRAGMA statement that I need to be executed whenever a new  model context is instantiated and the connection opened.
Does EF6 have some mechanism that allows me to do this? Or am I going to be modifying my code everywhere that the model is used to check the PRAGMA and set it to the desired value?  Note that there is no connection string property that corresponds to this PRAGMA or I'd do it there.
EDIT
In the interests of completeness, this is not a code-first model.  It's a database first model.  I know that the context class is a partial.  Could add a custom constructor in a partial file for the context and then I just need to call it instead of the default constructor?

A: The actual problem is that you need to run a PRAGMA each time a connection is opened, not when a context is created. A PRAGMA statement or any SQL statement can only be executed after a connection opens. This happens when you explicitly call Open or implicitly when you save changes.
You can attach an event handler to the Connection.StateChange event, as shown in this SO question:
db.Connection.StateChange += ConnectionStateChange;

void ConnectionStateChange(object sender, System.Data.StateChangeEventArgs e)
{
    if (e.CurrentState == System.Data.ConnectionState.Open)
         db.ExecuteStoreCommand("PRAGMA foreign_keys = true;");
}


text:
Q: How to get mask from numpy array according to all values on third axis I have numpy array like:
A = np.zeros((X,Y,Z))

Later I fill the array with values and I need to find x,y coordinates according to values in arrays on z axis to replace it with different array.
Example withZ=2 I have array
A = [ [ [1,2], [2,1], [0, 0] ],
      [ [1,1], [1,1], [0, 0] ], ]

I need something like
A[ where A[x,y,:] == [1,2] ] = [2,1]

What will produce array
A = [ [ [2,1], [2,1], [0, 0] ],
      [ [1,1], [1,1], [0, 0] ], ]

Is it possible to achieve that somehow simple? I would like to avoid iteration over the x,y coordinates.

A: One vectorized approach -
A[(A == [1,2]).all(-1)] = [2,1]

Sample run -
In [15]: A
Out[15]:
array([[[1, 2],
        [2, 1],
        [0, 0]],

       [[1, 1],
        [1, 2],
        [0, 0]]])

In [16]: A[(A == [1,2]).all(-1)] = [2,1]

In [17]: A
Out[17]:
array([[[2, 1],
        [2, 1],
        [0, 0]],

       [[1, 1],
        [2, 1],
        [0, 0]]])


text:
Q: IList, IEnumerable and ObservableCollection I have two classes defined like
public class PostleitzahlList : ObservableCollection<Postleitzahl> {
}

public class Postleitzahl : IPostleitzahl {
}

Now I have a Service-Class which contains
PostleitzahlList _postleitzahlList;

This Serviceclass has also to implement a Property of a Service-Interface which returns _postleitzahlList - but this Interface only knows IPostleitzahl - it doesn't know PostleitzahlList or Postleitzahl. this Property should be used for Binding in WPF.
I am trying now to declare and implement this Property. I have tried
    public ObservableCollection<IPostleitzahl> PostleitzahlList {
        get { return this._postleitzahlList; }
    }

and
    public IList<IPostleitzahl> PostleitzahlList {
        get { return this._postleitzahlList; }
    }

But both does not work.
The fallowing seems to work:
    public IEnumerable<IPostleitzahl> PostleitzahlList {
        get { return this._postleitzahlList; }
    }

I ask me now
1. why does the first and second try not working?
2. what is the best solution to solve this?

A: The problem is with covariance. An ObservableCollection<Postleitzahl> isn't an ObservableCollection<IPostleitzahl>, and ditto with lists. Here's an example of why not:
ObservableCollection<string> strings = new ObservableCollection<string>();

// This is invalid, but it's what you're trying to do, effectively.
ObservableCollection<object> objects = strings;

// This would have to work... it's fine...
objects.Add(new object());

// And this should be fine too...
string x = strings[0];

... but as you can see, you're now trying to fetch a non-string reference and store it in a string variable. The only viable outcome would be an execution-time failure... and half the point of generics is to push error detection to compile-time.
Now IEnumerable<T> is covariant in T because you can't add any items via it - that makes it safe to apply that sort of conversion:
// There's nothing you can do to violate type safety here...
Observable<string> strings = new ObservableCollection<string>();
IEnumerable<object> objects = strings;

For more information, read up on covariance and contravariance in generics in MSDN.
Do you need the IPostleitzahl interface? If you just exposed the properties via ObservableCollection<Postleitzahl> or IList<Postleitzahl> it would be fine. Alternatively, you could change your variable to be an ObservableCollection<IPostleitzahl> and just happen to populate it by creating Postleitzahl instances.

A: can you change PostleitzahlList to
public class PostleitzahlList : ObservableCollection<IPostleitzahl> {
}

with elementtype IPostleitzahl instead of Postleitzahl?
for explanation see @jon skeet answer


text:
Q: R Newbie...calculating averages I'm very new to R and I'm still quite close to the bottom of the very steep learning curve I think. So...
I have a data frame (imported from a .csv file). Contains a number of fields - let's call them Field1, Field2, Field3... Field 10.
The fields are numeric. For each row of data I'd like to calculate the average of the lowest 3 (say) numbers. In other words:
((smallest number) + (second smallest number) + (third smallest number))/3
Also there are some NAs in the data so I'd like the calculation to return NA if there aren't actually three numbers to avarage over (although perhaps R will do this naturally anyway).
Is there a succinct way to do this in R and (better still) to store the result as a new field in the existing data frame?
Grateful for any advice.
Thanks.
A

A:  data(mtcars)

 avg3 <- sapply(mtcars, function(x) mean(head(sort(x[!is.na(x)]), 3)))

 avg3

 mtcars.avg3 <- rbind(mtcars, avg3)

 mtcars.avg3

A:
For each row of data I'd like to calculate the average of the lowest 3 (say) numbers.

I think this should achieve what you're asking:
data <- mtcars
data$low.mean <- apply(data, 1, function(x) mean(head(sort(x[!is.na(x)]), n = 3)))


text:
Q: "..." notation in append() doesn't work for appending different type slices I need an abstracted slice that contains multiple types. The most simplified code is this:
package main

import "fmt"

type A interface{}

type X string

func main() {
    sliceA := make([]A, 0, 0)
    sliceX := []X{"x1", "x2"}
    var appendedSlice []A
    appendedSlice = append(sliceA, sliceX[0], sliceX[1])  // (1) works
    appendedSlice = append(sliceA, sliceX...)             // (2) doesn't work
    fmt.Println(appendedSlice)

}

In my real program, the interface A defines some functions, and X and also other types implement it.
Line (2) raises an error cannot use sliceX (type []X) as type []A in append.
I thought (2) is a syntax sugar for (1), but I'm probably missing something... Do I have to always add an element X into slice A one by one?
Thank you guys in advance!

A: The problem is that interface{} and string are two different types.
To convert a slice from string to interface{} you will have to do it in one of the following ways:
create sliceA and initialize its size to sliceX length
sliceA := make([]A, len(sliceX))
for ix, item := range sliceX {
    sliceA[ix] = item
}

dynamically append sliceX items to appendedSlice
var appendedSlice []A
for ix := range sliceX {
    appendedSlice = append(appendedSlice, sliceX[ix])
}

Please read more here
Convert []string to []interface{}


text:
Q: How to keep the session alive while subscribing push topic using lightning empApi? I have a requirement to subscribe to push topic for which i have implemented using lightning empApi and have open the browser in a VM for continuous reading of events and do some actions. The issue is with session settings and i am getting logged out after session timeout stating - You've been logged out due to inactivity.
Is there a way to keep listening to the push topic and avoid this message?


text:
Q: Finding the ranges values of k The profit per day, in RM, of a shop is given by P = n^2-10n+k+45, where k is a constant and n is the number of products sold by the shop. Find the range of values of k if the shop must earn the profit at least RM 600 per day.
This was a question set in my Additional Mathematics examination. I have tried it many times, but  I still couldn't get the answers. Hope you can help me. Thank you.

A: I would read the question to require that the profit be at least $600$ regardless of the value of $n$.  The worst case is when $n^2-10n$ is minimized, which comes at $n=5$.  In that case the profit is $k+20$, so we must have $k \ge 580$


text:
Q: how to find an element value in xml when we have multiple namespaces I want to get the value of the element rsm:CIIHExchangedDocument/ram:ID
But I have problem with multiple namespaces, and null values (I can not know if requested element exists)
It can be achieved this way:
XElement invoice = XElement.Load(invoiceStream);
XNamespace rsm = invoice.GetNamespaceOfPrefix("rsm");
XNamespace ram = invoice.GetNamespaceOfPrefix("ram");
if ((invoice.Element(rsm + "CIIHExchangedDocument")) != null)
{
    if (invoice.Element(rsm + "CIIHExchangedDocument").Element(ram + "ID") != null)
    {
        string id = invoice.Element(rsm + "CIIHExchangedDocument").Element(ram + "ID").Value;
    }
}

but I think using xPath will suit my needs better. I want to do something like this:
invoice.XPathSelectElement("rsm:CIIHExchangedDocument/ram:ID"):

I need to retrieve a lot of elements of different depth in the document, and I have many namespaces.
What is the simplest whay to achive this? Execution speed is also important to me.

A: I believe what you are looking for is the XPathNavigator class.  An example of how to use can be found here XpathNaivigator


text:
Q: How can I make SQL Server 2019 pretend that a stored proc is in progress? I have a stored procedure that refreshes several tables in my reporting database from my live production database.
I run:
EXEC Reporting.dbo.RefreshTemps

This stored proc is super simple, all it does is truncate several tables and then runs an INSERT INTO them to get a refreshed snapshot of data. It takes around 10 minutes to complete as they're pretty chunky tables.
However, many people, processes or other procedures might want to use this procedure during the day. It's entirely plausible that User A may start the proc running then User B starts the same proc running before User A's run has completed.
This would mean once User A's proc completed, user B's proc would be in the process of truncating and refreshing the same tables. Which would be bad.
Ideally, SQL would not run User B's proc, wait for User A's run to complete and both User A and User B would be exposed to the updated tables at the same time.
Is there a way I can fool SQL into thinking that User B's proc is running normally, but what it's actually doing is waiting for User A's run to complete?

A: The simplest thing to do here is to use a SQL Server Agent job.  You can start a job with sp_start_job, and only one copy of a job can run at any time.
Like Dan Guzman suggested you could also use sp_getapplock.  But you'd probably want to use session locks, otherwise your long-running job would have to run in a transaction.  And session locks can be tricky.  It's easy to get a blocked process.  Anyway it might look something like this:
create or alter procedure ThereCanBeOnlyOne @sql nvarchar(max)
as
begin

  --hash the sql batch to generate the app lock name
  declare @lockname nvarchar(255) =  concat('lock_',convert(nvarchar(255), hashbytes('MD5', @sql) , 1));
  print @lockname

  declare @result int
  --request an applock with an immediate timeout
  exec @result = sp_getapplock @Resource=@lockname, @LockMode='Exclusive',@LockOwner='Session',@LockTimeout=0
  if @result = -1 --lock timeout procedure is already running
  begin
     --wait for other session to finish and return
     exec sp_getapplock @Resource=@lockname, @LockMode='Exclusive',@LockOwner='Session';
     exec sp_releaseapplock @Resource=@lockname, @LockOwner='Session';
     print 'batch completed in another session';
     return 0;
  end
  begin try
    --actually run the batch
    exec (@sql);
    exec sp_releaseapplock @Resource=@lockname, @lockOwner='Session';
    print 'batch completed in this session';
    return 0;
  end try
  begin catch
       if (APPLOCK_MODE('public', @lockname, 'Session') = 'Exclusive')
        exec sp_releaseapplock @Resource=@lockname, @lockOwner='Session';
       throw;
  end catch

end


text:
Q: principal.getName() throws NullPointer in a RestController Post method I need to access the currently logged in user in one of my methods. I am using spring security and i am positive that when there is a logged in user and the javascript sends a POST request to the RestController the principal throws NullPointerException. Here is the Spring Security configuration
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private IUsersService usersService;

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(usersService);
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/",
                    "/css/**",
                    "/static/**",
                    "/api/**",
                    "/home",
                    "/register",
                    "/forgot-password",
                    "/api/createArena")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .defaultSuccessUrl("/dashboard", true)
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/register", "/api/createArena");
  }

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(usersService)
            .passwordEncoder(passwordEncoder());
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
}

Here is the RestController responsible for the handling of the POST method in mind. The curious thing is that i have tested the first GET method and the principal there is not null and shows the correct currently signed in user.
@RestController
@RequestMapping("/api")
public class ArenasController {
  private final IArenasService arenasService;
  private final IUsersService usersService;

  @Autowired
  public ArenasController(IArenasService arenasService,
                          IUsersService usersService) {
    this.arenasService = arenasService;
    this.usersService = usersService;
  }

  @RequestMapping(value = "/arena/{id}", method = RequestMethod.GET)
  @ResponseBody
  public Arena getArena(@PathVariable String id) {
    return this.arenasService.getArena(Integer.parseInt(id));
  }

  @RequestMapping(value = "/createArena", method = RequestMethod.POST)
  @ResponseBody
  public Arena createArena(@RequestBody Arena arena, Principal principal) {
    String userEmail = principal.getName(); // Here is the exception thrown
    User user = this.usersService.getUserByEmail(userEmail);
    Arena created = this.arenasService.createArena(arena);
    if(created.getId() != 0){
      this.usersService.installationCompleted(user);
    }

    return created;
  }
}

Here is the stack trace:
java.lang.NullPointerException: null
    at hristian.iliev.airsofter.controllers.rest.ArenasController.createArena(ArenasController.java:42) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:209) ~[spring-security-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_161]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_161]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_161]

I have been researching and i know that there are other questions like that but none of the solutions work for my case. Thank you in advance.


text:
Q: SIEMENS PLC S7 1200 TOF issue Let's say I have a Boolean input which can switch its state automatically. Swichting from 0 to 1 and from 1 to 0 sets a cycle. To determine if that cycle is valid, the cycle time must be at least 10 seconds.
I can determine if one semicicle is invalid, but I can't figure out how could to be able to determine at the end of the cycle if it has been invalid.
This is what I have:

A: You seem to be saying if the status of the input signal is not stable for 10 seconds, you have an invalid cycle and you want to check for that.
To do that, you obviously need a timer triggered by each transition. (I'm not specifically familiar with your PLC but they're all pretty similar so I'll assume that's what you have, and you appropriately have two, triggered on different transitions.
The invalid transition condition for positive-transition is:
        positive_input_transition_timer_q and  not  input

That is, the timer must be running and the input must go to the wrong state.
Now, the input might spike low then go high again immediately; you probably don't want lose the fact that you had an invalid transition.  So what you really want to do is latch the detection of invalid transition.
I'm not good at pretty ladder logic graphics so I'll write in old style:
   --+----[ ]----[TON]----+------[/]-----[/]------( )------
     |   Input  Positive  |     Unlatch  Input  Invalid
     |         Transition |     Invalid         Positive
     |                    |     Positive        Cycle
     +--------[]----------+     Cycle
            Invalid
            Positive
            Cycle

A corresponding ladder rung is needed for negative transition.
Presumably, some other bit of code will notice the InvalidPositive, respond appropriately, and then unlatch the condition.


text:
Q: boundary for arbitrary property path in SPARQL 1.1 Is it possible to bound the length of property path? For example getting all the triples with lengths that are between (m,n) or all that are not between this range?  For instance, how could this be done with the following query?
select ?x ?y
where {?x p* ?y}

A: Some endpoints support this directly
Some SPARQL engines support a method for doing this directly, with a regular-expression-like syntax.  E.g.,
?s :p{n,m} ?o

would be a path with a length between n and m.  That syntax is described in SPARQL 1.1 Property Paths: W3C Working Draft 26 January 2010.  There is also support for exact lengths, minimum lengths, and maximum lengths.  For better of for worse, that syntax didn't make it into the final SPARQL 1.1 standard.  Some SPARQL endpoints will still accept it though, so it's worth trying.
A general workaround
But there is a workaround.  The idea is to split the candidate path into two parts.  By checking how many ways it can be split into two parts, you can find the length of the path.  That is, you do something like this to, for instance, find ?s and ?p where they are joined by a path of length ten:
select ?s ?o {
  ?s :p* ?mid .
  ?mid :p* ?o .
}
group by ?s ?o
having (count(?mid) = 10)

Be sure to check the actual counts if you use this approach.  It's easy to get an off-by-one (or -two) error depending on how you want to calculate length.  There are a few options (whether to count the properties or the nodes, whether to count the endpoints or not, etc.), so a little bit of experimentation is worth while.
References and Examples
For some more examples of how you can use this pattern, have a look at:

*

*Is it possible to get the position of an element in an RDF Collection in SPARQL?

*Calculate length of path between nodes?