text:
Q: Hashing for array indices In my C program, I have four 8-bit (char) variables allocated in a structure. If I want to hash these numbers in order to create keys (representing the whole structures) which will index an array, how shall I do? (In the program there are many of these structures; since I often have to search in a symbol table to see whether they exist, if I don't want to create others, I haven't known which hashing algorithm to use, if I'd want to do a key-indexed search).
I've thought about a kind of hashing which takes the four numbers, turns them in hexadecimal numbers, puts them in succession, and then converts the number that comes out to a decimal number.
But I need something less "heavy"... this method seems too vain, and I think it's not so appropriate for creating array indices.
Is it? Is there another kind of hash functions, which also takes less memory than 32 bits, if it's possible?

A: One possibility (that I don't think the OP is describing) would be to combine the 4 char values into a single 32-bit integer and then mod that with the size of the hash table (presumably a prime number):
unsigned int combined = (c1 << 24 ) | (c2 << 16 ) | (c3 << 8 ) | (c4);
unsigned int hashval = combined % hashtablesize;

It depends of course on the actual expected values for the 4 individual bytes, but this type of hash is reasonably efficient and typically has a good distribution.  It would be good to test the resulting hash values with an expected data set to make sure the distribution is somewhat even.

A: You may want to have a look at this list of hash functions.
For implementing a hash table (which is your goal I suppose) you'd want a hash function with avalanche effect to avoid too many hash collisions for similar input values.
Of course, you could use any function to turn your characters into an arbitrary integer representation, but if this representation does not vary for different inputs you effectively have the performance of a linked list (imagine using one of the other suggestions with a table size of 256 and none of the structs varies on byte 4). What is your concern about 32-bit hashes? Of course you would use hash%tablesize for indexing?
Normally you wouldn't use a cryptographic hash function (e.g. md5, sha-1) either.  Just pick one of the non-cryptographic hash functions (e.g. Pearson/Jenkins hash).
/* jenkins hash, copied from http://en.wikipedia.org/wiki/Jenkins_hash_function */
uint32_t jenkins_one_at_a_time_hash(char *key, size_t len)
{
  uint32_t hash, i;
  for(hash = i = 0; i < len; ++i)
  {
    hash += key[i];
    hash += (hash << 10);
    hash ^= (hash >> 6);
  }
  hash += (hash << 3);
  hash ^= (hash >> 11);
  hash += (hash << 15);
  return hash;
}

Side note: When you have a good hash value distribution, also make sure that the size of the hash table is large enough. You will observe performance to degrade as the occupancy (load factor) of the array approaches 1, because the likelihood of hash collisions will increase.

A: Why don't you put the structures in an array?
#include <stdio.h>

typedef struct {
  char a,b,c,d;
} item;
item items[20];

int main(int argc, char *argv[])
{
  items[0].a = 4;
  items[0].b = 6;
  items[0].c = 1;
  items[0].d = 3;
  // ...
  items[4].a = 12;
  // ...
  printf("%d %d %d %d\n", items[0].a, items[0].b, items[0].c, items[0].d);
  return 0;
}

Obviously, this is the solution with less memory footprint, as the data is stored directly in the main array, so there is no need for hashing indexes, as the index of the array does the job with no memory consumption.
Of course you could use pointers, some C++ vector functionality, etc. But this is the most simple and efficient way.
The only caveat is that you must know the size of the array (how many items you will have) or a there-will-be-no-more-than-XXX maximum...

A:
Is there another kind of hash functions, which also takes less memory
  than 32 bits, if it's possible?

This is an illusory issue.  The key is an array index -- it isn't stored anywhere, it's calculated on look-up.  Arrays in C are contiguous blocks, individual elements are accessed based on the start of the array and size of the type multiplied by the index.
For the key, just cast the value to an unsigned 32-bit type (don't just use int or unsigned int as the size is not necessarily 32-bits):
#include <inttypes.h>
char x[4] = { 'A', 'B', 'C', 'D' };
uint32_t *key = (uint32_t*)&x;

Then do modulus based on the table size.


text:
Q: How to call 2d arrays int data to a text label? I am trying to extract an array value in C# WPF Environment. I have a 2D array as var.
I've tried calling the array directly to a text label and it shows as
"<>f__AnonymousType0`2[System.String,System.String][]"
Here's how my 2d array looked like
            var iitems = new[] {
                new { Text = "HSKL", Value = "7149191" },
                new { Text = "VKL", Value = "7149192" },
            };

            comboBox1.DataSource = iitems;

and here's how i try to call them.
            string ivitems = comboBox1.DataSource.ToString();
            hsklTotal.Text = ivitems;

I wanted to only extract the Value of my array and i believe i am doing something wrong here. How do i proceed?

A: To get "7149191" you can do
dynamic[] items = (dynamic[])comboBox1.DataSource;
hsklTotal.Text = items[0].Value;

A: You are not calling the value in the line below, rather ToString implementation of your anonymous type
string ivitems = comboBox1.DataSource.ToString();

You should use this:
iitems[0].Value

redpajama_set_name: RedPajamaStackExchange


text:
Q: Database Backups and logs file size too large I'm running SQL Server 2019 and I need to do manage my backups and logs better.
My main database (mdf) is only 9GB however the log (ldf) is 792GB. I've created back ups of these using SSMS > Tasks > Back up... I was expecting after a back up of the database the logs would reset. As this did not happen against googles advice I tried to shrink the log file, nothing happened.
I've tried setting the max size of the log file to something less, however it won't allow this as the log file is already too big. This is a dev server and very shortly I will be switching this to prod. And so don't currently need historical back ups, but will do once live.
In the meantime I've had to delete other databases and log files to free up space. I've put mdf and ldf on different partitions.
EDIT:
I was in Full Recover model however I have now switched this to SIMPLE. I will want point in time in the future but for now this will do. I took a backup however in simple recovery model only full and differential backup types are available, I can not now back up the log. I did both options available, hoping this would reduce the size of the log, it did not.
Question:
Now I have a backup, can I just delete the log file and will SQL server create a new one. I can just repeat this process, when the disk fills up?

A: Point-in-Time Recovery
Do you need point-in-time recovery? If not, check your recovery model, and consider changing to SIMPLE. With the SIMPLE recovery model, transactions data is only retained in the transaction log for the duration of the active transaction, and then released.
If you do need point-in-time recovery, you're going to need to start taking Log Backups, in addition to Full Backups. Figure out what the business RPO/RTO is, and plan a backup schedule accordingly. My preference is to take log backups every 15-minutes as a good starting point. But, it's not uncommon for people to run them as often as every 5-minutes, or even every 1-minute.
Once you choose one of the above options, you should then be able to truncate your log file back down to a manageable size.

A: What type of backup did you take?
Only a Transaction Log backup will have any effect on the Transaction log.


text:
Q: Submit event not fired on transaction submit I need to intercept the submitted transactions in my app, so i can inject on them previously stored cookies.
But the THTTPEvent::ESubmit is never fired. (Tested with a breakpoint on Debug using Carbide C++)
The code of the Event Handler is this:
void CHttpEventHandler::MHFRunL(RHTTPTransaction aTransaction,
        const THTTPEvent& aEvent)
    {
    switch (aEvent.iStatus)
        {
        case THTTPEvent::ESubmit:
            {
            //This CASE is never executed!
            User::InfoPrint(_L("Submitting Transaction!"));
            //TODO : Inject cookies in header =)
            }
            break;
        } // end switch
    }

A: You can set request header values before submitting the transaction in the first place.
Get the RHTTPHeaders handle with transaction.Request().GetHeaderCollection() and then use SetFieldL() calls to add Cookie: foo=bar request header fields.


text:
Q: Javascript output an image by taking onclick input from multiple images/buttons How can I output an image based on several clicks of options? The colors are images and also the shapes are images. When you click on a color and a shape the related image should come in the output section. How can I do this in javascript?
This is the image of my layout where I display options for user:

    <title>Test</title>

Choose your color

Choose your shape

Your output

        <divv class="outputimage">

A: I recommend using jQuery. Give each of the images a specific id and a category class(e.g color or shape) then use a control variable such as color and shape and set the value of those variables to the clicked element's id when the images are clicked.
First make sure to use the jQuery CDN just below your head tag:

For example:
HTML:

Choose your color

Choose your shape

JS:
let shape;
let color;

$('img').click(function(e){
  var id = $(this).attr('id');
  var elementClass = $(this).attr('class');
   if(elementClass == "shape"){
     shape = id;
     console.log(shape)
   }

  if(elementClass == "color"){
    color = id;
    console.log(color)
  }
})

A: I've achieved this using javascript by refreshing code and using branching statements. Below is the code.

    <title>Test</title>

Choose your color

Choose your shape

Your output


text:
Q: Позиционирование изображений за пределы страницы Необходимо разместить пару картинок, по бокам веб страницы, но так чтобы они на половину выходили за пределы страницы, сделал при помощи абсолютного позиционирования и overflow: hidden  но их границы (угол у блока) налазит на контент и перекрывает его так что нельзя взаимодействовать с ним. z-index не помогает как еще можно решить подобную проблему?

A: Пример на jsbin
Смысл: контенту задать z индекс с position: relative.


text:
Q: doing a pivot-table-ish JOIN in SQL My employer has a batch compute cluster that processes jobs submitted by users.  Each batch job consists of three steps:
*

*job started

*job finished

*results reported to the user

The batch job management software logs when each of these steps happen, and the logfile consists of a tuple with an ID code of the employee who submitted the job, what step occurred, and a timestamp of when it occurred.  In CSV, it looks like:
ID  step    timestamp
--  ------  ---------
A   start   3533
B   start   3538
B   finish  3549
C   start   3551
A   finish  3557
B   report  3559
C   finish  3602
A   report  3603
B   start   3611
C   report  3623
B   finish  3643
B   report  3657

And so forth.
One additional characteristic of the dataset is that there is concurrence between employees, but no concurrence within employees; ie, each employee has to wait until their current job has reported before their next job starts.  So when I sort by date and limit the results to a single employee, the records always come out in the order "start","finish","report".
I want to create a pivot table that groups each job into a single row.  So the above data becomes:
employee-ID  started  finished  reported
-----------  -------  --------  --------
A            3533     3557      3603
B            3538     3549      3559
B            3611     3643      3657
C            3551     3602      3623

So, on to the SQL:
SELECT
    log.ID AS employee-ID,
    start.timestamp AS started,
    finish.timestamp AS finished,
    report.timestamp AS reported
FROM
    log

    LEFT OUTER JOIN log start ON
    log.ID = start.ID
        AND start.step = 'start'

    LEFT OUTER JOIN log finish ON
    log.ID = finish.ID
        AND finish.step = 'finish'
        AND start.timestamp < finish.timestamp

    LEFT OUTER JOIN log report ON
    log.ID = report.ID
        AND report.step = 'report'
        AND finish.timestamp < report.timestamp

ORDER BY employee-ID,started,finished,reported;

I do need LEFT OUTER JOIN, because I also need to identify the jobs that were started but were not finished or reported.
This works pretty well.  It does give me the rows that I need.  But it gives me a lot of spurious rows, because the JOINs match finish and report entries for future jobs of the same employee in addition to the current job.  So the report comes out looking like:
employee-ID  started  finished  reported
-----------  -------  --------  --------
A            3533     3557      3603
B            3538     3549      3559
B            3538     3549      3657 <-- spurious
B            3538     3643      3657 <-- spurious
B            3611     3643      3657
C            3551     3602      3623

It's easy to recognize the spurious rows: each job gets started only once, so given the sorting, the correct row is the first row with a unique "started" value.  I'm working around the spurious rows problem right now at the application level by just skipping over the spurious rows, but that just seems, well, inelegant.  And it's costly: some of these employees have dozens of jobs submitted, so currently, the results of my queries are about 15% legitimate entries and 85% spurious.  That's a lot of wasted time skipping over bogus entries.  It would be nice if each job had a unique ID, but I just don't have that data.
I need to somehow limit the JOIN so that it picks off only one "finished" and "reported" entry for each "started" entry: the single entry that has the minimum timestamp greater than the timestamp of the preceding step.  I tried doing this by using a subquery as the table to which I was JOINing, but I couldn't figure out how to do it without a correlated subquery.  I also tried doing it by using "GROUP BY employee-ID,started", but this didn't necessarily pick the "correct" row.  Most of the rows the "GROUP BY" reported were the wrong ones.
So, SQL gurus, is it possible to report just the rows I need to?  And if so, how?  I am using sqlite3 right now, but could transfer the database to MySQL if needed.

A: The problem is how you're joining to finish and report
You don't want the start.timestamp < finish.timestamp you really want   start.timestamp < MIN(finish.timestamp)
Of course that doesn't work so you'll have to do it after the join.
e.g.
SELECT
    log.ID AS employee_ID,
    start.timestamp AS started,
    MIN(finish.timestamp) AS finished,
    MIN(report.timestamp) AS reported
FROM
    log

LEFT OUTER JOIN log start ON
log.ID = start.ID
    AND start.step = 'start'

LEFT OUTER JOIN log finish ON
log.ID = finish.ID
    AND finish.step = 'finish'
    AND start.timestamp < finish.timestamp

LEFT OUTER JOIN log report ON
log.ID = report.ID
    AND report.step = 'report'
    AND finish.timestamp < report.timestamp

GROUP BY log.ID,
    start.timestamp
ORDER BY
    employee_ID,started,finished,reported

Also you could probably convert the start to an inner join as it doesn't make a whole lot of sense to have a finish without a start


text:
Q: Error: Tried to register widget with id==class_level_grid but that id is already registered in DOJO Hi I am getting a error while again selecting the drop down in DOJO
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"
    %>
    <!DOCTYPE html>

    `enter code here`

                         Select
                        class Level
                        class Level

Error is coming as Error: Tried to register widget with id==class_level_grid but that id is already registered.
when again selecting the drop down kindly help me.

A: you can't populate grid above another grid without destroying the first one that you created.
so if you have grid with id=MyGrid placed at a div this div will be removed and the grid will replace it.
so you have to use two methods the placeAt and the grid.destroyRecursive(true);
the code below should work fine.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"
    %>
    <!DOCTYPE html>

    `enter code here`

                         Select
                        class Level
                        class Level


text:
Q: Using vba, is it possible to open multiple Excel workbooks from the same folder and keep them open at the same time? This is not the first time I ask this question, but I have slightly altered the details to hopefully make it clearer. Here is one version of the code I have tried:
Private Sub OpenWbsInPath(zPath As String)
Dim zFile As String
zPath = IIf(Right$(zPath, 1) = "\", zPath, zPath & "\")   ' Ensure zPath ends with "\".
zFile = Dir(zPath & "*.xls*")                             ' "xxxx\*.xls*". OK.
Do While zFile <> ""
    Workbooks.Open Filename:=zPath & zFile      ' Fails with error 1004 on 2nd iteration.
    DoEvents                                    ' Makes no difference.
    zFile = Dir()                               ' Next filename. Path also OK.
Loop
End Sub

I have also tried a similar procedure using CreateObject("Scripting.FileSystemObject"). In all approaches I have tried so far, including one in which I created an array of file names first and then tried to open each file individually, the first file opens OK, then the next file fails to open with error 1004.
The really strange thing is that in an older version of the program, all the files open OK. I have even tried copying the identical code, but it still doesn't work in the new location. I am running out of ideas - do I need to create a temporary folder for each workbook before I open it? Seems crazy.

A: I've run your code, and can confirm it works fine, if the files can be opened, and fails with error 1004 if they can't.
Possible reasons that a file can't be opened include

*

*it's corrupt, or.

*it's already open.

A file can't be open if:

*

*you or your code opened it already (is the file containing the code also in the folder?),

*someone else has it open (is the folder shared?),

*another instance of Excel has it open (check task manager for extra instances).

Can you manually open the file the code fails on? Add a Debug.Print zFile before the Open to see what file fails


text:
Q: Как выполнять поиск по topic в своих репозиториях github? Есть ли у github функция поиска по Topics:

Хочу упорядочить свои репозитории по таким "тегам" что бы быстро искать нужные примеры из своего кода, но поиск по репозиториям учитывает только их названия.

Есть ли такой-же способ по Topics выполнять поиск в рамках своего аккаунта?
Если его не существует, то буду признателен за советы кто как эту проблему решает.

A: Добавьте к строке поиска user:<имя юзера>, например:
user:gil9red topic:fun


text:
Q: Adding a marker for vim syntax folding I usually code in C, and I have in my .vimrc set foldmethod=syntax, which works very well as it folds braces and comments and everything.
But sometimes I need to fold big chunks of code so that they don't get in my way (for example a group of related functions), and I usually do this with set foldmethod=marker and the markers >>> and <<<.
I have been trying to add a new sync region and the nearest thing I have come with is:
syn region cFoldMarkers start='>>>' end='<<<' containedin=cComment transparent fold

but this creates a mess as it somehow it matches with comments.
Is there a way of achieving both objectives? or should I give up of doing this with syntax and just set markers for braces, comments and my custom one?
Thanks in advance

A: Okay, after... like 5 hours trying to do it with syntax folding, I have given up and changed to expression folding.
Following this question: LLVM-IR syntax folding for vim I have created a folding function that more or less does what I want:
function! CFold()
    let this_line = getline(v:lnum)

    " Matching of braces
    if match(this_line, '}') >= 0
        return 's1'
    elseif match(this_line, '{$') >= 0
        return 'a1'
    " Matching of comments
    elseif match(this_line, '/\*') >= 0
        if match(this_line, '\*/$') == -1
            return 'a1'
        " Matching custom folding
        elseif match(this_line, '>>>') >= 0
            return 'a1'
        elseif match(this_line, '<<<') >= 0
            return 's1'
        endif
    elseif match(this_line, '\*/$') >= 0
        return 's1'
    endif
    return '='
endfunction

setlocal foldmethod=expr
setlocal foldexpr=CFold()

A: Plugin syntaxMarkerFold adds this functionality.

containedin=cComment means that whole region (whole fold) is contained in single comment; we want only markers to be in comments (two separate comments).
Surprisingly enough, it matches markers not belonging to any syntax group too; it's also undesired behaviour for us.
By leaving only
syn region cFoldMarkers start='>>>' end='<<<' transparent fold

it finds start of region and folds it. But it doesn't have so much luck with the end, so Vim just folds to the end of file.
So we need to add matching comments to the RegExp of region (\s*//.\{-}) and for some pecultiar reason, define matchgroup=Comment
syn region cFoldMarkers matchgroup=Comment start='\s*//.\{-}>>>' end='\s*//.\{-}<<<' transparent fold

Now it should fold just where we want.

Of course, there are more edge cases, which require more handling.
We would also like to be able to use any marker and different valid comments than just //.
Not to mention leveled marker folding (e.g. {{{1).
Have a look at the code of my syntaxMarkerFold plugin to check how I've resolved those issues.


text:
Q: Input numbers return values inputted I was given a problem to solve, it was like this:

Write a program that asks the user to input numbers and to end the program type -1, after return the sum of the numbers inputted.

This is what I've done:
num=0
i = 0

while num != -1:                          #loop to get the numbers
    i = i + num                           #this will make the sum of the inputted numbers
    num = int(input("Input a number: "))  #save the input given into "num"
    print(num)                            #this shows the number that has been inputted by the user
    print("Input -1 to terminate")

print(i)                                  #this shows the total sum of all the inputted numbers

It does what it was asked, but now I want on my last print() to give the numbers the user inputted, not the sum of them all. How can I do that?

A: You can store the user's numbers in a Python list: https://www.w3schools.com/python/python_lists.asp
You can create a new list by doing something like numbers = [], which will create an empty Python list. Then, on each iteration in your while loop, you can add the number to this list by doing numbers.append(i), which will add the new number to the end of this list. Once you are ready to display all the numbers, you can use a for loop to display all of the numbers that are held in the list: for num in numbers: print(num)


text:
Q: Applicative typeclass based on two different functors Is there something similar to the Applicative type class, but where there are two functors for each side of the application which are different?
i.e. (<*>) :: (Functor f, Functor g) => f (a -> b) -> g a -> f b

A: (Following a suggestion from @dfeuer in the comments.)
There is a construction called day convolution that lets you preserve the distinction between two functors when performing applicative operations, and delay the moment of transforming one into the other.
The Day type is simply a pair of functorial values, together with a function that combines their respective results:
data Day f g a = forall b c. Day (f b) (g c) (b -> c -> a)

Notice that the actual return values of the functors are existencialized; the return value of the composition is that of the function.
Day has advantages over other ways of combining applicative functors. Unlike Sum, the composition is still applicative. Unlike Compose, the composition is "unbiased" and doesn't impose a nesting order. Unlike Product, it lets us easily combine applicative actions with different return types, we just need to provide a suitable adapter function.
For example, here are two Day ZipList (Vec Nat2) Char values:
{-# LANGUAGE DataKinds #-}
import           Data.Functor.Day -- from "kan-extensions"
import           Data.Type.Nat -- from "fin"
import           Data.Vec.Lazy -- from "vec"
import           Control.Applicative

day1 :: Day ZipList (Vec Nat2) Char
day1 = Day (pure ()) ('b' ::: 'a' ::: VNil) (flip const)

day2 :: Day ZipList (Vec Nat2) Char
day2 = Day (ZipList "foo") (pure ()) const

(Nat2 is from the fin package, it is used to parameterize a fixed-size Vec from vec.)
We can zip them together just fine:
res :: Day ZipList (Vec Nat2) (Char,Char)
res = (,) <$> day1 <*> day2

And then transform the Vec into a ZipList and collapse the Day:
res' :: ZipList (Char,Char)
res' = dap $ trans2 (ZipList . toList) res

ghci> res'
ZipList {getZipList = [('b','f'),('a','o')]}

Using the dap and trans2 functions.
Possible performance catch: when we lift one of the functors to Day, the other is given a dummy pure () value. But this is dead weight when combining Days with (<*>). One can work smarter by wrapping the functors in Lift for transformers, to get faster operations for the simple "pure" cases.

A: One general concept of "sequence type" is a free monoid. Since you're looking at polymorphic sequence types, we can build on Traversable.
class Semigroup1 t where
  (<=>) :: t a -> t a -> t a

class Semigroup1 t => Monoid1 t where
  mempty1 :: t a

See note below.
class (Traversable t, Monoid1 t) => Sequence t where
  singleton :: a -> t a

How is that a sequence type? Very inefficiently. But we could add a bunch of methods with default implementations to make it efficient. Here are some basic functions:
cons :: Sequence t => a -> t a -> t a
cons x xs = singleton x <=> xs

fromList
  :: (Foldable f, Sequence t)
  => f a -> t a
fromList = foldr cons mempty1

uncons :: Sequence t => t a -> Maybe (a, t a)
uncons xs = case toList xs of
  y:ys -> Just (y, fromList ys)
  [] -> Nothing

With these tools, you can zip any two sequences to make a third.
zipApp :: (Foldable t, Foldable u, Sequence v) = t (a -> b) -> u a -> v b
zipApp fs xs = fromList $ zipWith ($) (toList fs) (toList xs)

Note on recent GHC versions
For bleeding edge GHC, you can use QuantifiedConstraints and RankNTypes and ConstraintKinds and define
type Semigroup1 t = forall a. Semigroup (t a)

type Monoid1 t = forall a. Monoid (t a)

Doing it this way would let you write, e.g.,
fromList = foldMap singleton

A: From your comment, I think you might be trying to construct:
import Data.Foldable
import Data.Traversable
foo :: (Traversable f, Foldable g) => f (a -> b) -> g a -> f b
foo f g = snd $ mapAccumR (\(a:as) fab -> (as, fab a)) (toList g) f

This allows, for example:
> import qualified Data.Vector as V
> foo [(+1),(+2),(+3)] (V.fromList [5,6,7])
[8,8,8]
>

A: I don't know of any general fromList.  I would write the concrete version, or at most generalize over the input types.  Here are examples with Vector, ignoring that Data.Vector.zip already exists.
import qualified Data.Vector as V
import Data.Vector (Vector)
import Data.Foldable
import GHC.Exts (IsList(fromList))

zipV1 :: Vector (a -> b) -> Vector a -> Vector b
zipV1 fs as = V.fromList (zipWith ($) (V.toList fs) (V.toList as))

zipV2 :: (Foldable f, Foldable g, IsList (f b)) => f (a -> b) -> g a -> f b
zipV2 fs as = fromList (zipWith ($) (toList fs) (toList as))

You could use IsList instead of Foldable in the second example.


text: Q: Is there any way to apply different texture to different surfaces of the same cube in "Processing"? I am trying to create a cube that has different numbers assigned to different surfaces e.g. 1-6 for 6 different surfaces or maybe 6 different textures for 6 different surfaces. In doing so I am able to apply a single texture all over the cube. Can anyone please help me with this?


text:
Q: Why is the generation of my TYPO3 documentation failing without a proper error? I have a new laptop and I try to render the Changelogs of TYPO3 locally based on the steps on https://docs.typo3.org/m/typo3/docs-how-to-document/master/en-us/RenderingDocs/Quickstart.html#render-documenation-with-docker. It continues until the end but show some non-zero exit codes at the end.
project : 0.0.0 : Makedir
   makedir /ALL/Makedir
   2021-02-16 10:32:50 654198,  took: 173.34 seconds,  toolchain: RenderDocumentation
   REBUILD_NEEDED because of change,  age 448186.6 of 168.0 hours,  18674.4 of 7.0 days
   OK:
   ------------------------------------------------
   FINAL STATUS is: FAILURE (exitcode 255)
                    because HTML builder failed
   ------------------------------------------------
   exitcode:   0            39 ms

When I run the command in another documentation project, it renders just fine.

A: I found the issue with this. It seemed the docker container did not have enough memory allocated. I changed the available memory from 2 Gb to 4 Gb in Docker Desktop and this issue is solved with that.

A: You already solved the problem. But in case of similar errors: To get more information on a failure, you can also use this trick:
Create a directory tmp-GENERATED-temp before rendering. Usually, this is automatically created and then removedd after rendering. If you create it before rendering, you will find logfiles with more details in this directory.
See the Troubleshooting page.
I had some errors where I found the output in the console insufficient and this helped me to narrow down the problem.

In case of other problems, I would file an issue in the GitHub repo: https://github.com/t3docs/docker-render-documentation

Note: This is specific to TYPO3 docs rendering and may change in the future.


text:
Q: What's the meaning of "I casually drink alcohol" and "I socially drink alcohol" If I said,

I casually drink alcohol

or

I socially drink alcohol

What would you think about how often I drink?

A: A "casual drinker" would be someone who occasionally has up to a few drinks (enough to "get buzzed", i.e. to know that you are intoxicated, but not so much that you become seriously impaired).  I would expect a casual drinker to enjoy a couple of beers after a particularly tough workday, or to have a glass of wine with dinner occasionally.
A "social drinker" would be someone who generally drinks in the company of their friends; either you have friends over and serve alcohol, or you go over to a friend's house and drink the alcohol they serve, or you all go out to a bar together.
You can be a social drinker who becomes excessively intoxicated or who never has more than one drink, or you can be a casual drinker who does not drink socially, or who only drinks when friends are over; the phrases are not necessarily points along the same spectrum.  (One deals with how much alcohol you consume at a time, the other with what situations in which you tend to consume.)

A: I personally prefer I drink alcohol socially as your sentence form doesn't sound right to me, and if we add only, it makes the sentence clearer as one could say: I drink alcohol socially and at every other opportunity for a drink.
I have never heard of drinking casually. I only drink casually suggests that when you drink alcohol you stand there looking really cool and not like an unrelaxed misfit in the corner of the room.
 I go along with the answer where a person could be described as a casual drinker, which in my definition is not very much.
I only drink socially implies that it is not habitually, i.e., you drink at social occasions with company and not routinely e.g., every weekend or always after work.
But we could even think that I only drink alcohol socially means that when I drink I'm sociable and don't get totally pissed and insult everyone in the room.

A: Casually might be drinking on your own infrequently (at home alone)
Socially would be only with a group of people or on a date or at a bar

A: "socially" tells me the situations in which you drink, that you tend to (or only) drink in company of other drinkers.
"casually" tells me the frequency with which you drink, lower than I might expect otherwise.

A: Every friday/saturday night.
Maybe a glass of wine each night.
Beers after work.


text:
Q: Overlapping ImageView or Layout on Line in Android Intentionnaly
In the picture you can see what kind of result I am trying to create.
Actually my layout code is:
`
        <View
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:background="#A1A1A1"
            android:orientation="vertical" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="60dp"
            android:layout_marginBottom="20dp" >

            <TextView
                android:id="@+id/txtTitleDetail"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#000000"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/txtPriceDetail"
                android:layout_width="60dp"
                android:layout_height="fill_parent"
                android:layout_marginRight="30dp"
                android:background="@drawable/price_circle_background"
                android:gravity="center"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/blue_amount" />
        </LinearLayout>`

The line stay on the top of the picture and don't come under it.How can I create a picture that go under on another?

A: Hi You can you play around with FramLayout. You will get the same result. Go through these links click here , click here

A: try this it ll help you,here i am using marginTop in negative to get the line under image.
.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/mainActLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<View
    android:layout_width="fill_parent"
    android:layout_height="5dp"
    android:layout_marginTop="150dp"
    android:background="#000022" />

<ImageView
    android:id="@+id/logoBackgroundImg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="-30dp"
    android:background="@drawable/ic_launcher"
    android:scaleType="fitCenter" /></LinearLayout>

adjust marginTop according to your need

A: It's quit simple, wrap the view inside the Linear Layout.
For Android, it's always recommended to use the relative layout. It works well as a charm, also you can ask views to be placed in relation to the placement of the other companion views.
1) Prefer using match_parent than fill_parent.
2) for Images try using wrap_content for height and width params.
Try this:
   <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:orientation="horizontal" >

    <!-- View for the text to the left of the picture -->
    <TextView
        android:id="@+id/txtTitleDetail"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/txtPriceDetail"
        android:gravity="center_vertical"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:ellipsize="end"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000000"
        android:textSize="16sp"
        android:textStyle="bold" />

     <!-- If you wish to add pictures, go for ImageViews,
      as they are optimized for their purpose. -->
    <ImageView
        android:id="@+id/txtPriceDetail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="30dp"
        android:layout_alignParentRight="true"
        android:background="@drawable/price_circle_background"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/blue_amount" />

    </RelativeLayout>

    <!-- View for the horizontal line of 1 dip -->
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="#A1A1A1" />

A: Finally I did it a other way...
I create a background image with the gray line "bg_detail_price"  and voila :)
simpler like this
http://imgur.com/qGJWHsm
The final result is.
http://imgur.com/56ETZS0

<LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="60dp"
            android:layout_marginBottom="20dp"
            android:background="@drawable/bg_detail_price" >

            <TextView
                android:id="@+id/txtTitleDetail"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:paddingTop="15dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#000000"
                android:textSize="16sp" />

            <LinearLayout
                android:layout_width="55dp"
                android:layout_height="55dp"
                android:layout_marginRight="35dp"
                android:background="@drawable/price_circle_background"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/txtEarn"
                    android:layout_marginTop="11dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="@string/txt_earn"
                    android:textColor="@color/blue_amount"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/txtPriceDetail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:textColor="@color/blue_amount"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>


text:
Q: I should like to install windowsBuilder on Eclips-luna I should like to install Window_Builder plugin on Eclipse- luna, I have tried different ways that given on sites i.e go to Help>>install new software>> and try with both like Luna as well as  "All available sites" but every time display following error
Unable to read repository

A: Help >> Eclipse Marketplace >> search for windows builder >> install

A: You can try and download the pluggin as a offline .zip file and include it in your eclipse: http://eclipse.org/windowbuilder/download.php


text:
Q: увеличений шагов в цикле Почему-то при каждом нажатии на вариант из списка, каждый раз в верхнее поле добавляется 2 лишних варианта и стирается только изначальное состояние элемента, а то, что было добавлено потом, уже не стирается, и к нему просто прибавляется новое

function dropMenu(n) {
  let addressIn = n.querySelector(".price__addresses_in");
  let content = addressIn.querySelector(".price__addresses_content");

  let downMenu = n.querySelector(".price__addresses_content-down");

  if (downMenu.style.display == "none") {
    downMenu.style.display = "block";
  } else {
    downMenu.style.display = "none";
  };

  let addresses = downMenu.querySelectorAll(".price__addresses_content");

  addresses.forEach(el => {
    el.addEventListener('click', () => {
      let content = addressIn.querySelector(".price__addresses_content");
      content.innerHTML = "";
      content.insertAdjacentHTML('beforebegin', el.innerHTML);
      return
    })
    return
  })
}
.price__addresses_content {
  border: 1px solid black;
}

Медцентр на Малой Юшуньской

    <button>&#8595</button>

Медцентр на Малой Юшуньской

Медцентр на Большой Юшуньской

Медцентр на Средней Юшуньской

A:
добавляется 2 лишних варианта

Естественно. Вы на каждый клик добавляете обработчики событий. А потом они все выстреливают.

A: почему то всё решилось изменением content.insertAdjacentHTML('beforebegin', el.innerHTML);, а точнее 'beforebegin' заменил на 'afterbegin', но мне кажется, что это больше костыль


text:
Q: How to integrate live Skype status in my application? I have a webpage where a person's Skypename is present along with a Skype icon.By clicking on the button it will open Skype.But now I want to add live Skype Status i.e showing if the person is online or offline or busy,etc.I want to show this through a changing image button

A: Standard Skype buttons can detect and show the status of the user. Have a look here. If you wanted the status to be real-time, you could refresh it using AJAX.
However, if you prefer to handle the code yourself, you can easily retrieve your skype status by using
http://mystatus.skype.com/nnnn.num

where nnnn is the Skype name you're interested in. It returns the following:
0 – unknown
1 – offline
2 – online
3 – away
4 – not available
5 – do not disturb
6 – invisible
7 – skype me

A: check this article talks about status in skype : http://www.codeproject.com/KB/aspnet/IMStatusIndicator.aspx (Instant Messenger Status Indicator - AIM, Yahoo, ICQ, MSN, Skype ...)


text:
Q: '\0' related issue Looking at this loop that copies one c-string to another:
void strcpyr(char *s, char *t)
{
    while(*s++=*t++)// Why does this work?
        ;
}

Why do we not check for the '\0' character in the while loop, like this?
while((*s++=*r++)!='\0')..

How does the first loop terminate?

A: When we hit the '\0' in the string initially pointed to by t, the *s++=*t++, which does the assignment, also returns the value that's assigned to the position pointed to by s, or '\0', which evaluates to false and terminates the loop.
In your second example, you explicitly rely on the fact that the assignment returns the assigned character, while the first example implicitly uses this fact (and the fact that the 0 character (also written '\0') is considered to be false, while all other characters evaluate to true, so the expression c != '\0' will yield the same result as c.

A: The loop is going to terminate because '\0' is effectively 0, and the what the "while" is evaluating is not a the result of an equality test (==), but the right-value of the assignment expression.

A: The statement *s++=*t++ not only assigns the next character from t to s but also returns the current value of *t as the result of the expression. The while loop terminates on any false value, including '\0'.
Think of it this way. If you did:
char c = *s++ = *t++;

in addition to copying a char from *t to *s and incrementing both, it would also set c to the current value of *t.

A: The reason we are not explicitly checking for zero is that in C 0 is false.
Therefore the loop
while(*s++=*t++)
;

will terminate when the character pointed to by t is 0.
-Adam

A: I think you mean to write this:
void strcpyr(char *s, char *t) {
  while (*s++ = *t++);
}

The loop terminates when the value pointed to by "t" is zero. For C (and C++) loops and conditionals, any integer that is non-zero is true.

A: The while loop is testing the result of the assignment.
The result of an assignment is the value assigned into the left-hand side of the statement.  On the last iteration, when *t == '\0', the '\0' is assigned into s, which becomes the value the while loop considers before deciding it is time to quit.

A: In C, a=b is actually an expression which is evaluated as 'b'. It is easier to write:

if(a=b) {
 //some block
}

then:

a=b;
if(a!=0) {
 //some block
}

In C language within if, while, for statement the check that is made is: is expression not zero?


text:
Q: $\ell_0$ penalised and $K$ sparse problems Consider the $\ell_0$ penalized problem:
$$\min_{x\in \mathbb{R}^n} \frac{1}{2}\|Ax-b\|_2^2+\lambda\|x\|_0 \qquad \qquad \qquad \qquad \qquad \qquad (1)$$
and $K$-sparse problem
$$\min\frac{1}{2}\|Ax-b\|_2^2 \qquad \mbox{ s.t. } \qquad \|x\|_0\leq K \qquad \qquad \qquad (2)$$
1. Since $\ell_0$ is a discontinuous function or the set $\{x:\; \|x\|_0\leq K\}$ is not bounded, does (1) or (2) always admit a solution?

*What is the relationship between solution sets of the two problems depending on $\lambda$, i.e., is there any $\lambda$ such that these solution set sare equal? Assume that we have found a solution $x^*$ of (1), can we find a solution of (2) from $x^*$?

A: 1) Yes. Both forms always admit a solution, but it's not necessarily unique.
The constrained form (your second formulation) is a bit easier to analyze.
As you note, the constraint set $\mathcal{C} = \{x : \|x\|_0 \leq K\}$ is not bounded, so it's not entirely obvious that there will be a minimum. (More precisely, it's not compact so we don't get the usual "easy" guarantees that a minimum exists and is obtained.)
However, in this case, we can guarantee that a solution exists just by considering the problem directly. The 'trick' is in the structure of the constraint set. Note that it can be written as the union of simpler sets - for example, if $K = 4$, then
$\begin{aligned}\{x: \|x\|_0 \leq K\} =&\phantom{\cup+}\{x: (x_1, x_2, x_3, x_4) \in \mathbb{R}, (x_5, \dots, x_n) = 0 \} \\
&\cup  \{x: (x_1, x_2, x_3, x_5) \in \mathbb{R}, (x_4, x_6, \dots, x_n) = 0 \} \\
&\cup \{x: (x_1, x_2, x_3, x_6) \in \mathbb{R}, (x_4, x_5, x_7, \dots, x_n) = 0 \} \\ &\cup \dots\ \\ =&\bigcup_{S \text{ is a set of 4 integers $\leq N$}} \underbrace{\{x: x_i = 0 \quad \forall i \notin S\}}_{\mathcal{C}_S}\end{aligned} $
This is a union over a finite set of convex sets, so we can solve the original problem by simply solving $\min_{x \in \mathcal{C}_i} \|Ax - b\|_2^2$ and then taking the minimum over all the solutions and using that as our global solution.
In symbols:
$\begin{aligned} \min_{x \in \mathcal{C}} \|Ax-b\|_2^2 = \min_{S \in \mathcal{S}} \min_{x \in S} \|Ax-b\|_2^2\end{aligned}$
where $\mathcal{S}$ is the set of (distinct) $K$-tuples.
A bit less formally, we can always solve the $K$-sparse problem, by finding the best possible solution for every sets of at most $K$ columns of $A$ and then just taking the 'best of the best' as our global solution.
This 'brute force' approach is slow when $K$ is bigger than 2 or 3 (since we have to solve $\sum_{i=0}^K \binom{n}{i}$ OLS problems), but if you're clever and have a big computer and some time to burn, it's doable up to $n \approx 1000$. [1] gives the gory details and [2] provides an R package implementing the approach in [1].
If $K$ is large or if there is redundancy among columns of $A$ (the formal condition is $\text{rank}(A) < K$), two of these sub-problems may give the same value, so you aren't guaranteed a unique $\text{arg min}$ solution, but you always have a unique $\text{min}$ because it's just the minimum over a finite set.
2) No. They aren't quite equivalent, but it is true that if you have a solution to (1) for a given $\lambda$, you can pick a $K$ such that it is a solution to (2). You can't always find $K$ such that a solution to (1) that matches a given solution to (2) however. This phenomenon is noted in Section 1.3 of [3], but it's not discussed at length.
[1] D. Bertsimas, A. King, R. Mazumder. "Best subset selection via a modern optimization lens." Annals of Statistics 44(2), p.813-852, 2016. https://projecteuclid.org/euclid.aos/1458245736
[2] https://github.com/ryantibs/best-subset
[3] R.J. Tibshirani. "Degrees of Freedom and Model Search." Statistica Sinica 25, p.1265-1296, 2015.


text:
Q: IN and NOT IN HiveQL I am new to HiveQL and is IN and NOT IN supported in it? Especially when using Qubole?
Here is my query:
SELECT DISTINCT vId FROM table1
WHERE d.columnOne = "123"
AND NOT d.columnTwo
AND timestamp between 1523550000000 AND 1523930000000
AND NOT h.columnThree regexp "000.000.000.00|111.111.111.11|222.22.222.22"
AND vId in (select vId from table2 where colOne regexp "000|111|222")

my error is

"Unsupported language features in query: "


text:
Q: Given an trigonometric sum, extract amplitudes and angles as separate lists How can I extract amplitudes and angles as separate lists from an trigonometric expression?
Sample input:
$$A_{1} \cos \left(\phi -\frac{2 \pi }{3}\right)+
  A_{2} \cos \left(2 \phi +\frac{\pi }{3}\right)+
  A_{3} \cos \left(3 \phi -\frac{\pi }{2}\right)$$
A1 Cos[ϕ - 2 Pi/3] + A2 Cos[2 ϕ + Pi/3] + A3 Cos[3 ϕ - Pi/2]

Desired outputs:

*

*List of amplitudes: $[A_{1}, A_{2}, A_{3}]$ , {A1,A2,A3}

*List of angles: $[\phi -\frac{2 \pi}{3}, 2 \phi +\frac{\pi}{3}, 3 \phi -\frac{\pi}{2}]$ {ϕ - 2 Pi/3,2 ϕ + Pi/3,3 ϕ - Pi/2}

A: exp = A1 Cos[ϕ - 2 Pi/3] + A2 Cos[2 ϕ + Pi/3] + A3 Cos[3 ϕ - Pi/2] // HoldForm

{amplitudes, angles} = Transpose[exp /. {Plus -> List} /. {A_*Cos[phi_] :> {A,
     Total@phi}} // ReleaseHold]
(*{{A1, A2, A3}, {-((2 π)/3) + ϕ, π/3 + 2 ϕ, -(π/2) + 3 ϕ}}*)

A: exp = Sum[ RandomReal[] Cos[RandomReal[] ϕ + RandomReal[]], {k, 10}]

0.58841 Cos[0.255484 + 0.116817 ϕ] +
 0.410137 Cos[0.606744 + 0.187887 ϕ] +
 0.0087033 Cos[0.267439 + 0.220191 ϕ] +
 0.231662 Cos[0.389939 + 0.232118 ϕ] +
 0.851933 Cos[0.0605113 + 0.275988 ϕ] +
 0.127151 Cos[0.724798 + 0.316905 ϕ] +
 0.587836 Cos[0.0236456 + 0.371794 ϕ] +
 0.453645 Cos[0.459396 + 0.440963 ϕ] +
 0.55557 Cos[0.623873 + 0.71966 ϕ] +
 0.588512 Cos[0.0700004 + 0.939417 ϕ]

{amplitudes, angles} = Transpose@Cases[exp, Times[a_, Cos[b_]] ->  {a, b}]

OR
ReplaceAll[List @@ exp,
 {
  Times[a_, Sin[b_]] -> {a, π/2 - b},
  Times[a_, Cos[b_]] -> {a, b}
  }]


text:
Q: How do uploaded file public, DOWNLOADING available without authorization? I upload file like this:
    if (isset($_FILES[$name])) {
        $service = new Google_DriveService($client);

        //Insert a file
        $file = new Google_DriveFile();
        $file->setTitle($_FILES[$name]['name']);
        $file->setMimeType($_FILES[$name]['type']);
        $file->setParents(array('imgs'));

        $insertedFile = $service->files->insert($file, array(
            'data' => file_get_contents($_FILES[$name]['tmp_name']),
            'mimeType' => $_FILES[$name]['type']
        ));

        return $insertedFile;
    }

Get insertedFile as this:
Array
(
    [kind] => drive#file
    [id] => 1sASTlgG7IFzcZyTUihp53uJbppFtxLs_GK_V2jYwapE
    [etag] => "vGmlhiWxP02tugPmRvLynwC_A0Y/MTM2NjE4NTYyNzQwOQ"
    [selfLink] => https://www.googleapis.com/drive/v2/files/1sASTlgG7IFzcZyTUihp53uJbppFtxLs_GK_V2jYwapE
    [alternateLink] => ...

But when i go to selfLink, i get an error
{
  ...
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

What is the correct way to get uploaded file without any kind of authorization? Looks like file is only available through the API.

A: If you want to download the content, make an authenticated request to the download URL.
// Get the contents of the file.
$request = new Google_HttpRequest($file->downloadUrl);
$response = $client->getIo()->authenticatedRequest($request);
$content = $response->getResponseBody();


text:
Q: How to show a specific div in a view from controller in Codeigniter? I am trying to use two divs in a view. If I am logged in as a user I want to show the div named as 'user'. If logged in as an admin I want to load a view which has div named as 'admin'. I want to do this in CodeIgniter.
My sample code is as follows,
if ($Admin == 0)
{
    $data['visible']=$this->login_model->show_menu();
}
else
{
    echo "I'm Admin";
    $this->load->view('home');
}

A: The doc : http://www.codeigniter.com/user_guide/general/views.html
Adding Dynamic Data to the View
Let's try it with your controller file. Open it add this code:
<?php
class Blog extends CI_Controller {

    function index()
    {
        $data['title'] = "My Real Title";
        $data['heading'] = "My Real Heading";

        $this->load->view('blogview', $data);
    }
}
?>

Now open your view file and change the text to variables that correspond to the array keys in your data:

<title><?php echo $title;?></title>

<?php echo $heading;?>

So, in your case, you can do something like that :
if ($Admin == 0)
{
    $data['visible']=$this->login_model->show_menu();
}
else
{
    $data['visible']='admin';
    echo "I'm Admin";
    $this->load->view('home', $data);
}

And in your view :
if($visible == 'admin') {
    echo '
Your admin display
';
}
else {
    echo '
',$visible,'
';
}

A: Take 2 variables
$showAdmin and $showUser
In controller
function showView() {
 $showAdmin = FALSE;
 $showUser = FALSE;
 if ($isAdminLoggedInYourCode) {
  $showAdmin = TRUE;
 }
 else if ($isUserLoggedInYourCode) {
  $showUser = TRUE;
 }
 $data['showAdmin'] = $showAdmin;
 $data['showUser'] = $showUser;
 $this->load->view('home', $data);
}

And in view,
if ($showAdmin) {
 // Show Admin div
}
else if ($showUser) {
 // Show User div
}

A: Have you tried this ?
if ($Admin == 0)
{
    $data['visible']=$this->login_model->show_menu();
}
else
{
    echo "I'm Admin";
    $this->load->view('home');
}

A: Use two different views for user and admin
class MY_Controller extends CI_Controller
{

    public function index()
    {
        $data = getSomeStuff();
        $admin = checkAdmin();

        if($admin == 0) {
            $this->load->view('user', $data);
        } else {
            $this->load->view('admin', $data);
        }
    }
}


text:
Q: Using biblatex+memoir+refsection: Why are the references included in the ToC? Consider this example taken and modified from a previous question:
\begin{filecontents*}{references.bib}
@BOOK{childs_temperature,
  title = {Practical Temperature Measurement},
  publisher = {Butterworth - Heinemann},
  year = {2001},
  author = {Childs, Peter R N},
  address = {Great Britain},
  edition = {1},
  isbn = {0 7506 5080 X}
  }

  @PHDTHESIS{hashemian,
  author = {Hashemian, Hashem Mehrdad},
  title = {Measurements of dynamic temperatures and pressures in nuclear power plants},
  school = {{The University of Western Ontario}},
  year = {2011},
  type = {PhD {T}hesis}
  }
\end{filecontents*}

\documentclass{memoir}
 \usepackage[style=alphabetic,refsection=chapter]{biblatex}
 \addbibresource{references.bib}

 \begin{document}

 \tableofcontents
 % \begin{refsection}
 \chapter{First chapter}
 \section{Foo}
 Some text \cite{childs_temperature}.
\printbibliography[heading=subbibliography]
 % \end{refsection}

 % \begin{refsection}
 \chapter{Second chapter}
 \section{Bar}
 Some text \cite{hashemian}.
 \printbibliography[heading=subbibliography]
 % \end{refsection}

 \end{document}

According to the documentation of biblatex, the printbibliography command generates a section with the references of each chapter, since the refsection=chapter option was used, but it should not be included in the ToC, because the subbibliography heading does not add it to the ToC (see the following biblatex.def extract):
  \defbibheading{subbibliography}[\refname]{%
    \subsection*{#1}}
  \defbibheading{subbibintoc}[\refname]{%
    \subsection*{#1}%
    \addcontentsline{toc}{subsection}{#1}}

However, in this example, it is included in the ToC.

Moreover, if the refsection=chapter is not used and the \begin{refsection} \end{refsection} parts are uncommented, the reference section is not included in the ToC, as advertised by the docs.
Another interesting clue, and maybe the key clue for this enigma, is that when I use the book document class instead of memoir, the references and ToC work as expected.
Can anyone explain this behavior? I'm sure that I misunderstood or did not find my way in the vast biblatex and memoir documentation.

A: Look down further in biblatex.def and you will find
\or % memoir (book)
% ....
\defbibheading{subbibliography}[\refname]{%
    \section*{#1}%
    \ifmemoirbibintoc
      {\phantomsection
       \addcontentsline{toc}{section}{#1}}
      {}%
    \if@twoside\markright{\memUChead{#1}}\fi}

Thus if \memoirbibintoc is true, it will add a reference header to the toc.

And that variable is tied directly to \nobibintoc as mentioned by jon (in blx-compat.def)


text:
Q: How can i do this multiple JOIN query? I need to build a query with multiple JOIN, to be more especific, 2 JOINS, but it gets duplicated results, check this:
My current tables:
food_shops
id, slug, name

categories_food_shops
id, id_cat, id_food_shop

pictures_food_shops
id, pic_slug, id_food_shop

And I need to get * from food_shops, the id_cat from categories_food_shops and pic_slug from pictures_food_shops...
My current query is like this:
SELECT food_shops.id, food_shops.slug, food_shops.name,
GROUP_CONCAT(categories_food_shops.id_category) as categories,
GROUP_CONCAT(pictures_food_shops.slug) as pictures
FROM
food_shops
JOIN categories_food_shops
    ON food_shops.id = categories_food_shops.id_food_shop
JOIN pictures_food_shops
    ON food_shops.id = pictures_food_shops.id_food_shop
GROUP BY food_shops.slug, pictures_food_shops.id_food_shop

But since my pictures_food_shops have more results as the categories_food_shops, my result is gettin "quadruplicated":

What can I do to prevent this and get only the correct amount of categories?
Only 1 at the first row, 3 and 5 in the second one and 7,1,6 at the last one?
Thanks!

A: You can try this:
...
GROUP_CONCAT(DISTINCT categories_food_shops.id_category) as categories,
....

This should work for pictures also.
Here is the documentation  with DISTINCT usage example.


text:
Q: Change output directory in "sbt-native-packager" Sorry, I'm new to sbt and the "sbt-native-packager". What I need to do is to map whole directories to the .zip file and change the output path.
This how I've done my mapping of the directory:
mappings in Universal <++= (packageBin in Compile, baseDirectory ) map { (_, baseDirectory) =>
    val dir = baseDirectory / "migrations"
    (dir.***) pair relativeTo(dir.getParentFile)
}

The mapping works perfectly fine, but I need to have a specific folder structure in the resulting .zip file.
In this example this directory is mapped to ".../target/stage/universal/migrations" but I need it to be mapped into a folder "db" like this: ".../target/stage/db/universal/migrations"
Many thanks in advance!

A: For mapping complete directories there are some MappingHelpers you can use. Your code can be simplified to
mappings in Universal ++= directory(baseDirectory.value / "migrations")

Regarding your second question, how to change the output folder. The question is not quite correct, as it should be: "how to change the destination path of a mapping". The universal packaging is a bit special as the target ouput looks like the resulting package.
Native packager uses mappings (sequence of File -> String tuples) that define a file and the corresponding output path in the resulting package. So if you want to change
# current
./target/stage/universal/migrations
# expected
./target/stage/db/universal/migrations

I assume you want the migrations in your zip file in a db folder like this
/        # zip root
  bin/   # start scripts
  db/    # migrations go here
  conf/  # configuration files
  lib/   # jars

In order to accomplish this you have to change the destination string. This would look something like this ( not tested ):
mappings in Universal ++= contentOf(baseDirectory.value / "migrations").map {
   case (file, dest) => file -> s"db/$dest"
}

cheers,
Muki


text:
Q: Specifying Moxy runtime for Play project with model in dependency I'm working on a Play Framework project (WebProject) where I am using a jaxb/Moxy model defined in a jar I am importing through SBT. This jar is created from another project (ModelProject) by adding a "jaxb.properties" file to the package containing the model classes:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
To get this working for the unit tests in the ModelProject I had to add the following line to the build.sbt file:
resourceDirectory in Compile <<= baseDirectory { _ / "src" }
My question is: Is there a way that I can use the Moxy runtime when I create a JAXBContext in the WebProject, using a class from the ModelProject to bootstrap it? Ideally I'd like to specify this within the ModelProject as it will be used by other projects in the future.
Thanks.

A: Maybe not an ideal solution but I just decided to create a package in the WebProject containing a "MoxyBootstrapper" class and a jaxb.properties file containing the javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory line.
I then pass this class in when creating a new instance of the JAXBContext.


text:
Q: Deploy application to wildfly on a certain port By default, applications in wildfly are deployed to localhost:8080/app. How to deploy application on dedicated port, i.e. open it on localhost:8282 without application name ending?
I need to change the port for certain application, not the default port.

A: I have not tried this, but AFAICT it should be possible to:

*

*run a single Wildfly instance listening on multiple HTTP ports. This is, in theory at least, possible (ref: https://developer.jboss.org/thread/233414?start=0&tstart=0)

*Configure undertow subsystem as a reverse proxy, and proxy your app to the other port/location (ref: http://www.mastertheboss.com/jboss-server/wildfly-8/configuring-a-reverse-proxy-with-undertow). That said, I have never used undertow for a reverse proxy and as such cannot speak for whether this really works.
Once you have done this, you have effectively just turned your Wildfly instance into an overly complex application server and reverse proxy in one. Ultimately however, the app in question would still be running on both ports, but you redirect the traffic using the proxy the way you would like.
The same proxy configuration in an Apache (ref: https://httpd.apache.org/docs/current/mod/mod_proxy.html#forwardreverse or https://www.leaseweb.com/labs/2014/12/tutorial-apache-2-4-transparent-reverse-proxy/) or NGINX (ref: https://www.nginx.com/resources/admin-guide/reverse-proxy/) would be IMHO less complex and better tested in countless production scenarios.


text:
Q: Angular 2+ Promise Unit testing Hi I'm trying to write jasmine unit test for following angular service.
However, I'm struggling how to write test for return promise value and wasn't able to find any elaborate resource how to write for these cases.
Most struggle comes from not knowing how to test what has been called within the returned promise.
For example, I want to test calling this.createMap() invokes this._mapResolver with map instance new google.maps.Map(el, mapOptions)
Could an Angular 2+ guru help me understand writing spec for promises? or references to learn from?
declare let google: any;

/**
 * Wrapper class that handles the communication with the Google Maps Javascript
 * API v3
 */
@Injectable()
export class GoogleMapsAPIWrapper {
  private _map: Promise<mapTypes.GoogleMap>;
  private _mapResolver: (value?: mapTypes.GoogleMap) => void;

  constructor(private _loader: MapsAPILoader, private _zone: NgZone) {
    this._map =
      new Promise<mapTypes.GoogleMap>((resolve: () => void) => { this._mapResolver = resolve; });
  }

  createMap(el: HTMLElement, mapOptions: mapTypes.MapOptions): Promise<void> {
    return this._loader.load().then(() => {
      const map = new google.maps.Map(el, mapOptions);
      this._mapResolver(<mapTypes.GoogleMap>map);
      return;
    });
  }

  setMapOptions(options: mapTypes.MapOptions) {
    this._map.then((m: mapTypes.GoogleMap) => { m.setOptions(options); });
  }
}

Solution suggested by @ArmenVardanyan
describe('Service: GoogleMapsAPIWrapper', () => {

  const loaderServiceStub = {
    load: () => Promise.resolve()
  };

  let service;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [
        GoogleMapsAPIWrapper,
        {provide: MapsAPILoader, useValue: loaderServiceStub}
      ]
    });
  }));

  beforeEach(async(inject([GoogleMapsAPIWrapper], (_service: GoogleMapsAPIWrapper) => {
    service = _service;
  })));

  it('should be created',() => {
    expect(service).toBeTruthy();
  });

  it('should be call _mapResolver with specified arguments', async(() => {
    const elem = document.createElement('div');
    const spyOnCreateMap = spyOn(service, '_mapResolver');
    service.createMap(elem, {})
      .then(() => {
        expect(spyOnCreateMap).toHaveBeenCalled();
        expect(spyOnCreateMap).toHaveBeenCalledWith(new google.maps.Map(elem, {}));
      });
  }));

});

A: I don't remember how to correctly inject NgZone int tests, but as I see it is irrelevant to your question. So You just have to mock the MapsAPILoader service and test the _mapResolver.

const loaderServiceStub = {
  load: () => Promise.resolve()
};

describe('GoogleMapsAPIWrapper', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        GoogleMapsAPIWrapper,
        {provide: MapsAPILoader, useValue: loaderServiceStub}
      ]
    });
  });

  it('should be created', inject([GoogleMapsAPIWrapper], (service: GoogleMapsAPIWrapper) => {
    expect(service).toBeTruthy();
  }));

  it('should be call _mapResolver with specified arguments', inject([GoogleMapsAPIWrapper], (service: GoogleMapsAPIWrapper) => {
    const spyOnCreateMap = spyOn(service, '_mapResolver');
    service.createMap(new HTMLDivElement(), {/*options */});
    expect(spyOnCreateMap).toHaveBeenCalled();
  }));
});

So you basically mock the loader service to just return a resolved Promise when load is called, and then check if _mapResolver has been called. But you cannot check if the arguments provided were correct, because of this lines:
const map = new google.maps.Map(el, mapOptions);
this._mapResolver(<mapTypes.GoogleMap>map);

There is a map being created inside the callback passed to the then method, but you cannot know what that object is going to be. You can try
expect(spyOnCreateMap).toHaveBeenCalledWith(new google.maps.Map(el, mapOptions));

but I'm almost sure it is not going to work. The same issue goes with the second Test you want to write: the _map promise will return an object which has a setOptions method, but you don't really know what that object is going to be. Or else you will have to mock that Promise either and then make sure your mocked setOptions method has been called.


text:
Q: App keep crashing when I try to save image to gallery I wanted to take a photo and save it to gallery. Then read this photo from gallery and convert it to text( using ocr)
But my app keep crashing when I try to save it with this line of code
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);

I debug my app and found this line is the responsible for crash. But without this line I can't save my image. How can I do that ?
package com.example.takepicture;

import ...

public class MainActivity extends AppCompatActivity {
    private static final int CAMERA_REQUEST = 1888;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnCamera = (Button) findViewById(R.id.btnCamera);
        imageView = (ImageView) findViewById(R.id.ImageView);

        btnCamera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                String pictureName = getPictureName();

                File imageFile = new File(pictureDirectory,pictureName);
                Uri pictureUri = Uri.fromFile(imageFile);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
                //capturarFoto();

            }
        });

    }

    private String getPictureName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        return "Img" + timeStamp + ".jpg";

    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_OK) {
            if (requestCode == CAMERA_REQUEST) {

            }
        }
    }
}

A: Fastest solution is adding:
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

somewhere before calling:
startActivityForResult(...)
But the correct one (for API >24) is:

*

*creating URI via FileProvider.getUriForFile(...) and

*creating provider (and adding it to Manifest file)
You can find more info there: https://stackoverflow.com/a/50265329/5529263


text:
Q: MySQL to offline database android I have a lot of data in server mysql database and want  to use data in android app in offline model of the application. What kind of architecture/design change can be used for offline model?

A: You could make a rest api for accessing the MySQL server data (or its parts) and then sync and store with SQLITE on Android.

A: You can use SQLite Database;
What you can do is make an async task and call it in some duration depending upon your requirements to refresh your SQLite data with MYSQL database using Rest Services
`Intent ishintent = new Intent(this, Asynctasktomysql.class);
        pintent = PendingIntent.getService(this, 0, ishintent, 0);
        alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pintent);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                50000, pintent);`

I set a duration of 50 sec in code. You can change it by Your self.
You can call your server for json Object and then parse it Like this :
Gson gson = new GsonBuilder()
                .disableHtmlEscaping()
                        .registerTypeAdapter(Date.class,
                                new JsonDateDeserializer()).create();
                Table1 table1vo = gson.fromJson(jsonObj, Table1.class);

After that put all your data in ContentValues and insert into data base
final ContentValues InfoCV = CVTransformers
                    .transformContactInfo(table1vo);
            contactInfoCV.put("SEQ", table1vo.getSEQ());
            dbHelper.insert("TABLE1_NAME", null, InfoCV);`


text:
Q: Processing Nested json file in pyspark with partition i have nested dict data in a json file stored in hdfs (2years of daily data),
i would like to process this data in pyspark with DATE as partitioned by column.
and store it to a hive table,
i tried to explode the nest first to get flat structure, but have not figured out How can i partition by Date as it nested, recurring and dynamic..what should be my approach?
df = spark.read.json('hdfs://namenode:9000/forex/forex_rates.json')
dfRates = df.select(explode(array(df['rates']))).toDF("rates")
dfdate=dfRates.select("rates.2018-02-22.NZD")

# Drop the duplicated rows based on the base and date columns
forex_rates = df.select('Date', 'base', 'rates_BGN',
'rates_CNY', 'rates_NZD').dropDuplicates(['base', 'Date']).fillna(0, subset=
['BGN', 'CNY', 'NZD'])

# Export the dataframe into the Hive table forex_rates
forex_rates.write.mode("append").insertInto("forex_rates")

Thank you in advance.
sample data:

           {'rates': {
                        '2018-01-22': {'BGN': 1.9558, 'TRY': 4.6552, 'CNY': 7.8374, 'NOK': 9.6223, 'NZD': 1.6758},
                        '2018-01-09': {'BGN': 1.8558, 'TRY': 4.4843, 'CNY': 7.7865, 'NOK': 9.6715, 'NZD': 1.6601}
                      },
            'start_at': '2018-01-01',
            'base': 'EUR',
            'end_at': '2018-02-01'
           }

expected df structure:

+------------+------+-----------+-----------+-----------+
| Date       | Base | rates_BGN | rates_CNY | rates_NZD |
+------------+------+-----------+-----------+-----------+
| 2018-01-22 | EUR  | 1.9558    | 4.6552    | 7.8374    |
+------------+------+-----------+-----------+-----------+
| 2018-01-09 | EUR  | 1.8558    | 4.4843    | 7.7865    |
+------------+------+-----------+-----------+-----------+
| .......... | ...  | ......    | .....     | ......    |
+------------+------+-----------+-----------+-----------+

A: This code might be helpful to you,
input JSON taken,
   {'rates': {
                '2018-01-22': {'BGN': 1.9558, 'TRY': 4.6552, 'CNY': 7.8374, 'NOK': 9.6223, 'NZD': 1.6758},
                '2018-01-09': {'BGN': 1.9558, 'TRY': 4.4843, 'CNY': 7.7865, 'NOK': 9.6715, 'NZD': 1.6601}
              },
    'start_at': '2018-01-01',
    'base': 'EUR',
    'end_at': '2018-02-01'
   }

code
from pyspark.sql.functions import *

df=spark.read.option("multiline","true").json("file:///home/sathya/test-datasets/forex_rates.json")

base=df.select("base").rdd.collect()[0].asDict()["base"]
start_at=df.select("start_at").rdd.collect()[0].asDict()["start_at"]
end_at=df.select("end_at").rdd.collect()[0].asDict()["end_at"]

df2=df.select("rates.*")
#python 2
stack_characteristics = str(len(df2.columns))+','+','.join(["'{}',`{}`".format(v,v) for v in df2.columns])

df2.select(expr('''stack({})'''.format(stack_characteristics)).alias('date','vals')).select('date', 'vals.*').withColumn("base",lit(base)).withColumn("start_at",lit(start_at)).withColumn("end_at",lit(end_at)).show()

#python3
#stack_characteristics = str(len(df.columns))+','+','.join([f"'{v}',`{v}`" for v in df.columns])

#df.select(expr(f'''stack({stack_characteristics})''').alias('date','vals')).select('date', 'vals.*').withColumn("base",lit(base)).withColumn("start_at",lit(start_at)).withColumn("end_at",lit(end_at)).show()
'''
+----------+------+------+------+------+------+----+----------+----------+
|      date|   BGN|   CNY|   NOK|   NZD|   TRY|base|  start_at|    end_at|
+----------+------+------+------+------+------+----+----------+----------+
|2018-01-09|1.9558|7.7865|9.6715|1.6601|4.4843| EUR|2018-01-01|2018-02-01|
|2018-01-22|1.9558|7.8374|9.6223|1.6758|4.6552| EUR|2018-01-01|2018-02-01|
+----------+------+------+------+------+------+----+----------+----------+
'''


text:
Q: SQL Software development tools How do I interact with the code behind my SQL server ? I am using Microsoft's SQL Server Management Studio but that is a GUI, I would like to hard code parts of my database, using SQL.
Thanks

A: Ordinary SQL Server is used as backend only and SQL Server Management Studio is used for debugging and database maintenance.
Applications are developed in different system/languages (SQL Server most of the time is paired with Microsoft .NET and languages such as C# or VB.NET).
So develop your front-end and middle-tier in a .NET language and use SQL Server as a backend database.


text:
Q: Continuity ( Find unknown) $f(x) = a \sin \{(pi/2)(x+1)\}$ if $x \leq 0$
$(tan x - sin x)/x^3$ if $x > 0$
$f(x)$ is continious at $x = 0$
find a
I did like this --->
lim f(x) = a
x->0+
lim   (tan x - sin x)/x^3 = a
x->0+
put x = 0 + h
lim (tan h - sin h)/h^3 = a
h->0
lim (tan h)/h^3 - lim (sin h)/h^3 = a
h->0              h->01
lim tan h / h  .  lim 1/h^2 -  lim sin h / h  .  lim 1/h^2 = a
h->0              h->0         h->0              h->0
lim (1/h^2) - (1/h^2) = 0 = a
h->0
implies that a = 0

As $\lim_{h \to 0} \tan h/h = 1$
$lim \sin_{h \to 0} h/h = 1$
but a does not equal 0 it equals 1/2
where is the mistake.

A: for the second limes write
$$\frac{\sin(x)(1-\cos(x))(1+\cos(x)}{x^3\cos(x)(1+\cos(x))}$$
and this tends to $\frac{1}{2}$ for $x$ tends to Zero, so $a=\frac{1}{2}$


text:
Q: Java EE Spring framework related questions Ok this is long and has many stupid questions, because I am a dumb beginner.
Im a single developer working on a project (Java Web App) and I am relatively new to Java. I am even newer to the Spring framework. I have managed to write a small project that uses one servlet and some jsp's to authenticate users against a database and route them to either a welcome page or an error page based on login credentials. I have gotten to this point but it is only the beginning of what this application will do ofcourse. Most importantly, I am not using any Spring.
I understand that it is in my interest to learn the spring framework if I am to design Java EE enterprise applications because it makes many things easier. So, in that quest, I headed over to the tutorials on this website:
http://spring.io/guides/gs/serving-web-content/
in order to do some learning. I relized quickly that all of their examples include a Maven or Gradle script for dependencies and for build. So, I thought oh no now I have to learn about one of these build tools if I need to use Spring framework? So, with my limited knowledge and reading around, I picked Gradle when I started understanding that it is the latest generation build tool in the line of Ant->Maven->Gradle. So, I thought Gradle is what I should invest my time in.
Anyway, when I started to work on the Spring tutorial above, I quickly realized that they are doing this at the command line and not on an IDE. That confused me even further because I thought why would anyone used command line in todays world full of capable IDEs. I had Eclipse (plain vanilla + Spring Tool Suite) installed already so I thought I will do this on Eclipse instead. That's where my confusion skyrocketed.
For starters, I couldn't figure out what kind of project template to start with. Should it be a "Dynamic Web Project?" No wait it has to be some kind of a Spring template right? Otherwise why would I go through the trouble of adding the Spring Tool Suite and get all these new templates? Ok, so I picked a Spring template. I quickly realized that I also have the option to import the Spring MVC tutorial that I was doing into Eclipse. So, I did that. More confusion, now I realized that if I right click on the imported example project, there is no longer a "Run on server" option in the "Run as" menu. I thought why is that gone? I must have picked the wrong project template. But wait, I couldn't have picked the wrong template because I imported the whole project from the Spring website. Oh man my head hurts. After some thinking I remembered.....oh yes they talked about Gradle and I already downloaded it and set my Path environment variable for it so I'll use Gradle to build and run this project. Ok now how do I invoke Gradle from within Elipse? More reading told me I must have Eclipse Gradle Integration. So I downloaded that plugin into eclipse. Now, in my right click menu I have a "Gradle" and "Gradle..." option but still no "Run on server". Man, why is this so complicated I am a beginner simply trying to run a tutorial Spring MVC project. Anyway, I chose "Gradle" from the "run as" option and I saw that Gradle prints out a bunch of a stuff in the Eclipse console like when its starting the embedded servlet container and other good stuff. But I see nothing else happening. I expected the Eclipse embedded web browser to show me "Hello world". But wait this isn't a web project because there is no Web-Inf folder in its hierarchy, so why would I see a browser...okay but I also don't see "hello world" in the console? Where is the project running? Ahaha..finally I launched my own Chrome browser and pointed it to localhost URL and glory, I saw "hello world".
It took me two and a half days of playing around to figure all out up to this point. As you can see, my understanding is in its infancy on these things and I need some questions answered. If am looking to build a Java web application and I am the only developer:

*

*Do I need a build tool? I thought this was for teams.

*If so, is Gradle ok?

*Which Eclipse template to start with?

*Some other Spring MVC tutorials I saw online like the one from tutorialspoint do include jsp's and are web based(and not simply command line). Those tutorials ask you to import some jars(Spring and related jars like commons-logging) into the project at some point. How do these guys know which of the spring jars they need? Is it from experience or is there another source for this knowledge? I thought this dependency management is where the whole need for the build tool comes in and that's what Gradle will handle for me, nevermind I don't know how to ask Gradle to do that yet.

*Once I start a project and start using Spring incrementally, how do I know what additional jars I need at certain points?

Thanks for reading until this line and thanks for your help.

A:
Do I need a build tool? I thought this was for teams.

Yes, you need when you work with a large project which need lot jars, classes and configuration files to run application, by using a build tool that will take care of all these things. build tool will save some time typing commands. As you can probably guess, it's not reasonable to use the command line if you have many source code modules and they should be compiled and linked in a particular order.
you said your a single developer, so build tool is just an overhead.

If so, is Gradle ok?

Ok.

Which Eclipse template to start with?

Dynamic Web Project.

Some other Spring MVC tutorials....
  How do these guys know which of the spring jars they need?.....

Well, when you going to develop a web application with spring, then you need to have jar files like: spring-core.jar, spring-web.jar, spring-webmvc.jar etc. same when you need any ORM framework like hibernate then you need to add hibernate releated jar files in project build path. When you go through some tutorials they will be listed like what are jar or dependencies you need to add.

Once I start a project and start using Spring incrementally, how do I
  know what additional jars I need at certain points?

It depends upon you which frameworks you need to use further in your application, then, you should make available all the dependencies(jar files) of the framework to your project build path.


text:
Q: How to export a project in UIMA I have a java annotator and now I want to use it in UIMA.
I followed the guide to make a new annotator in UIMA and now I do not know where to put my JAVA code, which folders to put my files and how they relate to the XML file.
  I am stuck.
Can you help?

A: first follow these steps:
1, Defining Types

*Generating Java Source Files for CAS Types

*Developing Your Annotator Code

*Creating the XML Descriptor

*Testing Your Annotator
and 4th point is your required answer after creating java annotator code


text:
Q: ¿Como sacar la suma total de todo los subtotales? //Creo una función donde voy a sumar todos los valores totales de la última columna
var sumaTotales = function(){
  //Inicializo en 0 el valor a establecer indicando el resultado de la sumatoria
  var totales = 0;
  //Recorro todas las filas de la tabla
  $('tr','#tablaDetalleMaterialEinsumo').each(function(){
     //Obtengo el campo del cual quiero tomar el valor para sumarlo
     var campo_total = $(this).find('input[type="text"]:eq(4)');
     //Agrego a totales el nuevo valor
     var numero = parseInt(campo_total.val()); totales += isNaN(numero) ? 0 : numero;
   });
  //Establezco el resultado de la suma
  $('#valor_unitario').val(totales);
  $('#suma_1').val(totales);
};

//Esta tabla es para agregar Detalle materiales, repuestos e insumos
var sumaValores = function(){
    //Obtengo la última fila ingresada en la tabla
    var fila = $("#tablaDetalleMaterialEinsumo").find('tr:last');
    //Obtengo el campo referente a la cantidad de insumo ':eq(2)'
    var campo1 = fila.find('input[type="text"]:eq(2)');
    //Obtengo el campo referente al precio_unitario_insumo ':eq(3)'
    var campo2 = fila.find('input[type="text"]:eq(3)');
    //Obtengo el campo donde se escribirá el resultado
    var destino = fila.find('input[type="text"]:eq(4)');

    campo1.on('change', function(){
      destino.val(parseInt(campo1.val())*parseInt(campo2.val()));
        //Llamo a la función para que se actualice cada vez que se cambie algo en este campo
        sumaTotales();

      });

    campo2.on('change', function(){
      destino.val(parseInt(campo1.val())*parseInt(campo2.val()));
        //Llamo a la función para que se actualice cada vez que se cambie algo en este campo
        sumaTotales();

      });
  };

  function funcNuevaDetalleMaterialEinsumo()
  {
    $("#tablaDetalleMaterialEinsumo")
    .append
    (
      $('
')
      .append
      (
        $('')
        .append
        (
          $('<input>').attr('type', 'text').addClass('form-control').attr('name', 'detalle_insumo[]')
          )
        )
      .append
      (
        $('')
        .append
        (
          $('<input>').attr('type', 'text').addClass('form-control').attr('name', 'unidad_insumo[]')
          )
        )
      .append
      (
        $('')
        .append
        (
          $('<input>').attr('type', 'text').addClass('form-control').attr('name', 'cantidad_insumo[]')
          )
        )
      .append
      (
       $('')
       .append
       (
        $('<input>').attr('type', 'text').addClass('form-control').attr('name', 'precio_unitario_insumo[]')
        )
       )
      .append
      (
       $('')
       .append
       (
        $('<input>').attr('type', 'text').addClass('form-control').attr('name', 'valor_total_insumo[]').prop('readonly', true)
        )
       )
      .append
      (
        $('').addClass('text-center')

        .append
        (
          $('
').addClass('btn btn-danger').text('Eliminar')
          )
        )
      );
    sumaValores();

  }

GASTOS GENERALES

        DESCRIPCION
        PORCENTAJE
        SUB TOTAL
        TOTAL

        GASTOS GENERALES
        <input type="text" class="form-control" name="porcentaje_gasto_generales" value="">
        <input type="text" class="form-control" name="sub_total_gasto_generales"  id="sub_total_gasto_generales" value="" readonly>
        <input type="text" class="form-control" name="total_gasto_generales" value="" readonly>

        UTILIDAD
        <input type="text" class="form-control" name="porcentaje_utilidad" value="">
        <input type="text" class="form-control" name="sub_total_utilidad"  value="" readonly>
        <input type="text" class="form-control" name="total_utilidad" value="" readonly>

A: Esta es la respuesta: Lo que hice fue recorrer todas las tablas que se encuentran separadas e hice una funcion que sumara todo los subtotales, y despues son mostrado en el subtotal de gastos generales
//esta funcion es para sumar todo los subtotales de los detalles
var sumaTotalGeneral = function(){
  //Inicializo en 0 el valor a establecer indicando el resultado de la sumatoria
  var totalgeneralsuma0 = 0;
  var totalgeneralsuma1 = 0;
  var totalgeneralsuma2 = 0;
  //Recorro todas las filas de la tabla
  $('tr','#tablaDetalleMaterialEinsumo').each(function(){
     //Obtengo el campo del cual quiero tomar el valor para sumarlo
     var campo_total0 = $(this).find('input[type="text"]:eq(4)');
     //Agrego a totales el nuevo valor
     var numero0 = parseInt(campo_total0.val());
     totalgeneralsuma0 += isNaN(numero0) ? 0 : numero0;
   });

  $('tr','#tablaDetallePersonaEmaquina').each(function(){
     //Obtengo el campo del cual quiero tomar el valor para sumarlo
     var campo_total2 = $(this).find('input[type="text"]:eq(5)');
     //Agrego a totales el nuevo valor
     var numero1 = parseInt(campo_total2.val());
     totalgeneralsuma1 += isNaN(numero1) ? 0 : numero1;
   });

  $('tr','#tablaDetalleGastoGeneral').each(function(){
     //Obtengo el campo del cual quiero tomar el valor para sumarlo
     var campo_total3 = $(this).find('input[type="text"]:eq(4)');
     //Agrego a totales el nuevo valor
     var numero2 = parseInt(campo_total3.val());
     totalgeneralsuma2 += isNaN(numero2) ? 0 : numero2;
   });

  var to= totalgeneralsuma0+totalgeneralsuma1+totalgeneralsuma2;
  //Establezco el resultado de la suma
  $('#sub_total_gasto_generales').val(to);

  };


text:
Q: Can we Count API HIT's using Throttling in Django DRF I created some API using Djanago- DRF.
Now, I want to count the API HIT's through Throttling and if total count is reached 500 user will deative mode(is_active = False)
So, any idea how can do this through throtting.
if any other approach is there plz suggest me


text: Q: Android EasyPusher JNI error, solve or disable? I am using EasyPusher to stream camera through RTSP. The app is working with no any issue, but in the Logcat, it keeps printing this error easypusher_jni: ____isActivated__....... userPtr=-1195202048 during streaming. Is it a way to resolve the error, or how to just disable the error as the app is working fine.


text:
Q: f.collection_select not showing up I'm working in rails 4 with simple_form and I have two models, one called content and the other one called category. Category has many content and the content belongs to a category. The problem is that when i want a collection_select to show in my form is not showing.
Here is the code:
<%= simple_form_for @content, html: { multipart: true } do |f| %>

  <%= f.input :title, required: true %>
  <%= f.input :tagline, required: true, label: 'Short description', input_html: { maxlength: 20 }%>
  <%= f.input :description, required: true %>
  <%= f.input :price, required: true %>
  <%= f.input :team, required: true, label: 'Team member number' %>
  <%= f.input :equity, required: true, label: 'Equity percentage'%>
  <%= f.input :website, label: 'Website Link', as: :string%>
  <%= f.input :linkedin, label: 'Linkedin Link', as: :string %>
  <%=f.collection_select :category_id, Category.all, :id, :name, {prompt: "Chose a category"} %>

  <%= f.input :copertina, required: true, label: 'Image Cover' %>

  <%= f.button :submit %>

<% end %>

Thanks for the help.
Edit: Could it be a js problem?

A: Have you tried   <%= f.association :categories %>?

A: For selecting the associated Category for an instance of Content, @content)
collection_select(:content, :category_id, Category.all, :id, :name, prompt: true)

A: = f.select(:category_id, Category.all.collect {|c| [c.name, c.id] },{include_blank: true} )

Hope, that helps!


text: Q: Difference between glmnet and nnls for non-negative least squares in R I'm trying to do some non-negative linear regressions in R, and I found in the blog here https://www.r-bloggers.com/2019/11/non-negative-least-squares/ that either the package nnls or glmnet could work. I tried both and found that their results differ a bit, so I'm wondering what are some differences between these two methods and whether one is more reliable than the other.


text:
Q: Missing debug file is slowing down my application? I've created a solution with a portable class library and a windows phone project. In the PCL i do some HttpClient action but I experience that my app is so slow.
So I went in and did a Debug(timestap) all over the place, narrowing it down to where I did get HttpClient request magic, :-). I then noticed the following line
'TaskHost.exe' (CLR C:\windows\system32\coreclr.dll: Silverlight AppDomain): Loaded 'C:\Data\Programs\..\System.Net.Http.Primitives.DLL'. Cannot find or open the PDB file.

What is this? Can I skip it? My request to my server takes forever (10-20 sec) and if its using this time to look for the PDB file that does not exits I totally get it. I changed my solution to use RELEASE settings but i get that same output from my debugger.
How can I fix that?


text:
Q: When does a protocol function get called? I have adopted a protocol in viewController class and defined it's method (only one method). The method is suppose to update an array which is initially empty. Here is some code.
var contact = ContactList()

func getContactData( entry: ContactListEntry ) {

    contact.updateEntry(entry)

}

also
override func tableView(tableView: UITableView, cellForRowAtIndexPath     indexPath: NSIndexPath) -> UITableViewCell {
    self.detailViewController?.delgate = self
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as      UITableViewCell

    cell.textLabel!.text = contact.entries [indexPath.row].firstName

    return cell
    }

It's giving fatal error: Cannot index empty buffer
(lldb)
My question is, at what point does getContactData () get called? I need it to be called before the tableView functions so I can make the array available with something in it.

A: cellForRowAtIndexPath is called when iOS needs to display the cell. This is also true for other methods from UITableViewDataSource


text:
Q: I can't upgrade my .NET to anything over 4.8 I've installed multiple .NET SDKs from Microsoft site. They do not appear in Visual Studio when I want to change it. How do I fix this?
I've downloaded SDKs, Nugets, and nothing. I want to be able to use .net 7+ on a C# project.

A: Your project is a .NET Framework project (the "older" dot net). You'll not be able to select dotnet 5+ directly in the visual studio project's properties as dotnet net 5+ is the evolution of the dotnet core branch. Those versions will not appear at all.
You can create a new dotnet core project and import your code (and adapt if necessary), or use the tool microsoft released to "upgrade" a .NET Framework project to dotnet core one. (https://dotnet.microsoft.com/en-us/platform/upgrade-assistant)
You'll then be able to select any dotnet core framework you want (ie 7.0)

A: If your project is targeting .Net framework 4.8, you can't simply upgrade to .Net 7 by selecting from a list,
You need to migrate your project to .Net 7,
A very useful tool is the .Net upgrade assistant provided by Microsoft.
You can find it here:
https://dotnet.microsoft.com/en-us/platform/upgrade-assistant/tutorial/install-sdk
and follow the step-by-step instructions in that page to complete your migration.

A: Try installing everything related to .NET using the Visual Studio Installer - https://visualstudio.microsoft.com/downloads
In order to be able to create .NET 7 application, you will need to select ".NET 7 Runtime" under the "Individual components" section.

After the installation, you should be able to select ".NET 7" as your application Framework.