text:
Q: Show that $a^6-1$ is divisible by $168$ whenever $(a,42)=1$. I have been running into this type of problem a lot:

Show that $a^6-1$ is divisible by $168$ whenever $(a,42)=1$.

First of all, by Euler's theorem, we have that
$$a^{\phi(42)}\equiv a^{12}\equiv1\pmod{42}.$$
Notice that
$$a^6a^6\equiv1\pmod{42}\text{ and }168=4\cdot42.$$
It follows that
$$a^{12}\equiv1\pmod{168},$$
$$a^{12}-a^6\equiv1-a^6\pmod{168},$$
$$a^6(a^6-1)\equiv1-a^6\pmod{168},$$
$$a^6-1\equiv a^6(1-a^6)\pmod{168},$$
$$a^6-1\equiv a^6-a^{12}\pmod{168}.$$
I get stuck here: How can I show that the RHS is congruent to zero modulo $168$?

A: By Fermat's Theorem, $a^6\equiv 1 \pmod 7$.  Also by Fermat's Theorem, or otherwise, $a^2\equiv 1 \pmod 3$.  Thus $a^6\equiv 1 \pmod 3$.  So far, we have that
$$a^6\equiv 1 \pmod {21}.$$
But $a$ is odd, so $a^2\equiv 1 \pmod 8$. It follows that
$$a^6 \equiv 1 \pmod {8}.$$
Now it's over.

A: Hint $\ $ Either apply Carmichael's generalization of Euler-Fermat, or proceed directly via
$$\rm A^{N_j}\equiv 1\ \ (mod\ M_j)\ \Rightarrow\ A^{lcm\ N_j}\equiv 1\ \ (mod\ lcm\ M_j)$$
for $\rm \begin{cases}\rm \:N = (2,2,6)\\ \rm M = (8,3,7)\end{cases}\, $ by CCRT. That's what Andre does. It's worth emphasis it's general form.


text:
Q: Elementary set theory - Confused about A $\cup$ B = B I am trying to solve:
Proof that  $\exists!A\subset U(\forall B \subset U(A \cup B = B)$.
But once I think about it, I can see not one but 2 solutions.
a) $ \varnothing \cup B = B $
b) $ B \cup B = B $
The solution is supposed to be a), what is wrong about b)?
Thanks!

A: What's wrong with b) is that the question asks you to find some subset $A$ of $U$ such that, for each subset $B$ of $U$, $A\subset B$. Saying that the answer is $B$ makes no sense. What is $B$? On the other hand, $\emptyset$ makes sense (and it is correct since, indeed, $\emptyset\subset B$, for each $B\subset U$).
It's like someone asks you whether there is a natural number $n$ such that $n\leqslant m$ for each natural number $m$. Would you say that an answer is $m$? I guess not. I suppose that you would say that the answer is $1$ (or $0$, if, for you, $0\in\mathbb N$).

A: It needs to work for all possible sets $B$.  Not just one specific $B$.
For example: if $U =\mathbb R$ the we need to find an $A$ so that $A \cup B = B$ for ALL $B$.  So for example $A \cup [5, 7.3) = [5, 7.3)$ and $A \cup \mathbb Q = \mathbb Q$ and $A \cup \{-27, 0, \sqrt{\pi}, e^{-\frac 23}\}= \{-27, 0, \sqrt{\pi}, e^{-\frac 23}\}$.
It should be clear from those examples that the only possible set that will do that is $A = \emptyset$.
We can formally prove that.  But notice because $A\cup [5,7.30)  = [5,7.30)$ then $2 \not \in A\cup [5,7.3)$ so $2 \not \in A$ and $A \cup \{-27, 0, \sqrt{\pi}, e^{-\frac 23}\}= \{-27, 0, \sqrt{\pi}, e^{-\frac 23}\}$ so $5\frac 12 \not \in A \cup \{-27, 0, \sqrt{\pi}, e^{-\frac 23}\}= \{-27, 0, \sqrt{\pi}, e^{-\frac 23}\}$ so $5\frac 12 \not \in A$, etc.  Can anything be in $A$?  Well, no because.... if $x \in U$ then $A\cup \{x\}^c = \{x\}^c$ and $x \not \in A\cup \{x\}^c$ so $x \not \in A$.
=====
By the way.  Using your incorrect  interpretation of the question: If $B\subset U$ then show there exists a $A$ so that $A \cup B = B$. (a different question than what was asked.) Then the answer to that can be any subset of $B$.  Not just $\emptyset$ or $B$ but for any $A \subset B$ then $A \cup B = B$.
But that's an entirely different question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issues in Use of performSelectorOnMainThread in every millisecond I wanna show the amplitude of real time sound on a UIView by graph.
I set sound sample rate as 1000 in a second.
And, To Update Graph, I did like this. this is called in every millisecond.
[Audio performSelectorOnMainThread:@selector(updateGraph) withObject:nil waitUntilDone:NO];

and inside of updateGraph is like this.
- (void) updateGraph{
    [graphview setNeedsDisplay];
}

But it draws graph angularly.
http://achievstar.tistory.com/234
(I'm new in this site so i couldn't upload pictures)
(I guess) it is because of the "waitUntilDone:NO".
iphone 4S and also iPad2 couldn't catch up the rate of 1000.
I also tried "YES" for "waitUntilDone". It draws rightly,
http://achievstar.tistory.com/234
(see the below figure)
but also, the devices couldn't catch up with the rate of 1000,
so in this way, graphing speed was slow.
is there a way to fix the graph better?
I'm really stock here that i couldn't even find good solution any more.

A: performSelectorOnMainThread function is mainly used when you are on the background thread and you want to get back on the main thread or you want to perform a function on main thread.
if you are not using any thread or background thread then there is no need to use the performSelectorOnMainThread function. you can directly call that function.
try calling the updateGraph by using simple self.
i.e [self updateGraph]; and then see the result..

A: I Just Got a Answer on my own!
I was getting sound input in every millisecond,
and within' it I also updated graph in every millisecond too.
that means I updated every fixel of 480 in a millisecond.
I thought i should update graph immediately when i get sound input,
to show graph smoothly.
But I was wrong. That was not necessary to update every fixel.
Because It really takes a lot of process.
So I changed the code to update UI not in every millisecond. and it works really well.


text:
Q: Update полей в разных таблицах в одном запросе Есть 2 связанных таблицы:
CREATE TABLE rooms
(
    id          INT NOT NULL AUTO_INCREMENT,
    room_status INT NOT NULL,
    room_price  INT,
    delete_time DATE,
    PRIMARY KEY (id)
);

CREATE TABLE bookings
(
    id          INT  NOT NULL AUTO_INCREMENT,
    room_id     INT  NOT NULL,
    user_id     INT  NOT NULL,
    start_date  DATE NOT NULL,
    end_date    DATE NOT NULL,
    delete_time DATE,
    PRIMARY KEY (ID),
    FOREIGN KEY (room_id) REFERENCES rooms (id),
    FOREIGN KEY (user_id) REFERENCES users (id)
);

Мне необходимо реализовать обновление поля delete_time в обеих таблицах в едином запросе по room_id.
Я придумал такой запрос:
update rooms r, bookings b
set r.delete_time = sysdate(), b.delete_time = sysdate()
where r.id = 7 and r.id = b.room_id;

И он отлично работает, если на комнату есть хотя бы одно бронирование.
Но В случае, если бронирований на комнату нет, мне надо просто обновлять поле delete_time у комнаты. Как это можно реализовать?

A: Можно просто сделать LEFT JOIN:
UPDATE rooms AS r
  LEFT JOIN bookings AS b ON r.id = b.room_id
SET r.delete_time = sysdate(), b.delete_time = sysdate()
WHERE r.id = 7;


text:
Q: List blob storage by modified/upload date Is there a way to list anything newer/older than a certain date in blob storage only? Trying to avoid listing the full container as it grows.
This has been asked before pointing to various hacks. I'm hoping Microsoft added some functionality.


text:
Q: print multiple copies of a document Applescripting a printer's app I'm trying to automate some hard printing.
I already can print one copy of a document accessing the printer's app like this :
tell application "hp LaserJet 2300 series (BDB806)" --my printer's app, could be any other model
    print myFile
end tell

This snippet works.
But it becomes tricky when I try to print multiple copies. According to the printer's app dictionnary, I should be able to achieve it by doing :
tell application "hp LaserJet 2300 series (BDB806)"
    print myFile with properties {copies:n} -- n being an integer
end tell

But this doesn't work.
Please let me know what I'm doing wrong.

A: Happens the same to me with this code:
set d to ((path to home folder) as string) & "Desktop:" & "untitled.txt"
set n to 3
tell application "EPSON WP-4595 Series"
    print d with properties {copies:n}
end tell

Only one copy is printed.
As far as I know nothing is wrong with the code, maybe something is wrong with AppleScript..
Not very elegant but you could always do
...
    repeat n times
        print d
    end repeat


text:
Q: How to limit search results while using foreach and while loops The following code works well, but I couldn't find a way to limit the number of results. Any ideas please?
    $q = "some keywords for search"; // always escape
    $keys = explode( " ",$q );
    $query = "SELECT * FROM table WHERE para LIKE '%$q%' ";

    foreach($keys as $k)
    {
        $query .= " OR para LIKE '%$k%'";
    }

    $result = $mysqli->query($query);

    while( $row = $result->fetch_assoc())
    {
       if ($row != 0) {
       $title = $row['title'];
    }
    }

Any help while be appreciated.
Note: the $q holds the search keywords, and then the code explode it, and search for the keywords in 2 steps:
1- as one sentence using ($q as it is).
2- it searches for each keyword as an array after exploding the $q (here is the part that the "foreach" does).
After that the code loops using "while" to find all results match the search request.

A: Use LIMIT after completing your query.
Also, if you want to get results sorted by some fields in your table, you could also say " ORDER BY fieldname ASC|DESC"
As follows:
$q = "some keywords for search"; // always escape
$keys = explode( " ",$q );
$query = "SELECT * FROM table WHERE para LIKE '%$q%' ";

foreach($keys as $k)
{
    $query .= " OR para LIKE '%$k%'";
}

$query .= " LIMIT 10"; //<<<<<<<<<<<<<<<

$result = $mysqli->query($query);

while( $row = $result->fetch_assoc())
{
   if ($row != 0) {
   $title = $row['title'];
}

A: Use LIMIT.
SELECT * FROM table WHERE para LIKE '%$q%' LIMIT 2

A: You can limit the number of results in your MySQL query, like so:
$query = "SELECT * FROM table WHERE para LIKE '%$q%' LIMIT 5";

this will limit it to 5 results.  If you want 10, change it to 10


text:
Q: Conservation of momentum equation, how do I factor out v0Final and v1Final? I am trying to figure out an equation for conservation of momentum. So,
If combined momentum before and after the collision is the same, and momentum is velocity times mass, then for 2 objects (A,B), it will be:
$(m_0 \times v_0) + (m_1 \times v_1) = (m_0 \times v_0^{Final}) + (m_1 \times v_0^{Final})$
The final velocities for A,B are $v_0^{Final}$ and $v_1^{Final}$. The way to solve an equation that has 2 unknowns is to find another equation with the same 2 unknowns.
So we are using kinetic energy equation, $E_k = 0.5 \times m \times v^2$
If kinetic energy before and after a collision is the same it will be:
$E_{k,0} + E_{k,1} = E_{k,0}^{Final} + E_{k,1}^{Final}$
or
$(0.5 \times m_0 \times v_0^2) + (0.5 \times m_1 \times v_1^2) = (0.5 \times m_0 \times {v_0^{Final}}^2) + (0.5 \times m_1 \times {v_1^{Final}}^2)$
So, given:
$(m_0 \times v_0) + (m_1 \times v_1) = (m_0 \times v_0^{Final}) + (m_1 \times v_1^{Final})$
and
$(0.5 \times m_0 \times v_0^2) + (0.5 \times m_1 \times v_1^2) = (0.5 \times m_0 \times {v_0^{Final}}^2) + (0.5 \times m_1 \times {v_1^{Final}}^2)$
How do I factor out $v_0^{Final}$ and $v_1^{Final}$ and express it in $m_0$, $m_1$, $v_0$ and $v_1$? Can somebody show me the steps?
The answer:
$ v_0^{Final} = \frac{(m_0 - m_1) \times v_0 + 2 \times m_1 \times v_1}{m_0 + m_1}$
$v_1^{Final} = \frac{(m_1 - m_0) \times v_1 + 2 \times m_0 \times v_0}{m_0 + m_1}$
Thanks! V.

A: The easy way to do problems like this is to work in the centre of mass frame. The trick is to add a velocity that makes the total momentum zero, then calculate what happens in the collision, and finally add the centre of mass velocity back on.
Working in the centre of mass frame makes things easy because if the total momentum before the collision is zero the total momentum after the collision must be zero as well. That gives you the useful relation:
$$m_0v_{final 0} + m_1v_{final 1} = 0$$
You can calculate the velocity of the centre of mass frame by requiring that the initial momentum be zero:
$$m_0(v_0 + v_{com}) + m_1(v_1 + v_{com}) = 0$$
which gives you:
$$ v_{com} = - \frac {m_0v_0 + m_1v_1}{m_0 + m_1} $$
More info: in the centre of mass frame the collision looks like:

because we are in the centre of mass frame we know the momentum after the collision is zero, so:
$$m_1 v_1 + m_2 v_2 = 0 $$
the kinetic energy is:
$$ \frac{1}{2} m_1 v_1^2 + \frac{1}{2} m_2 v_2^2 = E $$
where E is the initial kinetic energy ($1/2m_1u_1^2 + 1/2m_2u_2^2$) so you can use the first equation to substitute into the second e.g. you can rearrange the first equation to be:
$$ v_1 = -\frac{m_2}{m_1} v_2 $$
Use this to substitute for $v_1$ in the second equation and after some juggling it gives you:
$$ \frac{1}{2} m_2 \left( \frac{m_2}{m_1} + 1 \right) v_2^2 = E $$
So now you have $v_2$ you can substitute back in the first equation to get $v_1$. Now just subtract off the centre of mass velocity to get back to your initial frame.
You could have done the calculation without using the centre of mass frame, but it makes the algebra easier. NB be careful about the signs of the velocities; remember that velocities in opposite directions have opposite signs. It's easy to lose a minus sign and get the wrong answer!

A: From conservation of energy:
$$ m_1 (v_1^2 - v_{1f}^2) + m_2 (v_2^2 - v_{2f}^2) = 0 $$
$$ m_1 \Delta v_1 (v_1 + v_{1f}) + m_2 \Delta v_2(v_2 + v_{2f}) = 0$$
where $\Delta v_1 = v_1 - v_{1f}$ and $\Delta v_2 = v_2 - v_{2f}$.
But $m_1\Delta v_1 = - m_2\Delta v_2$ since this is the momentum transferred between the bodies $\Delta P$ by conservation of momentum, so:
$$ \Delta P ( v_1 + v_1^f - v_2 - v_2^f) = 0 $$
and this is the factorization you are looking for. The reason it exists is because you automatically know one solution to the quadratic equation--- the particles pass through each other without interacting ($\Delta P$ is zero). This means that the equation must factor out for this root.


text:
Q: How to set Oracle connection string for dotNET core console app? I created a .net core 2.1 console app in vs2019. In the DB context OnConfiguring method, I have:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    var conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConsoleApp1Core"].ConnectionString; // this does not work
    var conn = "User Id=xxx;Password=xxx;Data Source=xxx:xxx/xxx"; // this works
    optionsBuilder.UseOracle(conn);
}

App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="ConsoleApp1Core" connectionString="User Id=xxx;Password=xxx;Data Source=xxx:xxx/xxx" />
  </connectionStrings>
</configuration>

error:
PM> get-dbcontext
System.NullReferenceException: Object reference not set to an instance of an object.
   at ConsoleApp1Core.Program.BloggingContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:\ConsoleApp1Core\Program.cs:line 21
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.GetContextInfo(String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.GetContextInfoImpl(String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.

A: The problem was I forgot to set App.config to copy to output directory.
Got the hint from https://stackoverflow.com/a/46999609/310767.


text:
Q: Explicitly define enum values, even if the default value is the same? There are times when an enum's values are important: it is not necessary for them to be unique, they also need to have specific values. In such cases, should the values be explicitly defined, even if they coincide with the defaults? An example:
enum Car {
    DeLorean = 0,
    Lada = 1
};

Imagine that for whatever reason your application assumes that DeLorean and Lada have those specific values. Incidentally, they are the same as the default values but does that mean it is no longer necessary to use explicit definitions?
Leaving them implicit makes me uneasy. It seams to me that having them explicitly defined is communicating to future programmers that the specific values are important and it helps prevent mistakes like this:
enum Car {
    Dacia,
    DeLorean,
    Lada
};

In the example above, another programmer who is not aware of the restriction I mentioned introduces a new enum value and, wanting to keep the code tidy, puts it in alphabetical order. However, DeLorean and Lada now have different numerical values and a potentially silent bug has been introduced.
My reasoning seems correct to me (obviously), but the code review team for a company I used to work with didn't agree. Am I wrong?

A: This is very much a judgement call, but I would agree with you that explicit values are the way to go, plus a comment at the start explaining the significance of the explicit values.
As an example of a prominent project that is doing it this way, look at Clang's AST serialization. It uses a huge enum to define codes for all of its AST nodes, and the enum has explicit values.
That said, I also sympathize with the opinion of the architecture team that touching old code that works when there's more important things to be done is not the best idea.
I don't like the compromise solution, though. It adds nothing.

A: If you are storing or transmitting those values then they must be specific.
Normally you would define the protocol in a header file shared by both parties. If you have some kind of versioning mechanism then it will not be a big problem. But it is always better to be explicit. I am a fan of 'say what you mean' in the code. It doesn't cost anything and your code is much more readable.
But for internal modules and APIs where the enum values are not stored, the defaults are just fine.
It communicates that the value of the enum itself is not important. What is important is what those value mean and the fact that you are using stonger typing to make it clear what the code is using and help to prevent invalid values from vein used.

A: Consider C++11's enum class; it allows you and your company to eliminate the need for explicit values while removing the subtle bugs enum has.

A: In new code, if it is part of the system or business requirements that a particular enumeration be equal to a specific value then it should definitely be explicit, commented and documented. Failure to do so invites a maintenance nightmare.
The only factor in your scenario that would delay me from making such enums explicit is the fact that this is old code from a working code base and other tasks might have priority.

A: With enums, there are three philosophies that work, and one that doesn't

*

*Value agnostic - use default values for ALL options with the underlying values irrelevant

*Sequence specific - define the first value leaving all others as increments

*Value specific - specify values for ALL options and the value is important (eg comms message IDs)

The one that doesn't

*Some specified - some values are specified, and some are not

Option (4) is deprecated by MISRA C (and other such standards)... likewise, the purist in me questions why (2) should be necessary (other than for the default = 0) but there are probably legitimate reasons for this.
Of course, where a value is specified, then there should be adequate documentation to explain why!
IMHO it is quite dangerous to rely on knowing the underlying value of an enumeration, and even more so to assume a sequence - the problems you can get into incrementing and decrementing an enum type...

A: It is purely a software coding guidelines call (process compliance call).
enumerated values are crux of many algorithms and it should be handled with utmost care. One another option of usage is that it is better that the name of the enumeration constant conveys the value via its name itself to make the understanding clear.
Example :
enum retries {
    RETRY_ZERO,
    RETRY_ONE,
    RETRY_TWO,
    RETRY_THREE
};


text:
Q: JSP Get property | I am trying to use the jsp tag as following without jsp:useBean tag.
Value being set in servlet and forwarded to a jsp:
request.setAttribute("person", p);

In jsp trying to get value:
<jsp:getProperty name="person" property="title"/>

Sometimes it gets the value and sometimes it throws the following exception:
org.apache.jasper.JasperException: file:/index.jsp(17,0)
jsp:getProperty for bean with name 'person'.
Name was not previously introduced as per JSP.5.3

Kindly suggest why the behavior is not predictable?

A: I guess you are using tomcat6 or later, right?
Try to use jsp:useBean tag to reference the bean again before invoke jsp:getProperty. It may work:
<jsp:useBean id="person" class="xxx.xxx.Person" />
<jsp:getProperty name="person" property="title" />

This might be a bug of tomcat. Check this out: https://issues.apache.org/bugzilla/show_bug.cgi?id=48701


text:
Q: Using third-party JavaScript file in Node.js I have a JavaScript file which is not written for Node.js. It is actually written by me, but this question may be more understandable if you think of it as a third-party library.
Normally, a Node.js module only exposes the module.exports object to external code. This requires the file to be written with Node.js in mind.
However, the file isn't written for Node.js, yet I want to include it into a Node.js module. I can't edit this file, since it will be used later, independently of Node.js.
I imagine I could pull it off by reading the file and calling eval on the contents, but is there a better way?
TL;DR
How can I include a .js file into a Node.js module, without rewriting it to use Node.js-specific code like exports?
P.S. The reason I want to use it in Node.js is for a few tests before it's deployed elsewhere.

A: It depends on how the code is written on that file. If the file contains a class or a single object then you can do this:
(function(global) {

    function MyClass() {

    }

    MyClass.prototype = {
            ...
    };

    if( typeof module !== "undefined" && module.exports ) {
        module.exports = MyClass;
    }
    else if ( global ) {
        global.MyClass = MyClass;
    }

})(this);

You can modify the global assignment to be a deeper namespace instead if required.


text:
Q: SQL query in OO Base with where and if I'm totally blank about sql, but im have to make sql query in OO Base. Query have to avoid compare, when cell in table is blank.
I hope somebody will help me.
SELECT "D"."Imię", "D"."Nazwisko", "D"."Data badania", "D"."Rodzaj auta", "D"."Obszar badany", "D"."Jednostka kierująca 1", "D"."Jednostka kierująca 2"
FROM "Dane" AS "D", "Szukanie" AS "S"
WHERE "D"."Data badania" BETWEEN "S"."Data_od" AND "S"."Data_do" AND
IF "S"."Imię" != "" THEN "D"."Imię" = "S"."Imię" AND
IF "S"."Nazwisko" != THEN "D"."Nazwisko" = "S"."Nazwisko" AND
IF "S"."Rodzaj auta" != "" THEN "D"."Rodzaj auta" = "S"."Rodzaj auta" AND
IF "S"."Obszar badany" != "" THEN "D"."Obszar badany" = "S"."Obszar badany" AND
IF "S"."Jednostka kierująca 1" != "" THEN "D"."Jednostka kierująca 1" = "S"."Jednostka kierująca 1" AND
IF "S"."Jednostka kierująca 2" != "" THEN "D"."Jednostka kierująca 2" = "S"."Jednostka kierująca 2" AND
END IF

A: Try:
 SELECT "D"."Imię", "D"."Nazwisko", "D"."Data badania",
 "D"."Rodzaj auta", "D"."Obszar badany",
 "D"."Jednostka kierująca 1", "D"."Jednostka kierująca 2"
 FROM "Dane" AS "D", "Szukanie" AS "S"
 WHERE "D"."Data badania" BETWEEN "S"."Data_od" AND "S"."Data_do"
 AND ("S"."Imię" = "" OR "D"."Imię" = "S"."Imię" )
 AND ("S"."Nazwisko" =  "" OR "D"."Nazwisko" = "S"."Nazwisko")
 AND ("S"."Rodzaj auta" = "" OR "D"."Rodzaj auta" = "S"."Rodzaj auta"
 AND ("S"."Obszar badany" = "" OR "D"."Obszar badany" = "S"."Obszar badany")
 AND ("S"."Jednostka kierująca 1" = "" OR "D"."Jednostka kierująca 1" = "S"."Jednostka kierująca 1")
 AND ("S"."Jednostka kierująca 2" = "" OR "D"."Jednostka kierująca 2" = "S"."Jednostka kierująca 2")


text:
Q: Passing A primary key to the next page in with Django So I have the following files:
Views.py:
def home(request):
    return render(request, 'home/index.html')

def add(request):
    if request.method == 'POST': # If the form has been submitted...
        # ContactForm was defined in the previous section
        form1 = AddEventForm(request.POST) # A form bound to the POST data
        #person = AddPersonForm(request.POST) # A form bound to the POST data
        if form1.is_valid(): # All validation rules pass
            form = form1.save()
            request.session['event_data'] = request.POST
            #request.session['event_data2'] = form
            return HttpResponseRedirect('/add_person/')
            #return HttpResponseRedirect(reverse('/add_person', kwargs={'PK':form.pk}))
    else:
        form1 = AddEventForm() # An unbound form
        person = AddPersonForm() # A form bound to the POST data

    return render(request, 'add/add.html', {
        'form1': form1, 'person': person,
    })

def add_person(request):

    event_data = request.session.get('event_data')
    if request.method == 'POST':
        person = AddPersonForm(request.POST)
    else:
        person = AddPersonForm()

    return render(request, 'add_person/add_person.html',{'event_data': event_data, 'person': person,})

models.py:
class event(models.Model):
    event_name = models.CharField(max_length=200)
    date = models.DateField('Date',default=date.today)
    event_id = models.AutoField(primary_key=True)
    admin_username = models.CharField(max_length=50)

    def __unicode__(self):
        return ('%s %s %d') % (self.date, self.event_name, self.event_id)

class Person(models.Model):
    eventID = models.ForeignKey(event)
    first_name = models.CharField(max_length=50)
    second_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=50)
    phone = models.CharField(max_length=25)
    company = models.CharField(max_length=200)
    favourite = models.BooleanField(default=False)

    def __unicode__(self):
        return eventID

This problem has been bugging me for hours. I have an initial page where the user enters some information about an event. If the checks pass the form saves and a primary key is generated. The user is then redirected to another page where they fill out a form about the people they have met there. The problem is I cannot find a way of passing the primary key to the second page (add_people). I need the primary key because it is my foreign key in my Person table and I need to use to pre-populate the eventID in the add_people page.
I initially thought the primary key would be in the request.POST after the form is saved but its not.

A: Query the table for the primary key using the form inputs as arguments. Once you get the key, pass it as a session variable in the request object.

A: Here's an answer to the same question but with class-based views instead of function-based views: How do I pass a parent id as an fk to child object's ModelForm using generic class-based views in Django?.  In that example, the foreign key is passed from the parent page to the child page by being a parameter in the URL.  The child page catches it as a form parameter (in the form's __init__ function), stores it in a hidden field for display (by the View class's get_context_data and html code in the form template), and then submits it as part of the form.

A: If your form is validated, then your have to set session value as eventID but not request.POST
if form1.is_valid(): # All validation rules pass
    form1.save(commit=False)
    request.session['event_data'] = form1.cleaned_data['eventID']
    form1.save()
    return HttpResponseRedirect('/add_person/')


text:
Q: I get 502 Bad Gateway nginx/1.22.0 (Ubuntu) when deploying django app to linode with gunicorn and nginx I'm deploying a django app to linode with gunicorn and nginx. I have followed a few different tutorials, but for the setting up of gunicorn and nginx I followed this, which took me to the end with no errors, but at the end I got 502 Bad Gateway error from nginx when trying to open the url directly on my browser.
The error.log I get when refreshing the page is the following:
tail -f /var/log/nginx/error.log

2022/11/20 11:24:33 [crit] 4949#4949: *5 connect() to unix:/home/djangouser/djangoproject/djangoproject.sock failed (13: Permission denied) while connecting to upstream, client: 181.43.95.34, server: 555.555.55.555, request: "GET / HTTP/1.1", upstream: "http://unix:/home/djangouser/djangoproject/djangoproject.sock:/", host: "555.555.55.555"
(The IP, user and project names have been changed, not sure if this is unsafe, but just in case)
The relevant settings are as follows:
ufw status on server:

To                         Action      From
--                         ------      ---- 22/tcp                     ALLOW       Anywhere                   Nginx Full
ALLOW       Anywhere                   22/tcp (v6)
ALLOW       Anywhere (v6)              Nginx Full (v6)
ALLOW       Anywhere (v6)

/etc/systemd/system/gunicorn.service

[Unit] Description=gunicorn daemon After=network.target
[Service] User=djangouser Group=www-data
WorkingDirectory=/home/djangouser/djangoproject
ExecStart=/home/djangouser/djangoproject/.venv/bin/gunicorn
--access-logfile - --workers 3 --bind unix:/home/djangouser/djangoproject/djangoproject.sock
polman_project.wsgi:application
[Install] WantedBy=multi-user.target

/etc/nginx/sites-available/djangoproject

server {
listen 80;
server_name 555.555.55.555;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/djangouser/djangoproject;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/djangouser/djangoproject/djangoproject.sock;
}
}

I would appreciate any advice.


text:
Q: Enable MIC in genymotion / Any other good android emulator I am making a app that use mic to record audio.
How can I enable mic in genymotion emulator?
or
Is there any other good emulator for android app dev?
need help
Thanks!

A: Genymotion can actually use your computer's microphone.
Depending on your computer it sometimes does not work because of VirtualBox hardward support.
Here is a conversation about this topic on the Genymotion's Google Group.
You should try to play with the sound configuration on VirtualBox:

*

*Open VirtualBox

*Choose a VM and open its settings

*Go to sound tab and change the audio controler or audio pilot

Let me know what is your configuration (OS, Genymotion version).

A: This emulator does not support microphone if you are using windows host OS.
Genymotion developers are aware of this, they even filled a virtualbox bug.


text:
Q: Check for already running copy of process and communcation Ok so I have a few ideas for checking whether or not an instance of a process is already running but I wanna find out what other people already do/use first. I'm looking to do something like firefox does sometimes where it says firefox is already running blah blah blah, it only checks to see if there is another copy of itself running, I'm not really looking to check to see if there is just an arbitrary named process running just if there is another copy of itself.
I don't know whether or not it would be easier to just set up a system to look for an arbitrary process and just look for itself or if it would be better to implement a system for looking for just that process.
I am trying to eventually to lead into being able to communicate with another process so that I could send messages to it.
So say to do the following just as an example: suppose you have firefox already running then you do a command of firefox URLHERE it opens up the new url in the original window that was opened.
I am also trying to figure out how to implement this so if you have any ideas on the best ways in which to do this then by all means please do let me know as well.
Thanks

A: Assuming Windows - other operating systems may provide similar constructs but implementation details will vary.
Look into named pipes or named mutexes.
A named mutex solution will be easier to code but it will not give you inter-process communication. The theory goes like this: your process attempts to create a named mutex. If it fails it means that another copy of the process is already running. This is guaranteed by the OS - only one named mutex can be created with a specific name. The trick is then in choosing an appropriate name for your mutex so you don't run the risk of accidental conflict with another program wanting to create/use the same named mutex. For this you could use a GUID. Note however, that a nefarious application could create the named mutex that you're looking for and prevent your application from ever running
The second option is to use a named pipe (same story regarding choosing the name). Your process will attempt to create a pipe with a certain name on startup. If creating the pipe fails because the pipe already exists it will go ahead and attempt to connect to the pipe and then you can have the second process exchange information with the first process (i.e. pass on its arguments so that the original process can perform an action)


text:
Q: C# DllImport help (Mac Os) I'm developing an app in Mac Os X in C# (with mono), I need to interop with some functions, but I don't know how can I do this..
I've made a simple app in C, but now I need to do the same in C#, I know that i should use DllImport, but I don't know how can I do this..
The function that I want to call in C# is this one:
mach_vm_read(vm_map_t target_task, mach_vm_address_t address, mach_vm_size_t size, vm_offset_t *data. mach_msg_type_number_t *data_count);

is defined in one of those files
#include <mach/mach.h>
#include <mach/mach_vm.h>

Thanks

A: You can declare and call the method in C# by decorating the method call with the [DllImport()] attribute, like so (provided your method you want to call is indeed a static method, and has no return type):
[DllImport("YourDll.dll")]
public static extern void mach_vm_read(vm_map_t target_task, mach_vm_address_t address, mach_vm_size_t size, vm_offset_t *data. mach_msg_type_number_t *data_count);

A: This page is going to be the most useful for you:
Interop with Native Libraries
In general, P/Invoke on OS X / Linux in Mono works just like it does on Windows.

A: If you have a lot of c++ you can use a tool called Swig to generate a C# wrapper for all of your exposed c++ functions using simple templates. We have used this to great success on Windows, Mac OS and Linux.


text:
Q: Make CSS Button active when click and change the content of the div. My desired result is to have a menu css buttons, when click it changes the content of the div... Of course I manage to do that...
Well here's the problem:
Whenever I click the 2nd or 3rd button/link it manages to change the div content but when you started to click anywhere in the page it changes back to its default content...
I want to make both button/link and the div content stays active even when I click anywhere in the page.
I want to achieve this in Pure CSS only. I know there is a code for that, though I'm not that good enough to make it happen. Can anyone help me with this problem?
This is my HTML Code looks like

  Video
  Apps
  Music

Video Content here

Video Content here

Apps Content here

Music Content here

This is my CSS code
The #def id is the default content and the #videocontent is the mirror of the default whenever I want to go back to the video div content

#mynavtabcontent{
 font-family: Verdana;
 font-size: 18px;
}
#mynavtabcontent a{
 text-decoration: none;
 padding: 7 7 7 7px;
 background-color: yellow;
 color: #222;
}
#mynavtabcontent a:hover{
 background-color: #333;
 color: white;
 cursor: pointer;
}
#content{
 border:1px dashed black;
 background-color: pink;
 height: 400px;
 width: 200px;
 margin-top: 50px;
}
#videocontent, #appscontent, #musiccontent{
 display: none;
}
#video1:focus~#content div:nth-child(1),
#video:focus~#content div:nth-child(2),
#apps:focus~#content div:nth-child(3),
#music:focus~#content div:nth-child(4){
 display: block;

}
#video1:focus~#content #def,
#video:focus~#content #def,
#apps:focus~#content #def,
#music:focus~#content #def{
 display:none;
}

Here is the result
Run code snippet Click 2nd or 3rd button then click anywhere in the content. To see what I mean about making it active so it won't go back to the default state when you click anywhere.

#mynavtabcontent{
 font-family: Verdana;
 font-size: 18px;
}
#mynavtabcontent a{
 text-decoration: none;
 padding: 7 7 7 7px;
 background-color: yellow;
 color: #222;
}
#mynavtabcontent a:hover{
 background-color: #333;
 color: white;
 cursor: pointer;
}
#content{
 border:1px dashed black;
 background-color: pink;
 height: 400px;
 width: 200px;
 margin-top: 50px;
}
#videocontent, #appscontent, #musiccontent{
 display: none;
}
#video1:focus~#content div:nth-child(1),
#video:focus~#content div:nth-child(2),
#apps:focus~#content div:nth-child(3),
#music:focus~#content div:nth-child(4){
 display: block;

}
#video1:focus~#content #def,
#video:focus~#content #def,
#apps:focus~#content #def,
#music:focus~#content #def{
 display:none;
}

  Video
  Apps
  Music

Video Content here

Video Content here

Apps Content here

Music Content here

If there is no other way with CSS... Can anyone provide me a javascipt code for this? It would really help me thanks! -edited.

A: There really anything you can do for CSS as far as actions. CSS is styling only.
You will need to use some javascript to handle the actions.
Javascript interacts with the DOM to make the syntax changes in the browser.
However, you can have limited control with things such as animation using CSS properties such as transition, transform, :hover, :active, :focus, and @key-frames.

A: Your links looses focus as soon as you click elsewhere. You need to use something that can preserve state - :checked pseudo element is a perfect fit. You could have hidden inputs and manage it states with labels. Here is your code with changes applied to it:

  <input type="radio" name="content-toggle" id="video"> Video
  <input type="radio" name="content-toggle" id="apps"> Apps
  <input type="radio" name="content-toggle" id="music"> Music

Video Content here

Video Content here

Apps Content here

Music Content here

and css:
#mynavtabcontent input {
  display: none;
}

#mynavtabcontent{
  font-family: Verdana;
  font-size: 18px;
}
#mynavtabcontent label{
  text-decoration: none;
  padding: 7 7 7 7px;
  background-color: yellow;
  color: #222;
}
#mynavtabcontent label:hover{
  background-color: #333;
  color: white;
  cursor: pointer;
}
#content{
  border:1px dashed black;
  background-color: pink;
  height: 400px;
  width: 200px;
  margin-top: 50px;
}
#videocontent, #appscontent, #musiccontent{
  display: none;
}
#video1:checked~#content div:nth-child(1),
#video:checked~#content div:nth-child(2),
#apps:checked~#content div:nth-child(3),
#music:checked~#content div:nth-child(4){
  display: block;

}
#video1:checked~#content #def,
#video:checked~#content #def,
#apps:checked~#content #def,
#music:checked~#content #def{
  display:none;
}

http://codepen.io/MakiBM/pen/KgXzma


text:
Q: How to logout from Relying Party? I am using Dotnetopenid for login.
I am logs in my application by using dotnetopenid provider suppose google.
At the time of logout I am ending the my application user's session by FormsAuthentication.SignOut(); but if I am not closing the browser and logs in using google it will not ask me for id-password and land me on secured page of my apllication.
Also, if i will try gmail.com it will directly lands me user account without asking id-password.
So how could I logout completely from my application and google too ?
thanks in advance

A: I think you are mistaking the Relying Party and the OpenID Provider.  Using StackOverflow as an example, SO is the Relying Party and other sites (e.g. Google) are the OpenID Provider(s).
The Relying Party (e.g. SO) has no say in when the OpenID Provider (e.g. Google) chooses to "forget" the user for their own purposes.
EDIT: I was not familiar with the PAPE extension.  However, if I understand correctly, it does not provide a way for the RP to say to the OP, "On your end, forget this user's authentication", which is what I think rehan wants.  It just provides a way for the RP to demand another authentication for the RP's purposes.
I still see no way for (e.g.) SO to log a Google user out of Gmail after SO logs them out.

A: It sounds like what you're looking for is a Logout feature that will allow the relying party to also log the user out of the Provider at the same time.
DotNetOpenId doesn't offer this feature because OpenID itself doesn't have this feature in its spec.  There's simply no way to do it right now.  The OpenID community have had conversations about spec'ing out such a feature, but so far it's not there.  If and when OpenID adds such a feature to its spec, DotNetOpenId will add support for it.

A: i had the same issue. So tried this.....when i logged out of my website which uses dotnetopenid, i also made a call to the following gmail logout link https://mail.google.com/mail/?logout&hl=en. This logged me out of gmail also.

A: https://www.google.com/accounts/Logout
try this one....


text:
Q: LESS files dont't work on dreamweaver CC Is it possible that LESS files don't work in dreamweaver CC? Because probably my syntaxt is correct, but I don't understand why my style.less file doesn't work, even with simple commands like "color: #ff0"

A: if you want include less direct to html file you have to read this topic: Less css file include in <head> section
or you can convert .less to .css file: http://koala-app.com/
or you can use gruntJS: http://gruntjs.com/

A: use this in head: make sure you are using rel="stylesheet/less"
  <link rel="stylesheet/less" type="text/css" href="styles.less" />

and before the html closing tag
  <script src="less.js" type="text/javascript"></script>

Source:
client-side-usage

A: It's working if I put the entire project inside the "local server folder" (xampp in this case) even if I  'm using only simple html tag, .js and .less file. No php, mysql and others.
Could you tell me why of this behaviour?


text:
Q: A garbage character appears when using substr() on a Chinese language string I am trying to get some character(s) from a Chinese string. But always a garbage character appears at the end.
How can I get some char from Chinese string?

A: Assuming that you are using PHP:
when using non ascii character you should use the multibyte functions, in this case the function mb_substr. Remember to set the internal encoding to use through the mb_internal_encoding function.


text:
Q: Displaying single bxslider within Bootstrap tabs I have several tabs within my page that show / hide content when pressed

        Video

        Photos

When I click the photos tab the bxslider should load, currently when I click photos the images don't load, all that is shown is the pagination. When I resize the browser or click the tab for a second time, the slider loads.
$(document).ready(function(){
  $('.property-gallery').bxSlider({
    pager: true,
    autoHover: true,
    maxSlides: 1,
    minSlides: 1,
    controls: true,
    hideControlOnEnd: false,
    moveSlides:1
  });
});

I've tried loads of different solutions posted but nothing has worked for me yet! I just want to reload the slider every time you click the photos tab!
My slider within the tab

      {% if property.photos.size > 0 %}

            {% for photo in property.photos %}

            {% endfor %}

      {% endif %}

A: Boostrap tab handles display:none; to hide container tabs. When BxSlider is initialized it ain't got a width/height reference to be displayed with the 100% container wide.
Adding this to your css file could fix it:
    .tab-content > .tab-pane,
    .pill-content > .pill-pane {
        display: block;
        height: 0;
        overflow-y: hidden;
    }

  .tab-content > .active,
    .pill-content > .active {
        height: auto;
    }

Here I  change display:none with display:block and I start to play with the height to hide/show container


text:
Q: Trim supports for Kington SSD is in default or not? I have just installed Ubuntu 17.10 on a Kington SSD.
I heard that Ubuntu enables Trim by default, but it is only for some brands like Intel and Samsung while Sandisk and Kingston are not included in the list (source).
Thus, I want to ask:

*

*How do I check Trim was enabled for the SSD brands I am using (Kington and Sandisk)?

*How do I enable if the trim is disabled?
Update:
Main question I want to ask you is Kington is not in supported list of fstrim,
[And I have already read some old threads at here and somewhere at here that, enable Trim ubuntu only effect to supported brands (samsung, Intel)]
=> How to check/ enable/ disable Trim function for Kington SSD (special brand, which is not in the support list)
Because the old threads I read is maybe outdate.
Update 2: Kington technical supporter informed me that no need to care about Trim function in OS, because Garbage collection is a function was built-in firmware of Kington SSD.
Best regard,
Thanks in advance,


text:
Q: Multithreaded game server using C# I am quite new at this and would like some help with configuring a C# server for a LAN game. The server needs to send an object to all the clients connected to the server and then wait for their response . After all players respond , the server announces the winner to all participants and generates a new game (After the winner is announced I wait about 5 seconds for the next game to generate)
I'm having trouble sending that object through NetworkStream
Server side:
public static void broadcast(string uName, bool flag)
    {
        game.Generate();
        foreach (Client Item in clientsList)
        {
            TcpClient broadcastSocket;
            broadcastSocket = (TcpClient)Item.clientSocket;
            NetworkStream broadcastStream = broadcastSocket.GetStream();
            Byte[] broadcastBytes = null;

            if (flag == true)
            {
                broadcastBytes = Encoding.ASCII.GetBytes("Winner is " + uName);
            }
            else
            {

                broadcastBytes = ToByteArray(game);

            }

            broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
            broadcastStream.Flush();
        }
    }

    public static byte[] ToByteArray(Game24 obj)
    {
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }
    }

Client side:
private void getMessage()
    {
        while (true)
        {
            serverStream = clientSocket.GetStream();
            int buffSize = 0;
            byte[] inStream = new byte[10025];
            buffSize = clientSocket.ReceiveBufferSize;
            serverStream.Read(inStream, 0, buffSize);
            try
            {
                GenerateGame(inStream);
                isGame = true;   // testing
            }
            catch(Exception ex) {
                MessageBox.Show("No object");
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                readData = "" + returndata;
            }

            if (isGame)
                MessageBox.Show("Works  " + readData);

        }
    }

    private Game24 deserializeData(byte[] arr) {

        IFormatter br = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream(arr))
        {
            object obj = br.Deserialize(ms);
            return (Game24)obj;
        }
    }

    private void GenerateGame(byte[] arrBytes)
    {

        game = deserializeData(arrBytes);
        Generate();

            MessageBox.Show("Test2");
            timer1.Start();
            timer2.Start();

    }

It always shows the "No object" message


text:
Q: remove lines in file from stream cat file_a
aaa
bbb
ccc

cat file_b
ddd
eee
fff

cat file_x
bbb
ccc
ddd
eee

I want to cat file_a file_b | remove_from_stream_what_is_in(file_x)
Result:
aaa
fff

If there is no basic filter to do this with, then I wonder if there is a way with ruby -ne '...'.

A: Try:
$ cat file_a file_b | grep -vFf file_x
aaa
fff

-v means remove matching lines.
-F tells grep to treat the match patterns as fixed strings, not regular expressions.
-f file_x tells grep to get the match patterns from the lines of file_x.
Other options that you may want to consider are:
-w tells grep to match only complete words.
-x tells grep to match only complete lines.

A: IO.write('file_a', %w| aaa bbb ccc |.join("\n"))     #=> 11
IO.write('file_b', %w| ddd eee fff |.join("\n"))     #=> 11
IO.write('file_x', %w| bbb ccc ddd eee |.join("\n")) #=> 15

From Ruby:
IO.readlines('file_a', chomp: true) + IO.readlines('file_b', chomp: true) -
  IO.readlines('file_x', chomp: true)
  #=> ["aaa", "fff"]


text:
Q: How to make linq to entities or dbcontext use output in an insert statement? Output is defined here
Can I utilize output or am I forced to enter the data into two different tables using linq to entities or dbcontext?

A: This is not supported by EF. If you want to use OUTPUT clause you must execute SQL directly at your own or through ADO.NET directly or trhough Database.ExecuteSqlCommand.


text:
Q: AmChart multiples date values I'm trying to create a chart with multiples date values but it's not working. I thing that the logic is good and that amChart doesn't like this date format. Any ideas ?
The working exemple :
var chart = AmCharts.makeChart( "chartdiv", {
  type: "xy",
  dataProvider: [ {
    "ax": 16.10, <--------
    "ay": 2,
    "bx": 16.11, <--------
    "by": 2
  }, {
    "ax": 16.20, <--------
    "ay": 3,
    "bx": 16.21, <--------
    "by": 3
  }],
  graphs: [ {
    "xField": "ax",
    "yField": "ay"
  }, {
    "xField": "bx",
    "yField": "by"
  } ],
} );

What I'm trying to get :
  var chart = AmCharts.makeChart( "chartdiv", {
  type: "xy",
  dataProvider: [ {
    "ax": "2017/04/27 09:16:10", <--------
    "ay": 2,
    "bx": "2017/04/27 09:16:11", <--------
    "by": 2
  }, {
    "ax": "2017/04/27 09:16:20", <--------
    "ay": 3,
    "bx": "2017/04/27 09:16:21", <--------
    "by": 3
  }],
  graphs: [ {
    "xField": "ax",
    "yField": "ay"
  }, {
    "xField": "bx",
    "yField": "by"
  } ],
} );

http://jsfiddle.net/Lktv4s4b/1/

A: For date-based data, you have to specify a dataDateFormat for your chart object so that AmCharts knows how to correctly parse your date. Since you're using an XY chart, you also have to tell AmCharts that you have a date-based value axis (XY charts only have value axes, unlike Serial charts) and you have to specify which one is date-based. Going by your data, your X axis is date-based, so you need to at least tell it that the bottom value axis' type is "date":
AmCharts.makeChart("chartdiv", {
  type: "xy",
  dataDateFormat: "YYYY/MM/DD JJ:NN:SS",
  valueAxes: [{
    position: "bottom",
    type: "date"
  }], //you can also specify the second value axis' properties if needed, but it will create a numeric y-axis for you by default if you don't
  // ... rest of your properties omitted ...
});

Updated fiddle: http://jsfiddle.net/Lktv4s4b/2/


text:
Q: On Image selected , set as wallpaper I am new to Android development.
For learning purpose, I used an app from github.
This app consists of a wallpaper, which changes when the user swipes.
I want to know, if there is a way that, on longpress on that image,
the user can set that image as the wallpaper for the device (with crop option).
Here is my code for the image view.
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class ShivaGallery extends Activity implements ViewSwitcher.ViewFactory,OnItemSelectedListener {
    /** Called when the activity is first created. */
    private Gallery gallery;
    private ImageSwitcher imageSwitcher;
    int i=0;

    private ImageAdapter ia;
    int[] IMAGE_IDS = {
            R.drawable.shivji1, R.drawable.shivji2, R.drawable.shivji3, R.drawable.shivji4, R.drawable.shivji5,
            R.drawable.shivji6, R.drawable.shivji7, R.drawable.shivji8,R.drawable.shivji9,
            R.drawable.shivji10,R.drawable.shivji11, R.drawable.shivji12, R.drawable.shivji13, R.drawable.shivji14,
            R.drawable.shivji15
      };

    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.shivagallery);

         gallery = (Gallery) findViewById(R.id.gallery);
         imageSwitcher = (ImageSwitcher) findViewById(R.id.image_switcher);

         imageSwitcher.setFactory(this);
         imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                   android.R.anim.slide_in_left));
         imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                   android.R.anim.slide_out_right));

         ia = new ImageAdapter(this);
         gallery.setAdapter(ia);

         //Event listener
         gallery.setOnItemSelectedListener(this);
    }

    private class ImageAdapter extends BaseAdapter {
         private Context context;

         private ImageAdapter(Context context) {
              this.context = context;
         }

         public int getCount() {
              return IMAGE_IDS.length;
         }

         public Object getItem(int position) {
              return IMAGE_IDS[position];
         }

         public long getItemId(int position) {
              return position;
         }

         public View getView(int position, View convertView, ViewGroup parent) {
              ImageView iv = new ImageView(context);
              iv.setImageResource(IMAGE_IDS[position]);
              iv.setScaleType(ScaleType.FIT_XY);
             // iv.setLayoutParams(new Gallery.LayoutParams(1000, 800));

              return iv;
         }
    }

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
         int imageResourceId = (Integer) ia.getItem(position);
         imageSwitcher.setImageResource(imageResourceId);
         i=position;
    }

    public void onNothingSelected(AdapterView<?> parent) {
    }

    public View makeView() {
         ImageView i = new ImageView(this);
         i.setScaleType(ImageView.ScaleType.FIT_CENTER);
         return i;
    }

}

A: Button buttonSetWallpaper = (Button)findViewById(R.id.set);
ImageView imagePreview = (ImageView)findViewById(R.id.preview);
imagePreview.setImageResource(R.drawable.five);

buttonSetWallpaper.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            WallpaperManager myWallpaperManager
            = WallpaperManager.getInstance(getApplicationContext());
            try {
                myWallpaperManager.setResource(R.drawable.five);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
}});

Here the code to click which will make it a background image. For crop option you might use another open library or another view you would like to do.
and dont forget the permission:
<uses-permission android:name="android.permission.SET_WALLPAPER" />


text:
Q: Vue Component - Rendering in wrong location I am seeing strange behavior between a vue component and inline template.
Example #1: Inline Template
This is working as expected.  The vue component is unchanged as per example #2 below, the only difference is i've copied the template content into the tag as an inline template.
See: https://jsfiddle.net/pobffmnv/

Current Clients

                Client Name
                No. Projects
                Time (7 days)
                Edit

            <clientlistitem inline-template>

                    Test
                    0
                    0

                            <button type="button" class="btn small btn-primary">Edit</button>

            </clientlistitem>

This correctly shows the following:

Example #2: Not inline
The following is my Vue template.  Below is the change to the code to remove the inline template.
See: https://jsfiddle.net/Ld47hoy2/
<template>

        Test
        0
        0

                <button type="button" class="btn small btn-primary">
                    Edit
                </button>

</template>

Updated page code:

Current Clients

                Client Name
                No. Projects
                Time (7 days)
                Edit

            <clientlistitem></clientlistitem>

However, with the above, the following is displayed:

Looking at the source code of the output of the page, it appears to have put the rendered code BEFORE my table...?  I am expecting this to be between the

 tags..

Any reason why Vue would output the code to that location instead of the one expected?

A: The issue here is that with in DOM templates the templates are first rendered by the browser and HTML tables only allow certain kinds of elements inside. That being the case, the component clientlistitem is first rendered outside the table, then Vue compiles the template which results in the component in the wrong place.
To fix that, use the is special attribute.

The browser will accept this and render the tr in the correct place, but Vue will interpret it as your component.
Here is your fiddle updated.


text:
Q: How to get code completion working for c++ in Sublime Text 3? Is it possible to get code completion working in Sublime Text 3 for C++? I tried the CTags plugin and I don't like that fact that it creates tag database in all directories. I work on a project that has a shared codebase and consists of a large number of sub-directories containing source files.

A: https://forum.sublimetext.com/t/sublime-text-3-sublimeclang-cygwin-mingw-64bit/16253
I just documented my config for c++ code completion. Hope this helps.


text:
Q: Durandal - Failed to load routed module Details: undefined is not a function What does the error "Failed to load routed module (edit/user/index). Details: undefined is not a function" mean?
I get this error intermittetly and my stack trace looks like this:
logError system.js?bust=1398976887311:92
(anonymous function) router.js?bust=1398976887311:362
l jquery.min.js:6
c.fireWith jquery.min.js:6
(anonymous function) jquery.min.js:6
l jquery.min.js:6
c.fireWith jquery.min.js:6
i.(anonymous function) jquery.min.js:6
(anonymous function) system.js?bust=1398976887311:260
(anonymous function) require.js:129
(anonymous function) require.js:1154
each require.js:57
Module.emit require.js:1153
(anonymous function) require.js:529
each require.js:57
onError require.js:522
Module.check require.js:893
(anonymous function) require.js:1111
(anonymous function) require.js:129
(anonymous function) require.js:1154
each require.js:57
Module.emit require.js:1153
Module.check require.js:924
Module.enable require.js:1141
Module.init require.js:778
callGetModule require.js:1168
context.completeLoad require.js:1530
context.onScriptLoad

I have a module global that looks like this:
    define(['jquery', 'knockout', 'plugins/ajax'], function ($, ko,ajax) {
    'use strict';

    var obj = {};

    obj.loading = ko.observable(false);
    obj.activate = function () {

        obj.loading.subscribe(function (newValue) {
            if (newValue) {
                $.blockUI({
                    css: {
                        border: 'none',
                        padding: '15px',
                        backgroundColor: '#333',
                        '-webkit-border-radius': '10px',
                        '-moz-border-radius': '10px',
                        opacity: 0.9,
                        color: '#fff',
                        fontSize: '26px',
                        fontFamily: "'Helvetica Neue', Helvetica"
                    },
                    overlayCSS: {
                        opacity: 0.2,
                    },
                    message: 'Please wait...',
                    fadeIn: 0
                });
            }
            else
                $.unblockUI();
        });

        obj.promise = $.when(
                   ajax.wrap('Durandal/GetUnitModel', { Id: '1' }, function (response) {
                       ajax.updateModel(obj, 'unitModel', response.Model);
                   }),
                   ajax.wrap('Durandal/GetUserModel', { Id: '1' }, function (response) {
                       ajax.updateModel(obj, 'userModel', response.Model);
                   }),
                   ajax.wrap('Durandal/GetOfficeModels', { Id: '1' }, function (response) {
                       ajax.updateModel(obj, 'Offices', response.Model);
                   }),
                   ajax.wrap('Durandal/GetUserGroupModels', { Id: '1' }, function (response) {
                       ajax.updateModel(obj, 'UserGroups', response.Model);
                   })
               );

        return obj.promise;

    };

    return obj;
});

My edit user module that intermittently doesn't load (half the time it works fine) is:
define(['durandal/global','plugins/router', 'plugins/http', 'durandal/app', 'knockout', 'plugins/ajax', 'plugins/dialog', 'plugins/permissions', 'plugins/utility'], function (global,router, http, app, ko, ajax, dialog, permissions,utility) {

    var vm = {};
    vm.permissions = permissions;
    vm.utility = utility;
    vm.global = global;
    vm.AddOffices = ko.computed(function () {
        var ao = [];
        $.each(global.Offices(), function (i, v) {
            if (v.Name() != 'N/A' && v.Name() != 'Office of Afghanistan and Pakistan Affairs')
                ao.push(v);
        });

        return ao;
    });

    vm.getUser = function (personId) {

        if (personId == '0') {
            return $.when(global.promise).then(function () {

                ajax.updateModel(vm, 'newPersonRecord', {
                    "Email": ko.observable(""),
                    "FirstName": ko.observable(""),
                    "LastName": ko.observable(""),
                    "UserGroup": { Id: ko.observable("3"), Name: ko.observable("Viewer") },
                    "UserGroupId": ko.observable("3"),
                    "Office": { Id: ko.observable(global.Offices()[0].Id()), Name: ko.observable(global.Offices()[0].Name()) },
                    "OfficeId": ko.observable(global.Offices()[0].Id()),
                    "CotrExpirationDate": ko.observable(""),
                    "UserExpirationDate": ko.observable(Date.today().add(6).months().add(-1).days().toString('M/d/yyyy')),
                    "Id": ko.observable("0"),
                    "UnitId": global.userModel.UnitId(),
                    "UnitName": global.userModel.UnitName(),
                    "PasswordResetDate": ko.observable(""),
                    "Name": ko.observable(""),
                    "UserGroupName": ko.observable(""),
                    "OfficeName": ko.observable("")
                });
            });

                }
                else
                    return ajax.wrap('UserAdmin/GetUser', { PersonId: personId }, function (response) {
                        ajax.updateModel(vm, 'newPersonRecord', response.Model);
                    });
    };

    vm.activate = function (personId) {

        return vm.getUser(personId);
    };
    vm.save = function () {
        if ($("[name='validationError']:visible").length > 0) {
            alert('Please correct all errors before continuing.');
            return;
        }
        else {
            if (vm.newPersonRecord.OfficeId() != '40')
                ajax.wrap("UserAdmin/Update", vm.newPersonRecord, function (response) { if (!response.Success) alert(response.Message); else alert('User record saved.'); vm.back();});
            else
                ajax.wrap("UserAdmin/UpdatePartner", vm.newPersonRecord, function (response) { if (!response.Success) alert(response.Message); else alert('User recrord saved.'); vm.back(); });
        }
    };

    vm.back = function () {
        router.navigateBack();
    };

    vm.chars = function (str, numChars) {
        if (str.length > numChars)
            return false;

        return true;
    };

    vm.validEmail = function () {
        if (vm.newPersonRecord.Name().indexOf("@") == -1)
            return false;
        if (vm.newPersonRecord.Name().indexOf("'") != -1)
            return false;
        if (vm.newPersonRecord.Name().indexOf(",") != -1)
            return false;
        if (vm.newPersonRecord.Name().length < 4)
            return false;

        return true;
    };

    vm.emailExists = function () {
        var emailExists = false;

        $.each(viewModel.People(), function (index, value) {
            if (value.Name() == newPersonRecord.Name())
                emailExists = true;
        });

        return emailExists;

    };
    vm.cacheViews = false;

    return vm;
});

My shells.js module looks like this:
define(['plugins/router', 'durandal/app', 'plugins/ajax', 'durandal/global', 'durandal/activator'], function (router, app, ajax, global, activator) {

    var vm = {};

    vm.global = activator.create();
    //call this to refresh menu items
    vm.rebuildRouter = function () {
        return ajax.wrap('Durandal/GetMenuItems', { menuName:'viewmodels/shell.js' }, function (response) {
                vm.router.deactivate();
                vm.router.reset();
                vm.router.routes = [];
                vm.router.map(response.Model).buildNavigationModel();
                vm.router.activate();
            });
        /* { route: 'Map*details', title: 'Map', moduleId: 'map/index', nav: true, hash: '#Map' },*/

    };

    vm.activate = function () {
        var promise = vm.global.activateItem(global);

        return $.when(promise, vm.rebuildRouter());
    }

    vm.refreshUnit = function () {

        ajax.wrap('PostLogin/DurandalSwitchUnit', { unitId: vm.global().userModel.UnitId() }, function (response) { $.when(global.activate(),vm.activate()).then(function () { router.navigate();}); });

    };

    vm.router = router;

    return vm;
});

Any help debugging this would be greatly appreciated. Has anyone else run into such an error, what did it mean? It would help to even know roughly where to look, why does Durandal throw this error, it says something is 'undefined' but what is it looking for that is undefined in this case?

A: Assuming you're using Durandal 2.x, change the following line in your module global:
define(['jquery', 'knockout', 'plugins/ajax'], function ($, ko,ajax) {...

to this:
define(['knockout', 'plugins/ajax'], function (ko,ajax) {...

See if that that solves the problem.

A: This error message led me down hours of wild goose chases.
Eventually I found and fixed an error in my code where I had attempted to use the underscore library and this is what was failing.
If you get this error message, anything could be wrong anywhere in your module. You probably put a symbol like _ or $ somewhere in your code and it isn't defined.


text:
Q: Select Options - Slider I have this codes:
jQuery
$(function(){
    var s1 = $('#clarityfrom');

    var slider = $('#slider').slider({
        min: 1,
        max: 6,
        values: [s1[0].selectedIndex + 1],
        slide: function (e, ui) {
            var r1 = $('#clarityfrom option').eq(ui.values[0]-1).text();
            s1.val(ui.values[0]);
            $('#clarRange').html('Buy '+r1+'');
        }
    });
});

HTML

Select a Plan

<select name="clarityfrom" id="clarityfrom">
    <option value="1">10.000 Coins + 5.000 Pixels - 150 Rubys</option>
    <option value="2">20.000 Coins + 10.000 Pixels - 300 Rubys</option>
    <option value="3">40.000 Coins + 20.000 Pixels - 600 Rubys</option>
    <option value="4">60.000 Coins + 30.000 Pixels - 900 Rubys</option>
    <option value="5">90.000 Coins + 40.000 Pixels - 1200 Rubys</option>
    <option value="6">120.000 Coins + 50.000 Pixels - 1500 Rubys</option>
</select>

When the user select the option by slider, the script just change the text of "a" tag.
I need to change the text and the href="" according to the selected value.
Ex:
Buy 10.000 Coins + 5.000 Pixels - 150 Rubys
Is a little confused, but I hope you understand


text:
Q: How to parse Json file in swift for 2 collection Views? I have JSON file like this
{
  "dicts": [
    {
      "main": "",
      "note1": "",
      "note2": "",
      "note3": "",
      "note4": ""
    },
    {
      "main": "",
      "note1": "",
      "note2": "",
      "note3": "",
      "note4": "",
      "note5": ""
    },
    {
      "main": "",
      "note1": "",
      "note2": ""
    }
  ]
}

My App has 2 view controllers each having collection view. In first collection view I will display JSON data main for each cell and when I click main I have trouble setting note data for that respective main content in each cell. All I came able to call any one note value.
Model:
struct SecPage {
    var note1:String?
    var note1:String?
    var note2:String?
    var note3:String?
    var note4:String?
    var note5:String?
}

static func downSec () -> [SecPage] {
    let jsonFile = Bundle.main.url(forResource: "info", withExtension: "json")
    let jsonData = try? Data(contentsOf: jsonFile!)
    var noteArray = [SecPage]()

    do{
        if let jsonResult = try JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers) as? Dictionary<String,AnyObject>{
            let name = jsonResult["dicts"] as? [Dictionary<String,AnyObject>]
            for note in name!{
                let note1 = note["note1"] as? String
                let note2 = note["note2"] as? String
                let note3 = note["note3"] as? String
                let note4 = note["note4"] as? String
                let note5 = note["note5"] as? String
                let noteinfo = SecPage(note1: note1 ,note2:    note2,note3: note3, note4: note4, note5: note5, note6: note6)
                noteArray.append(noteinfo)    }}  } catch{print("note not found")}
    return noteArray
}

View
class CollectionViewCell2: UICollectionViewCell {
    @IBOutlet weak var img: UIImageView!
    @IBOutlet weak var names: UILabel!

    func updateUIsec(data:dataObj)  {
        names.text = data.note1
    }
}

How to update in cell when I can able to enter only one data in name.text and how to efficiently use Model class to retrieve json file and send to view.

A: I'm still unsure if this is what you are looking for, your question is too broad and hard to understand. Comment the answer and I'll update it as needed ;)
VC1:
class VC1: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    @IBOutlet weak var collectionView: UICollectionView!
    var modelData = [SecPage]()
    var selectedItem: SecPage?

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate   = self
        collectionView.dataSource = self

        //collectionView.register... // Register UICollectionView cell subclass
        modelData = SecPage.downSec()
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let secPage = modelData[indexPath.row]
        let cell = collectionView.dequeue...
        cell.textLabel.text = secPage.main

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if let destination = segue.destination as? VC2{
            destination.selectedItem = selectedItem
        }
    }

    override func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {

        selectedItem = modelData[indexPath.row]
        performSegue...
    }
}

VC2:
class VC2: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    @IBOutlet weak var collectionView: UICollectionView!
    var selectedItem: SecPage? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate   = self
        collectionView.dataSource = self

        //collectionView.register... // Register UICollectionView cell subclass
        modelData = SecPage.downSec()
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeue...
        cell.updateUIsec(data: selectedItem!)

        return cell
    }
}

Cell:
class CollectionViewCell2: UICollectionViewCell {
    @IBOutlet weak var img: UIImageView!
    @IBOutlet weak var names: UILabel!

    func updateUIsec(data: SecPage)  {
        names.text = data.note1
    }
}


text:
Q: "Creating publish preview" Suddenly very slow to LocalDB I'm using LocalDB to mock up a SQLServer DB in Visual Studio 2013. It's been working well but suddenly when I publish my changes to the DB, the "creating publish preview" step is taking several minutes whereas it used to take only a few seconds. The Database has not suddenly become very large (about 6 stored procedures and 6 tables) or changes to any great extent.
Can anyone suggest why this might be and what I can do to resolve it? It's pretty much unworkable having to wait several minutes every time I change anything and want to test it.


text:
Q: Stop OpenOffice from removing decimal places In a table-cell when I type 1.00 and move the focus from the cell OpenOffice
removes the decimal places from the number and makes it 1!

Why is this happening?
  How do I stop this from happening?

A:
Why is this happening?

OpenOffice is interpreting 1.00 a number, not as a string. As trailing decimal places of numbers are redundant so they're automatically stripped off.

How do I stop this from happening?

*

*Right-click on table.

*Disable Number Recognition.


text:
Q: Error notifying registry change listener. Invalid registry object after installing Google Plug-in for Eclipse (I've installed JDK 1.6 + Eclipse HELIOS)
After installing Google Plugin for Eclipse 3.6 , I restarted Eclipse and found:

*

*Google Sign-in doesn't work ( gives an OAuth error, saying invalid client_id )

*The Google toolbar  doesn't show up.

*The (Google)Web Application option from New Project doesn't show up.

So, I uninstalled the plugin(It showed up in the plugins list).
I installed it again and this time: I chose to "APPLY CHANGES" instead of "RESTART" eclipse right after installation completed.
I see the following error when I did so.
"Error notifying registry change listener. Invalid registry object"
Screenshot:
http://1.bp.blogspot.com/-Lh0-6WQSouI/TxBqsIJScAI/AAAAAAAAAPo/9oa9KuHhyis/s1600/gae-eclipse-issue.jpg
I installed EGIT . It worked fine. I'm using a Windows 7 box.
Please suggest me a workaround.


text:
Q: How do I apply events to a dynamically created picturebox? I wrote the code below so that I can drag and drop a picturebox. And it works fine. However, I'm making an application which may have like 100 different pictureboxes. Is there a way to apply the events in my code to every single picturebox there is?
Also the 100 is not a pre-defined amount. Because I'll be making a toolbox in my application from where users can drag images (pictureboxes) onto the form.
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
        dragging = true;
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e) {
        if (dragging) {
            dragging = false;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
        if (dragging) {
            pictureBox1.Left = Cursor.Position.X - pictureBox1.Width;
            pictureBox1.Top = Cursor.Position.Y - pictureBox1.Height;
        }
    }


text:
Q: DocuSign JWT Authentication .p12 needed instead of PEM i am trying to work with docusign JWT.
The environment where i develop only supports .p12 files. Docusign offers me a pem file. Is there a way to convert the .pem into a .p12 or even better to generate a .p12 directly from docusign ?
When trying to convert it to a .p12 i need the certificates. Can anybody help me on where i can get the corresponding / matching certificates ? I am completely lost.
Thanks!
BR
Martin

A: Procedure

*

*Go to https://www.openssl.org/community/binaries.html

*Download and install version 1.0.1p.

*

Run the following command format from the OpenSSL installation bin folder.
openssl pkcs12 -export -out Cert.p12 -in cert.pem -inkey key.pem -passin pass:root -passout pass:root

(original source)
However, you only need the private key to get a token using JWT.
.p12 files include both.
If you can extract the private key from them - you can use it. DocuSign doesn't provide
an SDK support to work with a .p12 file, but there are things in the web you can look into:
https://www.ssl.com/how-to/export-certificates-private-key-from-pkcs12-file-with-openssl/


text:
Q: JQuery gets loaded only on page refresh in Rails 4 application I have created a Rails 4 application and have added fancybox library for an image popup effect. It works fine but only when the page is being refreshed. If the page is not refreshed by the user then the jquery does not work at all. I tried testing it with small jquery methods also but all work only after page refresh. I am also using twitter bootstrap.
My assets/application.js file :
//= require jquery
//= require jquery_ujs
//= require fancybox
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .

$(document).ready(function() {
  $(".fancybox").fancybox();
    $("#hand").click(function(){
     if($("#check6").is(':visible'))
     {
      $("#check6").hide();
      }
     else
     {
      $("#check6").show();
      }
    });
});

A: I couldn't get things working until I followed both CodeWalrus's and Ian's answers, but for me there was more to it. As described on the jquery.turbolinks Readme, the order must be very specific.
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
//= require turbolinks

Also, as described here, if you have put the application javascript link in the footer for speed optimization reasons, as I had, you will need to move it into the <head> tag so that it loads before the content in the <body> tag.

A: Turbolinks are the problem here.Turbolinks are added in rails to improve performace of webpage.I have got this solution working
<%= link_to "Create New Form", sampleform_path, 'data-no-turbolink' => true %>
Fore more details refer this

A: Okay, I think I understand your problem enough to provide an answer. The thing about using turbolinks is that most plugins and libraries that bind to the document ready event stop working, since turbolinks prevents the browser from reloading the page. There are tricks to fix those issues, but the easiest way to fix it is to use jquery.turbolinks.
To use it, just add this to your Gemfile:
gem 'jquery-turbolinks'

and this to your assets/javascripts/application.js file:
//= require jquery.turbolinks

and you should be good to go.
FYI: You don't really need to use turbolinks, but it's useful and it makes requests faster by avoiding a full page refresh. Turbolinks fetches the contents of the link you clicked via AJAX and renders it on the same page, thus eliminating the overhead of reloading assets (JS and CSS). Try to make your page work with it. Using the library in the previous paragraph I've had no real issues. The more CSS and JS you have on your page, the bigger the improvement you get by using turbolinks.

A: Ian had a good answer, and this one is an add-on of sorts to that (SO won't let me actually comment to anyone at time of writing.)
From https://github.com/rails/turbolinks/#jqueryturbolinks :
Add the gem [gem 'jquery-turbolinks'] to your project, then add the following line to your JavaScript manifest file, after jquery.js but before turbolinks.js:

//= require jquery.turbolinks

Before I hadn't added require jquery.turbolinks in the right spot within the list, so it was being a bit picky. Then I added this a new way and I hope it works better.

A: Remove this line of code:
//= require turbolinks

Then add this one:
//= require jquery.turbolinks


text:
Q: tag  not clickable on relatively positioned block I have a little piece code:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Asia Maldivas</title>
        <link rel="stylesheet" href="css/reset.css">
        <link rel="stylesheet" href="css/style.css">

        TEST OUTER RELATIVE

           TEST

The CSS:
.bg {
    position: relative;
    background: linear-gradient(to bottom, rgba(18,138,167,0.95) 30px,rgba(62,195,209,0.95) 7%,rgba(12,115,160,1) 100%);
    z-index: -1;
}

a {
    text-decoration: underline;
    z-index: 99;
}

Now I have a link which is not clickable and I don't understand why.

A: It's caused by the z-index: -1; If you remove that, it will be clickable.

A: As Dan said, you need to remove z-index: -1 from the .bg. Here is live example:
https://jsfiddle.net/smmmrw7g/
It seems that z-index have some inheritance one from another.


text:
Q: Error installed 'wdm' gem on Windows system I have a fresh install of Ruby 2.2.1 (32-bit) on my Windows 7 system.  I also installed the devkit without any reported errors.  Naturally I thought I could just install the 'wdm' gem with:
gem install wdm

However, it errors out.  The entire output is a bit much to post the entire thing so truncated the following points come up.
C:/Ruby22/bin/ruby.exe -r ./siteconf20150318-1712-oq5nlb.rb extconf.rb
checking for main() in -lkernel32... yes
checking for windows.h... yes
checking for ruby.h... yes
checking for HAVE_RUBY_ENCODING_H... yes
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
generating wdm_ext-i386-mingw32.def
compiling entry.c
In file included from entry.c:1:0:
wdm.h:3:0: warning: "WINVER" redefined [enabled by default]
...
wdm.h:4:0: warning: "_WIN32_WINNT" redefined [enabled by default]
...
warning: #warning Please include winsock2.h before windows.h [-Wcpp]
compiling monitor.c  (this is repeated for multiple *.c files)
...
rb_monitor.o: In function `rb_monitor_run_bang':
C:\Ruby22\lib\ruby\gems\2.2.0\gems\wdm-0.1.0\ext\wdm/rb_monitor.c:508: undefined reference to `rb_thread_blocking_region'
collect2.exe: error: ld returned 1 exit status
make: *** [wdm_ext.so] Error 1

make failed, exit code 2

Did I miss something?

A: The wdm gem isn't compatible with 2.2. It calls the function rb_thread_blocking_region() which was deprecated in 2.0 and finally removed in 2.2. Also the gem isn't maintained anymore (see its repository and issue tracker).
You could fork the repo, merge the  existing PR that apparently fixes the issue, and build the gem by yourself. Using an older Ruby version could be a solution too.
Update:
The wdm gem was updated to 0.1.1 a while ago. The error is fixed by this version.


text:
Q: Fastify schema fails to validate type of a property of a nested object I am new in using Fastify Js. I have this route that fails to validate the type of properties inside the nested object from inside the body schema.
fastify.put('/comment', {
        schema: {
            body: {
                type: 'object',
                required: ['from', 'body', 'courseCode'],
                properties: {
                    from: {
                        type: 'object',
                        required: ['email', 'username'],
                        properties: {
                            // this is the part where validation fails
                            email: { type: 'string' },
                            username: { type: 'string' },
                        }
                    },
                    body: { type: 'string' },
                    courseCode: { type: 'string' },
                }
            }
        }
    }, async (req, rep) => {
        // logic
        return {someResponse};
    });

I am using REST Client extension in VSCode. This is my sample request
put http://localhost:3000/comment
Content-Type: application/json

{
    "from": {
        /* Notice the `email` and `username`, Fastify does not throw an error or some exception
        that tells this is suppose to be a string and not an integer */
        "email": 3123,
        "username": 123123
    },
    "body": "some comment from enginex",
    "courseCode": "d-c"
}

I also try using insomia.io and postman but the result is the same.
Did I miss something important here? Thank You so much.


text:
Q: How can I make a parametrized Job? I am trying to send parameters to my reader.
public JpaPagingItemReader<Person> reader(@Value("#{jobParameters['PersonId']}")
String id){
    JpaPagingItemReader<Person> reader = new JpaPagingItemReader<Person>();
    reader.setEntityManagerFactory(emf);
    reader.setQueryString("SELECT p from "+Person.class.getName()+" p where Id = "+id);
    reader.setPageSize(10);
    return reader;
}

This in turn would want the parameter to come from step and job methods.
@Bean
public Step step(String id){
    return stepBuilder.get("step").<Person,Person>chunk(100).reader(reader(id))
        .processor(processor())
        .writer(writer()).build();
}

@Bean
public Job personJob(String id){
    return jobBuilder.get("personJob").incrementer(new RunIdIncrementer()).flow(step(id)).end().build();
}

My main method implements CommandLineRunner and the run method is overridden as follows -
@Override
public void run(String... args) throws Exception {
    JobParameters parameters = new JobParametersBuilder()
        .addString("PersonId", "1")
        .toJobParameters();
    jobLauncher.run(job, parameters);
}

The method above will not accept jobParameters as jobLauncher.run(job,parameters) expects job to have no arguments but it does not accept jobLauncher.run(job(id),parameters).
The error received as -
Parameter 0 of method personJob in com.example.JobConfig required a bean of type 'java.lang.String' that could not be found.

Is there any way to get id in my reader?

A: You get this exception because public Step step(String id) is equivalent to public Step step(@Autowired String id) and you don't have a String bean defined in context.
To pass the id from JobParameters object you need to declare JobParameters jobParameters bean and either use @Value("#{jobParameters['PersonId']}" or directly the jobParameters bean.
I'm not familiar with Spring Batch but I guess config should be similar to smth like this:
@Configuration
public class PersonJobConfig {

    @Bean
    public JobParameters jobParameters() {
        return new JobParametersBuilder().addString("PersonId", "1").toJobParameters();
    }

    @Bean
    public Step step(JobParameters jobParameters){
        return stepBuilder.get("step").<Person,Person>chunk(100).reader(reader(jobParameters.getString("PersonId"))
            .processor(processor())
            .writer(writer()).build();
    }

    @Bean
    public Job personJob(JobParameters jobParameters){
        return jobBuilder.get("personJob").incrementer(new RunIdIncrementer()).flow(step(jobParameters.getString("PersonId"))).end().build();
    }

}

A: Your reader should be step-scoped to able to inject job parameters:
@Bean
@StepScope
public JpaPagingItemReader<Person> reader(@Value("#{jobParameters['PersonId']}") String id){
   JpaPagingItemReader<Person> reader = new JpaPagingItemReader<Person>();
   reader.setEntityManagerFactory(emf);
   reader.setQueryString("SELECT p from "+Person.class.getName()+" p where Id = "+id);
   reader.setPageSize(10);
   return reader;
}

This is explained in the StepScope section of the reference documentation.
You don't need to propagate the id in the signature of the step and job beans methods, you can pass null as follows:
@Bean
public Step step() {
   return stepBuilder.get("step")
    .<Person,Person>chunk(100)
    .reader(reader(null))
    .processor(processor())
    .writer(writer())
    .build();
}

@Bean
public Job personJob(){
    return jobBuilder.get("personJob")
       .incrementer(new RunIdIncrementer())
       .flow(step())
       .end()
       .build();
}

Finally, your run method is correct, there is nothing to change there.
Hope this helps.


text:
Q: Deleting Same Text at the Beginning of Every Post I'm importing an RSS feed into WordPress using the WPAllImport plugin and dividing it into posts. The content section of each post contains the same graphic and title at the beginning. I want to eliminate this bit from each post so it doesn't display. I don't know if I can do this with the plugin or in how I display the content in the template.
Thanks!

A: The search and replace command in WP-CLI is perfect for this sort of thing, if you have access to the command line on either your development or live site.
Or there's a search and replace plugin you could try.
Take a backup of your database first before using either of these.
If you want to leave the original posts intact, in case you change your mind later, you could use the the_content filter, and you'd need to use PHP's preg_replace command to swap out the text when the posts are displayed.


text:
Q: Change Chrome bookmark folder icons How can I change the chrome bookmark folder icons?
Right now I'm using a symbolic font:

Is it somehow possible to create custom icons or include FontAwesome for chrome? I'm using Windows 10.

A: Choosing custom icons for bookmark folders in the bookmarks bar is not currently possible. If you'd like to see this in the next Chrome upgrade, make sure to start a new thread with your feature request and also submit feedback directly in Chrome.
To submit feedback directly in Chrome:

*

*Click the Chrome menu (More)  in the top right corner of the browser.

*Select Help.

*Select Report an Issue.

*Add the details of your feature request.

A: Although you cant change folder icon, you can rename the folder name to an Emoji so that you can see next to the folder an icon .
For example you can go to https://emojipedia.org/ search for guitar, peak a result, roll down until you'll find "Copy and paste this emoji" .
Just copy and past it to the rename of the folder.

A: I answered a similar question here.
There isn't currently (November 2019) a way to do this natively, although this functionality is a Chrome feature-request that I would recommend up-voting.
Your options at present are (from easiest to difficult):

*

*Use an emoji in the folder name

*Install a Chrome extension, e.g. Bookmark Favicon Changer or Favicon Changer

*Create a custom HTML redirect on your PC or server as per this article


text:
Q: Upsert Bulk vs Batch Upsert in Salesforce I am trying to upsert large amount of data into Salesforce. I found there are two methods available for this.
1. Use UpsertBulk. This will upsert data in a single shot
2. Use Batching
Create upsert job. create batches for upsert operation.
What is the difference between these two methods?
What is the best way to do bulk upsert?

A: The best way to insert/update/upsert data in bulk is via the recently released and renewed BulkAPIv2. Please see this link: https://resources.docs.salesforce.com/210/latest/en-us/sfdc/pdf/api_bulk_v2.pdf
Bulk API 2.0 simplifies uploading large amounts of data by breaking the data into batches automatically. All you have to do is upload a CSV file with your record data and check back when the results are ready

A: Both methods are using Bulk API
Differences:

*

*Upsert bulk - single operation offered by Salesforce connector which creates a new Job in Salesforce and creates a Batch within the Job. After batch is processed you need to make sure Job will be closed.

*Create Job -> Create Batch - two separate operations of the Salesforce connector to create a new Job and add a new Batch within the Job. After batch(es) is processed you need to make sure Job will be closed.

Both options are pretty similar.
Which one is better for you? I would check the Bulk API limits first and then decide -> Salesforce Bulk API Limits
Depending on the volume of data you are going to process you may want to create one or multiple batches (or maybe use multiple jobs).


text:
Q: The behavior of $H^m_0$ functions on non-smooth boundary These days I am learning Dirichlet problems, which usually view the boundary condition $\partial_x^\beta \phi|_{\partial\Omega}=0$ to the condition that the solution lives in $H^m_0$.
This is acceptable if the boundary is smoot enough, as we can apply trace theorem to show that if $u \in H^m$, $u\in H^m_0 \iff u|_{\partial \Omega}=0$.
but is it true when the boudary is not smooth enough?
As usual notion, here $\Omega$ denotes a bounded open domain with $C^1$ boundary.
$H^m=\{u\in L^2(\Omega)|\partial_x^\beta u\in L^2(\Omega)\ \forall |\beta|\leq m \}$.
$H^m_0$ is the closure of $C_0^\infty(\Omega)$, which is all the smooth functions with compact support in $\Omega$
The question is, suppose $\phi\in C^m(\Omega)$, then is $\phi\in H^m_0 \iff \partial_x^\beta\phi|_{\partial \Omega}=0\  \forall |\beta|\le m-1$ true or not? Where the restriction is taken in classical sence.


text:
Q: runonuithread not called from asynctask doinbackground I have a multiple progressbars which are added in a fragment and are updated in an asynctask. Now I want to replace and reset a progressbar when it is completed. I start a new asynctask to get the other related content and updated the UI in its postexecute. This is how I am doing it:
//my asynctask to update the progressbar
@Override
    protected Integer doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        // display the images in now playing
        while (ScheduleManager.isScheduleRunning) {
            Iterator iterator = nowPlayingMediaSet.entrySet().iterator();
            // set images on now playing
            for (int i = 0; i < btnImgNowPlaying.length && iterator.hasNext(); ++i) {
                Map.Entry mEntry = (Map.Entry) iterator.next();
                Show mShowNowPlaying = (Show) mEntry.getKey();
                // get show status
                mProgressStatus[i] = ScheduleManager
                        .getCurrentPlayingShowStatus(mShowNowPlaying);

                if (mProgressStatus[i] > 100) {
                    this.newSchedule = (ChannelSchedule) mEntry
                            .getValue();
                    // get now playing show and replace it
                    this.newShow = ScheduleManager
                            .getNowPlayingShow(newSchedule.getListOfShows());
                    iterator.remove();
                    final int index = i;
                    FragmentTvGuide.GetParentActivity().runOnUiThread(
                            new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    new ScheduleListnerTask(
                                            btnImgNowPlaying[index])
                                            .execute(newShow
                                                    .getShowThumb()); //does not get invoked
                                }
                            });
                    this.newShowAdded = true;
                }
                // Update the progress bar

            }
            if (newShowAdded){
                this.nowPlayingMediaSet.put(newShow, newSchedule);
                newShowAdded = false;
            }
            publishProgress(mProgressStatus);
            // sleep 1 second to show the progress
            try {
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

//this is how get the parentactivity from fragment
//in onactivitycreated
context = getActivity();  //context is static
public static Activity GetParentActivity(){
        return (Activity) context;
    }

I do not know what has gone wrong here? Any ideas?
EDIT
This is the asynctask that I am trying to invoke:
public class ScheduleListnerTask extends AsyncTask<String, Void, Bitmap> {

    ImageButton btnImage;
    public ScheduleListnerTask(ImageButton btnImage){
        this.btnImage = btnImage;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        // TODO Auto-generated method stub
        String urldisplay = params[0];
        Bitmap mIcon11 = null;
        ImageLoader iLoader = ImageLoader.getInstance();
        try {
            mIcon11 = iLoader.loadImageSync(urldisplay);
        } catch (Exception e) {
            Log.e("Error", "image download error");
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        // TODO Auto-generated method stub
        btnImage.setImageBitmap(result);
    }
}

A: I think you forgot to call execute() on the new task...
EDIT: ok sorry, you didn't...
However I find starting a new asynctask out of another async task by running it on UIthread a little weired...Why don't you publish a progress at this point, and start the new task from onprogressupdated...?