text:
Q: Rails find record with zero has_many records associated This seems fairly simple but I can't get it to turn up on Google.
If I have:
class City < ActiveRecord::Base
  has_many :photos
end

class Photo < ActiveRecord::Base
  belongs_to :city
end

I want to find all cities that have no photos. I'd love to be able to call something like...
City.where( photos.empty? )

...but that doesn't exist. So, how do you do this kind of query?

Update:
Having now found an answer to the original question, I'm curious, how do you construct the inverse?
IE: if I wanted to create these as scopes:
scope :without_photos, includes(:photos).where( :photos => {:city_id=>nil} )
scope :with_photos, ???

A: I used a join to get all the ones with photos:
scope :with_photos, -> { joins(:photos).distinct }
Easier to write and understand, for that particular case. I'm not sure what the efficiency is of doing a join vs doing an includes, though

A: In Rails versions >= 5, to find all cities that have no photos, you can use left_outer_joins:
City.left_outer_joins(:photos).where(photos: {id: nil})

which will result in SQL like:
SELECT cities.*
FROM cities LEFT OUTER JOIN photos ON photos.city_id = city.id
WHERE photos.id IS NULL

Using includes:
City.includes(:photos).where(photos: {id: nil})

will have the same result, but will result in much uglier SQL like:
SELECT cities.id AS t0_r0, cities.attr1 AS t0_r1, cities.attr2 AS t0_r2, cities.created_at AS t0_r3, cities.updated_at AS t0_r4, photos.id AS t1_r0, photos.city_id AS t1_r1, photos.attr1 AS t1_r2, photos.attr2 AS t1_r3, photos.created_at AS t1_r4, photos.updated_at AS t1_r5
FROM cities LEFT OUTER JOIN photos ON photos.city_id = cities.id
WHERE photos.id IS NULL

A: When trying to find records with no matching records from the joined table, you need to use a LEFT OUTER JOIN
scope :with_photos, joins('LEFT OUTER JOIN photos ON cities.id = photos.city_id').group('cities.id').having('count(photos.id) > 0')
scope :without_photos, joins('LEFT OUTER JOIN photos ON cities.id = photos.city_id').group('cities.id').having('count(photos.id) = 0')

A: Bah, found it here: https://stackoverflow.com/a/5570221/417872
City.includes(:photos).where(photos: { city_id: nil })

A: I don't believe the accepted answer gives you exactly what you're looking for, as you want to do a LEFT OUTER JOIN and that answer will give you a INNER JOIN.  At least in Rails 5 you can use:
scope :without_photos, left_joins(:photos).where( photos: {id: nil} )

or you can use merge in cases where namespacing will make the where clause cumbersome:
scope :without_photos, left_joins(:photos).merge( Photos.where(id: nil) )

A: If you are not running Rails 5+ and performance is a must-have, avoid useless ActiveRecord creation and get just what you need:
City.where("NOT EXISTS(SELECT 1 FROM photos WHERE photos.city_id = cities.id LIMIT 1)")


text:
Q: video player caption not enable after set caption file I am using https://plyr.io/ to have a video player with captions. (Documentation: https://github.com/sampotts/plyr).
Below is the steps to reproduce caption issue with video player with example code:
In the page load initialize the video player in jquery document load.

<video controls
       crossorigin
       playsinline
       id="player">
</video>

inside jquery page load:

 const video = document.querySelector('video');
     const player = new Plyr(video, {
        captions: {active:false},
    });

*After page load upload the .mp4 file and set to the video player like below:

 player.source = {
            type: 'video',
            title: mvFileName,
            sources: [
                {
                    src: mvUrl,
                    type: mvfileContentType,
                    size: 720,
                }
            ],
            poster: posterPath,
        };

Till here i could able to set the .mp4 file to the video and it is playing the video fine.

*Then i upload the subtitle file(.vtt) and set to this video player like below:

const track = document.createElement('track');
        Object.assign(track, {
            kind: "captions",
            label: $('#hdnMVSubttleLangName').val(),
            srclang: $('#hdnMVSubttleShortLang').val(),
            src: jsonResponse.SubtitleUrl,
        });
        player.media.appendChild(track);

After this code when i inspect the video i could find like the track tag set inside the video tag with subtitle path like below:

<video crossorigin="" data-poster="/Content/Movies/MoviePoster/47eb9kRPz4g=MV.png" playsinline="" src="/Content/Movies/47eb9kRPz4g=MV.mp4"><source src="/Content/Movies/47eb9kRPz4g=MV.mp4" type="video/mp4" size="720">
<track kind="captions" label="English" srclang="en" src="/Content/Movies/MovieSubtitle/vdoSubtle.vtt">

</video>

After setting subtitle just after used below code to make the caption active:

player.captions.active = true;

Issue: Now in the video caption icon not enabled, Also in settings, I could see caption option available.
Also, Please suggest your best approach, If in above used any code is wrong.
Need help

redpajama_set_name: RedPajamaStackExchange


text:
Q: Haskell space leak in hash table insertion I have been coding a histogram and I have had some great help on here. I have been coding my histogram using a hash table to store the keys and frequency values because the distribution of the keys are unknown; so they might not be sorted or consecutively together.
The problem with my code is that it spends too much time in GC so looks like a space leak as the time spent in GC is 60.3% - so my productivity is a poor 39.7%.
What is going wrong? I have tried to make things strict in the histogram function and I've also in-lined it (GC time went from 69.1% to 59.4%.)
Please note I have simplified this code by not updating the frequencies in the HT.
{-# LANGUAGE BangPatterns #-}
import qualified Data.HashTable.IO as H
import qualified Data.Vector as V

type HashTable k v = H.BasicHashTable k v

n :: Int
n = 5000000

kv :: V.Vector (Int,Int)
kv = V.zip k v
 where
    k = V.generate n (\i -> i `mod` 10)
    v = V.generate n (\i -> 1)

histogram :: V.Vector (Int,Int) -> Int -> IO (H.CuckooHashTable Int Int)
histogram vec !n = do
    ht <- H.newSized n
    go ht (n-1)
        where
            go ht = go'
                where
                    go' (-1) = return ht
                    go' !i = do
                        let (k,v) = vec V.! i
                        H.insert ht k v
                        go' (i-1)
{-# INLINE histogram #-}

main :: IO ()
main = do
    ht <- histogram kv n
    putStrLn "done"

Here's how it is compiled:
ghc --make -O3 -fllvm -rtsopts histogram.hs

Diagnosis:
jap@devbox:~/dev$ ./histogram +RTS -sstderr
done
     863,187,472 bytes allocated in the heap
     708,960,048 bytes copied during GC
     410,476,592 bytes maximum residency (5 sample(s))
       4,791,736 bytes maximum slop
             613 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0      1284 colls,     0 par    0.46s    0.46s     0.0004s    0.0322s
  Gen  1         5 colls,     0 par    0.36s    0.36s     0.0730s    0.2053s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time    0.51s  (  0.50s elapsed)
  GC      time    0.82s  (  0.82s elapsed)
  EXIT    time    0.03s  (  0.04s elapsed)
  Total   time    1.36s  (  1.36s elapsed)

  %GC     time      60.3%  (60.4% elapsed)

  Alloc rate    1,708,131,822 bytes per MUT second

  Productivity  39.7% of total user, 39.7% of total elapsed

A: For the sake of comparison, this is what I get running your code as posted:
     863,187,472 bytes allocated in the heap
     708,960,048 bytes copied during GC
     410,476,592 bytes maximum residency (5 sample(s))
       4,791,736 bytes maximum slop
             613 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0      1284 colls,     0 par    1.01s    1.01s     0.0008s    0.0766s
  Gen  1         5 colls,     0 par    0.81s    0.81s     0.1626s    0.4783s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time    1.04s  (  1.04s elapsed)
  GC      time    1.82s  (  1.82s elapsed)
  EXIT    time    0.04s  (  0.04s elapsed)
  Total   time    2.91s  (  2.91s elapsed)

  %GC     time      62.6%  (62.6% elapsed)

  Alloc rate    827,493,210 bytes per MUT second

  Productivity  37.4% of total user, 37.4% of total elapsed

Given that your vector elements are just (Int, Int) tuples, we have no reason not to use Data.Vector.Unboxed instead of plain Data.Vector. That already leads to significant improvement:
     743,148,592 bytes allocated in the heap
          38,440 bytes copied during GC
     231,096,768 bytes maximum residency (4 sample(s))
       4,759,104 bytes maximum slop
             226 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0       977 colls,     0 par    0.23s    0.23s     0.0002s    0.0479s
  Gen  1         4 colls,     0 par    0.22s    0.22s     0.0543s    0.1080s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time    1.04s  (  1.04s elapsed)
  GC      time    0.45s  (  0.45s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time    1.49s  (  1.49s elapsed)

  %GC     time      30.2%  (30.2% elapsed)

  Alloc rate    715,050,070 bytes per MUT second

  Productivity  69.8% of total user, 69.9% of total elapsed

Next, instead of hand-rolling recursion over the vector, we might use the optimised functions the vector library provides for that purpose. Code...
import qualified Data.HashTable.IO as H
import qualified Data.Vector.Unboxed as V

n :: Int
n = 5000000

kv :: V.Vector (Int,Int)
kv = V.zip k v
 where
    k = V.generate n (\i -> i `mod` 10)
    v = V.generate n (\i -> 1)

histogram :: V.Vector (Int,Int) -> Int -> IO (H.CuckooHashTable Int Int)
histogram vec n = do
    ht <- H.newSized n
    V.mapM_ (\(k, v) -> H.insert ht k v) vec
    return ht
{-# INLINE histogram #-}

main :: IO ()
main = do
    ht <- histogram kv n
    putStrLn "done"

... and result:
     583,151,048 bytes allocated in the heap
          35,632 bytes copied during GC
     151,096,672 bytes maximum residency (3 sample(s))
       3,003,040 bytes maximum slop
             148 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0       826 colls,     0 par    0.20s    0.20s     0.0002s    0.0423s
  Gen  1         3 colls,     0 par    0.12s    0.12s     0.0411s    0.1222s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time    0.92s  (  0.92s elapsed)
  GC      time    0.32s  (  0.33s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time    1.25s  (  1.25s elapsed)

  %GC     time      25.9%  (26.0% elapsed)

  Alloc rate    631,677,209 bytes per MUT second

  Productivity  74.1% of total user, 74.0% of total elapsed

81MB saved, not bad at all. Can we do even better?
A heap profile (which should be the first thing you think of when having memory consumption woes - debugging them without one is shooting in the dark) will reveal that, even with the original code, peak memory consumption happens very early on. Strictly speaking we do not have a leak; we just spend a lot of memory from the beginning. Now, note that the hash table is created with ht <- H.newSized n, with n = 5000000. Unless you expect to have so many different keys (as opposed to elements), that is extremely wasteful. Changing the initial size to 10 (the number of keys you actually have in your test) improves things dramatically:
     432,059,960 bytes allocated in the heap
          50,200 bytes copied during GC
          44,416 bytes maximum residency (2 sample(s))
          25,216 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0       825 colls,     0 par    0.01s    0.01s     0.0000s    0.0000s
  Gen  1         2 colls,     0 par    0.00s    0.00s     0.0002s    0.0003s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time    0.90s  (  0.90s elapsed)
  GC      time    0.01s  (  0.01s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time    0.91s  (  0.90s elapsed)

  %GC     time       0.6%  (0.6% elapsed)

  Alloc rate    481,061,802 bytes per MUT second

  Productivity  99.4% of total user, 99.4% of total elapsed

Finally, we might as well make our life simpler and try using the pure, yet efficient, hash map from unordered-containers. Code...
import qualified Data.HashMap.Strict as M
import qualified Data.Vector.Unboxed as V

n :: Int
n = 5000000

kv :: V.Vector (Int,Int)
kv = V.zip k v
 where
    k = V.generate n (\i -> i `mod` 10)
    v = V.generate n (\i -> 1)

histogram :: V.Vector (Int,Int) -> M.HashMap Int Int
histogram vec =
    V.foldl' (\ht (k, v) -> M.insert k v ht) M.empty vec

main :: IO ()
main = do
    print $ M.size $ histogram kv
    putStrLn "done"

... and result.
          55,760 bytes allocated in the heap
           3,512 bytes copied during GC
          44,416 bytes maximum residency (1 sample(s))
          17,024 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0         0 colls,     0 par    0.00s    0.00s     0.0000s    0.0000s
  Gen  1         1 colls,     0 par    0.00s    0.00s     0.0002s    0.0002s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time    0.34s  (  0.34s elapsed)
  GC      time    0.00s  (  0.00s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time    0.34s  (  0.34s elapsed)

  %GC     time       0.0%  (0.0% elapsed)

  Alloc rate    162,667 bytes per MUT second

  Productivity  99.9% of total user, 100.0% of total elapsed

~60% faster. It remains to be seen how it would scale with a larger amount of keys, but with your test data unordered-containers ends up being not only more convenient (pure functions; actually updating the histogram values only takes changing M.insert to M.insertWith) but also faster.


text:
Q: slack api rtm.start missing_scope needed client I have get access token and when I try to post rtm.start, I am getting below error:
{
    error = "missing_scope";
    needed = client;
    ok = 0;
    provided = "identify,read,post";
}

I have set the scope to read,post,identify in authorize API. I have read the API document over and over again. Only rtm.start mentioned client scope. But in oauth document I didn't find a client scope. So, what's wrong?

A: Under App Credentials get your Client ID and Client Secret.
Goto:
https://#{team}.slack.com/oauth/authorize?client_id=#{cid}&scope=client

replacing #{team} and #{cid} with your values.
When you approve the authorization you'll goto that real url that doesn't resolve. Copy the whole url to your clipboard and paste it into a text file. Extract out just the "code" part.
Now goto:
https://#{team}.slack.com/api/oauth.access?client_id=#{cid}&client_secret=#{cs}&code=#{code}"

And you'll get back a token like:
xoxp-4422442222–3111111111–11111111118–11aeea211e
(from here: https://medium.com/@andrewarrow/how-to-get-slack-api-tokens-with-client-scope-e311856ebe9)

A: You have to do it before you get the token.
when you do the initial request to connect the app, include &scope="identify,read,post,client"


text:
Q: Angularjs: checking radio box automatically Here is my radio buttons code
<input type="radio"  ng-model="choice.phone" ng-value="1" name="phone" ng-
click="setPhoneType('cell')"> cell phone

<input type="radio"  ng-model="choice.phone" ng-value="2" name="phone" ng-
click="setPhoneType('Home')"> Home phone

Now when a user choose any of them then below radio button should be checked as default
<input type="radio" ng-model="choice.International" ng-value="1"
name="international" ng-click="setChoiceType('Inter')" ng-checked="choice.phone"> International call

The js code is as follow:
setPhoneType = function setPhoneType(phoneType) {
                    $scope.phone = phoneType;
                    $scope.setChoiceType('Inter');
                    return;
 },
 setChoiceType = function setChoiceType(callType) {
                    $scope.international = callType;
                    return;
                },

The problem is that when I choose any phone then the Inter is checked automatically but later on the value is undefined, It goes to setChoiceType but after that choice.International is undefined. If I manually choose Inter (by clicking on it) it is fine.

A: Your radio buttons are bound to properties of the choice object.  But, setPhoneType and setChoiceType update values directly on the scope - not the choice object.  Also, I think you want to use value, not ng-value.
Here is plnkr.


text:
Q: Open the quotes after the character string ')' I try to insert data to my table but the problem is that give me an error in
the clause Return Cmd.ExecuteReader:

Open the quotes after the character string ')'

here the code I have in My file MyModule.VB .
    Public Module MyModule1
Public ServerName As String = "MIRA"
Public dataBaseName As String = "BaseDB"

Public Cn As New SqlConnection("server=" & ServerName & "; initial catalog=" & dataBaseName & " ; integrated security= true")
Public Cmd As New SqlCommand
Public Dr As SqlDataReader

Public Sub OpenCn()
    If Cn.State <> ConnectionState.Open Then
        Cn.Open()

    End If
End Sub

Public Sub CloseCn()
    If Cn.State = ConnectionState.Open Then
        Cn.Close()

    End If
End Sub
'Type r = select w insert updaate delete
Public Function ExecSQL(ByVal sql As String, Optional ByVal type As String = "r")
    OpenCn()
    Cmd.CommandType = CommandType.Text
    Cmd.CommandText = sql
    Cmd.Connection = Cn
    If type = "r" Then
        Return Cmd.ExecuteReader

    Else
        Return Cmd.ExecuteNonQuery

    End If
    CloseCn()

End Function
Public Function AddDB(ByVal natureD As String, ByVal codeP As String, ByVal exigence As String, ByVal nomE As String, ByVal Dt As String, ByVal equipe As String, ByVal Dat1 As String, ByVal Suivi As String)
 Return ExecSQL("insert into DossierB values('" & natureD & "', '" & codeP & "', '" & exigence & "', '" & nomE & "', '" & Dt & "', '" & equipe & "', '" & Dat1 & "', '" & Suivi & "' )")

End Function
End Sub

HERE THE CODE OF AjoutDB.aspx.vb
Public Class AjoutDB
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim natureD = Request.Form("DropDownList1")

    Dim codeP = Request.Form("TextBox2")
    Dim exigence = Request.Form("TextBox5")
    Dim nomE = Request.Form("TextBox4")
     Dim dt = Request.Form("TextBox8")
    Dim equipe = Request.Form("TextBox6")
    Dim Dat1 = Request.Form("TextBox9")
    Dim Suivi = Request.Form("TextBox7")
    AddDB(natureD, codeP, exigence, nomE, dt, equipe, Dat1, Suivi)
    MsgBox("données inserees")
End Sub

End Class
THANKS A LOT

A: You need to parameterize your query. That doesn't directly answer your question, but until you paramterize your queries, there's no end to the errors you might see.
As it is, your database is easily manipulated by an attacker. In fact, the security of your entire machine could be in jeopardy.
Here's a basic explanation and an example of parameterization: https://stackoverflow.com/a/7505842/1415038


text:
Q: Cannot connect to Kafka running on a virtual machine I installed kafka_2.10-0.8.1.1 on a Ubuntu 12.04 (Linux ubuntu 3.8.0-44-generic) hosted by vmware player 6.0.3 build-1895310. On the host machine (Windows 8) I am using the C# client from https://github.com/Jroland/kafka-net. The ip of the kafka machine is correctly configured in C# code, the topic "test" is accordingly created in kafka etc. I get the following messages:

No connection to:http://:9092/.  Attempting to re-connect...
  Type a message and press enter...
  Awaiting message from: http://:9092/
  BrokerRouter: Refreshing metadata for topics: test
  Failed re-connection to:http://:9092/.  Will retry in:1000
  Failed re-connection to:http://:9092/.  Will retry in:2000
  Failed re-connection to:http://:9092/.  Will retry in:4000

The same client connects to a physical linux machine with kafka.
I would like to be able to develop with kafka running as a virtual machine. How could I solve the communication issue?
Thanks

A: I never used the c# version, but is your producer configure correctly?
From the error message, it seems that it doesn't have the IP/DNS configured...

No connection to:http://:9092/


text: Q: Key binding for image window ImageJ I am using IJ library in Java. I use ImageWindow to display some images. I know that I can key binding a Jcomponent as a shortkey to execute some function. Can I key binding to ImageWindow so I can save the image when pressing ctrl+s?


text:
Q: Internal subsets of nonstandard extensions. I am studying the first chapter of L. O. Arkeryd et. al: Nonstandard Analysis. Theory and Applications.
There it is shown that for the multiset $(\mathbb{X}, \mathcal{P}(\mathbb{X}))$ it is possible to find a nonstandard extension $(^*\mathbb{X}, {^*\mathcal{P}(\mathbb{X})})$ satisfying $\mathbb{X}\subset{^*\mathbb{X}}$ and ${^*\mathcal{P}(\mathbb{X})} \subset \mathcal{P}({^*\mathbb{X}})$. From thereon, it is always assumed that the considered nonstandard extension is of this form.
Recall that a subset of $^*\mathbb{X}$ is called internal if it is also an element of $^*\mathcal{P}(\mathbb{X})$.
In Exercise 5.5 one should show that every standard element of $^*\mathcal{P}(\mathbb{X})$ is an internal subset. This confuses me, since under the above assumption it looks like every element of $^*\mathcal{P}(\mathbb{X})$ is an internal subset. I also see how to show that every standard element of $^*\mathcal{P}(\mathbb{X})$ is an internal subset without the above assumption.
Basically my question is the following: Am I missing something here, i.e. under the assumption $^*\mathcal{P}(\mathbb{X})\subset \mathcal{P}(^*\mathbb{X})$ can there be an element of $^*\mathcal{P}(\mathbb{X})$ which is not an internal subset?


text:
Q: R functions with compiled C code slow the agrep function in R is based on C code and is executed as such.
However, I notice a significant (order of magnitude) performance gap between executing agrep from within R as compared to a direct system call to the command line executable of agrep. (tested only on Linux so far)
The essence of my code is this (x is a vector of 250K strings, xNoisy is a vector of 1000 randomly sampled strings in x, modified by a few random chars):
system.time( sapply(xNoisy, FUN = agrep,  x=x,max.distance = 2))
system.time(for (p in xNoisy) tmp=system(paste0("agrep -2 ", p, " strings.txt"),intern=TRUE) )

(Here strings.txt is the file containing the strings in x.)
The first line takes 700 secs, the second 10 (!) secs.
Why is this and is there any way to come closer to the performance of the Linux agrep within R ?


text:
Q: A few questions about dual bases and bilinear forms I'm on my journey to understanding linear algebra. I've reached the point where I have to understand the dual basis and bilinear forms. This is something I didn't find in the book that I learn from (David Poole's A Modern Introduction to Linear Algebra). My teacher at the university did some examples so I want to understand them.
I know what a basis is. I know also what the geometrical interpretation is. I also know what is a quadratic form (is it related in any way to bilinear forms?)
Could you please summarize what is a bilinear form and a dual base? Also, if there is any geometrical interpretation, please list it. Thank you a lot!

A: (I'm going to assume that we're talking about real finite-dimensional vector spaces here, although what I'm about to say mostly generalizes.)
Every vector space $V$ has a dual $V^*=Hom(V,\mathbb{R})=\{\mbox{ linear }x:V\to\mathbb{R}\}$.

Exercise: $V^*$ is a vector space.

In fact, $V^*$ is a finite-dimensional vector space.  See this by choosing a basis $\{b_i\}$ of $V$, and defining $\beta_i$ to be the linear function such that $\beta_i(b_j)=\delta_{ij}$.

Exercise: The $\beta_i$  form a basis of $V^*$.

These form the "dual basis" of $\{b_i\}$, and of course implies that $V^*$ has the same dimension as $V$.

Exercise: A choice of basis induces an isomorphism $V\leftrightarrow V^*$.

But a priori any isomorphism depends on a choice of basis!  $V$ is isomorphic to $V^*$, but without extra structure, one cannot say that $V$ is equal to $V^*$.
A bilinear form $\langle\cdot,\cdot\rangle$ is a bilinear map* $V\times V\to\mathbb{R}$.  The dot product on $\mathbb{R}^n$ is a bilinear form.  A choice of symmetric, nondegenerate* bilinear form determines an isomorphism $V\leftrightarrow V^*$ via $v\mapsto \langle -,v\rangle$.
*N.B.: Your professor's definition of "bilinear form" may vary from mine here.  The term is often taken to mean symmetric and positive-definite right out of the box.

Exercise: The map $v\mapsto\langle-,v\rangle$ induced by a symmetric, nondegenerate bilinear form is an isomorphism.

You'll want to make your peace someday with tensor algebras, which are the natural homes of symmetric bilinear forms.  Introducing you to them is beyond the scope of this post.
For an abstract, perhaps unreadable, introduction, you might consult chapter 2 of Warner, Introduction to Differentiable Manifolds and Lie Groups.  I would myself welcome any suggestions of advanced linear algebra textbooks.

A: To answer just one of your questions, let me work over a field $k$ of characteristic $\neq 2$, such as $\mathbf R$. Then one can pass back and forth between quadratic forms and symmetric bilinear forms as follows. A quadratic form $f\colon k^n \to k$ on $k^n$ (thought of as column vectors) corresponds to a (unique) symmetric $n \times n$ matrix $A$ such that
$$
f(x) = {}^txAx. \qquad \text{[${}^tx$ is the transpose of the column vector $x$]}
$$
But we can also define a map $g\colon k^n \times k^n \to k$ by
$$
g(x, y) = {}^txAy,
$$
and this is a symmetric bilinear form (take the transpose of the right-hand side). Can you see how to go in the other direction?


text:
Q: Git Update / Clone Error: "insufficient permission for adding an object" or "refs writable by group" I'm using an network external drive to backup my git server (a Debian system, git version 1.7.10.4).
In very short the external backup drive is mounted using
mount -t cifs //external/backup/drive/path /media/drive/ -o user=a_user,password=a_password

For new repo, my script does
sudo git clone --mirror file:///new_repo

For existing repos
sudo git remote update

Everything went OK, but recently I started to get error reports on new repos:
fatal: Could not make /media/drive/new_repo.git/refs writable by group

and on some of the old ones
error: insufficient permission for adding an object to repository database ./objects

I have checked consistency of user (root) read/write access among various repo, both on the server and on the backup drive
drwxr-xr-x 0 root root 4096 Nov 10 12:18 repo1.git
drwxr-xr-x 0 root root 4096 Nov 10 12:18 repo2.git
drwxr-xr-x 0 root root 4096 Nov 10 12:20 repo3.git
drwxr-xr-x 0 root root 4096 Nov 10 12:25 repo4.git

and didn't found any issue. I know files are not "group writable" but since it works for 80% of the repos, I suspect the issue is not their.
I have also checked that core.sharedRepository is set to true as suggested in related topics without success.
I suspected different rights between root (the one running the backup script) and the login used to mount the drive. But then why do I get different behavior on various repos??
Please bear with me if my question is not original enough, but I search intensively this site and the rest of the internet without success. This is really starting to drive me nuts.
With best regards


text:
Q: How to keep vertical scroll position of jqGrid while trigger reloadGrid?
Possible Duplicate:
How to reload JQuery grid keeping scroll position and collapse elements open

The jqGrid will scroll top when trigger reloadGrid.
Is there a option of JqGrid or any idea to keep the vertical scroll position of jqGrid while trigger reloadGrid?
Many thanks!


text:
Q: Generate random value by condition I've an array:
$themes = ['class-A', 'class-B','class-C','class-D','class-E','class-F']

And I have the following condition:
I need to generate 12 classes out of that where:

*

*class-A will occur exactly once or none.

*class-B will occur either 3 or 6 times.

*class-C or class-D has no limit, can occur as many times.

*Class-E  will occur exactly twice or none.

*class-F will occur exactly once or none.

How can I achieve this? Thanks!

A: I implemented a working Demo here that must satisfy all of your rules
<?php

$randomClassesArr = [];

while (sizeof($randomClassesArr) <= 12) {
  $letter = chr(rand(65,70));
  $classLetter = 'class-' . $letter;

  if($letter === 'A' || $letter === 'F') {
    if(!in_array($classLetter, $randomClassesArr)) {
      $randomClassesArr[] = $classLetter;
    }
  } elseif($letter === 'B') {
    $occurences = array_count_values($randomClassesArr);
    $classBOccurence = $occurences[$classLetter] ?? 0;

    if($classBOccurence !== 3) {
      $randomClassesArr[] = $classLetter;
    }

  } elseif($letter === 'E') {
    $occurences = array_count_values($randomClassesArr);
    $classEOccurence = $occurences[$classLetter] ?? 0;

    if($classEOccurence !== 2) {
      $randomClassesArr[] = $classLetter;
    }
  } else {
    $randomClassesArr[] = $classLetter;
  }
}

highlight_string("<?php\n\$randomClassesArr =\n" . var_export($randomClassesArr, true) . ";\n?>");

echo '

';

highlight_string("<?php\n\$countValues =\n" . var_export(array_count_values($randomClassesArr), true) . ";\n?>");

?>

Check working demo here and feel free to edit on top of it.

A: Another possible implementation
<?php

$classAPossibleOccuences = [0,1];
$classARandomChosenOccurence = $classAPossibleOccuences[array_rand($classAPossibleOccuences)];

$classBPossibleOccuences = [3,6];
$classBRandomChosenOccurence = $classBPossibleOccuences[array_rand($classBPossibleOccuences)];

$classEPossibleOccuences = [0,2];
$classERandomChosenOccurence = $classEPossibleOccuences[array_rand($classEPossibleOccuences)];

$classFPossibleOccuences = [0,1];
$classFRandomChosenOccurence = $classFPossibleOccuences[array_rand($classFPossibleOccuences)];

$generatedRandomClassesArr = [];

if($classARandomChosenOccurence) {
  $generatedRandomClassesArr[] = 'class-A';
}

if($classFRandomChosenOccurence) {
  $generatedRandomClassesArr[] = 'class-F';
}

for($i = 0; $i < $classBRandomChosenOccurence; $i++) {
  $generatedRandomClassesArr[] = 'class-B';
}

if($classERandomChosenOccurence) {
  for($i = 0; $i < $classERandomChosenOccurence; $i++) {
    $generatedRandomClassesArr[] = 'class-E';
  }
}

while(sizeof($generatedRandomClassesArr) < 12) {
  $randomCOrD = ['C','D'];
  $randomClass = $randomCOrD[array_rand($randomCOrD)];
  $generatedRandomClassesArr[] = 'class-' . $randomClass;
}

//randomize array elements
shuffle($generatedRandomClassesArr);

highlight_string("<?php\n\$generatedRandomClassesArr =\n" . var_export($generatedRandomClassesArr, true) . ";\n?>");

echo '

';

highlight_string("<?php\n\$countValues =\n" . var_export(array_count_values($generatedRandomClassesArr), true) . ";\n?>");

?>

Check working demo


text:
Q: Why is the composer command not found? Why is the composer instruction from README, is failing when i apply as below?

Tried as below but failing:
# uname -a
Linux signal 3.10.0-123.8.1.el7.x86_64 #1 SMP Mon Sep 22 19:06:58 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

# php --version
PHP 5.4.16 (cli) (built: Oct 31 2014 12:59:36)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies

# ls
LICENSE    bootstrap.php  detect.php  index.php
README.md  composer.json  hooks       templates

# composer create-project whichbrowser/server .
-bash: composer: command not found

# php composer create-project whichbrowser/server .
Could not open input file: composer

EDIT:
[root@signal wb]# php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
Installer verified
[root@signal wb]# php composer-setup.php
All settings correct for using Composer
Downloading 1.2.1...

Composer successfully installed to: /var/www/html/sip-phone/tls/website/wb/composer.phar
Use it: php composer.phar
[root@signal wb]# php -r "unlink('composer-setup.php');"
[root@signal wb]# php composer.phar create-project whichbrowser/server .
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Installing whichbrowser/server (v2.0.12)

  [InvalidArgumentException]
  Project directory ./ is not empty.

create-project [-s|--stability STABILITY] [--prefer-source] [--prefer-dist] [--repository REPOSITORY] [--repository-url REPOSITORY-URL] [--dev] [--no-dev] [--no-custom-installers] [--no-scripts] [--no-progress] [--no-secure-http] [--keep-vcs] [--no-install] [--ignore-platform-reqs] [--] [<package>] [<directory>] [<version>]

[root@signal wb]#

A: You not installed composer, please install it:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

EDIT:
Read how to install: https://getcomposer.org/download/
you create project whichbrowser/server at non empty directory, try create project at empty directory:
mkdir ./myproject
php composer.phar create-project whichbrowser/server ./myproject


text:
Q: UICollectionViewCell gets squished after running in simulator I have designed a collection view cell, seen below:
,
When I try to run it in the simulator it is getting resized, as below:

I have not set any constraints to the collection view and didn't resize it programatically.  How can I correct this issue?

A: If you are trying to make it shown correctly,
you should use size class or constrains, since Xcode will resize it for all models, not knowing your thoughts.
You can't leave it there without adding constrains


text:
Q: Why does the jQuery slide bounce on selection? This is my first attempt to create a button based slider.
Every slide is divided into 2 parts, the left part contains an image and the right part contains some text. When switching slides there's an unexpected bounce just before the slide loads and I can't seem to understand why it occurs.
Is there any good way to implement this same slide?
Here is the code:

$( function() {
  imw_slider();
})

function imw_slider() {
    var button = $( '.slide-button' );
    button.click( function() {
     button.css( 'background-color', '#fff' );
     $(this).css( 'background-color', '#eee' );
        var index = $(this).index();
        var image = $(this).parent().prev();
 image.children('.slide:not(:nth-child('+(index+1)+'))').fadeOut( function() {
            image.children('.slide:nth-child('+(index+1)+')').fadeIn();
        });
    });
}
.image-box > .images {
    text-align: center;
}

.image-box > .images > .slide:nth-child(1) {
    display: block;
}

.image-box .slide.slide-2 {
    position: relative;
    max-width: 80rem;
    margin: 0 auto;
}

.image-box > .images > .slide {
    display: none;
}

.image-box > .images > .slide:after {
  display: block;
  content: '';
  clear: both;
}

.image-box .slide.slide-2 > div {
    width: 50%;
    float: left;
}

.image-box .buttons {
    display: table;
    margin: 0 auto;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 4px;
    overflow: hidden;
}

.image-box .buttons .slide-button {
    display: table-cell;
    cursor: pointer;
    padding: 2px 10px;
    border-right: 1px solid #ccc;
}

This is the text for slide 1

This is the text for slide 2

This is the text for slide 3

button-1button-2button-3

A: Instead of fading out all the slides other than the one that is been faded in, you can first hide them and fade in the current slide using this:
image.children('.slide:not(:nth-child('+(index+1)+'))').hide();
image.children('.slide:nth-child('+(index+1)+')').fadeIn();

Or better still, you can save the last active slide and fade out that and fade in the current one:
    if (prev_slide) {
      prev_slide.fadeOut(function() {
        prev_slide = image.children('.slide:nth-child(' + (index + 1) + ')');
        prev_slide.fadeIn();
      });
    } else {
      prev_slide = image.children('.slide:nth-child(' + (index + 1) + ')');
      prev_slide.fadeIn();
    }

See demo below:

$(function() {
  imw_slider();
})
var prev_slide = null;

function imw_slider() {
  var button = $('.slide-button');
  button.click(function() {
    button.css('background-color', '#fff');
    $(this).css('background-color', '#eee');
    var index = $(this).index();
    var image = $(this).parent().prev();
    if (prev_slide) {
      prev_slide.fadeOut(function() {
        prev_slide = image.children('.slide:nth-child(' + (index + 1) + ')');
        prev_slide.fadeIn();
      });
    } else {
      prev_slide = image.children('.slide:nth-child(' + (index + 1) + ')');
      prev_slide.fadeIn();
    }
  });
}
.image-box > .images {
  text-align: center;
}
.image-box > .images > .slide:nth-child(1) {
  display: block;
}
.image-box .slide.slide-2 {
  position: relative;
  max-width: 80rem;
  margin: 0 auto;
}
.image-box > .images > .slide {
  display: none;
}
.image-box > .images > .slide:after {
  display: block;
  content: '';
  clear: both;
}
.image-box .slide.slide-2 > div {
  width: 50%;
  float: left;
}
.image-box .buttons {
  display: table;
  margin: 0 auto;
  margin-top: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}
.image-box .buttons .slide-button {
  display: table-cell;
  cursor: pointer;
  padding: 2px 10px;
  border-right: 1px solid #ccc;
}

This is the text for slide 1

This is the text for slide 2

This is the text for slide 3

button-1button-2button-3

A: It seems JQuery is calling the callback of the fadeOut function immediately. There is a related discussion you can refer to: JQuery fadeOut(function(){fadeIn});
You can simply delay the fadeIn:

$( function() {
  imw_slider();
})

function imw_slider() {
    var button = $( '.slide-button' );
    button.click( function() {
     button.css( 'background-color', '#fff' );
     $(this).css( 'background-color', '#eee' );
        var index = $(this).index();
        var image = $(this).parent().prev();
 image.children('.slide:not(:nth-child('+(index+1)+'))').fadeOut( 1000, function() {
            image.children('.slide:nth-child('+(index+1)+')').delay(1000).fadeIn(1000);
        });
    });
}
.image-box > .images {
    text-align: center;
}

.image-box > .images > .slide:nth-child(1) {
    display: block;
}

.image-box .slide.slide-2 {
    position: relative;
    max-width: 80rem;
    margin: 0 auto;
}

.image-box > .images > .slide {
    display: none;
}

.image-box > .images > .slide:after {
  display: block;
  content: '';
  clear: both;
}

.image-box .slide.slide-2 > div {
    width: 50%;
    float: left;
}

.image-box .buttons {
    display: table;
    margin: 0 auto;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 4px;
    overflow: hidden;
}

.image-box .buttons .slide-button {
    display: table-cell;
    cursor: pointer;
    padding: 2px 10px;
    border-right: 1px solid #ccc;
}

This is the text for slide 1

This is the text for slide 2

This is the text for slide 3

button-1button-2button-3


text:
Q: My robot framework jar file with dependencies after maven install command is shown as corrupt file, Kindly assist A snapshot.jar file of robot framework and its dependencies was created in eclipse after running maven install command. But the jar file is not able to execute my robot test cases as an error throws up: corrupt jar file.
I have searched about configuring pom.xml for robot framework as suggested in How to run test cases using robot framework jar file?,  but could not build a proper jar file.
The primary purpose is that the jar file should be able to execute QA test cases in any remote or other system
Can someone please assist, its very important

A: Most likely, you are trying to add a tar.gz robot-selenium dependency instead of a jar robot-selenium dependency.
Follow the instructions here:
https://github.com/Hi-Fi/robotframework-seleniumlibrary-java
And here: http://robotframework.org/MavenPlugin/index.html


text:
Q: How to use proxy by curl_init? <?php
$url = 'http://www.php.net/';
$proxy = '104.41.154.213:8118';
//$proxyauth = 'user:password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$data = curl_exec($ch);
curl_close($ch);

if (preg_match('<body class="home ">', $data)) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

It's working when I am stopped using the proxy but not working on any proxy. Can anyone please help me where is the problem?

A: You need to set proxytype for your curl.
curl_setopt($ch,CURLOPT_PROXYTYPE,xxxxxxx);

You also can debug the curl error, with
if($data === false)
  echo 'Curl error: ' . curl_error($ch);


text:
Q: TinyMCE (with Ajax) - Re-adding editor causes undefined error I am reloading content of a div using an ajax request.
  <div>
        <textarea id="content-value" rows="15" cols="40" class="tinymce" style="width:100%"></textarea>
  </div>

Within this div I have a text area that is initialized with tinymce...
        tinyMCE.init({
            mode: "specific_textareas",
            editor_selector: "tinymce",
            theme : "advanced",
            theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|formatselect,fontsizeselect,|,code",
            theme_advanced_buttons2: "",
            theme_advanced_buttons3: "",
            theme_advanced_buttons4: "",
            height: "340",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : false
        });

After loading the content with an AJAX request, I remove the editor, replace the content, and then attempt to re-add the editor to tinyMCE.
   function OnCreateResponse(response) {
            if(response.success) {
                tinymce.EditorManager.execCommand('mceRemoveControl',true, 'content-value');
                $(dlgElem).html(response.html);
                tinymce.EditorManager.execCommand('mceAddControl', true, 'content-value');
            }
        }
    }

Upon re-adding tinyMCE gives me the following error

Error: tinyMCE.get("content-value") is
  undefined

when executing ...
tinymce.EditorManager.execCommand('mceAddControl', true, 'content-value');

Does anyone have any ideas as to what I am doing wrong?


text:
Q: What are all the ways to import modules in Python? I've done some research, and I came across the following article: http://effbot.org/zone/import-confusion.htm. While this seems to be a great guide, it was written in 1999, a while back. I'm am using Python 3.4.3, so I am thinking that some things have changed, which worries me, because I don't want to learn what is not applicable. Therefore, in Python 3, what are all of the ways to import packages and modules, in detail? Which ways are the most common and should be used above others?

A: The only ways that matter for ordinary usage are the first three ways listed on that page:

*

*import module

*from module import this, that, tother

*from module import *
These haven't changed in Python 3.  (Some of the details about where Python looks for the module.py file to load module have been tweaked, but the behavior of the import itself still works as described on the page you linked.)
One thing has been added, before Python 3 but since that article.  That is explicit relative imports.  These let you do things like from ..module import blah.  This kind of import can only be used from inside a package; it lets modules in a package refer to other modules in the same package in a way that is relative to the package (i.e., without having to specify how to import the top-level package).  You can read the details in PEP 328.  Even this, though, is basically just a new variation on the from module import blah style syntax mentioned on the page you linked to.
__import__ also still works in Python 3.  This is an internal function that you only would need to use if doing something rather unusual.  The same applies to various functions in the importlib module (and the deprecated imp module).  The exact level of wizardliness of these importing functions varies from one to another, but for ordinary usage of "I just want to import this module and use it", you essentially never need to use them.  They're only needed if you want to do something like dynamically import a module whose name isn't known until runtime.

A: The Zen of Python gives you some hints:
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

So given the simple, obvious method is: import module_name and it preserves namespaces I would suggest that while there are several import methods as you can see from the python3 manual entry and you can extend them by overriding the __import__() method or by rolling your own I would say stick with it until you have a good reason not to.
The fact that__import__() is surrounded by double underscores is also a hint to leave it alone.
If you are looking to understand the design decisions behind the import mechanisms then start with the manual then follow up into the PEPs 302 & 420 are good starting points.

A: I think import as tuple would be much better for readability and Maximum Line Length(pep8)
The import statement has two problems:

*

*Long import statements can be difficult to write, requiring various
contortions to fit Pythonic style guidelines.

*Imports can be ambiguous in the face of packages; within a package,
it's not clear whether import foo refers to a module within the package or some module outside the package.

*golang language have the same thing for that

so would more prefer import kinda this
from package import (x, y)

instead of this
from authentication.views import SignupView, LoginView, VerificationView, SignupDetailView

https://legacy.python.org/dev/peps/pep-0328/

A: We can import modules in Python using the following ways

*

*import module

*from module import function

*from module import *

Although using from module import *
  is not a good practice, because of readability: Other programmer cannot understand what all are actually used in the current module. Memory overload: All are loaded in to memory. Best practices for using import in a module.

A: Say you have python modules (mymod1.py, mymod2.py files containing different functions) inside mypkg package (folder having init.py file, it can be an empty file).
#mymod1.py
def add_fun(a,b):
    return a+b
def sub_fun(a,b):
    return a-b
def mul_fun(a,b):
    return a*b
def div_fun(a,b):
    return a/b

#mymod2.py
def fun1(...):
    ........
    ........
def fun2(...):
    ........
    ........

Following are different ways to import:
from mypkg.mymod1 import *  #import all the function from mymod1
add_fun(10, 20)
mul_fun(10, 2)

from mypkg.mymod1 import add_fun,div_fun  #import only needed functions from mymod1
add_fun(10, 20)
div_mul(10, 2)

from mypkg import mymod1  #import mymod module
mymod1.add_fun(10, 20)
mymod1.mul_fun(10, 2)

import mypkg    #import package and use different models inside it
mypkg.mymod1.add_fun(10, 20)
mypkg.mymod1.mul_fun(10, 2)


text:
Q: ListView postion in list after scrolling How can I detect listView item to change or make some actions when it was scrolled above the center of screen?
UPD  Solution
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {

        int half = visibleItemCount/2;
        int to = firstVisibleItem+half;

        for (int i=firstVisibleItem; i<to; i++) {
                          // actions for item above center
            Item item = (Item)adapter.getItem(i);
            item.read = true;
        }
        adapter.notifyDataSetChanged();
    }

A: You can achieve this using a combination of methods. If your ListView stretches the whole screen (i.e., height is set to MATCH_PARENT), you can determine the center of your screen as the total number of children / 2. Use the getChildCount() method for this job.
As Ayoub said, you can also use a ListView.OnScrollListener to listen for scroll changes in your ListView.
In case your ListView's height does not match the available window screen, you can use this to find the available window height:
 DisplayMetrics metrics = getResources().getDisplayMetrics();
 int windowWidth = metrics.widthPixels;
 int windowHeight = metrics.heightPixels

A: You can set a ListView.OnScrollListener, and check if the item you want scrolls above the center. The onScroll method will supply you with the number of items visible, the index of the first one and the total items of your list, knowing this you should be able to determinate when an element scrolls over a position.


text:
Q: How to convert QString to LPCSTR (Unicode) how can I convert QString to LPCSTR ?
How do I do it when #ifdef UNICODE is defined and when it isn't ?
Thanks very much :)

A: QString can always hold Unicode; LPCSTR is never Unicode. This means that you do have to consider what to do with the characters that won't fit. This isn't a "which method to use" question, but a design question.
It's quite possible that in your specific case, you absolutely know that the QString only contaisn characters from your local "ANSI" codepage (also known as ACP). In that case, the correct function is QString::toLocal8Bit ().
Alternatively, you might know that the QString only contains characters from Latin1 (ISO 8859-1). In that case, the correct function is QString::toLatin1().
You could try to call QString::toUtf8(). This will always produce a valid byte array, even if the QString contained all Unicode characters. However, formally you can't point a LPCSTR to it: UTF-8 is not a valid ACP codepage. And presumably, you want this LPCSTR to pass to another function outside your control. It's likely that function won't expect UTF-8. If it expected Unicode at all, it would take a LPCWSTR.

A: I guess:
QString str("ddddd");
LPCSTR lstr = str.toStdString().c_str();

A: I found following solution from here and it works flawlessly for me:
void fooSub(LPSTSTR X); // this is our function :-)

foo()
{
    QString text;
    if(sizeof(TCHAR) == 1)
        fooSub((LPCSTR)text.toLocal8Bit().constData()); // here you have to check, how to convert, you could also use utf8(), ...
    else
        fooSub((LPCWSTR)text.utf16());
}

A: LPCSTR == const char *

it's not unicode, then

LPCSTR s = (const char *)qtString;


text:
Q: SSL session migration I configured my tomcat (6.0.29) cluster "by the book", using only the NIO HTTP connector load balanced by httpd mod_proxy_balancer (HTTP/HTTPS). When using HTTP, i can kill servers and still use my session perfecty. When using HTTPS the session is lost on failover.
Anyone had this kind of problem or can give me a hint to where i should debug this? The logs show no errors. My current connector looks like this:
<Connector port="8080"
           protocol="org.apache.coyote.http11.Http11NioProtocol"
           connectionTimeout="5000"
           maxThreads="500"
           minSpareThreads="25"
           maxSpareThreads="75"
           acceptCount="10"
           redirectPort="443"
           proxyName="www.govdigital.com.br"
           proxyPort="80" />

httpd proxy.conf:
#SSL
LoadModule ssl_module modules/mod_ssl.so
Listen 443
NameVirtualHost *:443
<VirtualHost _default_:443>
  ErrorLog logs/ssl_error_log
  TransferLog logs/ssl_access_log
  LogLevel warn
  SSLEngine on
  SSLProtocol all -SSLv2
  SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW

  #Certificate, PK and CA Bundle
  SSLCertificateFile /srv/httpd/exported-pem.crt
  SSLCertificateKeyFile /srv/httpd/exported.key
  SSLCACertificateFile /srv/httpd/cabundle.pem
</VirtualHost>

#Proxy
ProxyRequests Off
ProxyPass / balancer://mycluster/ stickysession=JSESSIONID|jsessionid
ProxyPassReverse / balancer://mycluster/
<Proxy balancer://mycluster>
    AddDefaultCharset Off
    #Working nodes
    BalancerMember http://10.1.1.2:8080 route=worker1
    BalancerMember http://10.1.1.3:8080 route=worker2
</Proxy>

#Cache
CacheEnable disk /decorators
CacheEnable disk /scripts
CacheRoot /ram/cache/
CacheDirLevels 6
CacheDirLength 3

CacheMaxFileSize 1000000
CacheMinFileSize 1

#Agressive caching
CacheIgnoreCacheControl On
CacheIgnoreNoLastMod On
CacheIgnoreQueryString Off
CacheIgnoreHeaders None
CacheLastModifiedFactor 0.1
CacheDefaultExpire 3600
CacheMaxExpire 86400
CacheStoreNoStore On
CacheStorePrivate On

ErrorDocument 503 "Bad Servers<br/>No donuts for you"

thanks in advance :)


text:
Q: Diferencia en creación de objetos c# Cuál es la diferencia entre hacer esto:
Recibo recibo = new Recibo();

En donde Recibo es una clase, Y esto:
Impuestos impuestos;

En donde Impuestos también es una clase.

A: En la primera estas declarando una variable de tipo Recibo y además la estás instanciando con un nuevo objeto de tipo Recibo.
En el segundo caso solo estás declarando la variable de tipo Impuestos y al no instanciarla tendrá el valor por defecto que en el caso de los reference types es null.
Ten en cuenta que en el primer caso también pudiste haberlo definido de esta manera:
var recibo = new Recibo();

El resultado es exactamente el mismo: Se define una varible de tipo Recibo y se la instancia con un objeto de tipo Recibo ya que C# infiere el tipo de la variable con el tipo del valor de retorno de la expresión de la derecha de la asignación es decir new Recibo().
En el segundo caso ya que no se asigna nada es obligatorio indicar el tipo de la variable

A: Impuestos impuestos;

En C# en este caso no estas creando un objeto o instancia de Impuesto, sino solo la referencia a el, por lo tanto la variable impuestos tendrá valor null.
Recibo recibo = new Recibo();

En este caso, estas creando una instancia de Recibo y estas guardando su referencia en la variable "recibo".

A: Cuando escribes Recibo recibo = new Recibo(); creas una nueva instancia de la clase Recibo. Las instancias son objetos que se crean y almacenan en memoria. A ellos puedes acceder despues de inicializados junto con todas sus operaciones de ahí que se utilize new antes de la clase. Puedes inicializar una clase Object objeto = new Recibo() también.
La segunda linea Impuestos impuestos; solo declara la variable impuestos pero todavía no tiene guardada la instancia de Impuestos. De manera que si la llamas te retornara un valor nulo.
Normalmente al principio de tu código declaras las variables que quieres utilizar y despues la inicializas (Cuando quieres variables globales) pero si quieres trabajar de manera local lo haces todo en una sola línea.

A: Paso a aclarar un error de concepto.
Tanto:
Recibo recibo ...

Como:
Impuestos impuestos;

Son solamente declaraciones de variables del tipo Recibo e Impuestos respectivamente. Estas variables, para ser utilizadas, deberán primero apuntar a un objeto en memoria.
No es hasta que haces new de la clase que creas una nueva instancia de que puedes usar:
   Recibo recibo; // Aqui declaramos la variable recibo. La misma es sólo el punto de acceso a una futura instancia. Todavía no hay objeto en memoria asignado a la misma.

   recibo = new Recibo(); // Aqui es cuando, mediante la palabra reservada *new*, creamos el objeto en memoria. A partir de este momento es que pueden ser usados sus métodos y propiedades.

Espero haber aclarado tu duda. Saludos!


text:
Q: Pytsk - Sending files to a server from a disk image I am trying to send each file from a disk image to a remote server using paramiko.
class Server:
    def __init__(self):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect('xxx', username='xxx', password='xxx')

    def send_file(self, i_node, name):
        sftp = self.ssh.open_sftp()
        serverpath = '/home/paul/Testing/'
        try:
            sftp.chdir(serverpath)
        except IOError:
            sftp.mkdir(serverpath)
            sftp.chdir(serverpath)
        serverpath = '/home/Testing/' + name

        sftp.putfo(fs.open_meta(inode = i_node), serverpath)

However when I run this I get an error saying that "pytsk.File has no attribute read".
Is there any other way of sending this file to the server?

A: After a quick investigation I think I found what your problem is.  Paramiko's sftp.putfo expects a Python file object as the first parameter. The file object of Pytsk3 is a completely different thing. Your sftp object tries to perform "read" on this, but Pytsk3 file object does not have a method "read", hence the error.
You could in theory try expanding Pytsk3.File class and adding this method but I would not hold my breath that it actually works.
I would just read the file to a temporary one and send that. Something like this (you would need to make temp file name handling more clever and delete the file afterwards but you will get the idea):
serverpath = '/home/Testing/' + name
tmp_path = "/tmp/xyzzy"
file_obj = fs.open_meta(inode = i_node)

# Add here tests to confirm this is actually a file, not a directory

tha = open(tmp_path, "wb")
tha.write(file_obj.read_random(0, file_obj.info.meta.size))
tha.close()

rha = open(tmp_path, "rb")
sftp.putfo(rha, serverpath)
rha.close()
# Delete temp file here

Hope this helps. This will read the whole file in memory from fs image to be written to temp file, so if the file is massive you would run out of memory.
To work around that, you should read the file in chunks looping through it with read_random in suitable chunks (the parameters are start offset and amount of data to read), allowing you to construct the temp file in a chunks of for example a couple of megabytes.
This is just a simple example to illustrate your problem.
Hannu


text:
Q: Trying to implement a comments system with laravel Trying to implement a comments system using pusher on my laravel project. Everything seems to be in order, however every post request which is meant to send the input data to the database returns with error 500.
Used F12 on firefox to monitor what gets sent to /tip/select, it seems that it passes the text of the comment just fine, so it could be the issue with the controller.
Routes
    Route::get('/tip/select','TipController@select');
Route::post('/tip/select', 'TipController@addComment');

Comment model
namespace App;

use Illuminate\Database\Eloquent\Model;
use Zttp\Zttp;
use App\model\User;
use App\Tip;

class Comment extends Model
{
protected $guarded = [];

protected $table='comments';
//protected $fillable=['tip_id','user_id','body'];
public static function moderate($comment)
       {
           $response = Zttp::withoutVerifying()->post("https://commentator.now.sh", [
               'comment' => $comment,
               'limit' => -3,
           ])->json();
           if ($response['commentate']) {
               abort(400, "Comment not allowed");
           }
       }
public function tip(){
 return $this->belongsTo('App\Tip');
}
public function user(){
 return $this->belongsTo('App\model\User');
}
}

Controller

use Pusher\Laravel\Facades\Pusher;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Input;
use DB;
use Image;
use App\Tip;
use App\model\User;
use App\Subcategories;
use App\Category;
use App\City;
use App\Comment;
use App\CityAreas;
//use App\Http\Requests\TipFormRequest;

class TipController extends Controller
{
 public function select(){
     //$db=DB::table('tips')->orderBy('created_at','desc');
     $data=Tip::get();

     $url = Storage::disk('s3');
     //$data=Tip::paginate(10);
     //$data=$db->get();
     // dd($data);
     $comments = Comment::orderBy('id')->get();
     return view('tip', compact('data', 'url','comments'));
}

/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/

 public function create(){
   $categories=Category::all();
   $cities=City::all();
   return view('tip.create',compact('categories','cities'));
 }

 /**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/

 public function store(Request $request, City $city, Category $category){
   $this->validate($request, [
     'image' => 'image|nullable|max:1999']);
   $tipsnew = new Tip;
   $tipsnew->title = $request->title;
   $tipsnew->description = $request->description;
   $tipsnew->category_id = $request->category;
   $tipsnew->city_id = $request->city;
   $tipsnew->user_id = auth()->id();
   $tipsnew->url = $request->url;

  if ($request->hasFile('image')) {
     try{

       $file = $request->file('image');
       $name = time() . '.' . $file->getClientOriginalExtension();
       $img = \Image::make($file->getRealPath());
       $img->fit(1080);
       $img->stream();
       Storage::disk('s3')->put('tip'.'/'.$name, $img->__toString());
       $tipsnew->image = 'tip'.'/'.$name;
     }
     catch (\Exception $e)
               {
                   $response = [
                       'information' => 'Error. Something went wrong. Please try again',
                   ];
                   $statusCode = 400;
                   return response()->json($response, $statusCode);
             }
       }
   $tipsnew->save();

   return redirect ('tip/create')->with('status','your tip is created');
 }

 public function edit($id){
   $tip=Tip::whereId($id)->firstOrFail();
   $categories=Category::all();
   $selectedCategories=$tip->categories->lists('id')->toArray();
   return view('tip.edit',compact('tip','categories','selectedCategories'));
 }

 public function search(Request $request, City $city, Category $category, User $user){
     $q = $request->get('q');
     if ($q != ""){
      $tips = Tip::where('title','LIKE','%'.$q.'%')
                 ->orWhere('description','LIKE','%'.$q.'%')
                 ->orWhereHas('user', function($id) use($q){
                   return $id->where('name', 'LIKE','%'.$q.'%');
                 })
                 ->orWhereHas('city', function($id) use($q){
                   return $id->where('name', 'LIKE','%'.$q.'%');
                 })
                 ->orWhereHas('category', function($id) use($q){
                   return $id->where('name', 'LIKE','%'.$q.'%');
                 })
                 ->get();
              if(count($tips) > 0)
        return view('tip.search', ['tips' => $tips]);
     }
 }

 public function addComment(Request $request)
    {
        $data = $request;
        Comment::moderate($data['text']);
        $comment = Comment::create($data);
        Pusher::trigger('comments', 'new-comment', $comment, request()->header('X-Socket-Id'));
        //add creation of new comment to DB
        $commentnew = new Comment;
        $commentnew->user_id = Auth::user()->id();
        //$commentnew->tip_id= $request->post(['tip_id']);
        $commentnew->body = $request->text;
        $commentnew->save();
        return $comment;
    }
}

Snippet of the blade

Comments

<form onsubmit="addComment(event);">
                      <input type="text" placeholder="Add a comment" name="text" id="text" required>
                      <input type="hidden" name="tip_id" id="tip_id" value="{{$val->tip_id}}">
                      <input type="hidden" name="username" id="username" value="{{Auth::user()->name}}">
                      <button id="addCommentBtn">Comment</button>
                  </form>

                      @foreach($comments as $comment)

                              {{ $comment->username }}

                              {{ $comment->text }}

                      @endforeach


text:
Q: Condition import of dart:io or dart:html I need to use the File class which is different (as for what I understand) in web and html
I would like to be able to do
import if (dart.library.io) 'dart:io' if (dart.library.io) 'dart:html';

but this doesn't work.
What is the solution to reading File from dart:io on mobile apps and from dart:html in web?
Thank you

A: The cross_file package can help you. Or you can use conditional imports like :
import 'dart:io' if (dart.library.html) 'dart:html';


text:
Q: Redirect when login after build -- prod, Using Angular 5 After build --prod, when I login the http request is sent to the server, but when it back the page reload (redirect to the same page)
and I get no errors in the console log.
It is working in ng serve.
(The production server is running on Apache)
I also build ng build --prod --base-href http://system.******.com/
Service provider code
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';
import { Observable }     from 'rxjs/Observable';
import {HttpClient, HttpHeaders} from "@angular/common/http";
@Injectable()
export class UserServiceService {

baseUrl: string = 'http://api.equity.com.eg/api/';
private _options = { headers: new Headers({ 'Content-Type':'application/json' }) };

constructor(public http: HttpClient) {

}

login(userData){
let _options = {headers: new HttpHeaders({ 'Content-Type': 'application/json'})};
return this.http.post(`${this.baseUrl}login`, JSON.stringify(userData), _options);
// .catch(this.handleError);
  }
}

Component Code:
  goToHome() {

    this.userService.login(this.userLogin).subscribe((data: any) => {
      this.errMsg = false;
      this.cookieService.set('token', data.token);
      window.localStorage.setItem('token', data.token);
      let test = this.cookieService.get('token');
      this.router.navigateByUrl('pages');
    }, err => {
      console.log(err);
      this.errMsg = true;
    });

.htaccess code
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

I tried to change how the http request sent from the service provider to the old http Angular 4 way (.map) and the same problem occurs.
Also I tried to change the .htacces with other rules from the forums for angular in production, the same problem occurs.

A: Finally, the problem was happening because uglify not preventing form default behavior in angular cli  @angular/cli@1.6.2
so they solved it in in @angular/cli@1.6.3
to fix it install the latest cli global
$ npm uninstall -g angular-cli
$ npm install -g @angular/cli@latest

then in the angular project folder
$ rm -rf node_modules dist
$ npm uninstall --save-dev angular-cli
$ npm install --save-dev @angular/cli@latest
$ npm install


text:
Q: asp core web api http post is null I created a webapi by looking at the ms basic documentation.
ms Doc
it was work
todoitems
Besides todoitems I
Because I wanted to use it in the form of Avatar Chart
Insert the model Avatarchart, create Avatarchartcontext, and make the controller as a scaffold.
solution view
However, when I tried to receive data as a post, the data always came in null.
error
null
this is code
[Route("api/AvatarCharts")]
    [ApiController]
    public class AvatarChartsController : ControllerBase
    {
        private readonly AvatarChartContext _context;

        public AvatarChartsController(AvatarChartContext context)
        {
            _context = context;
        }

        // GET: api/AvatarCharts
        [HttpGet]
        public async Task<ActionResult<IEnumerable<AvatarChart>>> GetAvatarCharts()
        {
            return await _context.AvatarCharts.ToListAsync();
        }

        // GET: api/AvatarCharts/5
        [HttpGet("{modelId}")]
        public async Task<ActionResult<AvatarChart>> GetAvatarChart(long modelId)
        {
            var avatarChart = await _context.AvatarCharts.FindAsync(modelId);

            if (avatarChart == null)
            {
                return NotFound();
            }

            return avatarChart;
        }

        // PUT: api/AvatarCharts/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{modelId}")]
        public async Task<IActionResult> PutAvatarChart(long modelId, AvatarChart avatarChart)
        {
            if (modelId != avatarChart.modelId)
            {
                return BadRequest();
            }

            _context.Entry(avatarChart).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AvatarChartExists(modelId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/AvatarCharts
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<AvatarChart>> PostAvatarChart( AvatarChart avatarChart)
        {
            _context.AvatarCharts.Add(avatarChart);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
        }

        // DELETE: api/AvatarCharts/5
        [HttpDelete("{modelId}")]
        public async Task<IActionResult> DeleteAvatarChart(long modelId)
        {
            var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
            if (avatarChart == null)
            {
                return NotFound();
            }

            _context.AvatarCharts.Remove(avatarChart);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool AvatarChartExists(long modelId)
        {
            return _context.AvatarCharts.Any(e => e.modelId == modelId);
        }
    }

 public class AvatarChartContext :DbContext
    {
        public AvatarChartContext(DbContextOptions<AvatarChartContext> options) : base(options)
        {

        }
        public DbSet<AvatarChart> AvatarCharts { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AvatarChart>().HasKey(c => c.modelId);

        }
    }

public class AvatarChart
    {
        [Key]
        public long modelId;
        public string colorCode;
        public long dateTime;        //ex 20210101130000
        public string name;
        public string diagnose;

    }

swagger
add postgressql dbenter image description here

A: Update:
You missed the {get; set;}.
public class AvatarChart
{
    [Key]
    public long modelId {get; set;}
    public string colorCode {get; set;}
    public long dateTime {get; set;}        //ex 20210101130000
    public string name {get; set;}
    public string diagnose {get; set;}

}

A: Can you make these changes and tell me what value is being returned on the variable result. Also, can you validate your ModelState first?
[HttpPost]
public async Task<ActionResult> PostAvatarChart( AvatarChart avatarChart)
{
        await _context.AvatarCharts.AddAsync(avatarChart);
        var result = await _context.SaveChangesAsync() > 0;

        return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
    }


text:
Q: Cassandra 2.1.0-beta2: Invalid set literal for ColumnDefinition I'm trying out Cassandra 2.1.0-beta2 for nested user defined types. These are the structures that has been created through cqlsh 5.0.0:
CREATE TYPE channelsource(id text, sources set<text>);
CREATE TYPE primaryfeed(name text, type text, multisource channelsource);

CREATE TABLE somedata (
source text PRIMARY KEY,
unitid text,
dayssincebirth text,
reporttime text,
somefeed primaryfeed
);

This sample insert fails:
INSERT INTO somedata (source, unitid, dayssincebirth, reporttime, somefeed)
VALUES('GFDS8-v1.2.3', 'xxxxxxxx-ABCD-1234-B8F9-11111177F4', '89', '13:02:39',
{'dha', 'foo', {'someid', {'aa', 'cc'}}});

With this error:
code=2200 [Invalid query] message="Invalid set literal for ColumnDefinition
{name=somefeed, type=org.apache.cassandra.db.marshal.UserType
(bispace,7072696d61727966656564,6e616d65:org.apache.cassandra.db.marshal.UTF8Type,
74797065:org.apache.cassandra.db.marshal.UTF8Type,6d756c7469736f75726365:
org.apache.cassandra.db.marshal.UserType(bispace,6368616e6e656c736f75726365,6964
:org.apache.cassandra.db.marshal.UTF8Type,736f7572636573:
org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UTF8Type))),
 kind=REGULAR, componentIndex=0, indexName=null, indexType=null} of type primaryfeed"

Any pointers on what the correct syntax I should be using? I'm assuming that nested user defined types are supported in 2.1 onwards.

A: You basically need to pass also the name of the fields, i.e.
{name: 'dha', type: 'foo', ...}

More details are in this article http://www.datastax.com/dev/blog/cql-in-2-1
Note: the syntax you used ( {'val', 'val'}) is the syntax for sets and that explains the error you are seeing.


text:
Q: Separating phrases occuring a file-Unix Shell I have a file with tags for some file paths. they appear in sets as shown below:-
comp1 : path1
comp2 : path2
comp3 : path3
comp1 : path4
comp1 : path5
comp2 : path6
comp1 : path7
comp2 : path8
comp3 : path9
comp4 : path10
comp1 : path11
comp2 : path12

where

*

*compN :- are the tags

*pathN :- paths for different files

the expected output is:

comp1 : path11
comp2 : path12
I want to extract the last set from this file. but the problem is, these sets vary in the number of lines, i.e., some have just one line, some have upto ten. Is my doubt now clear?

A: You can use sort for that:
$ sort -u file
comp1
comp2
comp3
comp4

The -u flag tells sort to only keep unique lines
Or if you must use awk, you can do
awk '!a[$0]++' file

Answer to updated question
Use this awk command:
$ awk '{a[$1]=$0}END{for (i in a) print a[i]}' file
comp1 : path11
comp2 : path12
comp3 : path9
comp4 : path10

A: >cat comp.txt
comp1
comp2
comp3
comp4
comp1
comp2
comp3
comp1
comp2
comp1
comp2
comp3
comp4
>sort comp.txt | uniq
comp1
comp2
comp3
comp4

A: perl -lne '$count++;push @a,$_;$i=$count if(/comp1/);END{print join "\n",@a[($i-1)..(scalar(@a)-1)]}' your_file

tested below:
> cat temp
comp1
comp2
comp3
comp4
comp1
comp2
comp3
comp1
comp2
comp1
comp2
comp3
comp4
> perl -lne '$count++;push @a,$_;$i=$count if(/comp1/);END{print join "\n",@a[($i-1)..(scalar(@a)-1)]}' temp
comp1
comp2
comp3
comp4
>

A: I believe the Python solution is more readable then the Perl
for line in sorted(set(open('comp.txt').readlines())):
  print line.strip()

you would run it like
echo -e "for line in sorted(set(open('comp.txt').readlines())):\n  print line.strip()" | python
comp1
comp2
comp3
comp4

A: $ awk '/^comp1 /{set=""} {set=set $0 ORS} END{printf "%s",set}' file
comp1 : path11
comp2 : path12

A: one thing can be done is knowing that set always starts with comp1 we can traverse from the end till the first "comp1" occurs. Once index of "comp1" is known from the end, we can print out the lines or last "set".
awk -F':' 'BEGIN{cnt = 0} {a[cnt1++] = $1; b[cnt2++] = $2;}
END{for(i = NR; i >= 0; i--){if(a[0] == a[i]){cnt++;
if(cnt == 1){k= i;}}} for(j=k;j<NR;j++)print a[j],":",b[j];}' inputfile

a array collects comp entries, b array collects path entries, -F':' option used in awk command seperates both entries based on ':' delimiter.
Or simpler way,
awk '$1~/comp1/{cnt=NR}{array[count++]=$0}END{for(i=cnt-1;i<=NR;i++)print array[i]}'
inputfile


text:
Q: Updating a table row with random number fails I am using a while loop in a stored procedure to update each row of my table but the update value remains the same for all rows.For instance,in my table the generated number is 2266 for all rows instead of a unique digit.
My stored procedure looks like this
DELIMITER ;;
CREATE PROCEDURE lesrows()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE lesrand INT DEFAULT 0;
SELECT COUNT(*) FROM students INTO n;
select(FLOOR(2000 + RAND() * (3000 - 2000) )) into lesrand;
SET i=0;
WHILE i<n DO
  UPDATE students set student_number= lesrand;
  SET i = i + 1;
END WHILE;
End;
;;

call lesrows();

Why is it inserting a constant number for all rows instead of a unique number for every row?.

A: The while statement sets the whole table's student_number's the lesrand on every single iteration. You want a new random number of each iteration (inside the loop) and you want to select students one-by-one using WHERE with your variable i
Something like this:
SET i=0;
WHILE i<n DO
select(FLOOR(2000 + RAND() * (3000 - 2000) )) into lesrand;
UPDATE students set student_number= lesrand WHERE student_ID = i;
SET i = i + 1;
END WHILE;

A: I haven't tested it, but it looks like lesrand is only assigned once. Have you tried moving select(FLOOR(2000 + RAND() * (3000 - 2000) )) into lesrand; into the while loop like this:
DELIMITER ;;
CREATE PROCEDURE lesrows()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE lesrand INT DEFAULT 0;
SELECT COUNT(*) FROM students INTO n;
SET i=0;
WHILE i<n DO
  select(FLOOR(2000 + RAND() * (3000 - 2000) )) into lesrand;
  UPDATE students set student_number= lesrand;
  SET i = i + 1;
END WHILE;
End;
;;

call lesrows();

And why are you using a stored procedure. Wouldn't UPDATE students SET student_number = FLOOR(2000 + RAND() * (3000 - 2000)) have the same result?


text:
Q: cmake - how do i do add_cd_file but for directories I am trying to add cygwin to the reactos project. everytime i try doing
add_cd_file(${CMAKE_CURRENT_SOURCE_DIR}/cygwin DESTINATION reactos/cygwin FOR all)

It fails because it is not a file, I have tried to use copy but that just copies the file, it does not add it to the destination. So my question is how do I do something like this add_cd_dir?


text:
Q: Метка карты яндекс Как вывести координаты метки при нажатии на кнопку "ссылочка"? :
<!DOCTYPE html>

    <title>»񲰻顱򠰲. Ѡ譥񥭨塨𠪲飭褐롰򻠭ࡱ򰠭鷥</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    [JS]
    [/JS]

    Ссылочка

[JS][/JS]

[JS][/JS]

A:     ymaps.ready(init);

var myMap,
    myPlacemark;

function init(){
        myMap = new ymaps.Map("map", {
            center: [55.76, 37.64],
            zoom: 7
        });

        myPlacemark = new ymaps.Placemark([55.76, 37.64], {
            hintContent: 'Москва',
            balloonContent: 'БЛАБЛА'
        });

      myMap.geoObjects.add(myPlacemark);

    }

 function toggle(el) {
    var coordinates = myPlacemark.geometry.getCoordinates();

    el.innerHTML = coordinates;
    el.style.display = (el.style.display == 'none') ? '' : 'none'

}


text:
Q: Angular CDK Drag and Drop won't work after updating component's HTML I have a fresh system of Angular 8. There's one Module with one Component:
ng new my-app --enable-ivy
npm install --save @angular/material @angular/cdk @angular/animations
npm install --save hammerjs

In the Module I'm adding:
import { DragDropModule } from '@angular/cdk/drag-drop';

and also:
@NgModule({
  imports: [
    DragDropModule
  ]
})

In the Component's HTML I added this:
<div cdkDrag>
  Drag me around!
</div>

Now I serve the site using:
ng serve --port 4300

And voila, I can drag the item around.

However, when I update anything of the Component's HTML and the page refreshes, I can't drag the element anymore. The text changes are reflected for example. But the the drag functionality is gone.
When I restart the server on the CLI it works again, until I udate the markup.
This doesn't happen when I change the Component's TypeScript-file, only when the HTML is altered.
What is the problem?

A: This was an issue with Angular 8.0. Updating to Angular 8.2 and the corresponding Angular Material CDK package solved the problem.


text:
Q: UIFont fontName for Bold Lucida Grande I couldn't find the name system name of the Lucida Grande bold font, and I need to use it in [UIFont fontWithName:size:]. Can anybody give me the exact name? couldn't find it on internet lists.
Tnx!

A: You couldn't find it because its not available on the system. You'll need to pick a different font.

A: That font, like many other, is not available for use in iOS. To get the list of the available fonts, use:
    NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
    NSArray *fontNames;
    NSInteger indFamily, indFont;
    for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
    {
        NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
        fontNames = [[NSArray alloc] initWithArray:
                     [UIFont fontNamesForFamilyName:
                      [familyNames objectAtIndex:indFamily]]];
        for (indFont=0; indFont<[fontNames count]; ++indFont)
        {
            NSLog(@"    Font name: %@", [fontNames objectAtIndex:indFont]);
        }
        [fontNames release];
    }
    [familyNames release];

http://ajnaware.wordpress.com/2008/10/24/list-of-fonts-available-on-the-iphone/
Also note that the font list can change with iOS updates.


text:
Q: Android BOOT_COMPLETED not working! This is a simple program i created to test BOOT_COMPLETED event of Android but it's not working! am i doing something wrong here?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.enea.training.bootdemo"
      android:versionCode="1"
      android:versionName="1.0">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <receiver android:name=".BootDemoReceiver">
            <Intent-filter>
                <action android:name ="android.intent.action.BOOT_COMPLETED"></action>
            </Intent-filter>
        </receiver>
    </application>

    <uses-sdk android:minSdkVersion="3" />

</manifest>

java:
public class BootDemoReceiver extends BroadcastReceiver {

    static final String TAG = "BootDemoReceiver";

     @Override
     public void onReceive(final Context context, final Intent bootintent) {
         Log.v(TAG, "Come on");
     }
}

A: I'm not sure if it matters, but try changing <Intent-filter> to <intent-filter> (note lowercase 'i').


text:
Q: Custom dialog with a Timepicker I am starting a new activity from a main activity . I need to display a Time Pickerdialog when a radio button on the main activity is clicked .i am getting an error when i click on the radio button which is suppose to show me the dialog.
CODE
import java.util.Calendar;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.TimePicker;

public class Tilldate extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
    }

}

LOGCAT
10-16 13:01:37.539: E/AndroidRuntime(1435): FATAL EXCEPTION: main
10-16 13:01:37.539: E/AndroidRuntime(1435): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.avst.callxpressmobile/com.example.avst.callxpressmobile.Tilldate}: java.lang.ClassCastException: com.example.avst.callxpressmobile.Tilldate cannot be cast to android.app.Activity
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.os.Looper.loop(Looper.java:137)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.app.ActivityThread.main(ActivityThread.java:4745)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at java.lang.reflect.Method.invokeNative(Native Method)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at java.lang.reflect.Method.invoke(Method.java:511)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at dalvik.system.NativeStart.main(Native Method)
10-16 13:01:37.539: E/AndroidRuntime(1435): Caused by: java.lang.ClassCastException: com.example.avst.callxpressmobile.Tilldate cannot be cast to android.app.Activity
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
10-16 13:01:37.539: E/AndroidRuntime(1435):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
10-16 13:01:37.539: E/AndroidRuntime(1435):     ... 11 more

For my main activity please have a look at
Number of Custom Dialogs (Date and Time Picker) with relation to Radio Buttons

A: Since it is not an activity remove Tilldate from the AndroidManifest.xml and then assuming you are calling startActivity ,
use
  DialogFragment dialog = new Tilldate();

dialog .show(getFragmentManager(), "dialog");

  dialog .show(getFragmentManager().beginTransaction(), "dialog");

Instead of startActivity
If you need a custom dialog, extend TimePickerDialog.


text:
Q: The Projection Matrix Does More than Scaling, Right? As I have it understood, a projection matrix scales a polygon depending on how far away or close it is from the camera. Though I might be completely wrong. My question is, how does the projection matrix "know" to show the sides of the following cube, as the camera moves, when the matrix is only supposed "scale" polygons?
Notice in the image, the cube is off to the right side of the screen, by moving the camera to the left. If the camera is moved in the opposite direction (to the right) in order to center the cube, the side of the cube will disappear as expected.
Here is my matrix code:
private void createProjectionMatrix(){
      float aspectRatio = (float) Display.getWidth() / (float) Display.getHeight();
      float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV/2f))) * aspectRatio);
      float x_scale = y_scale / aspectRatio;
      float frustum_length = FAR_PLANE - NEAR_PLANE;
      projectionMatrix = new Matrix4f();
      projectionMatrix.m00 = x_scale;
      projectionMatrix.m11 = y_scale;
      projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustum_length);
      projectionMatrix.m23 = -1;
      projectionMatrix.m32 = -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length);
      projectionMatrix.m33 = 0;
}

A: The function of a projection matrix (in the context of graphics APIs, such as OpenGL) is to transform vertex positions from view-space into clip-space.
Clip space is generally a unit box (although in D3D it's a half-unit box). If a vertex position after being transformed into clip-space does not lie within that unit box, then it is clipped. This is essentially how the system "knows" the cube is visible on the screen.


text:
Q: How are big values stored in linux? For example, cat /proc/interrupts.
I see this value is constantly growing -
 36:   10273035      IPIC  36 Level     eth1_g0_rx

What happens when it reaches its maximum value: that is the maximum value uint64_t can hold.
How is overflow of the data is handled? what is the correct way of handling such a big data?

A: There's no general answer, it depends on the value.
Interrupt counters are per-CPU unsigned ints, and they are incremented using C addition. The value is informational only so it doesn't really matter that it won't be accurate after a little over two billion occurrences (on platforms where unsigned int is a 32-bit value).
For values where overflow handling is important, the storage itself doesn't change — i.e. its size will be chosen to fit the data, but there's no "magic" in the storage — but operations on the value will use overflow-checking variants.


text:
Q: Linux Terminal writing json but enter produces only a new line how to run the command i am using the Linux terminal to formulate an AWS command. After the command i have to specify the config via JSON.
So i am writing the JSON and want to trigger the command but whenever i press enter it only gives me a new line.
I am not using a specific text editor in the terminal.
I know this is a stupid question but i am searching now for an hour but i cant find the correct shortcut. I would really appreciate if somebody could give me a hint.
Thank you very much.

A: Have a look at you quotation marks If they are closed properly, it wont give you a new line.


text:
Q: Why are two directions enough for the Cauchy-Riemann equations to imply differentiability? If the complex function $f(z)$ is complex differentiable $\Rightarrow$ the Cauchy Riemann equations hold. $($This is because if $f'(z)$ is the same no matter in what direction $\delta z\rightarrow 0$. Choosing the special case of $\delta z\rightarrow 0$ along the real, then the imaginary, line yields the Cauchy Riemann equations, so it is obvious that any differentiable function will satisfy them$)$.
However, how is demonstrating that $f'(z)$ is the same for two perpendicular paths enough to show that $f'(z)$ is the same for all paths (i.e. how does one go from $\Rightarrow$ to $\Leftrightarrow$)? I have tried explicitly calculating the directional derivatives, but the mess that ensued did not enlighten whatsoever.
I do not know much about linear algebra if that helps in writing answers. Any geometric intuition would be greatly appreciated!

A: The directional derivative in any direction in $\mathbb{R}^n$ is completely determined by the directional derivative in $n$ linearly independent directions. This somewhat counterintuitive fact follows from linearity of the directional derivative: any vector $v$ can be expressed as $\sum \alpha_i b_i$ where $b_i$ are the linearly independent directions, and then
$$Df(v) = \sum \alpha_i Df(b_i).$$
In the case of $\mathbb{R}^2$, if the directional derivative of two functions agree in two directions, they must agree in all directions.
This same phenomenon also explains why the curvature of a surface in $\mathbb{R}^3$ is completely determined by the two principle curvatures, why the bending stiffness of a rod with non-circular cross section is completely determined by the bending stiffness in two directions, etc.
EDIT: You asked me for geometry and I gave you a bunch of linear algebra, so let me say a bit more from a geometric perspective. A function $f:\mathbb{R}^2\to \mathbb{R}$ has its first derivatives at a point determined by its tangent plane at that point. If you know two lines contained in that plane (which is what the two directional derivatives tell you) then you know the entire plane, since it passes through the point in question, and has as its normal the cross product of those two lines.
If you think of a complex function as $f:\mathbb{R}^2\to \mathbb{R}^2$, nothing much changes, since the tangent-plane interpretation applies to each component of $f$.


text:
Q: How to add Slide numbering to PowerPoint presentation I'd like to know how I can add the slide numbering (current page/total pages) to my Powerpoint presentation, please. Any idea how that can be accomplished?
Thank you.

A: Follow instructions here that are indicated in this link to add the number of pages / total number: http://office.microsoft.com/en-us/powerpoint-help/show-the-slide-number-and-total-number-of-slides-on-every-slide-HA010242545.aspx

*

*On the View tab, in the Presentation Views group, click Slide Master,
  and then click the slide master thumbnail.

*On the Insert tab, in the Text group, click Text Box, and then drag to
  draw the text box where you want the slide number to appear on your
  slides.

*With the cursor still in the text box, on the Insert tab, in
  the Text group, click Slide Number.

*In the text box, place your cursor
  before the <#>, and then type 'Slide'.

*Place your cursor after the <#>,
  and then type 'of x' , where x equals the total number of slides in your
  presentation.

A: On the Insert Menu, click "Slide Number"


text:
Q: How to get the status of apps in Win8.1 task manager? Is there any way can I get the status of the apps in task manager?

Edit:
Actually,I'm trying to get the status of metro app on Win8.1, such us show "Running" or "Suspended" in task manager "Detail" label.
I tried to use GetProcess() to get all the current process then get its' threads state. But the result is different from what task manager show.
Could any give me a gelp? I'm now using C# or C++ to coding.

A: After trying for hundreds times, I change my way to think "How to get info from task manager?"
So I think I just need to get info from task manager in command prompt.
There is a command I set:
tasklist /apps /fi "STATUS eq SUSPENDED"

There will show the metro apps name in SUSPENDED state!!!


text:
Q: foreach and current <?php
$a = array(1, 2, 3, 4, 5);
foreach ($a as $key => $elem) {
    echo "$key = $elem"; echo ' = ';
    var_dump(current($a));\
}
?>

The output I get when running that is as follows:
0 = 1 = int(2)

1 = 2 = int(2)

2 = 3 = int(2)

3 = 4 = int(2)

4 = 5 = int(2)

Seems to me that this is the output I should be getting?:
0 = 1 = int(1)

1 = 2 = int(2)

2 = 3 = int(3)

3 = 4 = int(4)

4 = 5 = int(5)

I do current() before the for loop on $a and get int(1). Thus it seems like it's the foreach loop that's causing it to increment. But if that's the case why is it only doing it once?
If I call next() in the for loop it increments but not otherwise. Of course next() starts out at int(3) (ie. the value after int(2))..

A: From reading the PHP documention on current, it does not look like you should expect foreach to move the current pointer.
Please see:
http://php.net/manual/en/function.current.php
What's a bit confusing is that the each function does move the current pointer.  So if you rewrite your array as a loop using each rather than foreach, then you will get the desired current behavior.
Here's your example rewritten with each(), which produces the expected results:
<?php
$a = array(1, 2, 3, 4, 5);
while ( list($key,$elem) = each($a)) {
    echo "$key = $elem"; echo ' = ';
    var_dump(current($a));
}
?>

A: current() uses the internal flag (pointer) and foreach uses it's own.
If you want to do this (which is kind of silly as you have the key in $key) you can use ArrayIterator

A: I just stumbled on the same problem, and I believe I have a theory.
Foreach doesn't access the array elements by value, it creates its own copy. However, while doing this, it increments the value returned by current() just once.
To check this:
<?php

$a = [0, 1, 2];
    foreach ($a as &$val){ // accessing the array elts by reference this time
    var_dump(current($a));
}

/*this outputs:
int(1)
int(2)
bool(false)*/