text:
Q: Control Android Brightness and Volume at Set Time I am trying to create an Android app that will change the volume and brightness of the user's device at a time either set by the user, or hard coded into the app itself.
I have searched on StackOverflow, but the closest I have got to is setting the brightness only in the app. I want the app to set the brightness and volume permanently across the entire device until the set time passes. Any idea how I can do this?

A: Take a look at this question. It looks similar to your problem
How to set volume in decibels using my android mobile application?
In the above mentioned question he has a media player object and he uses that to change the volume. The code to do that is -
public void OnPlay(View v){

mp = MediaPlayer.create(this, R.raw.twofiftybeep);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

mp.start();

mp.setOnCompletionListener(new OnCompletionListener() {

    @Override
    public void onCompletion(MediaPlayer mp) {
        // Playing the file continuously
        mp.setVolume(left, right);

        mp.start();

    }
} );
}

A: You can find the methods that you are looking for on the android developer documentation.
Setting Volume:
The AdjustVolume(int,int) method should be what you are looking for.
http://developer.android.com/reference/android/media/AudioManager.html#adjustVolume(int,%20int)
Settings Brightness:
private void setBrightness(int brightness) {
    try {
      IHardwareService hardware = IHardwareService.Stub.asInterface(
ServiceManager.getService("hardware"));
      if (hardware != null) {
        hardware.setScreenBacklight(brightness);
      }
    } catch (RemoteException doe) {
    }
  }

http://www.tutorialforandroid.com/2009/01/changing-screen-brightness.html


text:
Q: Swift: SKNode `contains(_:)` not always working I am having trouble with contains(_:) to check if an SKSpriteNode contains a point. Specifically a point from UIPanGestureRecognizer.location(in:).
Drawing two boxes (red and green) on the screen as SKSpriteNodes, another node (colored yellow) is added and will be dragged across the scene using an UIPanGestureRecognizer.
The result of contains(_:) seems to depend on the parent of the node that is being dragged, which I don't expect. It should simply check if a specific CGPoint lies inside of the coordinates of a node.
    var box1: SKSpriteNode?
    var box2: SKSpriteNode?
    var draggingNode: SKSpriteNode?

    box1 = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 50))
    box1?.position = CGPoint(x: 100, y: 100)
    addChild(box1!)

    box2 = SKSpriteNode(color: .green, size: CGSize(width: 50, height: 50))
    box2?.position = CGPoint(x: 200, y: 200)
    addChild(box2!)

    draggingNode = SKSpriteNode(color: .yellow, size: CGSize(width: 25, height:25))
    box1!.addChild(draggingNode!)

As seen above, the yellow draggingNode is a child of the red node box1.
Here is the gesture recogniser code that moves the draggingNode and print outs the results of the test:
    @objc func panned(sender: UIPanGestureRecognizer) {
        let pointInView: CGPoint = sender.location(in: view)
        let pointInScene = convertPoint(fromView: pointInView)

        if sender.state == .changed {
            let translation = sender.translation(in: view)
            draggingNode?.position.x += translation.x
            draggingNode?.position.y -= translation.y
            sender.setTranslation(.zero, in: view)

            print("is in box1: ", box1!.contains(pointInScene))
            print("is in box2: ", box2!.contains(pointInScene))
        }

*

*The expected result is that box1!.contains(pointInScene) only returns true if the draggingNode is actually above box1.

*The actual result is that box1!.contains(pointInScene) always returns true, no matter if the draggingNode is dragged above box1 or not.

For box2, of which the draggingNode is not a child, the results are correct.

*

*If I add the draggingNode as a child of box2, the results are reversed: box2!.contains(pointInScene) now always returns true and box1!.contains(pointInScene) works correctly.

*If I add the draggingNode as a child of the SKScene itself, everything works as expected.

Question: Why is the parent of draggingNode influencing the result of contains(_:), and how to fix it?

A: the reason is that if you add a child node to a parent they effectively create a two node system. and this affects the frame size. if you look at box1?.calculateAccumulatedFrame() you will see that box1's frame expands to include wherever the yellow draggingNode position is.
you are getting strange results because yellow is effectively doing a hit test against a rectangle that it's own position is helping to define.
solution: add both box1 and draggingNode to a third parent node (let's call it "container"). then box1's accumulated frame will not vary during the pan gesture, and your hit tests will be accurate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get a fully decoded string I am using $_SERVER['QUERY_STRING'] instead of $_GET to get all my parameters. However, $_SERVER['QUERY_STRING'] encodes the string by itself. Thus, if a user sends an encoded string, it gets encoded again with $_SERVER['QUERY_STRING']. Meaning I have to run urldecode twice.
Encoded string: https://www.example.com/test.php?info1234=3177%3B315961%3B317451%3B315511&info3598=121618%3B136803%3B13830%3B20532
If you use the link above to submit via the URL itself. Meaning you put the parameter in yourself, you get the string (which is what I want):
https://www.example.com/test.php?info1234=3177;315961;317451;315511&info3598=121618;136803;13830;20532

However, if you submit via form, you get a doubly encoded string. So when you decode, it only decodes once, and you have to run urldecode on it again to fully decode it:
https://www.example.com/test.php?info1234=3177%3B315961%3B317451%3B315511&info3598=121618%3B136803%3B13830%3B20532

How can I make sure I get the decoded string (I don't want to run urldecode twice on the string, as it makes my time complexity O(2n). I want to try keep it at O(1) or at the very least O(n). I know using urldecode means n every time.
<?php
$a = urldecode($_SERVER['QUERY_STRING']);

$b = urldecode($a);
if(strpos($a, "%") != false) {
    echo "We had to decode twice
";
    echo $a . "

Then to:
" . $b;
} else {
    echo "Only decoded once!!
";
    echo $a;
}
?>

<form action="test.php" method="get">
  myurl: <input type="text" name="myurl">

  <input type="submit" value="Submit">
</form>

Method 1:

*

*localhost/test.php?https://www.example.com/test.php?info1234=3177%3B315961%3B317451%3B315511&info3598=121618%3B136803%3B13830%3B20532

*This decodes once

Method 2:

*

*Go to localhost/test.php

*Submit this link via the form
https://www.example.com/test.php?info1234=3177%3B315961%3B317451%3B315511&info3598=121618%3B136803%3B13830%3B20532

*This decodes twice

You will see you get 2 different outputs


text:
Q: Using javascript how to target all HTML list elements which have been created by a loop of JSP scriplets If I target list item to change the background-color using java script only first occurrence of list item will be affected and remaining 3  list items will not be affected
In the  code below assume that x=5, then we will get 4 list items. Now in the javascript if i write document.getElementsByClassName("Booking-occupant").style.background="green" only first list item will get background color to be green but not remaining 3 list items. What code should I write in JAVASCRIPT so that all list items will get background color to be green for example??
<%int x=tourism.getMax_seats();
    while(x>1){

%>

        Available seat

<%
    x--;
    } %>


text:
Q: Acessar chave direta Gostaria de acessar a chave direta de um objeto array sem precisar fazer um loop (foreach)
Ao invés de ser assim:
    $nome = "";
    $codigo   = 0;
    $objeto  = DB::select( "SELECT NOME FROM TABELA WHERE CODIGO = ?", array( $codigo ) );
    foreach ( $objeto as $obj ){
        $nome = $obj->nome;
    }
    echo $nome;

Gostaria que eu não precisasse de foreach
Tipo
   $nome = $objeto->nome;

Mas dá a seguinte mensagem:

Trying to get property of non-object

A: Sua query esta errada:
SELECT NOME WHERE ID = ?

Falta FROM [NOME DA TABELA AQUI], deveria ser assim:
DB::select( "SELECT NOME FROM minhatabela WHERE ID = ?", $nome );

E só pra constar, eu não faço ideia se a variável $nome é um array ou uma string, mas acaso seja string você deve passar assim:
DB::select('SELECT NOME FROM minhatabela WHERE ID = ?', [ $nome ]);

[editado]
Sua query esta errada ainda:
SELECT CODIGO FROM TABELA WHERE ID=?

No SELECT você só pede a coluna CODIGO, mas você quer o objeto ->nome, logo é necessário selecionar ele também, assim:
SELECT codigo, nome FROM TABELA WHERE ID=?

Pra não precisar usar o foreach como só vai trazer um resultado pode usar assim:
$objeto = DB::select( "SELECT NOME FROM minhatabela WHERE ID = ?", [ $nome ])->first();

echo $objeto[0]->nome;

A: Quando tu faz uma consulta ele te retorna um array, se tu não passar por um foreach ele não vai trazer os atributos. Que no caso attributes é um índice desse array!


text:
Q: $ \sum_{k=0}^t\, {k \choose a}{b \choose k}\,y^{b-k}\,x^{k-a}\,=\,{b \choose a}{(y+x)}^{b-a} $ How to prove that, for every natural numbers like $t$, the following relation holds:
$$
\sum_{k=0}^t\, {k \choose a}{b \choose k}\,y^{b-k}\,x^{k-a}\,=\,{b \choose a}{(y+x)}^{b-a}
$$
where $0 \leq a,b\leq t-1$.  Thanks for any suggestion.
Edit(1): Based on the @callculus comment. For fixed values of $a,b,x,y$, I checkd with Maple that the equation holds  for every value of $t\in \Bbb{N}$ and $0 \leq a,b\leq t-1$.

A: Firstly note that $\binom{k}{a}\binom{b}{k} = \binom{b}{a}\binom{b - a}{k - a}$ for $k \ge a$. This is almost all. Also we need to see that $\binom{b}{k} = 0$ for all $k > b$ and $\binom{k}{a} = 0$ for all $k < a$, therefore
$$\sum_{k = 0}^t \binom{k}{a}\binom{b}{k}y^{b - k}x^{k - a} = \binom{b}{a}y^{b - a} \sum_{k = a}^b \binom{b - a}{k - a} y^{a - k}x^{k - a} \\
= \binom{b}{a}y^{b - a} \sum_{\ell = 0}^{b - a} \binom{b - a}{\ell} y^{-\ell}x^{\ell} = \binom{b}{a}y^{b - a} \left(1 + \frac{x}{y}\right)^{b - a} = \binom{b}{a}(y + x)^{b - a}$$
for all $b \ge a$.
If $b < a$ then all summands on the LHS are $0$ because either $k < a$ or $k > b$ for all $k$ and RSH is also $0$.


text:
Q: Setting VCTargetsPath to multiple directories So, I've been trying to generate cocos2d-x static libraries, and I ran cmd as admin, and entered
cocos gen-libs

After about ten minutes, I got an issue about cpp windows props. I found out through here that I was supposed to set the VCTargetsPath so gen-libs could use some build tools. So, I did that, ran gen-libs again, and got error
messages about the v140_xp toolset not being found. So, I then set the VCTargets path so it used that toolset. After using gen-libs again, it said it couldn't find the v120 toolset (the one it was set to use in the first VCTargetsPath change).
tl;dr I need to know how to make it so my VCTargetsPath can refer to more than one directory at once, so I can build the cocos2d-x static libraries on my machine without hassle.
If it helps any, I'm on Windows 10 64-bit, using cocos2d-x v3.15.1


text:
Q: Rails 5.2 credentials.yaml.enc and master.key not working on Heroku I'm setting up active storage for a new app, and haven't been able to get the app running on production after setting up my amazon credentials.

*

*I've included my s3 bucket credentials in my credentials.yaml.enc file

*I've added my RAILS_MASTER_KEY env variable to Heroku.

*I've set up my s3 bucket in the storage.yml file according to this.

*I've added the config.active_storage.service = :amazon line to my production.rb.

*I've added config.require_master_key = true to my production.rb

When I try running my app on Heroku, it doesn't load. Doing $ Heroku run rails console gives me the error:
"/app/vendor/bundle/ruby/2.3.0/gems/aws-sigv4-1.0.2/lib/aws-sigv4/signer.rb:517:in `extract_credentials_provider': Cannot load `Rails.config.active_storage.service`: (Aws::Sigv4::Errors::MissingCredentialsError)
missing credentials, provide credentials with one of the following options:
- :access_key_id and :secret_access_key
- :credentials
- :credentials_provider"

As far as I can tell I've set up my credentials the way Rails 5.2 intended. I've tried all sorts of asset precompiling stuff to no avail. When I try adding my amazon credentials as env. variables in Heroku, the app runs fine in production. Any idea what could be going wrong here?

A: Could it be that you forgot to add config.require_master_key = true to your production.rb?

A: I've had this problem before, seems to be a bug on Heroku.
You should just set up your environment variables through the dashboard on Heroku on the settings tab.
Then you can access that using ENV['NAME_OF_YOUR_VARIABLE']
This fixed my problem.
Also check your Heroku logs very well, by scrolling up to ensure all gems were installed.

A: Double check that you have the correct key in your config/credentials.yml.enc file. I had one key inverted- secret_key_access instead of secret_access_key, and was getting the same error. Fixing the key name in config/credentials.yml.enc fixed it for me.
In your rails console (locally), run:

Rails.application.credentials.dig(:aws, :access_key_id)

and

Rails.application.credentials.dig(:aws, :secret_access_key)

to make sure they have values.

A: Welp, this was dumb. Mystery solved. My credentials were commented out in the credentials.yaml.enc file - I was adding them to the top of the file with the default aws example, which is commented out.


text:
Q: How to search the value and update / add it some values in Nested Array Javascript? Find the value in nested array using Javascript and add or update the relevant array with the following information.
Search id:jkl and Add the following keys & values in relevant array {values:123,field:'Field Name'} .
Nested Array
[{
    id: "abc",
    name: "Parent Object",
    children: [{
        id: "def",
        name: "Child 1 Object",
        parentId: "abc",
        children: [{
            id: "ghi",
            name: "Child 2 Object",
            parentId: "def",
            children: [{
                id: "jkl",
                name: "Child 3 Object",
                parentId: "ghi",

            }]
        }]
    }]
}]

Thanks

A: What you are looking for is a recursive function.

const data = [{
    id: "abc",
    name: "Parent Object",
    children: [{
        id: "def",
        name: "Child 1 Object",
        parentId: "abc",
        children: [{
            id: "ghi",
            name: "Child 2 Object",
            parentId: "def",
            children: [{
                id: "jkl",
                name: "Child 3 Object",
                parentId: "ghi",

            }]
        }]
    }]
}]

function findNested (arr, id) {
  for (let item of arr) {
    if (item.id === id) return item // item found, return the current obj
    if (item.children instanceof Array) {
      // magic happens here
      return findNested(item.children, id)
    }
  }
  return null // nothing found
}

const obj = findNested(data, 'jkl')
// obj is a reference here. Changing it will also change the object in `data`
obj.values = 123

console.log(data)

A: You can build a recursive function to achieve that:

const arr = [{ id: "abc", name: "Parent Object", children: [{ id: "def", name: "Child 1 Object", parentId: "abc", children: [{ id: "ghi", name: "Child 2 Object", parentId: "def", children: [{ id: "jkl", name: "Child 3 Object", parentId: "ghi", }] }] }]}];

const getUpdated=(arr,obj, id)=>{
    return arr.map(k=> k.id == id ? ({...k, ...obj}) : ({...k, children: k.children ? getUpdated(k.children, obj, id) : []}))
};

console.log(getUpdated(arr, {values:123,field:'Field Name'}, 'jkl')); // updated array returned


text:
Q: find element by tag function is not working in php I am doing web parsing in php. I have done it successfully but now it is giving me error on find function. Is there any updation in this built i n php function?

A: The chances, that there's an error in a PHP-function is quite low, compared to if you have made something wrong in your code. :-)
And which PHP-version are you running? If you insert this on your PHP-page, then you'll get your current version:
<?php echo 'Current PHP version: ' . phpversion(); ?>

If you try writing the code that are giving you the error - and which error your are getting, then it's easier to help. I would have written this in a comment - but I don't have enough reputation-points to write comments yet. :-/


text:
Q: Can someone please explain this lazy evaluation code? So, this question was just asked on SO:
How to handle an "infinite" IEnumerable?
My sample code:
public static void Main(string[] args)
{
    foreach (var item in Numbers().Take(10))
        Console.WriteLine(item);
    Console.ReadKey();
}

public static IEnumerable<int> Numbers()
{
    int x = 0;
    while (true)
        yield return x++;
}

Can someone please explain why this is lazy evaluated? I've looked up this code in Reflector, and I'm more confused than when I began.
Reflector outputs:
public static IEnumerable<int> Numbers()
{
    return new <Numbers>d__0(-2);
}

For the numbers method, and looks to have generated a new type for that expression:
[DebuggerHidden]
public <Numbers>d__0(int <>1__state)
{
    this.<>1__state = <>1__state;
    this.<>l__initialThreadId = Thread.CurrentThread.ManagedThreadId;
}

This makes no sense to me. I would have assumed it was an infinite loop until I put that code together and executed it myself.
EDIT: So I understand now that .Take() can tell the foreach that the enumeration has 'ended', when it really hasn't, but shouldn't Numbers() be called in it's entirety before chaining forward to the Take()? The Take result is what is actually being enumerated over, correct? But how is Take executing when Numbers has not fully evaluated?
EDIT2: So is this just a specific compiler trick enforced by the 'yield' keyword?

A: This has to with:

*

*What iEnumerable does when certain methods are called

*The nature of enumeration and the Yield statement

When you enumerate over any sort of IEnumerable, the class gives you the next item that it's going to give you.  It doesn't do something to all its items, it just give you the next item.  It decides what that item is going to be.  (For example, some collections are ordered, some aren't.  Some don't guarantee a particular order, but seem to always give them back in the same order you put them in.).
The IEnumerable extension method Take() will enumerate 10 times, getting the first 10 items.  You could do Take(100000000), and it would give you a lot of numbers.  But you're just doing Take(10).  It just asks Numbers() for the next item . . . 10 times.
Each of those 10 items, Numbers gives the next item.  To understand how, you'll need to read up on the Yield statement.  It's syntactic sugar for something more complicated.  Yield is very powerful.  (I'm a VB developer and am very annoyed that I still don't have it.)  It's not a function; it's a keyword with certain restrictions.  And it makes defining an enumerator a lot easier than it otherwise might be.
Other IEnumerable extension methods always iterate through every single item.  Calling .AsList would blow it up.  Using it most LINQ queries would blow it up.

A: The reason this isn't an infinite loop is you are only enumerating 10 times according to the use of Linq's Take(10) call. Now if you wrote the code something like:
foreach (var item in Numbers())
{
}

Now this is an infinite loop because your enumerator will always return a new value. C# compiler takes this code and transforms it into a state machine. If your enumerator doesn't have a guard clause to break the execution then the caller must which in your sample it does.
The reason the code is lazy is also a reason why the code works. Essentially Take returns the first item, then your application consumes, then it takes another until it has taken 10 items.
Edit
This actually has nothing to do with the addition of take. These are called Iterators. The C# compiler performs a complicated transformation on your code creating an enumerator out of your method. I recommend reading up on it but basically (And this might not be 100% accurate), your code will enter the Numbers method which you could envision as initilizing the state machine.
Once your code hits a yield return, you are in essence saying Numbers() stop executing give them back this result and then when they ask for the next item resume execution at the next line after the yield return.
Erik Lippert has a great series on misc aspects of Iterators

A: Basically, your Numbers() function creates an Enumerator.
The foreach will check, in each iteration, if the enumrator has reached the end, and if not, it will continue. Your praticular enumrator will never end, but that doesn't matter. This is being lazyily-evaluated.
The Enumerator will generate the results "live".
What that means is if you would write .Take(3) in there, the loop will only be executed three times. The enumrator would still have some items "left" in it, but they would not be generated since no method needs them, at this time.
If you would try to generate all the numbers from 0 to infinity like the function implies, and returns them all at once, this program, that only uses 10 of them, would be much, much slower. That's the benefit of lazy evaluation - what's never used is never calculated.


text:
Q: How to use a UIScrollview to create a thumb wheel with the dynamic speed? UIThumbWheel
I'm developing a wheel, like an old fashioned volume control, that sticks out of the side of a  UIView and returns values. The issue I'm having is how to marry UIScrollView to the task while having the knob accelerate based upon the users speed of scrolling. For clarity my mock-up of the wheel would look like this.

I have create a UIScrollView that removes and add subviews to make the wheel. The issue I'm having is making the wheel control adjust the size of the returned values based upon the speed the user is spinning the wheel. The values of the three speed profiles should add to the sum total, slow (+500), medium (+1000), and fast (+10000). In order to maintain the rubber-banding at zero and the upper-bound I am using the contentOffset for display values.
When I try to manipulate the scrollView.bounds, or contentOffset by adding the movement based upon speed I end up with a stuttery experience. If I ignore the contentSize window, a la infinite scrolling, I lose the rubber-banding values.
Does anyone know how to get both speed-based movement and rubber-banding ends?

A: This is a nice little challenge you're facing with this, i like that! :)
Right now I'm developing something similar, sort of an rotational wheel like control with inertia spin and "rubber-banding" when reaching a certain threshold etc.!
If i got you right, you're using a UIScrollView for your control AND you're trying to use/abuse the already existing bouncing "feature" of the UIScrollView right? Do you have a problem with calculating the speed values based on the scrolling speed or does the kicking-in rubber-banding causing problems?
Did you consider implementing the rubber-banding effect on your own, via "touchesBegan.."/"touchesMoved"? Mimicking the rubber-banding is quite simple: from a certain threshold value on the on-screen movement of the view would be half the finger-drag movment until total stop.
see also: Mimicking the "rubber band" effect from iOS in the Gallery on Android
You could also check out the implementation of iCarousel maybe. It has similar "rubber-banding" effects custom programmed.
I know this is not an satisfying response/answer, but maybe it points your thoughts into some other direction.


text:
Q: iOS prev/next article or page in common apps using hardware volume buttons I'm trying to develop a tweak on my jailbroken iPhone to change the pages in Reeder, iBooks, etc. using the volume buttons but I'm stuck at the part where I tell the app what to do when I press the buttons. I found out that I can't simulate a touch so what options do I have?
Thanks.

A: What your going to need to do to tell the app to turn the pages is look through the header files for each app, and find methods that are used to turn the pages. The methods will most likely be different for each.
Once you've found them your going to need to hook some sort of initialization method and add the objects as an observer of AVSystemController_SystemVolumeDidChangeNotification, and set the selector to the one that you found previously.
Don't forget to remove the observer when the page view goes away, or when its no longer needed, otherwise you will get a crash.

A: Handle AVSystemController_SystemVolumeDidChangeNotification
like this
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:)
                                        name:@"AVSystemController_SystemVolumeDidChangeNotification"
                                        object:nil];

-(IBAction)volumeChanged:(id)sender{
  [volumeViewSlider _updateVolumeFromAVSystemController];
}


text:
Q: Get random element from Graphcool? Is it possible to return a random graphql element from a Graphcool backend? If so, how could this be done?
Alternatively, any tips on howto create custom queries for Graphcool backends?

A: The best way to do this is by using the API Gateway pattern.
The idea of that approach is to put a gateway server on top of Graphcool's CRUD API and thus customize the API. With this approach, you'd write an additional resolver function that retrieves the random element for you:
const extendTypeDefs = `
  extend type Query {
    randomItem: Item
  }
`

const mergedSchemas = mergeSchemas({
  schemas: [graphcoolSchema, extendTypeDefs],
  resolvers: mergeInfo => ({
    Query: {
      randomItem: {
        resolve: () => {
          return request(endpoint, allItemsQuery).then(data => {
            const { count } = data._allItemsMeta
            const randomIndex = Math.floor((Math.random() * (count-1)) + 0)
            const { id } = data.allItems[randomIndex]
            return request(endpoint, singleItemQuery, { id }).then(data => data.Item)
          })
        },
      }
    },
  }),
})

I created a full example of this here. Let me know if you have any additional questions :)


text:
Q: DLL compilation Error I have a problem again. I was able to compile my DLL properly. But once I begin linking it to a ready-to-compile executable. Something happens.
Here's the CMD:
>gcc -c -o dllmain.o dllmain.c -D ADD_EXPORTS
>gcc -o dllmain.dll dllmain.o -s -shared -Wl,--subsystem,windows

This part turned out just fine and produced a seemingly good-looking dllmain.dll.
Here's where the problem starts:
>gcc -c -o dllmain.o dllmain.c
>gcc -o main.exe -s main.o -L. -ladd
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: cannot find -ladd
collect2.exe: error: ld returned 1 exit status

Can someone tell me why it appears? (All filenames are triple-checked and are correct!)
Here's "dllmain.c"
/* Replace "dll.h" with the name of your header */
#include "dll.h"
#include <windows.h>
#include <stdio.h>

DLLIMPORT void HelloWorld()
{
    MessageBox(0,"Hello World from DLL!\n","Hi",MB_ICONINFORMATION);
}

DLLIMPORT CALL add(int a, int b)
{
   return a + b;
}

DLLIMPORT CALL subtract(int a, int b)
{
    return a - b;
}

DLLIMPORT CALL multiply(int a, int b)
{
   return a * b;
}

DLLIMPORT CALL divide(int a, int b)
{
    if(b = 0)
    {
        MessageBox(0, "Cannot divide by zero!", "Division Error", 1);
        return;
    }
    return a / b;
}

DLLIMPORT CALL modulo(int a, int b)
{
    if(b = 0)
    {
        MessageBox(0, "Cannot divide by zero!", "Modulo Error", 1);
    }
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
{
    switch(fdwReason)
    {
        case DLL_PROCESS_ATTACH:
        {
            break;
        }
        case DLL_PROCESS_DETACH:
        {
            break;
        }
        case DLL_THREAD_ATTACH:
        {
            break;
        }
        case DLL_THREAD_DETACH:
        {
            break;
        }
    }

    /* Return TRUE on success, FALSE on failure */
    return TRUE;
}

Here's "dll.h"
#if ADD_EXPORTS
#define DLLIMPORT __declspec(dllexport)
#else
#define DLLIMPORT __declspec(dllimport)
#endif

#define CALL __cdecl

#ifdef __cplusplus
extern "C"
{
#endif

DLLIMPORT void HelloWorld();
DLLIMPORT CALL add(int a, int b);
DLLIMPORT CALL subtract(int a, int b);
DLLIMPORT CALL multiply(int a, int b);
DLLIMPORT CALL divide(int a, int b);
DLLIMPORT CALL modulo(int a, int b);

#ifdef __cplusplus
}
#endif

Finally, "main.c"
#include <stdio.h>
#include <stdlib.h>
#include "dll.h"

main()
{
    int a, b, c;
    char chc;
    printf("Input 2 numbers: ");
    printf("Input operation: ");
    scanf("%c", &chc);
    switch(chc)
    {
        case '+': addition(a, b); break;
        case '-': subtraction(a, b); break;
        case '*': multiply(a, b); break;
        case '/': divide(a, b); break;
        case '%': modulo(a, b); break;
    }
    getch();
}

A: Simply use :
gcc -o main.exe main.c dllmain.dll
Linker looking for libadd.a , which doesn't exist in your case
Also for compiling you don't have to supply dllmain.o


text:
Q: Как при кнопке "Вернуться назад" сохранить вводные данные на предыдущей странице? я ввожу в input личные данные и при клике кнопки "Далее" я перехожу на другую страницу. В другой странице есть кнопка "Вернуться назад". Как сохранить вводные данные на предыдущей странице нажав на кнопку "Вернуться назад"?

A: Если это не SPA страницы, то вам нужно повесить обработчики на поля, которые при изменении поля будут записывать значения например в LocalStorage.
При инициализации страницы доставать оттуда значения и устанавливать инпутам
Если SPA и вы используете какой-то фреймворк, то внимательнее почитайте мануалы


text:
Q: Copying DVD's to my HDD Now here's what I want to do - I have a lot of Movie DVD's and Bluerays.  I want to copy some of them to my HDD.  In Windows I know how to do this,  but not in Ubuntu.  With Windows u use a DvD Ripper,  what can u use in Ubuntu ?
I would be glad for a solution - thanx !!!


text:
Q: How can I have a div with multiple children in ActiveAdmin/Arbre I have this code:
div class: item.ui_type do
  link_to image_tag(item.image.image_public_url), item.target)
  link_to item.label, item.target
end

Basically, I want a div with 2 links inside. However, only the last element is getting rendered, presumably because what gets rendered inside the body is the return value of the block.
I know I can declare those as an array and join them, but then I need to call html_safe. I'm trying to find a way to do this when you actually don't trust the input that you're receiving.
This seems like it should be an extremely simple thing to do, but I can't find it anywhere.
Any pointers?

A: I suspect the reason atomdev's example works and Daniel's does not is that link_to is a Rails tag helper and a is an Arbre tag, see this similar issue.  Try wrapping link_to with text_node, div or span.  It might be worth opening an Arbre GitHub issue for this.

A: Here's what I did to add two links inside the div
div(:class => "some_class") do
  [
    link_to("Link1", link1_path),
    link_to("Link2", link2_path)
  ].join.html_safe
end

Behind it does is first, create the link tag in strings inside an array, second, you join these strings and make it html_safe so div can accept it.


text:
Q: Double fetch to the nodejs server with undefined originalUrl I'm fetching a request to a nodeJS backend to query data from sql express server via the mssql library.  I make 2 requests to the server via fetch, first the users then the groups inside the THEN clause of the first promise and it works fine.
The problem is that when the THEN clause is executed the nodeJS backend receives a new request ( a third one ) with the req.originalURL with the value /undefined.
How can I avoid this third call to nodeJS ?
function readGroups(){
    const comando=`/grupos?id=1`
    var grupos=fetch(comando);      // generates a request.
                                    // and nodeJS sends data back. Thats Ok

    grupos.then(datos=>{   // But when I press F11 here it generates a new
                           // request to nodeJS with the req.originalURL
                           // with the value : /undefined

         return datos.json().then(data=>{return data;});
    }).then(datosJson=>{
        crearListaGrupos(datosJson);
    })
}

// Server side
app.get("*",(req,res)=>{
    console.log(req.originalUrl);   // it's /undefined
});


text:
Q: Return a value when WebBrowser finished loading Windows Phone I am trying to retrieve data from a WebBrowser with js .
I must wait my webView is loaded and then execute my js code and then my method returns the value .
Here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.Windows.Controls;
using System.Windows.Threading;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows;

namespace MobilAirSdk.Analytics.utils
{
    public class UserAgentHelper
    {
        static private Dictionary<string, string> uaDict;
        static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
        static WebBrowser browser;

        static string displayValue = null;

        public static Dictionary<string, string> GetUserAgent()
        {
            if (uaDict == null)
            {
                uaDict = new Dictionary<string, string>();

                Deployment.Current.Dispatcher.BeginInvoke( new Action( () =>
                {

                browser = new WebBrowser ();
                browser.IsScriptEnabled = true;
                browser.LoadCompleted += browser_LoadCompleted;

                browser.NavigateToString(@"<!DOCTYPE html>");

                  }));

                thread1Step.WaitOne();

            }
            return uaDict;
        }

        static void browser_LoadCompleted(object sender, NavigationEventArgs e)
        {
            displayValue = (string)browser.InvokeScript("fingerprint_display");
            uaDict.Add("display", displayValue);
            thread1Step.Set();
        }
    }
}

The problem is that my browser.Navigating is never called , and the application remains blocked.
Have you any idea?
thank you

A: Hello for those interested here is the solution :
public class UserAgentHelper
{
    static private Dictionary<string, string> uaDict;
    static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
    static WebBrowser browser;

    static string displayValue = null;

    public async static Task<Dictionary<string, string>> GetUserAgent()
    {
        TaskCompletionSource<Dictionary<string, string>> tcs = new TaskCompletionSource<Dictionary<string, string>>();

        if (uaDict == null)
        {
            uaDict = new Dictionary<string, string>();

            LoadCompletedEventHandler loadCompleted = null;
            loadCompleted = (_, __) =>
            {
                browser.LoadCompleted -= loadCompleted;
                displayValue = (string)browser.InvokeScript("fingerprint_display");
                uaDict.Add("display", displayValue);
                tcs.TrySetResult(uaDict);
            };

            Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
            {

                browser = new WebBrowser();
                browser.IsScriptEnabled = true;
                browser.LoadCompleted += loadCompleted;

                browser.NavigateToString(@"<!DOCTYPE html>");

            }));

            return await tcs.Task;
        }
        else return uaDict;

    }
}


text:
Q: DayPicker days not clickable REACT I tried to use this react-day-picker component to pick a single day on my site but it is not clickable.
I took the code from https://react-day-picker.js.org/ and there they show the day is clickable I did not understand what I did wrong
(i tried all their codes none is clickable )
this is the code I am using-
import React, { useState } from 'react';
import { DayPicker } from 'react-day-picker';

import { format } from 'date-fns';

export default function App() {
    const [selectedDay, setSelectedDay] = useState<Date>("");

    const footer = selectedDay
        ? `You selected ${format(selectedDay, 'PPP')}.`
        : `Please pick a day.`;

    return (
        <DayPicker
            mode="single"
            selected={selectedDay}
            onSelect={setSelectedDay}
            footer={footer}
        />
    );
}


text:
Q: How to get event when word process stopped in vb.net I am using ManagementEventWatcher to get message when process start and stop.
I am successfully getting message when word process start it displays me File name and datetime.
I have an issue in stopping process.
Public Class Form1
    Dim list As New List(Of String)
    Dim list1 As New List(Of String)
    Private processStartEvent As ManagementEventWatcher = New ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace")
    Private processStopEvent As ManagementEventWatcher = New ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace")

    Public Sub New()
        InitializeComponent()
        AddHandler processStartEvent.EventArrived, New EventArrivedEventHandler(AddressOf processStartEvent_EventArrived)
        processStartEvent.Start()
        AddHandler processStopEvent.EventArrived, New EventArrivedEventHandler(AddressOf processStopEvent_EventArrived)
        processStopEvent.Start()
    End Sub

    Private Sub processStartEvent_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
        Dim allProcesses = Process.GetProcesses().Where(Function(p) p.ProcessName.Contains("WINWORD"))
        Dim windowTitles = ChildWindowManager.GetChildWindowTitles(allProcesses.First().Id)
        For Each title In windowTitles
            If (title.Contains("- Word")) Then
                If Not (title.Contains("Opening - Word")) Then
                    If Not list.Contains(title) Then
                        list.Add(title)
                        MessageBox.Show("+ Process Started. File Name: " & String.Join(",", list.Item(list.Count - 1)) & " | Date & Time: " & System.DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") & vbNewLine & vbNewLine)
                    End If
                End If
            End If
        Next
    End Sub

    Private Sub processStopEvent_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)

    End Sub
End Class

Class ChildWindowManager
    Delegate Function EnumThreadDelegate(ByVal hWnd As IntPtr, ByVal lParam As IntPtr) As Boolean

    <DllImport("user32.dll")>
    Private Shared Function EnumThreadWindows(ByVal dwThreadId As Integer, ByVal lpfn As EnumThreadDelegate, ByVal lParam As IntPtr) As Boolean
    End Function

    <DllImport("user32.dll")>
    Public Shared Function GetWindowText(ByVal hwnd As Integer, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
    End Function

    <DllImport("user32.dll")>
    Private Shared Function GetWindowTextLength(ByVal hwnd As IntPtr) As Integer
    End Function

    Private Shared Function EnumerateProcessWindowHandles(ByVal processId As Integer) As List(Of IntPtr)
        Dim windowHandles = New List(Of IntPtr)()

        For Each thread As ProcessThread In Process.GetProcessById(processId).Threads
            EnumThreadWindows(thread.Id, Function(hWnd, lParam)
                                             windowHandles.Add(hWnd)
                                             Return True
                                         End Function, IntPtr.Zero)
        Next
        Return windowHandles
    End Function

    Private Shared Function GetWindowTitle(ByVal hWnd As IntPtr) As String
        Dim length As Integer = GetWindowTextLength(hWnd)
        If length = 0 Then Return Nothing

        Dim titleStringBuilder As New System.Text.StringBuilder("", length)

        GetWindowText(hWnd, titleStringBuilder, titleStringBuilder.Capacity + 1)
        Return titleStringBuilder.ToString()
    End Function

    Public Shared Function GetChildWindowTitles(processId As Integer) As List(Of String)
        Dim windowTitles As New List(Of String)

        For Each Handle In EnumerateProcessWindowHandles(processId)
            Dim windowText = GetWindowTitle(Handle)
            If windowText <> Nothing Then
                windowTitles.Add(windowText)
            End If
        Next

        Return windowTitles
    End Function
End Class


text:
Q: ExceptionFilterAttribute not handling properties exceptions I implemented an ExceptionFilterAttribute class and registered it in the WebApiConfig class.
The action filter works good and handles any exception happened in any action but the problem is: when an exception happens while in any of the controller properties the action filter not handle this exception
[NotImplExceptionFilterAttribute]
public class AnyController : APIController
{
    private readonly ModelDBContext _db = new ModelDBContext();

    //some actions
}

in the mentioned example, the constructor of ModelDBContext contains some logic which may cause exception. This exception will not be handled by the ExceptionFilterAttribute. Why??? And how to handle it?

A: basically, simple answer is simple: exception filter is action-level filter.
Check this diagram first: http://blogs.msdn.com/b/kiranchalla/archive/2012/05/06/asp-net-mvc4-web-api-stack-diagram-currently-in-development.aspx
Then navigate to ApiController, line #232. There you can see that if there is at least one filter then ExceptionFilterResult will be used to wrap end action result.
Inside ExceptionFilterResult there is simple try-catch, if exception is thrown then all registered exception filters are called.
So, short summary of everything written above:
1) exception filter is not responsible for handling errors above controller's action
2) exception filter does not exist at the moment when controller's instance is created by DI container and when your ModelDBContext throws an exception
I hope this answers your question.

A: The problem is scope.
When the controller is instanced the private class member _db will initialize before any class methods execute. This is a CLR behavior.
Thus, an action filter will not catch an exception incurred during construction/initialization of your controller object, such as a failure to construct a ModelDBContext instance.
One solution is to create and dispose of ModelDBContext instances on every request, and some may argue this is the proper approach if you intend to gracefully handle (or log) connectivity failures (whether it's to a DB or a back-end service.)
You may also find IServiceLocator and a framework such as 'Unity' or 'Ninject' useful so that you're not "hardcoding" new ModelDBContext(); statements everywhere, but that's another subject. The root cause is you're initializing outside of the scope of an action method, action filters won't catch it.


text:
Q: PDO: Pasar LAST_INSERT_ID de un método INSERT a otro método SELECT Mi intención es la de realizar al mismo tiempo la inserción de un registro y obtener el id (AUTO_INCREMENT) del mismo para usarlo como FK para insertar en otra tabla varios registros que la usarán. Primero quiero realizar una select, para más tarde crear un tercer método con el segundo insert, pero necesito saber cómo pasar esa ID de un método al otro.
//**
// INSERT

public function inserT(){
    $conexion = new Conexion();
    $consulta = $conexion->prepare('INSERT INTO '.self::TABLA.' (tienda_nombre) VALUES (:id_tipotienda,:tienda_nombre)');
    $consulta->bindParam(':tienda_nombre',  $this->tienda_nombre);
    $consulta->execute();
    $this->id= $conexion->lastInsertId();

}

En la misma clase pretendo usar otro método que recoja la última ID insertada resultante del lastInsertId
//**
// SELECT

public function selecT(){
    $conexion = new conexion();
    $consulta = $conexion->prepare("SELECT * FROM " . self::TABLA ." where id_tienda = :id_tienda");
    $consulta->execute(array(':id_tienda' => LAST_INSERT_ID));
    $registro = $consulta->fetch();
    if($registro){
        return new self($registro['tienda_nombre'],$id_tienda);
    } else {
        return false;
    }
}

Que luego recogeré con otra llamada desde otro fichero.
Necesito saber cómo pasar esa id de un método al otro
EDIT: Añado la clase completa
            class Tienda {

                private $id_tienda;
                const TABLA = 'generica_tienda';

                public function getId(){
                    return $this->id_tienda;
                }
                public function getNombre(){
                    return $this->tienda_nombre;
                }
                public function setId(){
                    $this->id_tienda = $id_tienda;
                }
                public function setNombre(){
                    $this->tienda_nombre = $tienda_nombre;
                }

                public function __construct($tienda_nombre,$id_tienda=null)
                {
                    $this->id_tienda = $id_tienda;
                    $this->tienda_nombre = $tienda_nombre;
                }

                public function inserT(){
                    $conexion = new Conexion();
                    $conexion->exec("SET NAMES 'utf8'");
                    $consulta = $conexion->prepare('INSERT INTO '.self::TABLA.' (tienda_nombre) VALUES (:tienda_nombre)');
                    $consulta->bindParam(':tienda_nombre',  $this->tienda_nombre);
                    $consulta->execute();
                    $id_tienda= $conexion->lastInsertId();
                }

                public static function selecT(){
                    $conexion = new conexion();
                    $conexion->exec("SET NAMES 'utf8'");
                    $consulta = $conexion->prepare("SELECT * FROM " . self::TABLA . " WHERE id_tienda = :id_tienda ");
                    $consulta->execute(array(':id_tienda' => $id_tienda));
                    $registro = $consulta->fetch();
                    if($registro){
                        return new self($registro['tienda_nombre'], $id_tienda);
                    } else {
                        return false;
                    }
                }
            }


text:
Q: My com.mongoDB jar file don't have a mongoClient
When I connect to mongoDB with java, my mongodb jar doesn't have a mongoClient, I don't know why ? pls help me fixes

A: You need Mongo Java Driver (JAR from Sonatype)
And here's Mongo Java Driver documentation


text:
Q: "'Calloc 'could not allocate memory" in 64-bit R I'm on Windows Server 2012 (64-bit) with 30.5 GB of RAM, running R v3.1.2 in RStudio 0.98, and am still having trouble with R hitting a memory limit.
I reviewed the FAQ here: http://cran.r-project.org/bin/windows/base/rw-FAQ.html#There-seems-to-be-a-limit-on-the-memory-it-uses_0021
Which states that the memory limit on 64-bit instances defaults to the total amount of RAM, and that the limit can be checked and set using memory.limit().
A call to memory.limit() returns 31249, confirming that it's able to see and use all 30 gigs.
However, when I make a modeling call on a large dataset (~10M rows):
ctree(as.formula(formula), data=d, control=ctree_control(mincriterion=0.9, minbucket=1000))

I get the following error:
'Calloc' could not allocate memory (18446744073673801728 of 8 bytes)

But looking at the system task manager I can see that over 25GB is still available, and that R is only using 2.3GB.
Running the modeling outside of RStudio and in R directly yields the same result, so RStudio isn't the variable.
I'm perplexed - why does R refuse to use all my memory?

A: The problem was a bug in the C code underlying the ctree() function (as correctly suspected by @JoshuaUlrich). The reason was an integer overflow that has been fixed now in the libcoin package version 1.0-2 that the partykit package builds on.
(Comments: We didn't learn about this bug earlier because the party tag was not used for the question here on StackOverflow and the problem was not reported to the package maintainer until today. Thanks to Kris Joanidis who reported the problem and also provided a patch, very much appreciated.)


text:
Q: How many subsets of three different integers between $1$ and $90$ inclusive are there whose sum is an even number
How many subsets of three different integers between $1$ and $90$ inclusive are there whose sum is an even number?

If I am not wrong then there are $45$ odd numbers and $45$ even . Also $$\text{even}+\text{even}+\text{even}=\text{even},\quad
\text{odd}+\text{odd}+\text{even}=\text{even}.$$
But we need 3 different integers subset. How should I proceed?

A: The sum of three numbers is even iff they are all even or there is one even and two odds. Hence if the three numbers belong to a set with $E$ even numbers and $O$ odd numbers then, in the first case the number of ways is $\binom{E}{3}$ and in the second case $\binom{E}{1}\cdot \binom{O}{2}$.

A: Hint for an easier calculation:
You might find it useful to consider the sets $\{a,b,c\}$ and $\{(91-a), (91-b), (91-c)\}$ and show that half the sets of three distinct elements have an even sum.

A: $$\binom{45}{2}\binom{45}{1}+\binom{45}{3}.$$


text:
Q: Подскажите как правильно написать SELECT Здравствуйте, подскажите как правильно записать цикл для создания массива значений meta_value после выборки. Пытаюсь так:
$team_id = (int)$slug;
$team_id=(string)preg_replace('/[^A-Za-z0-9]/', '', $team_id);
global $wpdb;
$newtable = $wpdb->get_results( "SELECT meta_id FROM wp_cfs_values where post_id='". $team_id ."'" );

$res=json_encode($newtable);
var_dump($res);
$wpdb->close();
foreach($res as $item)
{

    $newres=[];
    $newtable = $wpdb->get_results( "SELECT meta_value FROM wp_postmeta where meta_id='". $item['meta_id'] ."'" );
    $newtable['meta_value']=$newres['meta_value'];

}

$res=json_encode($newres);

return var_dump($res);

}
вардамп $res:
string(267) "[{"meta_id":"1630"},{"meta_id":"1631"},{"meta_id":"1632"},{"meta_id":"1633"},{"meta_id":"1634"},{"meta_id":"1635"},{"meta_id":"1636"},{"meta_id":"1637"},{"meta_id":"1638"},{"meta_id":"1639"},{"meta_id":"1640"},{"meta_id":"1641"},{"meta_id":"1642"},{"meta_id":"1643"}]" string(4) "null" 0

Вангую что не очень хорошо пытаюсь в цикле делать запросы по ключам, но как иначе? В общем подскажите куда копать.


text:
Q: Exc bad access after populating NSMutableArray with custom class extending CLPlacemark I have a PlaceAnnotation class that I fill into an NSMutableArray.  In viewDidLoad, i initiate ihatethis
_ihatethis = [[NSMutableArray alloc]init];

I use a MKLocalSearchCompletionHandler to search. And handle the mapitems like this:
for (MKMapItem *mapItem in [response mapItems]){

     PlaceAnnotation *place = [[PlaceAnnotation alloc] init];
     [place assignTitle:[[mapItem placemark] name];

     [_ihatethis addObject:place];
}

[_ihatethis removeObjectAtIndex:2]; /*BAD ACCESS HERE*/
[_tableView reloadData];

This is my PlaceAnnotation.h file
@interface PlaceAnnotation : CLPlacemark <MKAnnotation>

@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, readonly, copy) NSString *title;
@property (nonatomic) NSDictionary* dict;
//@property (nonatomic) NSURL *url;
@property (nonatomic) NSString *phoneNum;
@property (readonly) BOOL selected;

-(void)assignTitle:(NSString *)newTitle;
-(void)assignSelected:(BOOL) boolVal;

This is my PlaceAnnotation.m file
#import "PlaceAnnotation.h"

@interface PlaceAnnotation ()

@property (readwrite) NSString *title;
@property (readwrite) BOOL selected;

@end

@implementation PlaceAnnotation

-(void) assignTitle:(NSString *)newTitle {
    if ( ![newTitle isEqualToString:[self title]]){
        self.title = newTitle;
    }
}

-(void) assignSelected:(BOOL)boolVal{
    self.selected = boolVal;
}

@end

@end

This is my first post, I have read a ton of answers that responded to exc_bad_access questions and I cannot figure this out.  So I think that somehow the placeannotations are getting forgotten and released. So when i go to delete is later it is gone. I really am confused and angry.

A: If the crash really is in this line [_ihatethis removeObjectAtIndex:2]; and it's a EXC_BAD_ACCESS then there are two possibilities:

*

*_ihatethis is pointing to a broken array (unlikely, if the loop went through).

*An object in the array has been overreleased or has broken memory management in its dealloc method.

A: It may be that you're trying to remove an item at an index greater than the array's count. Try to output the count just before [_ihatethis removeObjectAtIndex:2];, like this:
`
NSLog(@"count: %d", [_ihatethis count]);
[_ihatethis removeObjectAtIndex:2]; /*BAD ACCESS HERE*/
`

If the count is smaller than 3, then you're trying to remove an object at an index outside the array's bounds.

A: I changed this
@interface PlaceAnnotation : CLPlacemark <MKAnnotation>

to this
@interface PlaceAnnotation : NSObject <MKAnnotation>

so i guess the problem was with the dealloc of CLPlacemark. Thanks


text:
Q: Jquery: function running before fadeOut Complete I'm having an issue with my jquery script... should an easy task, but having some strange behaviours that I can't figure out.
When I click on a link, I want my content to disappear, then the new content to reappear. All content is stored in  tags.
Here's what I'm using:
$("#events_link").click(function() {
   $("#content").children(".content").fadeOut(fadetime, function() {
      $("#events").fadeIn(fadetime);
   });
   return false
});

However, the fadeIn is not waiting until the content has faded out.
My full page is here (all code/script on one page):
http://dl.dropbox.com/u/4217965/HorrorInTheHammer/index.html
Any thoughts?

A: This will run for each of the .content_box elements...and the hidden ones will finish their animation immediately, so you want is this:
$("#events_link").click(function() {
   $("#content > .content_box:visible").fadeOut(fadetime, function() {
      $("#events").fadeIn(fadetime);
   });
   return false
});

The important change is the :visible selector, so only the visible one is faded out...and triggers the callback to show the next one.

A: windows.setTimeout is not always useful because sometimes the process might take more time than the timeout you have set. So it's better to use following code to run fadeIn only after fadeOut is done.
$("#events_link").click(function() {
   $.when(
      // Your function which you want to finish first
      // $("#content").children(".content").fadeOut(fadetime)
   ).done(function() {
      // The function which you want to run after finishing the previous function
      // $("#events").fadeIn(fadetime);
   });
   return false
});*

A: The current version of your page doesn't appear to be working at all because you have something like
$("#content").children(".content")

instead of
$('#content').children('.content_box')

Fix that and it will be easier to troubleshoot...
EDIT (now that above fix is done):
It does seem like the fadeOut function is not working quite as documented, at least in Firefox 3.5, in regard to callbacks.  I think what you probably want can be accomplished by using a little plain-old javascript:
$('#content').children('.content_box').fadeOut(fadetime);
window.setTimeout(function () { $('#events').fadeIn(fadetime); }, fadetime + 100);
return false;

I think that will more likely accomplish what you want by trying to ensure that the old content is gone and no longer actually taking up space before fading in the new content.  Let us all know if it works for you.


text:
Q: Simple Question regarding Java Web Start Applications Can a Java application launched using Java Web Start perform read/write operations
on user's hard drive. I know that this is not the case with java script embedded
in a web page. Basically what I am asking are there any such restrictions with
a java application invoked using a web browser?
Kurt
I am having trouble using the {} to insert code
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="file:///c:/Users/OPTRADER/" href="trader.jnlp">
  <information>
    <title>Optrader</title>
    <vendor>DS Software</vendor>
    <description>Optrader JNLP Demo </description>
    <offline-allowed/>
  </information>
  <resources>
    <jar href="Optrader.jar"/>
    <j2se version="1.6+" href="java.sun.com/products/autodl/j2se"/>
  </resources>
  <application-desc main-class="Optrader"/>
</jnlp>
    {

    Optrader
    DS Software
    Optrader JNLP Demo

A: Yes they can.  In the JNLP file for the application you can specify if the application has All permissions.  It can operate just like a normal Java desktop application.   The difference is that you need to sign the jars if you are going to grant the permission.  However, you have the ability to sign them yourself.

A: By default these applications run in a Sandbox to protect users from malicous code, so I'd say "no".

A: For a sand-boxed local file access with Webstart (and with JNLP-applets to, from Java 6, update 10, when the new plugin came out), use the services in the javax.jnlp package (linked from the Webstart documentation page.
In this case, a FileOpenService and/or FileSaveService lets the user confirm the action and select a file in a filechooser, and you then get a FileContents object, which you can then read from or write to.
You don't need special permissions for that, not even sign your code (but I think if you do, the confirmation dialog looks less intimidating, as it contains the information who wants this).
If you want to see how it looks like from user perspective, use our Applet here and select custom picture.

A: From your comments it seems that your problem is something completely different than in your original question.
To start your Webstart-application, save the XML file you have there under the name trader.jnlp in your directory c:/Users/OPTRADER/, and then double-click on it. If webstart is configured right and the jar file is also in the right place, it now should start your program.
If you get some error message saying that Windows does not now what to do with your file, then you should reinstall Java webstart (or your JRE/JDK).
If you get some error message from Webstart, add this message to your question (there is an edit link below it).
If your program runs and you have some other problem, describe the problem (also in your question).


text:
Q: How to truncate using std in Varnish VCL I'm trying to truncate a random number that I use for Varnish VCL, coming from STD vmod.
The problem is that std.real2integer() values are passed only to std.round(), that, as you can guess, can only round them :-(
Any ideas?

A: Not beautiful at all, but an option would be regsub(std.random(0.0, 100.0), "\.\d+$", "");.


text:
Q: What are some useful non-built-in Django tags? I'm relatively new to Django and I'm trying to build up my toolbox for future projects.  In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature.  I later would find a template tag that would have saved me time and ugly code.
So what are some useful template tags that doesn't come built into Django?

A: I'll start.
http://www.djangosnippets.org/snippets/1350/
Smart {% if %} template tag
If you've ever found yourself needing more than a test for True, this tag is for you.  It supports equality, greater than, and less than operators.
Simple Example
{% block list-products %}
    {% if products|length > 12 %}

    {% endif %}

{% endblock %}

A: smart-if. Allows normal if x > y constructs in templates, among other things.
A better if tag is now part of Django 1.2 (see the release notes), which is scheduled for release on March 9th 2010.

A: James Bennet's over-the-top-dynamic get_latest tag
edit as response to jpartogi's comment
class GetItemsNode(Node):
    def __init__(self, model, num, by, varname):
        self.num, self.varname = num, varname
        self.model = get_model(*model.split('.'))
        self.by = by

    def render(self, context):
        if hasattr(self.model, 'publicmgr') and not context['user'].is_authenticated():
            context[self.varname] = self.model.publicmgr.all().order_by(self.by)[:self.num]
        else:
            context[self.varname] = self.model._default_manager.all().order_by(self.by)[:self.num]
        return  ''

{% get_sorted_items cms.news 5 by -created_on as items %}
{% include 'snippets/dl.html' %}

{% get_sorted_items cms.event 5 by date as items %}
{% include 'snippets/dl.html' %}

I call it get_sorted_items, but it is based on James' blog-post

A: In come case {% autopaginate queryset %} (http://code.google.com/p/django-pagination/) is useful. For example:
#views.py
    obj_list = News.objects.filter(status=News.PUBLISHED)
    # do not use len(obj_list) - it's evaluate QuerySet
    obj_count = obj_list.count()

#news_index.html
    {% load pagination_tags %}
    ...
    # do not use {% if obj_list %}
    {% if obj_count %}

        {% autopaginate obj_list 10 %}
        {% for item in obj_list %}

{{ item.title }}

        {% endfor %}

        {% paginate %}
    {% else %}
        Empty list
    {% endif %}

Note, that obj_list must be lazy - read http://docs.djangoproject.com/en/dev/ref/models/querysets/#id1


text:
Q: Sparql - Concatenation fails if any one variable is not bound Hi am using AllegroGraph and Sparql query to retrieve the results. This is a sample data that reproduces my issue.
Consider below data where a person has first, middle and last names.
<http://mydomain.com/person1> <http://mydomain.com/firstName> "John"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>
<http://mydomain.com/person1> <http://mydomain.com/middleName> "Paul"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>
<http://mydomain.com/person1> <http://mydomain.com/lastName> "Jai"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>
<http://mydomain.com/person1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://mydomain.com/person>

<http://mydomain.com/person6> <http://mydomain.com/middleName> "Mannan"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>
<http://mydomain.com/person6> <http://mydomain.com/lastName> "Sathish"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>
<http://mydomain.com/person6> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://mydomain.com/person>

Now I need to compute the persons name by combining the all 3 names. The names are optional and a person may not have any of the first, middle and last names.
Query I tried
select ?person ?name ?firstName ?middleName ?lastName where
{
  ?person rdf:type  <http://mydomain.com/person>.
    optional {?person <http://mydomain.com/firstName> ?firstName}.
    optional {?person <http://mydomain.com/middleName> ?middleName}.
    optional {?person <http://mydomain.com/lastName> ?lastName}.
    bind (concat(str(?firstName),str(?middleName),str(?lastName)) as ?name).
}

But the result set does not contain the name for person6 (Mannan Sathish) since the first name is not present. Please let me know if I can ignore the firstName if it's not bound.

A: If a variable is not bound then str(...) will cause an error on evaluation and the whole BIND fails.
COALESCE can be used to give default values to expressions.
bind ( COALESCE(?firstName, "") As ?firstName1)
bind ( COALESCE(?middleName, "") As ?middleName1)
bind ( COALESCE(?lastName, "") As ?lastName1)
bind (concat(str(?firstName1),str(?middleName1),str(?lastName1)) as ?name


text:
Q: How should a person holding a foreign military rank be addressed? While researching how to call a person that holds a rank at a foreign (non English speaking) military, I came to very confusing results:
Wikipedia is not consistent on the issue:

*

*it sometimes gives the rank in the native language alone, as in the case for Erwin Rommel, Heinrich Himmler, Heinz Guderian, and Gerd von Rundstedt, all of whom are German, and the current Israeli Chief of General Staff Benny Gantz.

*In other cases, it gives the rank in the native language with an equivalent rank in English, as in the case for Israel Tal who was an Israeli general.

*And sometimes it only gives the equivalent rank, as in the case of Israeli Medal of Valor  recipient Zvika Greengold and Japanese military aviator Minoru Genda.
Other sources are also confusing:

*

*The Jewish Virtual Library, in their page about Erwin Rommel call Erwin Rommel, Heinz Guderian and Gerd von Runstedt Field Marshal, even though they have different ranks (Rommel and von Runstedt were Generalfeldmarschall and Guderian was a Generaloberst).

*The site's www.auschwitz.dk page about Himmler give's his rank as Reichsfuhrer-SS, while the United States Holocaust Memorial Museum gives his rank as the translation to English with the German rank in parentheses:

Heinrich Himmler (1900-1945) was the Reich Leader (Reichsführer) of the dreaded SS of the Nazi party from 1929 until 1945

*This article on rt.com about the letters of Erwin Rommel simply call him general.

*The articles in the Independent, the English version of Haaratz, The New York Times and Israel's Armored Corps Memorial Site about Israel Tal's Death all call him Major-General without mentioning the Hebrew rank.
After all of this I'm left confused as I can't really see any pattern of proper use his,

*

*Should the rank in the original language be used, the equivalent "English" rank be used, or a translation of the rank?

*Is there any difference if the original language is a non-Indo-European language vs. an Indo-European language (Hebrew vs. German)?

*In the case that an equivalent rank is used, what set of ranks is the standard (Wikipedia uses the NATO Code)?

*Finally, since my rank is Rav Samal, should I call myself Rav samal, Sergeant First Class (the NATO corresponding rank) or Master Sergeant (the translation)?

A: Your title isn't quite the same as the body of your question: military officers are usually addressed by the simplest form of their rank, such as Colonel for a lieutenant-colonel or General for a major-general; it's a mark of respect, rather than a precise identifier.
If referring to officers in a piece of prose, context is all. A book of Rommel's letters would probably be called The Letters of General Rommel without further specification, since everyone interested knows who is referred to, and understands it covers the period before the subject was promoted to Field Marshal; but the editor might have to specify 'Lieutenant-General Rommel' when explaining why one General was giving orders to another, or even 'Brigadefuhrer Rommel (equivalent to British brigadier or American brigadier-general)' if a point of etiquette came up.
Part of this is because many of the Western (not just Latin) languages use similar terms: German, English and French officers can all be generals, but the pronunciation and responsibilities are different.  The differences are not, however, important unless the armies are so closely allied that a single chain of command may become necessary, which is why NATO has a set of equivalencies and other countries do not.
In your own case, you need to ask yourself 'Is the distinction between a sergeant and a master sergeant important to this person (or is the distinction in his mind important to me)?' If not (including most civilians), you can simply introduce yourself as 'Sergeant Melamed'.  If so, and the person is Israeli, presumably it would be 'Rav Samal Melamed'. Otherwise, the polite way is to use the equivalent in the listener's army, but 'Sergeant First Class' is clear if you don't know how the two compare. 'Master Sergeant' is best avoided professionally (since literal translations can lead to misunderstandings), but it is used in formal contexts; as an example I happen to know, if you were a witness in a British court, the officials (with little or no military knowledge) would be careful not to refer to you merely as Sergeant but the next British rank of Sergeant-Major would be giving you a rank to which you were not entitled, so the precise translation Master Sergeant would be used.

A: You would generally put the ranks in English when they are comparable. For example, you would write Colonel Klink rather than Oberst Klink.    Using the foreign word is generally the sign of pretentious Sunday-supplement writers trying to sound worldly and "cultured".
If you are writing a technical assessment or a military history, then you may need to be more precise, like "Grand-Admiral Von somebody (equivalent to a British rear-admiral or a U.S. Navy fleet commander)".
If there is no comparable rank in English, as with Soviet Commissar or German Führer, then I would use the foreign rank rather than a literal translation.
There are also political considerations to consider, such as how for an Israeli audience, Führer has rather deeper meaning than simply leader.

A:
Finally, since my rank is Rav Samal, should I call myself Rav samal,
  Sergeant First Class (the NATO corresponding rank) or Master Sergeant
  (the translation)?

Generally, it's probably more appropriate to use "Rav samal". "Sergeant First Class" and "Master Sergeant" don't exist in all of the English speaking world. These seem to be mainly American. For example, the UK does not use them. See http://en.wikipedia.org/wiki/British_and_United_States_military_ranks_compared#US_.22Enlisted.22_and_UK_.22Other.22_ranks_compared This means that there is not always, an equivalent rank to translate "Rav samal", into.
An alternative in a general sense would be to use the Ranks and insignia of NATO http://en.wikipedia.org/wiki/NATO_ranks
You could use "Sergeant First Class" and "Master Sergeant" in a particular sense, if you are talking to people who are from countries that do have those ranks, such as Americans.


text:
Q: Create IncomingMessage test dummy in Jest I am trying to write a unit test for a function that takes IncomingMessage as a parameter. I understand it is a stream but I am unsure how to create a basic test dummy as the stream causes my tests to timeout

: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

My class
import { IncomingMessage } from 'http';

export class MyClass
  example(request: IncomingMessage): void {
    console.log(request.get('hello?'))
  }
}

My test
it('test', () => {
  const myclass = new MyClass();

  const request = {
    get: () => 'hello!'
  } as unknown as IncomingMessage

  const response = myclass.example(request);

  expect(response).toEqual('hello!');
});

I assume I need to close the stream so how can I do that when casting a 'dummy' object to type IncomingMessage?
I tried using
const request = {
  get: () => 'hello'
} as unknown as IncomingMessage
request.setTimeout(1)

but then I get an error that the function is not found, which makes sense since the dummy is basically an empty object with only one mocked function

TypeError: request.setTimeout is not a function

In this case I assume I need to actually create a real IncomingMessage? But I cannot find much documentation or examples on how to do this
What is the best way to create a real IncomingMessage stream, close it quickly and have a mocked get method? I think I would then need to mock a socket?
Or what is the correct way to test my class and function in this case?

A: Basically you need to mock your request object that can be done with below snippet:
function _mock_req() {
    let req = {
        get: jest.fn(() => 'hello!'),
    };
    return req;
}

Once mocking is done invoke it in your test case, here I'm using beforeEach that will take care of the issue: openHandler- Async callback was not invoked.
describe('http test', () => {
    let req, res;
    const myclass = new MyClass();

    beforeEach((done) => {
        req = _mock_req();
        res = myclass.example(req);
        done();
    });

    it('class test', () => {
        expect(res).toEqual('hello!');
    });
});

You also need to return request from your class to test get passed. While executing test case your mocked request object will get return from MyClass
export class MyClass {
    example(request: IncomingMessage): void {
        console.log(request.get('hello?'));
        return request.get('hello?')
    }
}

Test case result:

A: If you're not using express and using the built in http library for node you can do the following:
Note: This will also work with express too
import httpMocks from 'node-mocks-http';
import handleRequest from '../../../handlers/request';

describe('incoming message mock', () => {
  it('working example', () => {
    const mockRequest = httpMocks.createRequest({
      method: 'POST',
      url: '/my-fantastic-endpoint',
      headers: {
        'content-type': 'application/json',
        'accept': 'application/json',
        'content-length': '1',
        'x-forwarded-for': '127.0.0.1',
      },
    });

    mockRequest.destroy = jest.fn();

    const mockResponse = httpMocks.createResponse();

    handleRequest(mockRequest, mockResponse);

    mockRequest.send({
      example: 'hello!',
    });

    console.log(mockResponse._getData());

    expect(true).toBe(true);
  });
});


text:
Q: SignalR callback not getting executed even if it receives trigger from backEnd. How to fix it? I'm invoking a signalR connecting and listen to the callBack method. The console log shows that the callback method has been triggered, but the code inside the callback method is not getting executed.
The console log is printed as below:
SignalRConnection.proxy.on invoked. Calling listener next() ...
listener next() called.
The code snippet:
c.invoke('ABC', value, apiToken).then(() => {
        console.log('ABC Connected');
});

//call back method.
c.listenForRaw('receiveABCNotification')
        .subscribe((data: any[]) => {
          console.log('Data received from SIGNALr', data);
});

What should I do to make sure the code inside the listener method(callBack method) gets executed?


text:
Q: MongoDb compass complex filter I have a collection in mongo.
Sample single entry
{
    "_id": {
        "$oid": "6278dc35b07e447b14feef57"
    },
    "formId": "6278d9f7b07e447b14feef54",
    "formData": {
            "0": {
            "value": "297CSSIB"
        },
        "1": {
            "value": "Alba Gonzalez"
        },
        "2": {
            "value": "Concentrix"
        },
        "3": {
            "value": "San Salvador"
        }
    }
}

now I want to filter with formId and value San Salvador. (where formId = "6278d9f7b07e447b14feef54" and index 3 value of formData is San Salvador)
I am unable to find any solution for that Please help.

A: With the current document structure, it is only possible, if the value San Salvador, is always present at index 3.
In that case, the following query should work:
db.collection.find({
  formId: "6278d9f7b07e447b14feef54",
  "formData.3.value": "San Salvador"
})

However, I suggest you change your document structure so that formData is an array since it's keys are just indexes:
{
    "_id": {
      "$oid": "6278dc35b07e447b14feef57"
    },
    "formId": "6278d9f7b07e447b14feef54",
    "formData": [
      {
        "value": "297CSSIB"
      },
      {
        "value": "Alba Gonzalez"
      },
      {
        "value": "Concentrix"
      },
      {
        "value": "San Salvador"
      }
    ]
  }

In this way, the query can be more generic, rather than index specific:
db.collection.find({
  formId: "6278d9f7b07e447b14feef54",
  "formData.value": "San Salvador"
})


text:
Q: Defining primary key as virtual in Entity Framework What's the benefit of defining the primary key attribute as virtual in entity Framework?
AFAIK, virtual is used for lazy loading in navigation properties and for change tracking in other properties. But we don't need any of the mentioned features in primary keys.
So, Is it any use to define primary keys virtual?

A: Change tracking proxies are created only if all non-navigation mapped properties are virtual. MSDN:

Each property that is mapped to a
  property of an entity type in the data
  model must have non-sealed
  (NotOverridable in Visual Basic),
  public, and virtual (Overridable in
  Visual Basic) get and set accessors.


text:
Q: Mockito/GWT : mocked view's widgets are null I got a view (GWT MVP pattern) that contains a listbox.
I created a testcase using @Mock MyView viewThen in one test I want to be able to have a hand on the list box object using :
ListBox listBox = GwtReflectionUtils.getPrivateFieldValue(view, "tableListBox");

This returns null.
I followed this tutorial : http://code.google.com/p/gwt-test-utils/wiki/SimpleUnitTest which using the same way.
The only difference I see is I'm using UIBinder, however it should be supported from what I've read.
Thanks!

A: You are using a mock, of course fields aren't set. When working with mocks you have to think about interactions, not state. (Actually this statement is true with generated mocks like those of mockito, powermock, easymock, etc.)
The wiki links examples don't use mocks, they show real objects!
I think you will be more interested by a spy. You can use @Spy.
In mockito 1.9.0 you can write :
@Spy MyView view = new MyView(paramA, paramB);

or if MyView has default constructor
@Spy MyView view = new MyView();
@Spy MyView view; // equivalent, mockito will call the default constructor

For more information take a look at the javadoc.
Hope that helps.


text:
Q: On understanding a combinatorial argument: I am facing some problems in understanding this combinatorial argument:

Number of ways of putting $19$ identical balls in $16$ non-overlapping
  triangles such that no triangle is empty and there is a triangle
  containing exactly $3$ balls = $16 \times 15$

Could anybody rephrase this in way which provides more into why the calculation for this is $16 \times 15$?
ADDED:
What if the balls are distinct,how to approach that problem?

A: You have to have one triangle with 3 balls, one with 2 balls, and 14 with 1 ball each.  So you pick the triangle for 3 (16 ways), then pick some other triangle for 2 (15 ways).

A: Every one of the 16 triangles needs at least 1 ball in it, and at least one triangle needs exactly 3 balls in it. By Pigeonhole, this means that one triangle will have three balls, one triangle will have two balls, and the other triangles will all have one ball each. The triangles are distinct so you just have to pick the triangle with the three balls (16 choose 1 choices) and then one for the two balls (15 choose 1 choices) and the rest is determined (14 choose 14 choices). That's 16$\times$15$\times$1 = 240 possibilities in total.

Now suppose the balls are distinct. We could at first consider every permutation of the balls while in the triangles distinct (which would mean 19! times our original 240 possibilities), but permuting any of the balls independently in isolation in either the 3-ball triangle or the 2-ball triangle doesn't effect any change so we divide by $3!$ and $2!$ to get $${16\choose1}{15\choose1}{14\choose14}\frac{19!}{3!2!}=2432902008176640000.$$


text:
Q: What does "if the children breed with the children" mean? It's from a play based on Mary Shelley's novel.
What does "if the children breed with the children" mean?
Victor: I don't know. I have travelled where no man has travelled. I wonder
how far I can go. I can create people, Will! Living people! Look at me, I
breathe the breath of God!
William: And will they reproduce?
Victor: What?
William: Will they have wombs, the females? Will they breed? How quickly
will they breed? How fast is the cycle? How many in a litter? Fifty? A
hundred? A thousand?
Victor: William?
William: And if the children breed with the children? Will they do your
bidding?
Victor: What are you saying?
William: You are their king – will they do as you tell them? Or will they be
bad? Like the one who killed me?

A: I'm assuming this is based of Shelly's novel "Frankenstein."
Victor is gloating about how he can create living people.
William is trying to get Victor to think about the consequences.
First, Victor asks William about his creations themselves.
Will those creations- be able to reproduce and have children?
He then asks "And if the children breed with the children?"
Not only might the creations have children, but those children might have their own children.
"To breed" means to have offspring, to reproduce and have children.
It's usually used when referring to animals. We don't say people "breed" but we do "breed" horses etc.
Here it has the connotation that these creations are animal-like and they might be reproducing without limit.
That's whayt William wants Victor to think about.
Yes, Victor may be able to create living creatures.
But those creatures may breed- have offspring- in an out of control way, and he needs to be prepared for it.


text:
Q: Column font and width not changing, rest of the table is I have a document library with scripts to change the font size of the header row.  All the columns apart from one; "Short Description"; have changed.
I have just added a script to adjust the column width of this column and it's not responding to that either.
I have tested the script on other columns in the table and it works fine.
Its a Multiple Line Text column.  The colour changes for the header row and font have both worked.
Any ideas?
Scripts being used are:
    <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
type="text/javascript">
</script>
<script type="text/javascript">
$(function(){
$("div.ms-vh-div:contains('Topic')").css("width", "500px");});
</script>

and
    <style>
.ms-viewheadertr a,
.ms-viewheadertr div {
color: white;
}
.ms-vh2 {
font-size: 10pt ! important; }
.ms-vh {
font-size: 10pt ! important; }
.ms-viewheadertr {
font-size: 10pt ! important; }
.ms-viewheadertr {
background-color: #00646e; }
</style>

A: Problem Solved. I have faced these situation multiple times and solved by using simple styling. Here I have picked up the header element by its position. Here the column MLOT (multiple Line of Text) is at 7th position. You can choose based on your field's sequence. I have used Script editor web part for this. pls Refer below script:
<style type="text/css">
.ms-listviewtable thead tr th:nth-child(7){
    color: red !important;
    width: 250px !important;
    font-size: xx-large !important;
}
</style>

Screen Shot:

A: Put a script editor web part on the page and add following code. This will change the header styling.
<style>
.ms-listviewtable th{font-size: 24px;}
</style>

If you want to change the header of only one column then use script suggested by @DvG


text:
Q: How to find total number of sum of consecutive number of $n$?
How many ways are there to write $n$ as the sum of consecutive positive integers?

Example: $15$ has $3$ consecutive sums:

*

*$1+2+3+4+5=15$

*$7+8=15$

*$4+5+6=15$

A: Write $$\begin{align}n&=a+(a+1)+\cdots (a+k) \\&= (k+1)a + (1+2+\cdots+k) \\&= (k+1)a+\frac{k(k+1)}{2} \\&= \frac{(k+1)(k+2a)}{2}\end{align}$$
So $2n = (k+1)(k+2a)$.
So you want two write $2n$ as the product of an odd and an even number, and the odd number cannot be $1$. The reason they have to be odd and even is that $k+2a-(k+1)=2a-1$, so $k+1$ and $k+2a$ have different "parities" - they can't be both odd or both even.
So $2\cdot 30 = 3\cdot 10,5\cdot 6,15\cdot 2$.
This will always be equal to the number of odd factors of $n$ other than $1$. That's because an odd factor of $2n$ is an odd factor of $n$.
There isn't a good "magic" formula for this, unless you know to the prime factorization of $n$:
$$n= 2^{a_0}p_1^{a_1}\cdot p_k^{a_k}$$
Then the number of odd factors of $n$ other than $1$ is: $(a_1+1)(a_2+1)\cdots(a_k+1)-1$.
This can be seen because an odd factor of $n$ can be any number of the form $p_1^{b_1}\cdots p_k^{b_k}$ where $0\leq b_i\leq a_k$, so each $b_i$ can take any of $a_i+1$ values, but we have to subtract the one case when all the $b_i=0$, which counts the case when the odd number is $1$.
You can get rid of the "minus 1" thing if you count $15=15$ as the sum of one consecutive integer.
(This means that the only $n$ that cannot be written this way are the powers of $2$.)
Let's try an example. Let's take $n=42.$
Then if we factor $2n=84=7\cdot 12$. Then $k+1=7$ and $k+2a=12$, so $k=6,a=3$ and you get $42=3+4+5+6+7+8+9$.
On the other hand, if you take $2n=84=21\cdot 4$, then $k+1=4$ and $k+2a=21$ so $k=3$ and $a=9$ and you get $42=9+10+11+12$.

A: HINT:

Factorise $n$ and check the factors and use them accordingly.

Say, for a crude example:  $n=p_1p_2p_3$
If $p_2p_3$ is odd, then take $p_2p_3$ and $p_1-1$ numbers before and after $p_2p_3$ and you can write $n$ as a sum of these numbers.
Check for better examples or ask me if you need a more detailed explanation.


text:
Q: PHP Fatal error: Call to undefined function json_decode() Apache is logging PHP Fatal error:  Call to undefined function json_decode(). After some googling, it seems this problem is a result of not having the latest version of php. Oddly, running php --version ouputs
PHP 5.5.1-2+debphp.org~precise+2 (cli) (built: Aug  6 2013 10:49:43)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
    with Zend OPcache v7.0.2-dev, Copyright (c) 1999-2013, by Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

Clearly showing that my php version is greater than 5.1.
Any ideas as to what could cause this, or the steps to take to find out?
EDIT: The result of a script echoing phpversion is 5.5.1-2+debphp.org~precise
EDIT: The result of phpinfo() is also PHP Version 5.5.1-2+debphp.org~precise+2
Furthermore, in the phpinfo(), it lists the module JSON and the module authors (Omar Kilani, Scott MacVicar).

A: Solution for LAMP users:
apt-get install php5-json
service apache2 restart

Source

A: As a RHEL 8 user, this was fixed with:
yum install php-json

And then reloading nginx and php-fpm. So basically the json libraries where missing from the default php install.
This should also work on CENTOS 8.

A: If you're using phpbrew try to install json extension to fix error with undefined function json_decode():
phpbrew ext install json

A: Using Ubuntu?
Short answer:
sudo apt-get install php7.2-json

(or php7.1-json or  php5-json depending on the PHP version you're running)
Then of course make sure you restart Apache:
sudo service apache2 restart

Or if you are using PHP-FPM:
sudo service php7.2-fpm restart

(Or php7.1-fpm or php5-fpm)
Explanation
Debian has removed the previous JSON extension as of PHP 5.5rc2 due to a license conflict.
The JSON license has a clause which states:

The Software shall be used for Good, not Evil.

This causes a problem with Free Software Foundation's definition of free software which states:

The freedom to run the program, for any purpose (freedom 0).

FSF goes on to specifically list the JSON license as nonfree.
Yes it seems a bit silly. Nevertheless Debian has removed the non-compliant JSON extension, and instead offered a replacement extension that is functionally equivalent.
To be clear: PHP itself has NOT removed JSON, it's still in master. This is a distro / package manager issue.
Rasmus makes it pretty clear:

We have not removed json and we will never release a version of php without json support built in. Any changes in 5.5 is due to whatever distro packaging you are using which we have no control over.

More details
http://iteration99.com/2013/php-json-licensing-and-php-5-5/
http://liorkaplan.wordpress.com/2013/06/01/bye-bye-non-free-php-json-extension/
https://bugs.php.net/bug.php?id=63520
http://philsturgeon.co.uk/blog/2013/08/fud-cracker-php-55-never-lost-json-support

A: I have the same question: PHP Fatal error:  Call to undefined function json_decode(), but I run php under cygwin on Windows. When I run php -m, I found that there is no json module installed. So I run cygwin setup.exe again, check json package from the configuration interface, and the problem is solved.

A: The same issue with 7.1
apt-get install php7.1-json
sudo nano /etc/php/7.1/mods-available/json.ini

*

*Add json.so to the new file

*Add the appropriate sym link under conf.d

*Restart apache2 service (if needed)

A: With Ubuntu :
sudo apt-get install php5-json
sudo service php5-fpm restart

A: The module was install but symbolic link was not in /etc/php5/cli/conf.d

A: you might also consider avoiding the core PHP module altogether.
It is quite common to use the guzzle json tools as a library in PHP apps these days.  If your app is a composer app, it is trivial to include them as a part of a composer build.
The guzzle tool, as a library, would be a turnkey replacement for the json tool, if you tell PHP to autoinclude the tool.
http://docs.guzzlephp.org/en/stable/search.html?q=json_encode#
http://apigen.juzna.cz/doc/guzzle/guzzle/function-GuzzleHttp.json_decode.html

A:
CENTOS
Scene

I installed PHP in Centos Docker, this is my DockerFile:
FROM centos:7.6.1810

LABEL maintainer="teran.a.joan@gmail.com"

RUN yum install httpd-2.4.6-88.el7.centos -y
RUN rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
RUN rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
RUN yum install php72w -y
ENTRYPOINT ["/usr/sbin/httpd", "-D", "FOREGROUND"]

The app returned the same error with json_decode and json_encode

Resolution

Install PHP Common that has json_encode and json_decode
yum install -y php72w-common-7.2.14-1.w7.x86_64

How to find the resolution?

I have another Docker File what build the container for the API and it has the order to install php-mysql client:
yum install php72w-mysql.x86_64 -y

If i use these image to mount the app, the json_encode and json_decode works!!
Ok..... What dependencies does this have?
[root@c023b46b720c etc]# yum install php72w-mysql.x86_64
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
 * base: mirror.gtdinternet.com
 * epel: mirror.globo.com
 * extras: linorg.usp.br
 * updates: mirror.gtdinternet.com
 * webtatic: us-east.repo.webtatic.com
Resolving Dependencies
--> Running transaction check
---> Package php72w-mysql.x86_64 0:7.2.14-1.w7 will be installed
--> Processing Dependency: php72w-pdo(x86-64) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Processing Dependency: libmysqlclient.so.18(libmysqlclient_18)(64bit) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Processing Dependency: libmysqlclient.so.18()(64bit) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Running transaction check
---> Package mariadb-libs.x86_64 1:5.5.60-1.el7_5 will be installed
---> Package php72w-pdo.x86_64 0:7.2.14-1.w7 will be installed
--> Processing Dependency: php72w-common(x86-64) = 7.2.14-1.w7 for package: php72w-pdo-7.2.14-1.w7.x86_64
--> Running transaction check
---> Package php72w-common.x86_64 0:7.2.14-1.w7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================
 Package                   Arch               Version                        Repository            Size
========================================================================================================
Installing:
 php72w-mysql              x86_64             7.2.14-1.w7                    webtatic              82 k
Installing for dependencies:
 mariadb-libs              x86_64             1:5.5.60-1.el7_5               base                 758 k
 php72w-common             x86_64             7.2.14-1.w7                    webtatic             1.3 M
 php72w-pdo                x86_64             7.2.14-1.w7                    webtatic              89 k

Transaction Summary
========================================================================================================
Install  1 Package (+3 Dependent packages)

Total download size: 2.2 M
Installed size: 17 M
Is this ok [y/d/N]: y
Downloading packages:
(1/4): mariadb-libs-5.5.60-1.el7_5.x86_64.rpm                                    | 758 kB  00:00:00
(2/4): php72w-mysql-7.2.14-1.w7.x86_64.rpm                                       |  82 kB  00:00:01
(3/4): php72w-pdo-7.2.14-1.w7.x86_64.rpm                                         |  89 kB  00:00:01
(4/4): php72w-common-7.2.14-1.w7.x86_64.rpm                                      | 1.3 MB  00:00:06
--------------------------------------------------------------------------------------------------------
Total                                                                   336 kB/s | 2.2 MB  00:00:06
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 1:mariadb-libs-5.5.60-1.el7_5.x86_64                                                 1/4
  Installing : php72w-common-7.2.14-1.w7.x86_64                                                     2/4
  Installing : php72w-pdo-7.2.14-1.w7.x86_64                                                        3/4
  Installing : php72w-mysql-7.2.14-1.w7.x86_64                                                      4/4
  Verifying  : php72w-common-7.2.14-1.w7.x86_64                                                     1/4
  Verifying  : 1:mariadb-libs-5.5.60-1.el7_5.x86_64                                                 2/4
  Verifying  : php72w-pdo-7.2.14-1.w7.x86_64                                                        3/4
  Verifying  : php72w-mysql-7.2.14-1.w7.x86_64                                                      4/4

Installed:
  php72w-mysql.x86_64 0:7.2.14-1.w7

Dependency Installed:
  mariadb-libs.x86_64 1:5.5.60-1.el7_5                php72w-common.x86_64 0:7.2.14-1.w7
  php72w-pdo.x86_64 0:7.2.14-1.w7

Complete!

Yes! Inside the dependences is the common packages. I Installed it into my other container and it works! After, i put de directive into DockerFile, Git commit!! Git Tag!!!! Git Push!!!! Ready!

A: cPanel
Go to MultiPHP INI Editor and select the Editor Mode tab, enter the following to enable JSON extensions:
extension=json.so

Or, if you have an existing php.ini file in your root directory, check if this extension is listed and make sure it's not commented out (preceded by semi-colon).


text:
Q: Optimization using Lagrange multipliers: 55 gallon steel drum I am currently trying to figure out this particular problem with not a great understanding of Lagrange multipliers. I understand the process, but am not sure how the values are generated. Could anyone help me solve this with explanation behind the steps?

Using the dimensions in the figure below, use the method of Lagrange multipliers to optimize the steel drum(cylinder). Find the smallest possible surface area while maintaining (constraint) the desired volume of $57.20$ gallons or $13,213\;in^3$.

Minimize: $\;\; SA(r,h)=2\pi rh+2\pi r^2$
Constraint: $\;\; V(r,h)= \pi hr^2$
diameter $\;\;= 22\;\frac12$ inch,
height  $\;\; = 33\;\frac18$ inch.

A: Here is an outline of how to solve this problem.
Generally, Lagrange multipliers is not a recipe for solution and requires some extra thinking. This problem follows this pattern.
The problem is $\min \{ S(r,h) | V(r,h) = K \}$, where $K$ is some positive
constant, $S(r,h) = r^2+rh$ and $V(r,h) = h r^2$ (I stripped out irrelevant constants to simplify).
Step 1: The first, and typically overlooked, step is to convince yourself that there actually is a solution.
This problem can be solved directly without Lagrange multipliers. Note that in this case, $V(r,h) = K$ implies that $h>0$ and so we see that $h = {K \over r^2}$ and $S(r,{K \over r^2}) = r^2 + {K \over r}$. Plotting this shows that $S$ is unbounded below so technically it has no minimum.
Clearly a negative $r$ is aphysical, there is an implied constraint that $r \ge 0$.
We (well, me) still need to convince ourselves that there is a minimum. Note that if we pick any feasible $r,h$, for example, $(r,h) = (1,K)$, then any solution must have cost no larger than this so the problem is equivalent to $\min \{ S(r,h) | V(r,h) = K , S(r,h) \le S(1,K), r \ge 0\}$. It is straightforward to see that the feasible set is compact hence a solution exists. Hence we can drop the artificial $S(r,h) \le S(1,K)$ constraint.
To say a solution exists means that there is some point $(r^*,h^*)$ that is feasible and $\epsilon>0$ such that for any feasible $(r,h) \in B((r^*,h^*), \epsilon)$ that $S(r^*,h^*) \le S(r,h)$.
Furthermore, the $V$ constraint shows that at a solution we must have $r>0$
(and hence is not binding at the solution).
The whole point of this diatribe is that $(r^*,h^*)$ is a local solution to the original problem and so the Lagrange multiplier conditions hold at
this point.
Step 2: Actually use the multipliers.
We have the equations $h^*+2r^*+2 \lambda r^*h^* = 0$, $r^* + \lambda (r^*)^2 = 0$. We know that $r^* >0$ so the last equation gives $r^* = - {1 \over \lambda}$ and the
other equation gives $h^*=-{2 \over \lambda}$. Substituting into the
$V$ constraint gives $\lambda = -\sqrt[3]{2 \over K}$.
Hence $r^*= \sqrt[3]{K \over 2}$, $h^* = 2\sqrt[3]{K \over 2}$ with optimal surface area $S(r^*,h^*) = 3 \sqrt[3]{K^2 \over 4}$.
The numbers in the problem are a bit inconsistent, the volume constraint is $13,213$ cu.in. but the diameter and height given result in a volume of around $13,171$ cu.in.


text:
Q: What if user starts begging for upvote on his question? The OP wrote: "Please upvote me, if my question is good."
Isn't this a bit weird?
Upvoting or downvoting a question shouldn't be prompted.
Isn't this looked down on? I feel this is very undignified.
It should be one's personal choice whether one likes the question and if they want to upvote the question right?

A: Flag the comment for Moderators attention...it is unwanted noise and not welcome.
Edit
As for wanting to be upvoted, that is the Community's decision...ironically, he's more likely to be discouraging people from upvoting his question with that behaviour.