text:
Q: Throwing errors inside catch blocks allowed? I've come up with the following piece of code of submitting my form to Firebase using async-await with try-catch blocks.
Basically throwing the errors back to the onSubmit function that sets the firebaseError when an error has been thrown somewhere. Only when there was no error thrown, the user gets forwarded to the /posts authenticated page.
Is throwing the errors back correct or or is there a better option?
const [firebaseError, setFirebaseError] = useState(null)

  // Add user to Firestore
  const createUser = async (user) => {
    try {
      await db.collection('users').doc(user.uid).set(user)
    } catch (error) {
      throw error
    }
  }

  // Authenticate user
  const signUp = async ({ email, password }: LoginData) => {
    try {
      const userAuth = await auth.createUserWithEmailAndPassword(email, password)
      const userDb = await createUser({ uid: userAuth.user.uid, email })
      return userAuth
    } catch (error) {
      throw error
    }
  }

  // Callback for handleSubmit
  const onSubmit = async (data: LoginData) => {
    try {
      const user = await signUp(data)
      router.push('/posts')
    } catch (error) {
      setFirebaseError(error.message)
    }
  }

A: Doing
try {
      await db.collection('users').doc(user.uid).set(user)
    } catch (error) {
      throw error
    }

Is redundant. This will just do the same
await db.collection('users').doc(user.uid).set(user)

as catch just gets called when an error is thrown inside the try block, throwing it back is just the same as just letting it throw from the firestore async call and then catching it on the parent function (onSubmit).
Normally you would want to use catch when you want to do something rather than throwing the error, such as logging it to some observability platform, or setting some state besides/instead of throwing it.
In fact, sonarlint has a rule flagging this: https://rules.sonarsource.com/javascript/tag/unused/RSPEC-2737
A catch clause that only rethrows the caught exception has the same effect as omitting the catch altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads. Such clauses should either be eliminated or populated with the appropriate logic.

A: Can't see anything wrong with the way you're handling exceptions, basically when someone signs up you try to create a user and if everything went fine you redirect to /posts, and if any exceptions are being thrown in the end you catch it.
Only thing that I would personally add would be some user notification based upon the error if you have't already done in other parts of your code, and maybe even more important checking where the error happen, so you can do a cleanup, let's say
auth.createUserWithEmailAndPassword(email, password)

succeeded but the creating the user in the DB fails, in the catch block you should first try to clear the new created user and then throw the error.


text:
Q: C: Concatenation of 'n' strings How to concatenate multiple strings in C?
I have a function for concatenation of two strings (no strcat()):
char* concat(char *s1, char *s2)
{
    char *r, *t;
    int d1 = -1, d2 = -1;
    while (s1[++d1]);
    while (s2[++d2]);
    t = r = (char *)calloc(d1 + d2 + 1, sizeof(char));
    while (*t++ = *s1++);
    t--;
    while (*t++ = *s2++);
    return r;
}

Is there a way to use this function (or strcat()) to concatenate multiple strings?
Also, is this dynamic allocation right:
char* concat(char** array, int n)
{
    char *r; int i;
    r=(char *)calloc(n*MAX+1, sizeof(char));
    array=(char **)malloc(n * sizeof(char *));
    for(i=0;i<n;i++)
    {
        array[i]=(char *)malloc(MAX+1);
    }
   ... //concatenation//...
    free(r);
    free(array[i]);
    free(array);
    return r;
}

A: Yes, you can extend the code from the first function to deal with a whole array:
char* concat(char** array, size_t n) {
    size_t total = 1; // One for null terminator
    for (int i = 0 ; i != n ; i++) {
        total += strlen(array[i]);
    }
    char *res = malloc(total);
    char *wr = res;
    for (int i = 0 ; i != n ; i++) {
        char *rd = array[i];
        while ((*wr++ = *rd++))
            ;
        wr--;
    }
    *wr = '\0';
    return res;
}

You do not need to allocate temporary 2D structures. Since you can precompute the length of the result, a single allocation is sufficient.
Demo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Painting relative to scrollbars I am making some components for my own use, i am trying to make a "riff generator" for making tunes in midi format. Therefore i am writing a pianoroll editor (like in fl studio etc).

The problem im having is drawing relative to the scrollbar positions. I am trying it for two days now, but i cant seem to figure out how to do this. I already added variables and procedures for setting the scroll positions, but i dont understand how i can draw up/down and sideways when i scroll.
I added the code i have so far, i am using the GDI+ unit from Erik Bilsen (www.bilsen.com/gdiplus) for drawing.
If anyone can look at my code, and help me to get the drawing right that would be awesome! I will release this and other components as opensource when i finish, so other people will be able to use these components too.
The component code: https://pastebin.com/562yfDvu
FScrollPosX : Integer;
FScrollPosY : Integer;
FScrollMaxX : Integer;
FScrollMaxY : Integer;
FOldScrollX : Integer;
FOldScrollY : Integer;

A: Some typical calculations
Scrollbar range
Given Virtual extent (VirtExt) in pixels
Given Viewport extent (VPExt) in pixels

Scrollbar range = VirtExt - VPExt (to leave the last part visible in the viewport)

Object position in ViewPort with a given scroll position
Given Object.pos (ObjPos) (in virtual space)
Given Sroll position (ScrPos)

Position in viewport: ObjPos - ScrPos

Object visibility filter
Visible if (OPos >= ScrPos) and (OPos < ScrPos+VPExt)


text:
Q: how to exclude a source package when deploying an app on JBoss within Eclipse I'm developing a java web-based application and deploying it on JBoss 5.0 within Eclipse. I have some testing packages in my project which I'd like to avoid deploying them. Is there any means by which I can tell Eclipse to exclude these testing packages from the deploying war ?
I've tried with the run configuration but didn't find the way to exclude any package.
thanks!

A: I am not sure it is currently available (except for a custom xml script which would build a custom war to deploy).
I base this on JEE Status Meetings/2009-06-11:

Scenario: Create a source folder in a project that has test code (which should not be deployed) - need a way to exclude folders from deployment in component file

It does look like what you want, doesn't it?

The same page mentions:
"we are targeting these changes for WTP 3.2": no guarantee though that it will include that exact scenario, but if it makes WTP 3.2 (see plan) , it should be available for eclipse Helios 3.6 (late June 2010).
An intermediate milestone might include that feature before next year though.


text:
Q: How to rename all files to lowercase (solved) and simultaneously spaces to underscores I am trying to convert all files to lowercase in a directory tree and subsequently move spaces to underscores or hyphens. The first part I was able to get by searching which uses below code.
find . -depth -print0 | xargs -r0 perl-rename -n 's/(.*)\/([^\/]*)/$1\/\L$2/;'
Now I am trying to extend it to move spaces to _ also in a single regex but with no success till now. I tried with various combinations of \K operator as I think it'd be possible with that. Could you please help me out. The last command I tried was,
find . -depth -print0 | xargs -r0 perl-rename -n 's/(.*)\/([^\/]*)/$1\/\L$2/;s/(.*)\/\K(\S+)\s+\g1/_/g;'
but it doesn't seem to work.

A: As anubhava has indicated, the problem is with changing the names of directories while you are processing the tree. It is similar to the issue with modifying a Perl hash while you are iterating over it
This is the sort of thing that the File::Find module's finddepth function is for. It will report a directory name only immediately before the scan is about to back out of it, and after all the contents have been reported
As long as you are running Perl v5.14 or better, so that tr/// will accept the non-destructive susbtitution modifier /r, you can write it in one line like this
perl -MFile::Find=finddepth -e"finddepth(sub{ rename $_, tr/A-Z /a-z_/r }, '/path/to/root/dir')"

A: You can use:
find . -depth -print0 |
   xargs -0 perl-rename -n 's~([^/]+)$~\L$1~;s~(?:.*/|\G)\K(\S+)\s+(?![^/]*/)~$1_~g'

RegEx Demo

A: find . -depth -print0 |
xargs -r0 perl-rename -n  's!([^/]+$)!lc($1 =~s/ /_/gr)!e'


text:
Q: XLPagerTabStrip - Selected tab selection not working The selected tab indicator in the XLPagerTabStrip Library is not working with Swift 3 and XCode 8
I'm using the following customization for the Tab Strip
    super.viewDidLoad()

    buttonBarView.selectedBar.backgroundColor = UIColor(red: 240.0/255.0, green: 89.0/255.0, blue: 43.0/255.0, alpha: 1.0)
    buttonBarView.backgroundColor = UIColor.clear

    settings.style.selectedBarHeight = 3.0
    settings.style.selectedBarBackgroundColor = UIColor(red: 240.0/255.0, green: 89.0/255.0, blue: 43.0/255.0, alpha: 1.0)

    settings.style.buttonBarHeight = 45.0
    settings.style.buttonBarMinimumLineSpacing = 0.0
    settings.style.buttonBarLeftContentInset = 0.0
    settings.style.buttonBarRightContentInset = 0.0
    settings.style.buttonBarItemFont = UIFont(name: "Avenir-Book", size: 12.0)!
    settings.style.buttonBarItemBackgroundColor = UIColor.clear
    settings.style.buttonBarItemLeftRightMargin = 0.0
    settings.style.buttonBarItemTitleColor = UIColor.black

A: This is the solution for the above mentioned issue
    class ViewController: ButtonBarPagerTabStripViewController {

        override func viewDidAppear(_ animated: Bool) {
            let selectedBarHeight: CGFloat = 2

            buttonBarView.selectedBar.frame.origin.y = buttonBarView.frame.size.height - selectedBarHeight
            buttonBarView.selectedBar.frame.size.height = selectedBarHeight

        }

        override func viewDidLoad() {
            settings.style.selectedBarBackgroundColor = .green

            super.viewDidLoad()
        }
    }


text:
Q: Return an array between start A and B $array = []
def range(start_position,end_position)
  for i in start_position..end_position
    $array.push(i)
    puts $array
  end
  return $array
end

range(1,10)

I was wondering why exactly my array isnt returning. Clearly when I do puts $array, 1-10 is being inserted, but when I call my function I want the array to be returned. Any thoughts, I'm reading through documentation but can't find what i've done wrong or if I have made any syntax errors.

A: Your code is essentially correct you just need to omit the puts $array within your for block. And also no need for the optional return keyword. So fixing your code we would have:
$array = []
def range(start_position,end_position)
  for i in start_position..end_position
    $array.push(i)
  end
  $array
end

p range(1,10) #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Kernel#p performs the Kernel#inspect method which as stated in the documentation provides a human-readable representation of the object in question. In Ruby it would be much better to do something like this perhaps:
def range(start_position,end_position)
  (start_position..end_position).map {|i| i }
end

p range(1,10) #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

A: It returns an array, but you are not doing anything with it, so it is discarded. You could print it (with p range(1,10) or puts range(1,10) ) or assign it to a variable for later use ( result = range(1,10) ). Which is the same as result = (1..10).to_a, not using your method at all.

A: Your array does return, but you don't do anything with the return value. Try saving it to a variable or print the result:
print range(1, 3) # => [1, 2, 3]

If you're looking for a simpler way to implement this function, you could use Ruby ranges to do it, something like:
def range (start_position, end_position)
    # Create a range and convert it to an array
    # We can omit return
    (start_position .. end_position).to_a
end

print range(1, 3) # => [1, 2, 3]

Also beware your function will only work the first time, because you're using a global variable as your starting point. Check what happens when you call it multiple times:
print range(1, 3) # => [1, 2, 3]
print range(1, 3) # => [1, 2, 3, 1, 2, 3]


text:
Q: Android Recycler View with Inner Elevation I'd like to do something like this in a recycle view, but I don't know how to proceed.

In this recyclerview, there are 2 items (but can be more, it's dynamic), with no space between them, and elevation on the common background.
I tried to set a white background color and elevation on my recycler view, but to see the elevation I'm forced to put margins, which I don't want to. Padding don't solve this either.
I tried to add elevation on the children too, but I dont want space between them (as in the picture above)
It is the first time I'm having trouble with RecyclerView, so I don't even know where I can find an answer. Help me please !

A: This component is called CardView and here you have some tutorials how to use it:
https://developer.android.com/training/material/lists-cards.html
https://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-cardview-on-android--cms-23465
How to accomplish what you showed on image depends on how many cards you want to have and how many sub-items can be in each card. For example to have what's on the image you don't need RecyclerView, just one card with LinearLayout into which you can inflate several subviews.


text:
Q: Repast: Agent execution order I have an agent called truck, which will perform some actions (e.g. loading packages).
The problem here is related to the random sequence of agents executing actions. For instance, suppose I have three trucks, the loading sequence is random at each different run.
Run-1: truck-1, truck-3, truck-2
Run-2: truck-2, truck-1, truck-3
Run-3: truck-3, truck-1, truck-2
...

How to make sure the agent(truck) executing actions based on a sequence, e.g. by their id so that we can always get the consistant result from the simulation.
Run-1: truck-1, truck-2, truck-3
Run-2: truck-1, truck-2, truck-3
Run-3: truck-1, truck-2, truck-3
...

A: There's at least 3 ways to do this.

*

*If you set the random seed, the order of the trucks should be the same across runs, all other things being equal. It most likely won't be ordered by id, but it should be the same.

*Add all the trucks to an ArrayList when they are created. Sort this list by id and each tick of the simulation iterate through this list, executing the truck action on each truck. A quick google should show you how to order a Java List using a Comparator.

*Adapt the scheduling to reflect truck id - for example, truck 1 executes at 1.0 and every tick thereafter, truck 2 at 1.1 and every tick thereafter, truck 3 at 1.2, and so on.

*A kind of variation on 3. Set the scheduling priority by id -- all the trucks could execute at 1.0 and every tick thereafter, but with truck 1 having the highest priority, truck 2 the next, and so on.
As a side note, the random iteration of the items in a schedule is the default to prevent common ABM behavior execution ordering issues, such as first mover advantage.


text:
Q: How do I do this sql query in Zend? How do I do this sql query in Zend Framework, I need to some how do this in the PDO context I think? I tried ->query but not sure if I am getting this right. The three variables are user_id and to and from date.
SELECT
 ss.subcategory_id,
 ss.subcategory_name,
 ss.subcategory_issaving,
 IFNULL(SUM(m.mv_monthly_total),0) AS expendsum
FROM
 (SELECT
    s.subcategory_id,
    s.subcategory_name,
    s.subcategory_issaving
FROM
    subcategory s
  WHERE
    s.subcategory_isexpend = 'Y'
  AND
    s.subcategory_issaving = 'Y') ss
LEFT JOIN
  mv_monthly m
ON ss.subcategory_id = m.mv_monthly_subcategory_id
AND m.mv_monthly_user_id = 2
AND m.mv_monthly_month >= '2010-01-01'
AND m.mv_monthly_month <= '2020-01-01'
GROUP BY
 ss.subcategory_id,
 ss.subcategory_name,
 ss.subcategory_issaving
ORDER BY
 ss.subcategory_issaving DESC,
 expendsum;

I have tried the following with no luck
    $db = Zend_Db_Table::getDefaultAdapter();
    $dbExpr1 = new Zend_Db_Expr("s.subcategory_id, s.subcategory_name, s.subcategory_issaving");
    $dbExpr2 = new Zend_Db_Expr("ss.subcategory_id, ss.subcategory_name, ss.subcategory_issaving, IFNULL(SUM(m.mv_monthly_total),0) AS expendsum");
    $select = $db->select()
        ->from(
            array(
                'ss' => new Zend_Db_Expr(
                    '('. $db->select()
                        ->from(array("s" => "subcategory"), $dbExpr1)
                        ->where("s.subcategory_isexpend = 'Y'")
                        ->where("s.subcategory_issaving = 'Y'") .')'
                )
            ),
            $dbExpr2
        )
        ->joinLeft(array("m" => "mv_monthly"), "ss.subcategory_id = m.mv_monthly_subcategory_id")
        ->where("m.mv_monthly_user_id = ?", $user_id)
        ->where("m.mv_monthly_month >= ?", $fromMonth)
        ->where("m.mv_monthly_month <= ?", $toMonth)
        ->group(array("ss.subcategory_id","ss.subcategory_name","ss.subcategory_issaving"))
        ->order(array("ss.subcategory_issaving DESC", "expendsum"));
    $row = $db->fetchAll($select);

A: For such a complex query, you can just execute it directly rather than using the object oriented approach as it gets fairly complicated with a query like that.
Try something like this, replacing my query with yours, and binding your variables into the query:
    $db   = Zend_Db_Table::getDefaultAdapter();
    $stmt = new Zend_Db_Statement_Pdo($db, 'SELECT a, b, c FROM a WHERE username = ? AND date = ?');

    try {
        $res  = $stmt->execute(array($user_id, $fromMonth));

        if ($res) {
            $rows = $stmt->fetchAll();
        }
    } catch (Zend_Db_Statement_Exception $dbex) {
        // log Query failed with exception $dbex->getMessage();
    }

If you prefer to use the object oriented approach, or need to because some parts of the query will be conditional, I usually build by subqueries up first as their own select, and you can simply embed those in to the main query with the select object for the subquery.
Here is what I mean by that:
    $subselect = $this->getDbTable()
                      ->select()
                      ->from('mytable', array('time' => 'max(time)', 'id'))
                      ->where('id IN (?)', $serialNumbers)
                      ->group('id');

    $select    = $this->getDbTable()
                      ->select()
                      ->setIntegrityCheck(false)
                      ->from('mytable')
                      ->join('other', 'mytable.id = other.id', array('label'))
                      ->join(array('dt' => $subselect),
                             '(mytable.time, mytable.id) = (dt.time, dt.id)', '');


text:
Q: Hide drive for unprivileged user On Windows XP I want to create a new user for browsing only. Thus I want it to have access only to the download Folder. While this can be archived with file privileges easily, I cannot find a way to "hide" (as in "there is no way to access it") complete drives from the user. So the files that are in the root of the drive can be listed (not read) which poses a (quite small) security thread that I'd like to eliminate.
Edit
Obviously there is not much use in hiding my main partition where the system files are on. So this is about "hiding" partitions which are unrelated to both, my browser and files of the operating system.
Also to clarify "hiding" a bit more: From the perspective of the restricted user "hidden" drives should be unmounted. However, the restricted user is only used as a secondary login, so my main user is logged in at the same time and should continue to access the files happily.

A: I believe you want this policy, perhaps in tandem with Hyppy's suggestion.
http://technet.microsoft.com/en-us/library/cc978514.aspx
Keep in mind the following:

This policy does not prevent users from using programs to access local and network drives.

Any programs that rely on these drives will still operate normally.  Furthermore, unless they're locked down with proper NTFS permissions, users will be able to get a look at files on these drives using programs.

A: Using Group Policy, you can hide specific drives in My Computer.
Detailed explanation here: http://support.microsoft.com/kb/231289


text:
Q: Use every level of a categorical variable in a regression Short description
I am trying to run a (GLM) regression in Matlab (using the fitglm function) where one of the regressors is a categorical variable. However instead of adding an intercept and dropping the first level, I would like to include each level of the categorical variable and exclude the constant term.
Motivation
I know, that theoretically the results are the same either way, but I have two reasons against estimating the model with a constant and interpreting the dummy level coefficients differently:

*

*The smaller problem is that I am running many regressions as part of
a larger estimation procedure using different subsets of a large
dataset, and the available levels of my categorical variable might
not be the same across the regressions. In the end I would like
to compare estimated coefficients for the levels. It can be solved with
some additional code/hacking, but it would not be an elegant solution.

*The bigger problem is that there are orders of magnitudes
of difference between the coefficients of the levels: some of them
are extremely small. If such a level gets used as a base level, I am
afraid that it might cause numerical problems / optimization
problems.

Tried approaches
I tried subclassing the GeneralizedLinearModel class but unfortunately it is marked as final. Class composition also does not work as I cannot even inherit from the parent of the GeneralizedLinearModel class. Modifying Matlab's files is no option as I use a shared Matlab installation.
The only idea I could come up with is using dummyvar or something similar to turn my categorical variable into a set of dummies, and then using these dummy variables in the regression. AFAIK this is how Matlab works internally, but by taking this approach I lose the user-friendliness of dealing with categorical variables.
P.S. This question was also posted on MatlabCentral at this link.

A: As there seems to be no built-in way to do this, I am posting a short function that I wrote to get the job done.
I have a helper function to convert the categorical variable into an array of dummies:
function dummyTable = convert_to_dummy_table(catVar)
    dummyTable = array2table(dummyvar(catVar));
    varName = inputname(1);
    levels = categories(catVar)';
    dummyTable.Properties.VariableNames = strcat(varName, '_', levels);
end

The usage is quite simple. If you have a table T with some continuous explanatory variables X1, X2, X3, a categorical explanatory variable C and a response variable Y, then instead of using
M = fitglm(T, 'Distribution', 'binomial', 'Link', 'logit', 'ResponseVar', 'Y')

which would fit a logit model using k - 1 levels for the categorical variable and an intercept, one would do
estTable = [T(:, {'X1', 'X2', 'X3', 'Y'}), convert_to_dummy_table(T.C)]
M = fitglm(estTable, 'Distribution', 'binomial', 'Link', 'logit', ...
                     'ResponseVar', 'Y', 'Intercept', false)

It is not as nice and readable as the default way of handling categorical variables, but it has the advantage that the names of the dummy variables are identical to the names that Matlab automatically assigns during estimation using a categorical variable. Therefore the Coefficients table of the resulting M object is easy to parse or understand.


text:
Q: Is there a bug in Ruby lookbehind assertions (1.9/2.0)? Why doesn't the regex (?<=fo).* match foo (whereas (?<=f).* does)?
"foo" =~ /(?<=f).*/m          => 1
"foo" =~ /(?<=fo).*/m         => nil

This only seems to happen with singleline mode turned on (dot matches newline); without it, everything is OK:
"foo" =~ /(?<=f).*/           => 1
"foo" =~ /(?<=fo).*/          => 2

Tested on Ruby 1.9.3 and 2.0.0.
See it on Rubular
EDIT: Some more observations:
Adding an end-of-line anchor doesn't change anything:
"foo" =~ /(?<=fo).*$/m        => nil

But together with a lazy quantifier, it "works":
"foo" =~ /(?<=fo).*?$/m       => 2

EDIT: And some more observations:
.+ works as does its equivalent {1,}, but only in Ruby 1.9 (it seems that that's the only behavioral difference between the two in this scenario):
"foo" =~ /(?<=fo).+/m         => 2
"foo" =~ /(?<=fo).{1,}/       => 2

In Ruby 2.0:
"foo" =~ /(?<=fo).+/m         => nil
"foo" =~ /(?<=fo).{1,}/m      => nil

.{0,} is busted (in both 1.9 and 2.0):
"foo" =~ /(?<=fo).{0,}/m      => nil

But {n,m} works in both:
"foo" =~ /(?<=fo).{0,1}/m     => 2
"foo" =~ /(?<=fo).{0,2}/m     => 2
"foo" =~ /(?<=fo).{0,999}/m   => 2
"foo" =~ /(?<=fo).{1,999}/m   => 2

A: This has been officially classified as a bug and subsequently fixed, together with another problem concerning \Z anchors in multiline strings.


text:
Q: Melhor prática de persistência de dados Quando se trata de persistir os dados com o Core Data. Qual é a melhor maneira de persistir os dados?
Por exemplo:

Possuo um objeto Pessoa (subclasse de NSObject). E no momento da
  persistencia eu "converto" o PessoaMO (subclasse de
  NSManagedObject).

O que eu queria saber, é basicamente o seguinte:
A maneira correta de fazer isso, é como o exemplo citado acima ou diretamente com o NSManagedObject sem ter a classe Pessoa (subclasse de NSObject)?

A: Essa sua solução parece desrespeitar o DRY (Don't Repeat Yourself) pois além de existir uma duplicação no código as classes PessoaMO e Pessoa vão ser dependentes. (Qualquer mudança em uma quebra a outra).
Uma solução seria user diversos com NSManagedObjectContext's para fazer um melhor controle do que será persistido e o que será descartado. (Creio que seja isso que você esteja fazendo).


text:
Q: Web interface for SFTP server An SFTP client such as CuteFTP or Filezilla provides a rick user interface for an SFTP server. These are clients that are installed locally on the user's PC. Instead of a client installed at the user's side, is it possible to set up a web-based user interface on the SFTP server, so that a user with only a browser is able to access the files on the server? Are such open source or commerical products available that can be deployed on the SFTP server for enhancing the file transfer experience?
Note: The base server needs to be SFTP as there will be scripts that clients will be using to transfer files in a non-interactive manner. For interactive usage, I am looking for a web interface that be serve as an add-on.

A: I suggest you check out: https://filebrowser.org/features
There is another good one called "droppy" but its no longer active and apparently has too many git forks at the moment to know where it will go.
The question you need to answer is the application value/scope.
You can always go with Dropbox or something too depending on the user's intended application.


text:
Q: Upgrading C# application from .net Framework 1.0 to 3.5 I'm trying to use the VS2008 to upgrade an 1.0 app to 3.5, but I have many many problems.
And I was wondering if any of you had this experience before, so it might be wonderful if he can share with us any tricks or (I don't know) so I can solve those problems after upgrading .NET applications.

A: From my experience the most routine thing is that after automatic conversion you have to manually set each project's target framework. That's the main difficulty if you have a big number of projects.
The other potential problem (though easily solved) is that you need to add references to new libraries in order to use new features.
And then you find out that you don't need ArrayLists and Arrays anymore. And so you start changing your code...


text:
Q: Quartz - Spring - Java - Jobstore. how to set job in completed state I ask for help, I have jobs scheduled through quartz in a job shop, everything works some jobs that call procedures on Oracle. I would like to put the job in a complete state when a procedure returns a certain result. I can pause the job but not in completed.
if(!result.substring(0,4).equalsIgnoreCase("null")) {
                    fase_1.callJobResult("JOB_RESULT", key.getName().toString(), key.getGroup().toString(), strJobex+":"+parameter, result);
                }else {
                    // I pause the job because it has been completed
                    try {
                        fase_1.callJobResult("JOB_RESULT", key.getName().toString(), key.getGroup().toString(), strJobex+":"+parameter,"SUCCESS. Il job : " + key.getName().toString().toUpperCase() + " job completed");
                        System.out.println(result);

                        //Scheduler scheduler;
                        SchedulerFactory factory = new StdSchedulerFactory();
                        Scheduler scheduler = factory.getScheduler();

                        JobKey jobKey = new JobKey(key.getName().toString(), key.getGroup().toString());
                        //scheduler.pauseJob(jobKey); // example this work

                        Trigger trigger = jobExecutionContext.getTrigger();
                        //Trigger.CompletedExecutionInstruction.NOOP.SET_TRIGGER_COMPLETE()

                        TriggerListner tl = new TriggerListner();
                        tl.triggerComplete(trigger, jobExecutionContext, CompletedExecutionInstruction.SET_TRIGGER_COMPLETE);


text:
Q: Form Action submit over https I am trying to make my website PCI compliant.  It has a login form on top of each page in which the form tag is written like so:
<form id="wp_login_form" action="<?php echo site_url('wp-login.php', 'https') ?>" method="post">

According to wordpress documentation this should print an https url in the action, but it doesn't.  Any idea why or how I should go about this?

A: As written, I'd expect to see https://yoursitename.comwp-login.php  as a response .  I think you are missing a slash.   echo site_url('/wp-login.php', 'https')


text:
Q: Remove duplicates with row pivot I want to get rid of duplicates in one column (device_name) but keep related data from another column (app_id). Each device can have couple of applications (1 -> x, usually between 1-5) so  I want to put those app identifiers into a new columns which I want to  call [APP1],[APP2],[APP3] and so on. The best option would be kind of dynamic Pivot, but any static solution will be welcome as well.
Thanks for  help in advance.
PS
I came up with below code what so ever, but in only concatenate APP id's separated by comas into one column.

    USE tempdb;
    SELECT  DEVICE_NAME,
        NoOfApps,
        STUFF(( SELECT  ', ' + APP_ID
                FROM    dbo.Aperture_full_test apps
                WHERE   apps.DEVICE_NAME = Aperture_full_test.DEVICE_NAME
                FOR XML PATH(''), TYPE
                ).value('.', 'VARCHAR(MAX)'), 1, 2, '') AS Appid

    FROM    (   SELECT  DEVICE_NAME, COUNT(DEVICE_NAME) AS NoOfApps
            FROM    dbo.Aperture_full_test
            GROUP BY DEVICE_NAME
        ) Aperture_full_test
        ORDER BY NoOfApps DESC

Data sample:

    USE tempdb;
    GO

    IF OBJECT_ID('dbo.Aperture_full_test') IS NOT NULL
    DROP TABLE dbo.Aperture_full_test;
    GO

    CREATE TABLE dbo.Aperture_full_test
    (
    DEVICE_NAME   varchar(30) NOT NULL,
    APP_ID        varchar(10) NOT NULL
    );

    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('LDNSQLF700', 157848);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('LDNSQLF700', 155439);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('LDNSQLF700', 635533);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('NYSQL502', 189164);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('NYSQL502', 188641);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('AUSSQL140', 537990);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('AUSSQL140', 1349605);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('JAP543X2', 5646789);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('EU456CLX', 6545789);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('EUCTX654', 5637965);
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('EUCTX654', 6464367) ;
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('EUCTX654', 1323123) ;
    INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
    VALUES('EUCTX654', 1004326) ;
    GO

A: Since you are using SQL Server you can implement the PIVOT function.
If you have a known number of values then you can hard code the query using the following:
select device_name, App1, App2, App3, App4, App5
from
(
  select device_name, app_id,
    'App'+
      cast(row_number() over(partition by device_name
                            order by device_name) as varchar(10)) col
  from Aperture_full_test
) d
pivot
(
  max(app_id)
  for col in (App1, App2, App3, App4, App5)
) piv;

See SQL Fiddle with Demo.
But if you are going to have an unknown number of app_ids for each device, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ', ' + QUOTENAME('App'+cast(rn as varchar(10)))
                    from
                    (
                      select row_number() over(partition by device_name
                                              order by device_name) rn
                      from Aperture_full_test
                    ) d
                    group by rn
                    order by rn
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT device_name, ' + @cols + ' from
             (
                select device_name, app_id,
                  ''App''+
                    cast(row_number() over(partition by device_name
                                          order by device_name) as varchar(10)) col
                from Aperture_full_test
            ) x
            pivot
            (
                max(app_id)
                for col in (' + @cols + ')
            ) p '

execute(@query)

See SQL Fiddle with Demo. Both give the result:
| DEVICE_NAME |    APP1 |    APP2 |    APP3 |    APP4 |
-------------------------------------------------------
|   AUSSQL140 |  537990 | 1349605 |  (null) |  (null) |
|    EU456CLX | 6545789 |  (null) |  (null) |  (null) |
|    EUCTX654 | 5637965 | 6464367 | 1323123 | 1004326 |
|    JAP543X2 | 5646789 |  (null) |  (null) |  (null) |
|  LDNSQLF700 |  157848 |  155439 |  635533 |  (null) |
|    NYSQL502 |  189164 |  188641 |  (null) |  (null) |

Edit, If you want to count the total number of devices for each server, then you can use  count() over(). The hard-coded version will be:
select device_name, TotalDevices, App1, App2, App3, App4, App5
from
(
  select device_name, app_id,
    'App'+
      cast(row_number() over(partition by device_name
                            order by device_name) as varchar(10)) col,
    count(app_id) over(partition by device_name) TotalDevices  -- add this line
  from Aperture_full_test
) d
pivot
(
  max(app_id)
  for col in (App1, App2, App3, App4, App5)
) piv;

See SQL Fiddle with Demo

A: This is a pivot query, which can be done in the group by.  What you need is a sequence number for the Apps.
select aft.deviceName, COUNT(*) as NumApps,
       MAX(case when seqnum = 1 then App_id end) as App1,
       MAX(case when seqnum = 2 then App_id end) as App2,
       MAX(case when seqnum = 3 then App_id end) as App3,
       MAX(case when seqnum = 4 then App_id end) as App4,
       MAX(case when seqnum = 5 then App_id end) as App5
from (select aft.*,
             ROW_NUMBER() over (partition by device_name order by (select NULL)) as seqnum
      from Aperture_full_test aft
     ) aft
group by aft.deviceName
order by NumApps desc

This version does not have the Apps in a particular order becasue the xml code did not have them in a particular order.


text:
Q: Gradle - Fails to show: org.gradle.java.home I thought this would be a very simple thing. So far however I'm unable to access the String for my gradle job's Java.Home, the official name:

*

*For example, see: org.gradle.java.home
Apparently I can set this value with gradle.properties settings file. I've done that and the gradle output confirms this.
For all that, none of these print statements work...

*

*print "org.gradle.java.home = $org.gradle.java.home"

*print "org.gradle.java.home = "+ project.properties['org.gradle.java.home']

*print  "org.gradle.java.home = $gradle.java.home"

*print "${project.property('org.gradle.java.home')}"

Looking at back at this question, I would have thought one of the options tried would yield a result.
How can I access system level properties?

A: Only two options may work:

*

*print "org.gradle.java.home = "+ project.properties['org.gradle.java.home']

*print "${project.property('org.gradle.java.home')}"
and the second will fail since there's no checking if such property exists. Gradle throws an exception on access to non-existing property.
The last two will not work because there's no property org and gradle objects has no java property - more explanation can be found here - you need to understand how string interpolation works with groovy.
And finally, these properties are used to pass arguments to gradle. So the following will work:
print "org.gradle.java.home = "+

project.properties['org.gradle.java.home']
run with:
gradle -Dorg.gradle.java.home=random_dir

A: With some trial-and-much-error, I have found that one may print the java.home property on Windows with Gradle 2.4; when ...

*

*Use your gradle.properties file, e.g.

For example
  compile.options.fork    = true
  org.gradle.daemon       = true
  org.gradle.java.home    = b:/lang/java/jdk/v1.8u45

The same settings in GRADLE_OPTS had no effect.  The print command used, is:
 print "org.gradle.java.home = "+ "${project.property('org.gradle.java.home')}"

I believe the compile.options.fork is also required.  It had no effect before when I was using GRADLE_OPTS.  Although the Gradle message to use fork is quite clear on the matter.
see also:
- https://docs.gradle.org/2.4/userguide/gradle_daemon.html


text:
Q: Virtual function inheritance I have a confusion about the inheriting the virtual property of a method.
Let's suppose we have 4 classes: class A, class B, class C and class D.
The classes are inherited by this way: A -> B -> C -> D, where A is the base class.
By this time, I'm sure about this: Beginning the class method declaration with virtual in a base class (class A), makes the method virtual for all classes derived from the base class, including the derived ones of the derived classes. (B and C class methods determined to be virtual).
The confusion is here. What if, in the base class A, there wouldn't be any virtual member. Instead, let's say, that class B declares a method to be virtual. I assume, that this change would make the function virtual for all the derived classes that belong to the inheriting chain (C and D classes). So logically, B for C and D, is a sort of their "base class", right? Or am I wrong?

A: You are entirely correct. Child inherits what its ancestors have. Base classes can't inherit what the child has (such as a new function or variable). Virtual functions are simply functions that can be overridden by the child class if the that child class changes the implementation of the virtual function so that the base virtual function isn't called.
A is the base class for B,C,D. B is a the base class for C, D. and C is the base class for D too.

A: You're correct.
I think that in this case the best solution is to try:
#include <iostream>

using namespace std;

class A {
   public:
      void print(){ cout << "print A" << endl; };
};

class B: public A {
    public:
       virtual void print(){ cout << "print B" << endl; };
};

class C: public B {
     public:
        void print(){ cout << "print C" << endl; };
};

int main()
{
   A *a = new C();
   B *b = new C();

   a->print(); // will print 'print A'
   b->print(); // will print 'print C'

   return 1;
}

A: Of course you can do it. Virtual method is optional to override so it doesn't matter that you declare it in class A or B. If you dont want to use that method in class A then simply declare in in class B.


text:
Q: Git mirroring with bash scripting stuck in 3 for loop git1 ---> git3 (must use path1)
git2 ---> git4 (must use path2)
git1 can't clone to git4, or git2 can't clone to git3.Everytime it should work as above way.Script start to take git1 it has to be continue and hold next values with this way git1-git3-path1,when first loop finished it should be start second one like that git2-git4-path2
My scratch
A_sources=(git1 git2)
B_destinations=(git3 git4)
C_filename=(path1 path2)
workdir="/home/"

for A in "${A_sources[@]}"; do
    for B in "${B_destinations[@]}"; do
        for C in "${C_filename[@]}"; do
            git clone --mirror "${A}"
            cd "${workdir}/${C}"9
            git remote set-url --push origin "${B}"
        done
    done
done

A: one loop over indexes instead of three nested loops over elements, for example
# ensure the size are equal
(( ${#A_sources[@]} == ${#B_destinations[@]} && ${#B_destinations[@]} == ${#C_filename[@]})) || { echo "arrays sizes are not equals"; exit 1;}

for ((i=0;i<${#A_sources[@]};i+=1)); do
    git clone --mirror "${A_sources[i]}"
    cd "${workdir}/${C_filename[i]}"9
    git remote set-url --push origin "${B_destinations[i]}"
done


text:
Q: Using XML for dynamic contraints in Grails I am trying to dynamically populate the static constraint ={} at run time. Is there a way to  do this. Example code:
Normal statement:
static constraint = {
    lastName(blank:false, maxSize: 100)
}

What I am trying to do:
static constraint = {

    call to an XMLSlurper that returns a HashMap of lastName as a key and (blank: false, maxSize: 100) as a value.  // This part works.

    have the HashMap executed as if it where hard coded information to validate the fields. //This part does not work.

}

I hope this explains my problem well enough.

A: This is possible, but not the way you are trying to do it.  The constraints for a GORM class are loaded using GrailsHibernateDomainClass.  When the class is loaded, the evaluateConstraints method and the static property constraints is evaluated.  You can look at the evaluateConstraints method in GrailsDomainConfigurationUtil to see how they are evaluated.
If you want to add your own constraints from an alternative source, you will need to modify the domain class yourself.  The best way to do it is in a plugin.  Read up on the plugin documentation first, and your entry point is the doWithSpring method:
def doWithSpring { ->
  application.getArtefacts(DomainClassArtefactHandler.TYPE).each { domainClass ->
    def myConstraints = getConstraintsFromXml() /* Create a Map<ConstrainedProperty> from your XML */
    domainClass.constrainedProperties.putAll myConstraints
  }
}

A: Looking into the GrailsDomainConfigurationUtil, you can see that the constraints map is built from the domain class's static constraints property using the ConstrainedPropertyBuilder. You can of course populate the constraints map by calling the builder methods dynamically using the map slurped from the XML.
static constraints = {
  def fromXml = [lastName: [blank:false, maxSize: 100]]
  fromXml.each { property, constraints ->
    invokeMethod (property, constraints)
  }
}

This might be suitable if you only need the XML based constraints in a single domain class, otherwise a more general approach as suggested by Eric is probably better, allowing e.g. a naming scheme for the XML files and thus extrapolating the idea of convention over configuration.


text:
Q: Updating template after http call in Meteor I'm making a new app with Meteor and I'm trying to get some public Github repos. I've written this call-method tuple:
Meteor.call('getRepositories', function(error, results) {
  console.log(results);
});

Meteor.methods({
  getRepositories: function(user) {
    var response = Meteor.http
      .call('GET','https://api.github.com/users/{username}/repos');
    return response.data;
  }
});

The problem is... how can I achieve to update the template with repositories names?
Thanks!

A:
// your_tmpl template {{#each repos}}
    {{name}}
{{/each}}

// js template manager
var reactiveRepos = new ReactiveVar([]);

Meteor.call('getRepositories', function(error, results) {
    reactiveRepos.set(results); });

Template.your_tmpl.helpers({
    repos: function() {
        return reactiveRepos.get();
    } });

// server.js
Meteor.methods({
    getRepositories: function(user) {
        var response = Meteor.http
            .call('GET','https://api.github.com/users/{username}/repos');
        return response.data;
    }
});

You could use ReactiveVar (http://docs.meteor.com/#/full/reactivevar_pkg) package, that allow us to create reactive variables and use it in reactive environment, like helpers. Sure, you may want use it inside templates hooks as onRendered or onCreated for example, and bind it to your template.


text:
Q: To solve warning 'is never used' in WPF I have declared an event in "Question" class as:
public event SectionAffected OnSectionAffected;

I have not used this event in the entire class.But I have used it in another class as:
Question.OnSectionAffected += new Question.SectionAffected(ResetDependentSection);

I am getting warning as:
The event 'QuestionManager.OnSectionAffected' is never used in Question class.
How to solve this warning?

A: A warning is just that... a warning. Having warnings is not necessarily a bad thing. However, if you really want to remove it, you can specify that in Visual Studio. If you open the relevant project's property page (by pressing ALT + Enter when the project is focused), turn to the Build tab. Click the RadioButton named Specific warnings and enter the specific error code(s) that you want to supress in a comma separated list. You can find out more from the How to: Suppress Compiler Warnings page on MSDN.
UPDATE >>>
I believe that you are looking for the numerical error code number... for this, you should look in the Output Window of Visual Studio. If you don't already use this window when writing WPF, then I would strongly advise you to do so. However, these codes are not always shown in this window.
As an alternative, you can find descriptions and error codes in the C# Compiler Errors and Code Analysis for Managed Code Warnings pages on MSDN.
UPDATE 2 >>>
After doing a quick search online (which is really what you should have done), I found this page which seems about right: Compiler Warning (level 3) CS0219


text:
Q: eXist-DB transformation failure with XSLT - where to find error log? Environment: eXist 4.2.1 - xquery 3.1 - xslt 3.0 - TEI-XML document
Using the eXide interface, I am attempting to do a transformation of a TEI-XML document with an XSL file, with an output of HTML.
Until now I have been developing XML documents and their XSL transformations in Oxygen. Firing off the transformations in Oxygen or using a terminal, both have been working error free. Now I am preparing a web application using eXist (which will contains the thousands of TEI-XML docs).
I am trying to simply fire off the same transformation in eXist with the following xquery test:
let $result := transform:transform(doc("xmldb:exist://db/apps/deheresi/resources/documents/ms609_0001.xml"), doc("xmldb:exist://db/apps/deheresi/resources/documents/document_style.xsl"), ())

return $result?output

eXide returns me only this:
exerr:ERROR Unable to set up transformer: Stylesheet compilation failed: 62 errors reported [at line 3, column 16]
I'm new at eXist DB and have not been able to figure out how to get the reasons for errors.

*

*How do I access the error details (detail log?) in eXist? (I have searched without success my books and online documentation; for example https://exist-db.org/exist/apps/doc/xsl-transform doesn't help at all on errors).

*For Oxygen and terminal transformations, I use Saxon 9he. I understand that eXist uses the same?
NB: my documents are all organized in an eXist collection identical to the setup on my computer, thus all relative locations should function correctly?

A: First - when using doc and collection functions for the paths in the database you don't need the XML:DB URI, instead you can just use:
transform:transform(doc("/db/apps/deheresi/resources/documents/ms609_0001.xml"),
        doc("/db/apps/deheresi/resources/documents/document_style.xsl"), ())

The errors should be in exist.log the default location for that is $EXIST_HOME/webapp/WEB-INF/logs. You might otherwise find them on the "Standard Out" of the terminal session which is running eXist-db.
If you are using the YAJSW (Service Wrapper) to run eXist-db you might also need to check $EXIST_HOME/tools/yajsw/logs.


text:
Q: conversion of date in string variable to date variable how to convert date in string variable to date variable..??
Date in database is in yyyy-MM-dd format..
im entering in dd-MM-yyyy format..and trying to convert it in db format so that i can use 'between' query.. code is below
        <%String date1=(String)request.getAttribute("from");%>

        <%String date2=(String)request.getAttribute("to");%>
        <%String empcode=(String)request.getAttribute("occ");%>
        <%SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");%>
        <%Date date = new Date(); %>

        <%Date fromdate=formatter.parse(date1);%>
        <%Date todate=formatter.parse(date2);%>

A: You're using getAttribute, but I suspect you wanted getParameter (if you're trying to get information submitted as part of a GET or POST request).
Here's what getAttribute works with:

Attributes can be set two ways. The servlet container may set attributes to make available custom information about a request. For example, for requests made using HTTPS, the attribute javax.servlet.request.X509Certificate can be used to retrieve information on the certificate of the client. Attributes can also be set programatically using setAttribute(java.lang.String, java.lang.Object). This allows information to be embedded into a request before a RequestDispatcher call.

Here's what getParameter works with:

Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

Looking at the date formatting, you've mentioned two different formats in your question. If the date1 string looks like 2013-12-19, then that code will work. If it's 19-12-2013 then that code won't work because you've told SimpleDateFormat to use "yyyy-MM-dd" but you want "dd-MM-yyyy".
In both cases, the way to debug this is to look at what date1 and date2 contain. That would point the way toward how to fix it.

A: SimpleDateFormat formatter=new SimpleDateFormat("dd-MM-yyyy");
Date fromdate=formatter.parse(date1);
SimpleDateFormat formatter2=new SimpleDateFormat("yyyy-MM-dd");
String newDate1 = formatter2.format(fromdate);

newDate1 is now in format yyyy-MM-dd.
You can again create the date object with the new string
formatter2.parse(newDate1);

but not necessary I suppose


text:
Q: ngrams results are surprising python Just trying to play with the ngram library of the Python and I came across an issue which is related to the similarity of the string. The ratio output was a bit confusing. See what I tried:
>>> ngram.NGram.compare('alexp','Alex Cho',N=1)*100
30.0
>>>
>>> ngram.NGram.compare('alexp','Alex Plutzer',N=1)*100
21.428571428571427
>>> ngram.NGram.compare('alexp','Alex Plutzer'.lower(),N=1)*100
41.66666666666667
>>> ngram.NGram.compare('alexp','Alex Cho'.lower(),N=1)*100
44.44444444444444
>>> ngram.NGram.compare('alexp','AlexCho'.lower(),N=1)*100
50.0
>>> ngram.NGram.compare('alexp','AlexPlutzer'.lower(),N=1)*100
45.45454545454545

The most similar must be the one having alexp i.e. Alex Plutzer but the more score is getting assigned to the former one i.e. Alex Cho
What might be done to get an appropriate result, where I get to have the output as Alex Plutzer with high score as compare to the competitive one?

A: With a bit of domain knowledge, using that you consider 1-grams and curve fitting, I claim that the smiliarity of two strings S and T is computed via

where ngrams just gives the ngrams of a string, the curly braces denotes sets and the bars/pipes denote the count of elements in that set.
So the results you obtain are correct if this formula holds true, thus the results are correct concerning this formula. Maybe what suits your needs better could be the Levensthein-Distance
Maybe you want to check the following stackoverflow thread, additionally, you might want to check if nltk provides the similarity scores you need


text:
Q: SQL Compare Two tables with column value difference I've 2 tables with exact same structure and I would like compare the column values and display in specific format. I'm new to SQL. I tried with Minus function but its not helping. Find below scenario
Table 1
Key Col1 Col2
1   110  AAA
2   120  BBB

Table 2
Key  Col1    Col2
1    111     CCC
2    120     DDD

I need output in below format
Key   Field   Table1    Table2
1     Col1    110       111
1     Col2    AAA       CCC
2     Col2    BBB       DDD

How can this be accomplished?
Thanks,
Milind

A: This is an arcane structure for bringing the tables together.  I think this will work:
select t1.col1,
       (case when t2.key is not null then 'col2' else 'col1' end) as field,
       (case when t2.key is not null then t1.col2
             when seqnum = 1 then t1.col1
             when seqnum = 2 then t1.col2
        end) as Table1,
       (case when t2.key is not null then t2.col2
             when seqnum = 1 then t2.col1
             when seqnum = 2 then t2.col2
        end) as Table2
from table1 t1 left join
     table2 t2
     on t1.key = t2.key and t1.col1 = t2.col1 left join
     (select tt2.*, row_number() over (partition by tt2.key order by tt2.key) as seqnum
      from table2 tt2
     ) tt2
     on t1.key = tt2.key and t2.key is null;


text:
Q: Question about PrimeZetaP The PrimeZetaP function appears to give results for complex s with real part > 0. Apparently, the analytic continuation is built into the programming. Can anyone explain the mathematical calculation behind this function for $0<\sigma\leq 1?$ The analytic continuation of Zeta[s] is explained in many texts, but that is not the case for the so-called prime zeta function. I looked at the MathWorld article, which links to a paywalled article, and looked at the online Mathematica guide.

A: I discussed the prime zeta function at some length in this math.SE answer. In particular, the infinite Möbius inversion
$$P(s)=\sum_{k=1}^\infty \frac{\mu(k)}{k}\log\zeta(ks)$$
is the actual computational formula used, as recommended in Fröberg's paper. (It is also noted there that numerical evaluation becomes more difficult at values near the imaginary axis, where there is a dense fence of singularities.)


text:
Q: Why is this async function is running synchronously? I have some code here...

async function test() {
    for(let i = 0; i < 10000; i++){
        console.log("test");
    }
}

console.log("a");
test();
console.log("b");

Now my understanding is that test() here should run asynchronously and if I would want to run a routine after it's completion I would use .then() after it.
I'm not doing that here though so surely it should just do it's thing in the background while everything else contiunes running? With that understanding I would expect some output like this:
a
b
test
test
..etc

However what I actually get is this...
a
test
test
...etc

b

Why does this happen? It seems that console.log("b") waits until test() completes but that's synchronous behaviour.
Apologies if something similar has been asked before but I couldn't find anything on this myself.

A: Setting something as async will wrap the return object into a Promise. Promises are used to deal with asynchronous behavior, but there's nothing inherently asynchronous about the content of the test function. If instead you were to wrap the contents into a setTimeout function, that would cause a delay which would mimic asynchronous behavior and match the outcome you were expecting.

async function test() {
  setTimeout(() => {
    for(let i = 0; i < 2; i++){
        console.log("test");
    }
  })
}

console.log("a");
test();
console.log("b")

If you're looking to set up background tasks that can lock up the browser's main thread, you should check out WebWorkers. They are a way to offload performance impacting tasks onto a separate thread.

A: Synchronous code inside an async function runs synchronously. The interpreter will only move on to the next line after the call of the async function (here, the console.log("b");) after all synchronous code has finished - for example, if it runs into an await.
Here, since there's no await or anything asynchronous at all going on in test, test runs to the end before the next line (that logs b) runs.
It's pretty similar to how the Promise constructor runs.

A: From MDN:

An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

If you do not have an await expression you are never 'pausing' the coroutine and it will execute synchronously without letting other functions run.

A: an async function means that what is inside the function is expected to have some asynchronous calls. like if you had an Http call inside your test function.
and since nothing is asynchronous inside your function (you only have a normal loop) then your function will execute normally and sequentially until it finishes executing.

A: async keyword don't mean that function wil run asynchronously. To run it asynchronously use setTimeout or Promise etc.

function test() {
  setTimeout(() => {
    for(let i = 0; i < 3; i++){
        console.log("test");
    }
  });
}

console.log("a");
test();
console.log("b");

Async keyword usually is used with Promises and await keyword to write async code in synchronous way (to use await keyword we need put code inside async function)

function test() {
  return new Promise( res => {
    for(let i = 0; i < 3; i++){
        console.log("test");
    }
    res();
  });
}

async function start() {
  console.log("a");
  await test();
  console.log("b");
}

start();


text:
Q: Joining Blocks of content_tag (Form Builder) I am getting an number of errors and not sure how to join blocks of content_tags.

bs_form_builder.rb:36: syntax error, unexpected tSYMBEG, expecting end
  @template.content_tag :div, class: "input-group" do
bs_form_builder.rb:36: syntax error, unexpected do, expecting end ...g
  :div, class: "input-group" do ... ^~
bs_form_builder.rb:39: syntax error, unexpected '+', expecting end end
  + ^
bs_form_builder.rb:43: syntax error, unexpected end, expecting
  end-of-input end ^~~

class BsFormBuilder < ActionView::Helpers::FormBuilder

def bs_dollar_input(method, label)
    @template.content_tag :div, class: "form-group" do
      @template.label(@object_name, label)+
      @template.content_tag :div, class: "input-group" do
        @template.content_tag :div, class: "input-group-prepend" do
          @template.content_tag(:span, "$", class:'input-group-text')
        end +
        @template.text_field(@object_name, method, class: 'form-control')
      end
    end
  end
 end

Anticipated result:

      What is the value of your favorite car?

              $

          <input class="form-control" id="car" name="car" required="" type="text" value="0" />

A: Needed to add () on the content_tags.
def bs_dollar_input(method, label)
    @template.content_tag :div, class: "form-group" do
      @template.label(@object_name, label)+
      @template.content_tag(:div, class: "input-group") do
        @template.content_tag( :div, class: "input-group-prepend") do
          @template.content_tag(:span, "$", class:'input-group-text')
        end +
        @template.text_field(@object_name, method, class: 'form-control')
      end
    end
  end
 end


text:
Q: Switch from $AdS$ to $dS$ in quadratic gravity using $f(R)$ trick: problem I have some difficulties with effective quadratic gravity involving a cosmological constant with the "wrong sign". The following is the setup of my question.
Let's assume one has the following dimensionless action:
\begin{equation}
S=\int d^4 x\sqrt{-g}\underbrace{\left( \frac{1}{2}m^4+\alpha m^2 R+\beta R^2\right.}_{\equiv f(R)}+\left.\frac{1}{60}R_{\mu \nu}R^{\mu \nu} \right) \tag{1}
\end{equation}
Where $\alpha = \frac{1}{6}+\xi$ and $\beta = \frac{1}{2}\xi \left(\xi+\frac{1}{3} \right)+\frac{1}{120}$. Clearly, by expressing this action in terms of the Weyl quadratic invariant, and since the Bach tensor involves the Weyl tensor, an Anti-de Sitter space-time is a solution to the equations of motion associated with this action. Now, for some purpose I don't want to use the later representation of the action (1), I want it to stay as it is written in (1). Performing the usual f(R)-to-Scalar/tensor-theory trick I arrive at:
\begin{align}
S=&\frac{\gamma}{\zeta^2} \int d^4x \sqrt{-\tilde{g}}\left( \zeta^2 \tilde{R}-\frac{1}{2} \tilde{g}^{\mu \nu} \tilde{\partial}_\mu \Phi \tilde{\partial}_\nu \Phi-V(\Phi)\right.
\\
&\left.+\frac{\zeta^2}{\gamma}e^{-\frac{2 \Phi}{\sqrt{3}\zeta}} \left( \frac{1}{60}\tilde{R}_{\mu \nu} \tilde{R}^{\mu \nu}+\text{Coupl.}+W(\Phi) \right) \right)\tag{2}
\end{align}
With $\gamma$ and $\zeta$ two dimensionful constants coming from the definition of $\varphi=f'(\chi)=\gamma\, e^{\frac{\Phi}{\sqrt{3} \zeta}}$. $\text{Coupl.}$ stands for derivative non-minimal coupling terms, and $W(\Phi)$ is a potential involving four derivatives of $\Phi$. $m$ disappeared because of a redefinition of the conformal factor $e^{\frac{\Phi}{\sqrt{3} \zeta}} \leadsto e^{\frac{\Phi}{\sqrt{3} \zeta}-\ln\left( \frac{m^2}{90\alpha\gamma}\right)}$. Choosing the special phantom coupling $\xi=-\frac{1}{6}+\frac{\sqrt{10}}{30}+\delta$ for $0<\delta \ll 1$ on has:
\begin{equation}
    V(\Phi)\simeq -45 \gamma \zeta^2+\frac{3 \sqrt{10}}{4} \frac{\gamma}{\delta} \zeta^2\left(1-e^{-\frac{\Phi}{\sqrt{3}\zeta}} \right)^2 \tag{3}
\end{equation}
The second term is precisely the Starobinsky potential for $\zeta = \frac{\bar{m}_\text{Pl}}{\sqrt{2}}$. Assuming $1 \ll\gamma$, the dominant term in the action (2) is:
\begin{equation}
\frac{\gamma}{\zeta^2} \int d^4x \sqrt{-\tilde{g}}\left( \zeta^2 \tilde{R}-\frac{1}{2} \tilde{g}^{\mu \nu} \tilde{\partial}_\mu \Phi \tilde{\partial}_\nu \Phi-V(\Phi)\right) \tag{4}
\end{equation}
Since $\delta \ll 1$, the constant term in the potential (3) is negligible when dealing with the potential only. So the inflation parameters are the same as for Starobinsky's theory.
I have a big problem because as you can see, at the beginning of the inflation, the field $\Phi$ is usually understood to be far from the origin, so $V(\Phi)\sim c^{ste}>0$, and then the problem is of a scalar field in de Sitter background, which would mean that we changed the space-time solution from AdS to dS...
Question: Have I been too optimistic in my approximations? In particular, are the terms neglected from (2) to (4) enforcing an AdS background solution? To me, it seems unlikely to be able to change from AdS to dS just by changing the representation of the theory, but I am not sure about where I go wrong with these equations.

A: First, what is $\gamma,\zeta,S$, and where did $m$ go?
Second, beginning of inflation corresponds to large positive $V(\Phi)$, yes, but it is quasi-de-Sitter, not true de Sitter because $V$ and $\Phi$ still change with time, albeit slowly. The background is still AdS of course, since at the minimum the Starobinsky part vanishes, and the small negative cosmological constant is left.


text:
Q: React.js fetch multiple endpoints of API I am doing a React.js project. I am trying to pull data from an API that has multiple endpoints. I am having issues with creating a function that pulls all the data at once without having to do every endpoint separetly. The console.log gives an empty array and nothing gets display. The props 'films' is data from the parent and works fine. It is also from another enpoint of the same API. This is the code:
import { useEffect, useState } from "react";

import styles from './MovieDetail.module.css';

const MovieDetail = ({films}) => {
    const [results, setResults] = useState([]);

    const fetchApis = async () => {
        const peopleApiCall = await fetch('https://www.swapi.tech/api/people/');
        const planetsApiCall = await fetch('https://www.swapi.tech/api/planets/');
        const starshipsApiCall = await fetch('https://www.swapi.tech/api/starships/');
        const vehicleApiCall = await fetch('https://www.swapi.tech/api/vehicles/');
        const speciesApiCall = await fetch('https://www.swapi.tech/api/species/');
        const json = await [peopleApiCall, planetsApiCall, starshipsApiCall, vehicleApiCall, speciesApiCall].json();
        setResults(json.results)
    }

    useEffect(() => {
            fetchApis();
    }, [])

    console.log('results of fetchApis', results)

    return (

{films.properties.title}

{results.people.name}

{results.planets.name}

    );
}

export default MovieDetail;

UPDATE
I just added the post of Phil to the code and I uploaded to a codesanbox

A: You want to fetch and then retrieve the JSON stream from each request.
Something like this
const urls = {
  people: "https://www.swapi.tech/api/people/",
  planets: "https://www.swapi.tech/api/planets/",
  starships: "https://www.swapi.tech/api/starships/",
  vehicles: "https://www.swapi.tech/api/vehicles/",
  species: "https://www.swapi.tech/api/species/"
}

// ...

const [results, setResults] = useState({});

const fetchApis = async () => {
  try {
    const responses = await Promise.all(Object.entries(urls).map(async ([ key, url ]) => {
      const res = await fetch(url)
      return [ key, (await res.json()).results ]
    }))

     return Object.fromEntries(responses)
  } catch (err) {
    console.error(err)
  }
}

useEffect(() => {
  fetchApis().then(setResults)
}, [])

Each URL will resolve to an array like...
[ "people", [{ uid: ... }] ]

Once all these resolve, they will become an object (via Object.fromEntries()) like
{
  people: [{uid: ... }],
  planets: [ ... ],
  // ...
}

Take note that each property is an array so you'd need something like

{results.people[0].name}

or a loop.


text:
Q: How to locate source code that implemented a certain feature? I was wondering what are some techniques to locate which code implemented a specific feature, on a desktop application.
I am a junior developer, with only professional programming experience lying around web programming. In the Web it is easier to do that. For example, you "inspect" a button with the browser tools, and you can see what is being done when you click it. And then, presuming you have the full source code, you can drill down the hierarchy of the calls.
But how do you do this in desktop applications? At least, without having to dive into the full codebase?

A: *

*If you can find any related code at all, you can use your source control software to show you the entire commit or nearby commits that added it. That should show you everything that was required to implement that feature.

*One easy way to find some starting point to look would be to grep through your codebase looking for the text on the button.

*Often, people will put an issue id from their issue tracker in their commit messages. If you can find an issue describing the feature request, then you can search for commits with that issue id.

A: Back Tracing
Back tracing is locating an endpoint to an event associated with the feature (see below). Once there, a breakpoint is placed in the debugger. The feature is triggered and when the debugger stops. The call stack is reviewed to back trace the calling path. While walking up the call stack you can take notes on variable states, or place new breakpoints to inspect the event again.
The feature is trigger again and the debugger stops at the new breakpoints. You can then repeat back tracing or perform forward tracing until the goal is found.
Pros & Cons

*

*It's always easier to walk up the call stack and see how you got somewhere.

*There could be millions of conditions that need to be true before reaching an endpoint. If you know the endpoint already you've saved yourself lots of work.

*If the feature is broken. You may never reach the endpoint, and time can be wasted trying to figure out why.

Endpoint Discovery
To debug a feature you have to know where in the source code the final goal is achieved. Only from this point can you backtrace to see how the code got there. An example; To understand how undo is performed. You know where in the code things are undone, but you don't know how things get there. This would be a candidate for backtracing to figure out how the feature works.
Forward Tracing
Forward tracing is locating a start point for an event associated with a feature (see below). Once there, logging messages are inserted into the source code or breakpoints are set. This process is repeated as you progress further away from the start point until you discover the goal for the feature.
Pros & Cons

*

*It's the easiest starting point for finding a feature.

*Code complexity reduces the effectiveness of forward tracing. The more conditions there are in the code the greater the chance you'll go in the wrong direction.

*Forward tracing often results in setting breakpoints that will be triggered by unrelated events. Interrupting the debugging process and interfering with your search.

Start Point Discovery
You can use keywords, user interface identifiers (button IDs, window names) or easy to find event listeners associated with the feature. For example, you might start with the button used to trigger an undo feature.
Process Of Elimination
You can think of this as the middle point compared to start point and end point positions. You perform a process of elimination when you already know a piece of code is used in a feature, but it is neither the start or end of the feature.
The direction you take from the middle point depends upon the number of entries and exits. If the code chunk is used in many places, then back tracing from this position could be very time consuming as they all have to be inspected. You then employ a process of elimination to reduce this list. Alternative, you can perform a forward trace from this point, but again if the code chunk branches out to many places this can also be a problem.
You have to reduce position directions by not following paths that clearly wouldn't be executed for the feature. Moving past this code and only placing breakpoints where it's likely related to the feature.
Middle point debugging often requires more advance IDE features. The ability to see code hierarchy and dependencies. Without those tools it's difficult to do.
Pros & Cons

*

*Middle points are often the first peice of code that pops into your head when you think of the feature. You say to yourself "Ah, that has to use XXXX to work."

*Middle points can reveal start points the easiest.

*Middle points can be an easy way to pick up the trail to a feature when lost by  synchronization or threading changes.

*Middle points can take you to code you are not familiar with. Costing you time to learn what is going on.

A: Assuming that the feature is tied to some UI thingie, like a Button or Menu, what I tend to do follows (very tedious but it works).  This is looking through the Source Code, not using a debugger.

*

*Search for the (hopefully distinctive) text on the button, e.g. "Super Feature X3".

*That is probably in a file with some constant, e.g.  SUPER_BUTTON_3 = "Super Feature X3".  For future reference, remember this file name.

*There may be another layer (of even two) of abstraction, keep searching to get the "real" String that gets used by the Button.  Note how this is done for the future.

*Now search on that constant.  Hopefully you have now found the Button.  Maybe that is where they connect the ActionListener.  (I'm taking Java-ese here, YMMV, but the concept still holds)

*If necessary, search on that Button and you'll eventually find where it gets connected to a Listener.

*Perhaps that listener really redirects to other listeners (the "real" functionality)  based upon the constant, if so, follow that if/else or case statement.  NOTE: If there is a central dispatchy thing, this is a great place to setup breakpoints.

*Finally, you should be at the actual code.

As @amon noted, sometimes a Debugger is simpler...


text:
Q: Websphere Jython AdminConfig.modify with comma as value causes exception I have a script which sets the JVM properties on a WebSphere server. The script works perfectly unless the value contains a comma. I can't seem to find a work around for this. Does any one know of a way around this?
Example code
def SetJVMProp(jvm):
    attr_name  = ['name', 'globalDataFil ter.stockcount.maintenance']
    attr_value = ['value', 'FUEL,DELETED_PRODUCTS,MERCH_AND_PURCH_GROUP']
    attr_required = ['required', "false"]
    attr_description = ['description', '']
    attr_list = [attr_name, attr_value, attr_required, attr_description]
    property=['systemProperties',[attr_list]]
    AdminConfig.modify(jvm, [property])

Exception:
Unexpected error:  <type 'com.ibm.ws.scripting.ScriptingException'>com.ibm.ws .scripting.ScriptingException: java.lang.IllegalArgumentException:java.lang .IllegalArgumentException: WASX7122E: Expected "]"  not found. Attribute=value had invalid value=FUE for input parameter ['name'"globalDataFilter.stockcount.maintenance"]  ['value'"FUE",DELETED_PRODUCTS,MERCH_AND_PURCH_GROUP'] ['required' 'false'] ['description' '']

Websphere: 8.5.5
Jython: 2.5.4rc1


text:
Q: remove Border="0" inline Attribute of table generated by Asp:Datalist my code

                '>
                    <%#DataBinder.Eval(Container.DataItem, "Title")%>

which generate code like

                Dec 11, 2017

i want to remove border="0" on table
i have tried this script code
$('table#ctl00_ContentPlaceHolder1_DLID').removeAttr("border");
$('#ctl00_ContentPlaceHolder1_DLID').removeAttr("border");

tell me alternative solution

A: You're using C# probably server side language, When it comes to the client side, we all know about ClientID which gives us a unique ClientID of control to refer on the client side. But so far it was read-only (you cannot set it in code).
Try this: it will probably target the desired element
$('<%= DLID.ClientID %>').css("border","")

A: When I test your snippet, it generates html like this:
 without the border. This is in framework 4.5+
But you can remove it with jQuery removeAttr
$("#<%= DLID.ClientID %>").removeAttr("border");

A: Try
var stl= $('table#ctl00_ContentPlaceHolder1_DLID').css("border","")


text:
Q: Zendesk API to get password expiration time and password changed time of user Is there any Oauth Zendesk api, to retrive the org password expiration time and password changed time of org user

A: At the time of writing this answer, no support api end-point exposes this information.


text:
Q: The convex cone of a compact set not including the origin is always closed? Based on the examples given in https://en.wikipedia.org/wiki/Conical_combination, we know that the convex cone generated by a set containing the origin point does not necessarily a closed set, even if the convex cone is generated by convex compact set.
In addition, we also have the following known result.

S is a non-empty convex compact set which does not contain the origin, the convex conical hull of S is a closed set.

I am wondering if we relax the condition of convexity, is there a case such that the convex conical hull of compact set in $\mathbb{R}^n$ not including the origin is not closed.

A: This is not true and here is a counterexample in $\mathbb R^3$ (It is obviously true in $\mathbb R^1$ and I have the impression that it might be true in $\mathbb R^2$).
Let
$$
C_\pm := \{ (x,y,z) \in \mathbb R^3 \mid x = \pm 1 \text{ and } y^2 + (z-1)^2 = 1 \}
$$
and
$$
K := C_+ \cup C_-.
$$
Obviously, $K$ is compact.
Let us check that its convex, conical hull $D$ is not closed. It is clear that the points
$$
x_n := n \,(0, 1/n, 1 - \sqrt{1 - 1/n^2})
$$
belong to $D$ for $n \in \mathbb N$ and $x_n \to (0, 1, 0) =: x$. However, $x$ does not belong to $D$: Indeed, since the third component is zero, it can only be a convex conical combination of points of the form $(\pm 1, 0, 0)$ and this is not possible.


text:
Q: DWH and ETL explained In this post I am not asking any tutorials, how to do something, in this post, I am asking your help, if someone could explain me with simple words, what is DWH (data warehouse ) and what is ETL.
Of course,  I google'ed and youtube'd alot, I found many articles, videos, but still, I am not very sure what it is.
Why I am asking?
I need to know it very well before I am applying for a job.

A: This answer by no means should be treated as a complete definition of a data warehouse. It's only my attempt to explain the term in layman's terms.
Transactional (operational, OLTP) and analytical (data warehouses) systems can both use the same RDBMS as the back-end and they may contain exactly the same data. However, their data models will be completely different, because they are optimized for different access patterns.
In transactional systems you usually work with a single row (e.g. a customer or an invoice) and the write consistency is crucial, so the data model is normalized. On the contrary, data warehouses are optimized for reading large number of rows (e.g. all invoices from the previous year) and aggregating data, so dimensional models are flattened (star schema, Kimball's dimensions and facts).
Transactional systems store only the current version of entities (i.e. current customer's address), while data warehouses may use slowly changing dimensions (SCD) to preserve history (e.g. all addresses of the customer with date ranges to indicate when each of them was valid).
ETL stands for extract, transform, load and it is the procedure of:

*

*extracting data from a transactional system,

*transforming it into dimensional format,

*loading in a data warehouse.


text:
Q: How to plot a directed line in matplotlib? In matplotlib, it's easy to draw a line from data points with plt.plot(xs, ys, '-'+marker). This gets you an undirected line, where you can't tell from looking at the resulting diagram, which end corresponds to the beginning of the arrays of data points and which to the end of the arrays. It happens that for what I'm doing, it's important to be able to tell which end is which, or equivalently, which direction the line is going.  What is the recommended way to plot a line so as to obtain that visual distinction?

A: The following would be one option. It is to add some arrow heads along a line. This can be done using a FancyArrowPatch.
import numpy as np ; np.random.seed(7)
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch

class RL(object):
    def __init__(self, n, d, s=0.1):
        a = np.random.randn(n)*s
        a[0] = np.random.rand(1)*np.pi*2
        self.xy = np.random.rand(n,2)*5
        self.xy[1,:] = self.xy[0,:] + np.array([d*np.cos(a[0]),d*np.sin(a[0])])
        for i in range(2,n):
            (x,y), = np.diff(self.xy[i-2:i,:], axis=0)
            na = np.arctan2(y,x)+a[i]
            self.xy[i,:] = self.xy[i-1,:] + np.array([d*np.cos(na),d*np.sin(na)])
        self.x = self.xy[:,0]; self.y = self.xy[:,1]

l1 = RL(1000,0.005)
l2 = RL(1000,0.007)
l3 = RL(1000,0.005)

fig, ax = plt.subplots()
ax.set_aspect("equal")
ax.plot(l1.x, l1.y)
ax.plot(l2.x, l2.y)
ax.plot(l3.x, l3.y)
ax.plot(l1.x[0], l1.y[0], marker="o")

def arrow(x,y,ax,n):
    d = len(x)//(n+1)
    ind = np.arange(d,len(x),d)
    for i in ind:
        ar = FancyArrowPatch ((x[i-1],y[i-1]),(x[i],y[i]),
                              arrowstyle='->', mutation_scale=20)
        ax.add_patch(ar)

arrow(l1.x,l1.y,ax,3)
arrow(l2.x,l2.y,ax,6)
arrow(l3.x,l3.y,ax,10)

plt.show()


text:
Q: Android BroadcastReciever - Concept I tried to wrap my head around Android BroadcastReceiver  but with no success. I'm trying to implement something simple:

*

*Listen to an incoming SMS

*Check if the number is saved

*If it is saved do something

So far I registered / created the BroadcastReceiver and I'm able to catch the incoming messages. I did this in the following way:
public class SmsReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){

        //do things
  }
 }
}

I registered the receiver in the Manifest file in the following way:
 <receiver
        android:name=".SmsReceiver"
        android:permission="android.permission.BROADCAST_SMS"
        android:exported="true">

        <intent-filter android:priority="2147483647" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

Everything fine until now.
But, and here is the big BUT: I also created a class called 'UserManager' with a few basic tasks, for example: adding a new user, deleting a user, checking if the user exists, etc.
I store the users in a HashMap (phoneNumber, Name).
My questions are:

*

*How can I pass an Object to my BroadcastReceiver? ( I want to be able to access the HashMap from the "UserManager" class)

*I found a lot of topics regarding BroadcastReceivers. Some of them said that there are a couple ways of declaring a broadcast receiver. For example you could do it the way I did ( declaring it in Manifest), or you could do something more uhm... context based? Like declaring it BroadcastReceiver br = new MyBroadcastReceiver() and registering intentFilters to it. What is the difference? Which one should I use?

*Is there something called "good practice"? What should I pay attention to? Do you know any material which explains clearly the different ways of using a broadcastReceiver?

A: *

*You can use dependency injection. Or just hold reference to a class in you Application, that can be accessed by getApplicationContext

*Difference is - for receivers declared in manifest you can receiver messages even if you app is in destroyed state. If you broadcast receiver is created manually, well, you must create it before message will be delivered. Also Android forces some restriction on receivers declared in manifest.


text:
Q: Rspec validate uniqueness with scope I have this in my Line model
validates :home_team, :uniqueness => { :scope => [:visiting_team, :event_datetime],
:message => "** DOUBLE EVENT **" }

I have this in my spec
describe Line do
  it { should validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime) }

I get this error...
Failures:
1) Line
 Failure/Error:

it { should validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime) }
   Did not expect errors to include "has already been taken" when home_team is set to "arbitrary_string", got error:
# ./spec/models/line_spec.rb:7:in `block (2 levels) in <top (required)>'

Any ideas why this is failing?

A: I think you need to do this make it pass
it { should validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime).with_message("** DOUBLE EVENT **") }

The default error message of uniqueness is "has already been taken".

A: In case you follow rubocops ImplicitExpect you might what to use something like this:
it { is_expected.to validate(%i[home_team], uniqueness: { scope: [:visiting_team, :event_datetime] }) }

or
it { is_expected.to validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime) }

(note that I did not include the custom error message as the original question is very old and my purpose is to help visitors from google rather than the original question author)

A: Using the New "Expect" Lingo
let(:line) { build(:line) } # if using factory bot, or you could use fixtures
it {expect(line).to validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime)  }


text:
Q: How to get settings/properties into a Flex/FlashBuilder application? I have a Flash Builder application which uses URLs within its code and I want to be able to change these URL values without having to recompile my application, i.e. I want to have a plain text file I can edit which is used to populate these URL values when the application begins.  I've worked out what feels like a kludge to do this with ResourceBundles, but maybe there's a better or more straightforward way to go about this.
As an example here's what I have now:
var myUrl = "http://hard.coded.url";

I'd prefer to have the application read a properties file and set the variable accordingly:
var myUrl = getApplicationProperty("myUrl");

How would I go about writing getApplicationProperty()?  Is there a process cooked into ActionScript for this, or do I need to do it myself by opening a text (or XML) file and reading the properties as key/value pairs?
Thanks in advance for any suggestions.

A: You can certainly link to properties in .properties files (used for localization for example)
See http://www.visible-form.com/blog/flex-localization-with-resource-bundles/ for an example.
That said these get compiled in the swf and the only way to read them at runtime is to write your own properties parser.
In other words, XML would be the better fit for this case.

A: If you just want a config file with key=value thing you can use your own class which reads a config file passed to it and returns a AssociativeArray back to you.
It should be a pretty straightforward thing and should not take more than 20 minutes to get done.

A: As Neeraj said it will be very fast to accomplish with your own class. Create a singleton that loads your config, parse it and your done!
Or even easier solution - create your config as xml file and load it.
About ini files here a quick search result: https://stackoverflow.com/a/589725/965722
EDIT
There is another way: you can create a custom preloader class that will load your config at runtime.
https://stackoverflow.com/a/2788565/965722 - quick search with google.


text:
Q: Axiomatized Formal Theory T is an axiomatized formal theory whose wff's are constructed from "p", "q", and "r" and the familiar propositional connectives, and whose underlying logic is the standard propositional deduction system. The theory has the following axioms:

*

*~p

*q

*~r

How can one prove that T is negation-complete, that is every wff or its negation is a theorem of the system.  Thanks for all guidance,  AM

A: Without any rules of inference you cannot prove much. So since you said the "underlying logic is the standard propositional deduction system", I'm assuming we have the common rules such as modus ponens, 'from $A$ and $B$ deduce $A\land B$', etc., and tautologies of propositional logic such as $A\rightarrow A\lor B$ and $A\land B\rightarrow A$ as axioms of the system.
Since $p$, $q$, $r$ are the only propositional variables, the given set of axioms acts like a truth assignment. So they make every formula either true or false. To decide whether a formula is a theorem or not, first turn it into a CNF (or DNF) and then evaluate it using the "truth assignment". And then construct the proof based on the result of evaluation.
Example: $\phi = (p\lor q)\rightarrow r$
CNF: $(\neg p\lor r)\land (\neg q\lor r)$
Since the "truth assignment" makes $\phi$ false, it makes $\neg \phi$ true.  We can construct the proof of CNF (or DNF) of $\neg \phi$ using the three axioms, modus ponens and the axioms $A\rightarrow A\lor B$ and $A\land B\rightarrow A$. Proof of $\neg\phi$ from its CNF (or DNF) can be done in a straightforward way as well (although it may be long).


text:
Q: automator to run AppleScript for a shell script For a selected file in Finder, I like to run a perl script using Services. I created an Automator process that runs an AppleScript:
on run {input, parameters}
    tell application "Terminal"
        activate
        do script "/Users/myaccountname/Applications/TeXcount_3_0/texcount.pl \"" & (input as string) & "\""
    end tell
end run

The only problem is that the selected filename appears as something like:
"Macintosh HD:Users:myaccountname:Documents:texfile.tex"

which the perl script cannot understand. How can I make it a UNIX-like filename?

A: You'll need to get the POSIX path of the input file:
on run {input, parameters}
    tell application "Terminal"
        activate
        do script "/Users/myaccountname/Applications/TeXcount_3_0/texcount.pl \"" & ( POSIX path of input as string) & "\""
    end tell
end run

I found the answer over at StackOverflow.

A: You can also use quoted form of to escape the arguments:
on run {input, parameters}
    tell application "Terminal"
        do script "printf %s\\\\n " & quoted form of POSIX path of item 1 of input & ">/tmp/a"
    end tell
end run

Or if the service can receive multiple files as input:
on run {input, parameters}
    set args to ""
    repeat with f in input
        set args to args & " " & quoted form of POSIX path of f
    end repeat
    tell application "Terminal"
        do script "printf %s\\\\n " & args & ">/tmp/a"
    end tell
end run


text: Q: Advantages of Activiti I have gone through few threads which discuss about jBPM5 vs Activiti. New features have been added in jBPM6. what are the advantage of using activiti ..in which case activiti is suitable


text:
Q: Git Bash is not allowing me to execute changes: I am aiming to create backup storage for AWS code commit, following this AWS stack using an AWS sample (https://github.com/aws-samples/aws-codecommit-serverless-backup):
However, every time I try to execute the changes it on git bash it does not allow me to deploy the changes (Video I was aiming to replicate - https://www.youtube.com/watch?v=pilPILjSEmA ). From 3:00 mins to 3:10 on my git bash it does not allow me to deploy these changes and instead it displays this:
Git Bash Terminal


text:
Q: What does this equation represent? While doing the Franck-Hertz experiment I noticed that I have been asked to write the current as a function of the Mean Free Path as following: $$ I=a\cdot e^{-\frac{b}{\lambda}}$$
I- current
$\lambda$ - mean free path
a,b some constants that I try to figure out what they represent. So far, by simple dimension analysis, I understand $a$ should be current and $b$ should be length.
If anyone can tell me the name of that equation (if there is one) it will be much helpful

A: I'm not sure that it has a particular name in this context.  In the context of light moving through an absorbing medium, it's known as the Beer-Lambert law;  but more broadly speaking, it's a general property of particles moving through a medium that can scatter them.  Similar equations exist for x-ray transmission and neutron transmission, and I'm not sure there's a specific name for those equations either.


text:
Q: Find most popular strings in a table I am using MyISAM engine with fulltext indexing for storing a list of strings.
These strings can be a single word, or a sentence.
If I want to know how many times string hello appears in my table, I do
SELECT COUNT(*) Total
    FROM String s
WHERE
    MATCH (s.name) AGAINST ('hello')

I would like to create a similar report, but for all strings. Result should be a list of TOP-N strings that are the most common in this table (top ones most probably are "the", "a", "to" etc.).
Exact match case is pretty obvious:
SELECT name as String, count(*) as Total
    FROM String
GROUP
    BY name
ORDER
    BY total desc
LIMIT *some number*

But it counts only whole strings.
Is there any way to achieve my desired result?
Thanks.

A: I guess there is no easy way for this. I would create a "statistic table" for this purpose only. One column for words themselves, one column for the number of occurrences. (Primary key on the first column of course.)
For this with a PL/SQL block scanning all strings, and split them for words.
If the string is not found in the statistic table, you insert a new row.
If the string is found in the statistic table, you increase the value in the second column.
This can run for a pretty long time, but after the first run is ready, you only have to check the new strings on insert, perhaps with a trigger. (Assuming you want to use it not once but regularly.)
Hope this helps, I have no simpler answer.

A: i think if you use the LIKE command will works
select name, count(*) as total from String where name like '%hello%' group by name order by total

let me know

A: I didn't find any solution with SQL and my Full text index, but I managed to get my desired result by getting all of my strings from DB and processing them on the backend with php:
//get all strings from DB
$queryResult = $db->query("SELECT name as String FROM String");

//Combine all of them into array
while($row = $queryResult->fetch_array(MYSQLI_ASSOC)) {
    $stringArray[] = $row['String'];
}

//"Glue" all these strings into one huge string
$text = implode(" ", $stringArray);

//Make everything lowercase
$textLowercase = strtolower($text);

//Find all words
$result = preg_split('/[^a-z]/', $textLowercase, -1, PREG_SPLIT_NO_EMPTY);

//Filter some unwanted words
$result = array_filter($result, function($x){
    return !preg_match("/^(.|the|and|of|to|it|in|or|is|a|an|not|are)$/",$x);
});

//Count a number of occurrence of each word
$result = array_count_values($result);

//Sort
arsort($result);

//Select TOP-N strings, where N is $amount
$result = array_slice($result, 0, $amount);


text:
Q: Trouble parsing quotes with SAX parser (javax.xml.parsers.SAXParser) on Android API 1.5 When using a SAX parser, parsing fails when there is a " in the node content.  How can I resolve this? Do I need to convert all " characters?
In other words, anytime I have a quote in a node:
 <node>characters in node containing "quotes"</node>

That node gets butchered into multiple character arrays when the Handler is parsing it. Is this normal behaviour? Why should quotes cause such a problem?
Here is the code I am using:
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

 ...

HttpGet httpget = new HttpGet(GATEWAY_URL + "/"+ question.getId());
          httpget.setHeader("User-Agent", PayloadService.userAgent);
          httpget.setHeader("Content-Type", "application/xml");

          HttpResponse response = PayloadService.getHttpclient().execute(httpget);
          HttpEntity entity = response.getEntity();

          if(entity != null)
          {
              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();
              XMLReader xr = sp.getXMLReader();

              ConvoHandler convoHandler = new ConvoHandler();
              xr.setContentHandler(convoHandler);
              xr.parse(new InputSource(entity.getContent()));

              entity.consumeContent();

               messageList = convoHandler.getMessageList();

          }

A: The error is in your handler class referenced in your most recent comment.
A common error in writing a ContentHandler is to assume the characters method is only going  to be called once with all the character data.  It can in fact be called multiple times with chunks of the character data, which you have to collect.  The chopping up into multiple character arrays is normal behavior.
Probably you need to initiate a collector (maybe a StringBuffer) in your startElement method, collect data into it in your characters method and then use the data in your endElement method, which should be where the message.setText shown in your comment is called.

A: Correct answer has already been given (wrt no guarantees in character data being sent as single event). One thing to consider is that perhaps using a parser with Stax (or xmlpull) "pull" interface would work better; there is a way to force Stax parser to ensure all char data is reported as single token (enable coalescing). Stax (or pull parsers in general) are considered bit more convenient use than SAX, and there are implementations that run on Android as well (android SDK even bundles xmlpull I think); Woodstox and Aalto should work.


text:
Q: Integral involving gamma incomplete function. I'm interested (ref) in the following integral
$$I(m,d)=\int_0^{\infty} \left( \frac{\Gamma(m,x)}{\Gamma(m)} \right)^d dx=\frac{1}{((m-1)!)^d}\int_0^{\infty}  \Gamma(m,x)^d dx$$
where $\Gamma(m,x)$ is the (upper) incomplete gamma function, $m,d$ are positive integers.
In particular, I'm interested in $d=3$.
Exact solutions, approximations or asymptotics (for $m \to \infty$) are appreciated.
Numerically, it seems that $I(m,3) = m - a \sqrt{m} +O(1)$ with $a \approx
0.835$
Some values for $d=3$
2   0.96296
3   1.68313
4   2.44942
5   3.24473
10  7.44823
20  16.3304
50  44.1225
100 91.6395
200 188.1311
300 285.4399
400 383.1715
500 481.1731

In case this helps: Asymptotic expansions for the incomplete gamma function...

A: Answered in MathOverflow.
The asymptotic expansion for general $d$ is shown to be
$$I(m,d) \sim  m - m^{-1/2}  a_d$$
where $a_d$ has a rather complex form (see the linked answer).
For $d=3$,
$a_3=\frac{3}{2\sqrt{\pi}}=0.846284\cdots$ (in agreement with  metamorphy's comment).