text:
Q: how can I expire a session message in PHP after couple of seconds not by refreshing the page? I need to keep this 'session' 'message' alive for couple seconds and then destroy it, Not by refreshing the page any help please!
Here is the code bellow:
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
   echo $_SESSION['message'];
   unset($_SESSION['message']);
?>

<?php endif ?>

A: I don't think there's an easy way (or any way) to do this with PHP.
Using JavaScript makes this very easy though :
<?php if (isset($_SESSION['message'])): ?>
    <div class="alert alert-<?= $_SESSION['msg_type'] ?>">
        <?php
        echo $_SESSION['message'];
        unset($_SESSION['message']);
        ?>

<?php endif ?>


text:
Q: Svelte - event modifier "once" on form submit not working Any idea why the once modifier doesn't work on form submitting in Svelte?
In the following example:
<form action="./" on:submit|preventDefault|once={() => alert('You submitted the form')}>
  <button type="submit">Save</button>
</form>

when I submit the form  first time - I see the alert, but after that, when I submit - the page refreshes - as a normal form submitting.
(I tried with the button on:click - on:click|preventDefault|once... - but got same result.)

A: Looks like the 'once' is working, but after running and being removed the default submit behaviour of the form seems to be active again.
Couldn't find any information if disabling this listener is possible any other way than by adding a submit listener with preventDefault.
But this way, when adding a second listener only preventing the default, you can see that 'once' is only executed once -> REPL
<script>

    function submitOnce() {
        console.log('this logs once')
        // put logic here you want to execute once
    }
    function handleSubmit() {
        // console.log('this logs with every submit')
        // this prevents default submit behaviour
    }

</script>

<form on:submit|preventDefault={handleSubmit} on:submit|once={submitOnce}>
  <button>Submit</button>
</form>

can simply be replaced by on:submit|preventDefault={() => {}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I check if an element still exists in the DOM? How can I check if an element still exists in the DOM?

  ...

let parent = document.getElementById('parent');
let myElement = parent.getElementsByClassName('my-class')[0];
parent.remove();

function stillExists(element) {
   // check if element still exists in DOM
}

stillExists(myElement) // should be false

A: Simply do
document.contains(myElement)


text:
Q: warping and outputting coordinates of GeoTiff data: advice and error checking So I have a massive TIF file (projected in Lambert azimuthal equal-area), and I'm trying to get lat/lon coordinates for each point of the grid.
My first step is to warp the projection to the WGS84 datum using:
>gdalwarp giganticfile.tif warpedcroppedfile.tif -t_srs "+proj=longlat +ellps=WGS84" -te -120 25 -60 55

Then I make that tif file into the following xyz format file:
>gdal_translate -of XYZ warpedcroppedfile.tif latlongvalues.dat

I can read a manual page as well as anyone else, but I'm new to this, so my two questions are:

*

*does anyone have suggestions on how do do this better? I don't have ArcGIS access.

*How do I error check myself.

I plotted the warped/cropped file, and it looked 'reasonable'(i.e., I could see a map of the US), but I'm doing some numerical analysis with the outputs, and I want to make sure that my data are good. So how do I error check myself? Manually go through the math for a few points?

A: 1) Looks good, but you can crop, warp and convert data into XYZ with a single command by addind parameter -of XYZ to your gdalwarp command. However, some file formats are not good targets for gdalwarp which must append data to initialized target while the warping process is progressing. Make a trial and test if using tiff as on interim format is faster or not.
2) You can use gdallocationinfo for capturing reference data from the original tiff file.
gdallocationinfo -wgs84 giganticfile.tif x-longitude y-latitude


text:
Q: Stored Procedure resultset into sub query in another SP I want to use stored procedure result into inside of another stored procedure , like sub query. Is it possible..?
Below Sample Code : Password generation Logic created in one sp:
Create Procedure GetDynamicPassword
@Password out
As

Begin

    -- Password generate Logic createhere
        -- More than 100 line to generate password logic

End

I want to use the above result into another SP.
Unable to use temp table, because i need this result for so many records in single time.
I want to use above sp inside the below sp.
Create Procedure GetDynamicUsers

As

Begin

    Select a.col1, b.col2 , c.col3...
    ( I want to uses password here from above SP )
        ( like exec GetDynamicPassword) As Password
        from Table1 As a
    inner join Table2 As b on a.Code = b.Code
        inner join Table3 As c on a.Code = c.Code
    inner join Table4 As d on a.Code = d.Code

End

A: Rewrite your stored procedure GetDynamicPassword as a Scalar valued User-Defined Function.
Then you can use the function directly in your select statement.

A: The best practice to do that would be to create a function and then call it in your SP
Create function GetDynamicPassword
returns varchar(100)
As

Begin

-- Password generate Logic createhere
    -- More than 100 line to generate password logic

End

and then use it in your SP below
Create Procedure GetDynamicUsers

As

Begin

Select a.col1, b.col2 , c.col3...,
dbo.GetDynamicPassword() As Password
    from Table1 As a
inner join Table2 As b on a.Code = b.Code
    inner join Table3 As c on a.Code = c.Code
inner join Table4 As d on a.Code = d.Code

End


text:
Q: Displaying 5 rows of data from query I have a simple table (mgap_orders) with customer orders in it. Multiple have the the same id (mgap_ska_id) and I simply want to pull 5 records from the table and display all five.
I can easily get one record with the following query and PDO, but how can I display 5 rows instead of only one row?
  $result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id";

    while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
    {
    $item=$row_cat_sub['mgap_item_description'];
    $item_num=$row_cat_sub['mgap_item_number'];
    $item_type=$row_cat_sub['mgap_item_type'];
    $item_cat=$row_cat_sub['mgap_item_catalog_number'];
    $item_ven=$row_cat_sub['mgap_item_vendor'];
    $item_pur=$row_cat_sub['mgap_item_percent_purchased'];
    $item_sales=$row_cat_sub['mgap_item_sales'];
    }

A: Use limit 5 then put the results in an array, like this:
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id LIMIT 5";

$items = array();

while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
    $items['item']       = $row_cat_sub['mgap_item_description'];
    $items['item_num']   = $row_cat_sub['mgap_item_number'];
    $items['item_type']  = $row_cat_sub['mgap_item_type'];
    $items['item_cat']   = $row_cat_sub['mgap_item_catalog_number'];
    $items['item_ven']   = $row_cat_sub['mgap_item_vendor'];
    $items['item_pur']   = $row_cat_sub['mgap_item_percent_purchased'];
    $items['item_sales'] = $row_cat_sub['mgap_item_sales'];
}

Then you can do:
foreach($items as $item) {
    // echo $item['item'] or whatever
}

EDIT: Or you can skip putting them in the array and just use the while() to do what you need to do with the data.


text:
Q: Change Timestamp value in enterprise library exception handling formatter I am using enterprize library 5.0 with c# for exception handling and for that I am using formatter.Now In my log file Timestamp is not giving the right time.
Can I change the value of timestamp in formatter.

A:

Timestamp: {timestamp(local)} will get the local system time

A: The timestamp entry uses UTC so that exceptions logged in different timezones can be correlated. The best idea is to convert the time to local if and when you read the trace log file and present the information to the user.


text:
Q: Converting an ASP.NET Website that has C# and VB to a Web Application I have an ASP.NET Website project that I have converted to a Web Application. I converted the App_Code which has sub directories for vb and cs it renamed to the folder to Old_App_Code. Now the C# code will not compile, none of the syntax is recognized and several hundred errors show in the error list.
I know its possible to have both languages in a website project but how do I compile both in a web app project? or do I have to convert all the C# to VB?

A: To run C# and VB together you can do some changes in web.config such as;
<system.codedom>
<compilers>
        <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <providerOption name="CompilerVersion" value="%ASSEMBLY_VERSION%"/>
        </compiler>
        <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <providerOption name="CompilerVersion" value="%ASSEMBLY_VERSION%"/>
        </compiler>
    </compilers>

and
<compilation debug="true" defaultLanguage="VB">
<codeSubDirectories>
                <add directoryName="CS_Code"/>
            </codeSubDirectories>
        </compilation>

for the rest you you use this walktrough
https://stackoverflow.com/a/735062/929902


text:
Q: ¿Por qué me marca Error para ingresar a WordPress? Tengo una duda, trato de ingresar a WordPress como administrador y me arroja el siguiente error:
Fatal error: Cannot use object of type WP_Error as array in /home/IS/public_html/wp-content/plugins/themeisle-companion/vendor/codeinwp/themeisle-sdk/class-themeisle-sdk-feedback-translate.php on line 804

¿Saben a qué se deba o cómo puedo solucionarlo?

A: Accede a través de FTP o cPanel y renombrar la carpeta del plugins, puede ser algún tipo de error de compatibilidad de php, te recomiendo actualizar los plugins y la versión de WordPress.


text:
Q: React js core UI build error on compilation Am recently switched my domain [enter image description here][1]to React Js and trying to learn . I have been trying to create an admin panel using Core UI Reactjs components. But it shows an error like "This error occurred during the build time and cannot be dismissed " on the compilation.[][1]

A: Please try the below commands:

npm cache clean --force
npm cache verify

Then delete the node_modules, and run the below code

npm install --force


text:
Q: How can I reduce subscriptions in RxJs and simplify my code i got this code:

ngOnInit(): void {
    this.getEmployees();
    this.employeesService
      .reloadEmployees()
      .subscribe(() => this.getEmployees());

    this.employeesService.searchValue$
      .subscribe(value => this.employeesService.searchEmployees(value)
        .subscribe(el => this.allEmployees = el));
  }

Do you guys think that I can simplify that code? What should I do? I need to reduce that subscriptions, because at this point it doesnt look great

A: you should avoid to subscribe inside another subscription.
You can sole it like this:
this.employeesService.searchValue$.pipe(
  concatMap(value => this.employeesService.searchEmployees$(value))
).subscribe(el => this.allEmployees = el);


text:
Q: Samba 'homes' share and users randomly deciding to put capital letters in their usernames I created a 'homes' share in Samba, tested, and then moved all our user profiles over to it.
[homes]
    comment = User Profiles
    path = /tank/users/%U
    valid users = %U
    browseable = no
    writable = yes
    hide dot files = yes

During testing I had no problems with my test profiles.  I would sign in to Windows as 'aaron', and it would find my folder under /tank/users/aaron.
Then I moved it in to production and moved everyone over to the new server.
I immediately got calls from users that their desktops were gone.  After some digging, I found that some users were signing in as 'JSmith' which Samba translated into looking for /tank/users/JSmith instead of /tank/users/jsmith.  As a stop-gap, I simply renamed their folders to the case they were using to sign in.
But I still get sporadic calls from users who suddenly to decide to sign in as 'Jsmith' one day, 'JSmith' another day, 'jsmith' the following day, and even 'JSMITH' because they left their capslock on.
Digging through the samba docs, I don't see a way to force that path to be all lower-case regardless of what the user enters on the login screen.
Am I missing something?  Seems like this would be a frequent problem for people hosting files on Samba.


text:
Q: How can I stop excel from rounding to .00? My Excel formulas are producing answers that only give zeros after the decimal place. For example,
=QUOTIENT(10.90,0.0450)

gives the answer of 242.00, it should be 242.22. How can I keep this from happening?

A: The Quotient Function only gives answers in whole numbers. You can use the simple =10.90/0.0450 to get decimals in the answer.


text:
Q: Manifest is not valid JSON. Line: 18, column: 2, Trailing comma not allowed {
  "name": "test",
  "version": "1.0.0",
  "description": "test",
  "icons": {"16":  "images/icon16.png",
            "24":  "images/icon24.png",
            "32":  "images/icon32.png",
            "128":  "images/icon128.png"},
  "permissions": [
    "https://*.wikipedia.com"
  ],
  "browser_action": {
      "default_title": "test",
      "default_icon": "images/icon128.png",
      "default_popup": "popup.html"
  },
  "manifest_version": 2,
}

Hello !
This is the manifest.json file from my test extension.
Whenever I try to import it in Chrome it says: "Manifest is not valid JSON. Line: 18, column: 2, Trailing comma not allowed"

A: I think there is a problem in line "manifest_version": 2, usage of an unnecessary comma.


text:
Q: jQuery: How to get the HTTP status code from within the $.ajax.error method? I'm using jQuery to make an AJAX request. I want to perform different actions whether or not the HTTP status code is a 400 error or a 500 error. How can I achieve this?
$.ajax({
    type: 'POST',
    url: '/controller/action',
    data: $form.serialize(),
    success: function(data){
        alert('horray! 200 status code!');
    },
    error: function(data){
        //get the status code
        if (code == 400) {
            alert('400 status code! user error');
        }
        if (code == 500) {
            alert('500 status code! server error');
        }
    },
});

Update:
@GeorgeCummins mentioned that it "seemed odd" to work with the response body. This is the first time that I've attempted doing this sort of thing. Is my approach not a best-practice? What would you recommend? I created another StackOverflow question for this here: What response/status code should I send to an AJAX request when there is a user/form validation error?

A: You should create a map of actions using the statusCode setting:
$.ajax({
  statusCode: {
    400: function() {
      alert('400 status code! user error');
    },
    500: function() {
      alert('500 status code! server error');
    }
  }
});

Reference (Scroll to: 'statusCode')
EDIT (In response to comments)
If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error: instead of statusCode:
error:function (xhr, ajaxOptions, thrownError){
    switch (xhr.status) {
        case 404:
             // Take action, referencing xhr.responseText as needed.
    }
}

A: An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.
function checkHttpStatus(url) {
    $.ajax({
        type: "GET",
        data: {},
        url: url,
        error: function(response) {
            alert(url + " returns a " + response.status);
        }, success() {
            alert(url + " Good link");
        }
    });
}

A: If you're using jQuery 1.5, then statusCode will work.
If you're using jQuery 1.4, try this:
error: function(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.status);
    alert(textStatus);
    alert(errorThrown);
}

You should see the status code from the first alert.

A: use
   statusCode: {
    404: function() {
      alert('page not found');
    }
  }

-
$.ajax({
    type: 'POST',
    url: '/controller/action',
    data: $form.serialize(),
    success: function(data){
        alert('horray! 200 status code!');
    },
    statusCode: {
    404: function() {
      alert('page not found');
    },

    400: function() {
       alert('bad request');
   }
  }

});

A:
Here you can use this too it works for me

$.ajax({
  success: function(data, textStatus, xhr) {
    console.log(xhr.status);
  },
  complete: function(xhr, textStatus) {
    console.log(xhr.status);
  }
});


text:
Q: Algebra generated by a function and uniform limits We take $f: [ \alpha, \beta ] \to \mathbb{R}$ a continuous function. We consider $E = \{ P(f), P \in \mathbb{R}[X] \}$ the algebra generated by $f$.
And then, we have to find a necessary and sufficient condition on $f$ so that every continuous function defined on $[ \alpha, \beta ]$ is the uniform limit of a sequence of elements of $E$.
So if I am not mistaken, a necessary and sufficient condition is that the function $[\alpha, \beta] \to \mathbb{R}$, $x \mapsto x$ is the uniform limit of a sequence of elements of E.
But is there better ? Can we find something more simple ?
Thank you.


text:
Q: Prepositions: can we avoid them Example:

The tasks this layer is responsible for are
   meaningful to the business or necessary for
   interaction with the application layers of
   other systems.

Can we omit for in responsible for? Because for and are together sound very strange. Or this for is mandatory?

A: The "for" is mandatory with "responsible". You can be (just plain) "responsible" without any preposition, but if there is another noun (or pronoun, or other noun-like object) after responsible, you need a preposition there to specify the relationship between that noun and "responsible".
The combination "... for are ..." doesn't sound bad to me in this context. If you really don't like it, you could reword the sentence like this:

The tasks for which this layer is responsible are meaningful to the business or necessary for
  interaction with the application layers of
  other systems.

But, to me, it sounded fine the way it was. Either way, you've got a somewhat complicated sentence there.


text:
Q: GO redirect STD error from C# managed side I have a test code that has this stack C#->C->GO->C#(ERROR HERE).
Whenever an error happens on C# and if that C# code is called by GOLANG the error is not redirected to error.std file. However, if I start the code from VS with the attached debugger the error is redirected to the file.
C#:
Program.cs
class Program {
        [DllImport("gotestDLL.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        internal static extern void Error();

        [DllImport("gotestDLL.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        internal static extern void SetCSharpPointerHandler(IntPtr ptr);

        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate IntPtr CSharpPointerHandler(IntPtr message);

        private static CSharpPointerHandler _messageHandlerCb = new CSharpPointerHandler(SomeMethodWithError);
        private static IntPtr _messageHandlerCbPtr = Marshal.GetFunctionPointerForDelegate(_messageHandlerCb);

        static void Main(string[] args) {

            SetCSharpPointerHandler(_messageHandlerCbPtr);

            Console.WriteLine("|-C#->START OF C#");
            Error();

            Console.WriteLine("|-C#->Waiting for program to crash");
            do {

            } while (true);
        }

        private static IntPtr SomeMethodWithError(IntPtr messagePtr) {
            Console.WriteLine("|-C#->Back to C#");
            var a = 0;
            Console.WriteLine("|-C#->ERROR HAPPENS HERE C#");
            var b = 10 / a;
            Console.WriteLine(b);

            return IntPtr.Zero;
        }
    }

C:ctestdll.C
#include <stdio.h>
#include "gotestDLL.h"

void Error() {
    printf("|-C--->START OF C\n");
    RedirectStdError();

    printf("|-C--->START ERROR\n");
    StartError();
    printf("|-C--->END START ERROR\n");

    printf("|-C-->END OF C\n");
}

int main() {

}

H:ctestDLL.h
#include <stdio.h>
#include <stdbool.h>

typedef char* CSharpPointerHandler(char* query);

static inline char* RunCSharpPointerHandler(CSharpPointerHandler* handler, char* in) {
    return handler(in);
}

#ifdef __cplusplus
extern "C"
{
#endif

__declspec(dllexport) void SetCSharpPointerHandler(CSharpPointerHandler* handler);

__declspec(dllexport) void Error();

#ifdef __cplusplus
}
#endif

GO:gotestDLL.go
package main

/*
#include<stdio.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#include "ctestDLL.h"
*/
import "C"
import "fmt"
import "os"

var queryHandler   *C.CSharpPointerHandler = nil

//export SetCSharpPointerHandler
func SetCSharpPointerHandler(handler *C.CSharpPointerHandler) {
    queryHandler = handler
}

//export StartError
func StartError() {
    inc := C.CString("TEST")
    fmt.Println("|-GO--->Calling Handler from GO->C#")
    C.RunCSharpPointerHandler(queryHandler, inc)
    fmt.Println("|-GO--->END Calling Handler from GO")
}

//export RedirectStdError
func RedirectStdError() {
    f, err := os.OpenFile("error.std", os.O_WRONLY | os.O_CREATE | os.O_SYNC, 0777)
    if err != nil {
        fmt.Println("os.OpenFile")
    }
    newfd := C._open_osfhandle(C.intptr_t(f.Fd()), C._O_APPEND | C._O_TEXT)
    if newfd == C.int(-1) {
        fmt.Println("failed to create osfhandle: _open_osfhandle(%v, _O_APPEND|_O_TEXT)", C.intptr_t(f.Fd()))
    }
    stderr_fd := C._fileno(C.stderr)
    forwarded := C._dup2(newfd, stderr_fd)
    if forwarded == C.int(-1) {
        fmt.Println("failed to duplicate stderr fd: _dup2(%v, %v): %v", newfd, stderr_fd, forwarded)
    }
    os.Stderr = f
}

func main() {
    // Need a main function to make CGO compile package as C shared library
}

OUTPUT:
|-C#->START OF C#
|-C--->START OF C
|-C--->START ERROR
|-GO--->Calling Handler from GO->C#
|-C#->Back to C#
|-C#->ERROR HAPPENS HERE C#


text:
Q: Best practice for incorrect parameters on a remove method So I have an abstract data type called RegionModel with a series of values (Region), each mapped to an index.  It's possible to remove a number of regions by calling:
regionModel.removeRegions(index, numberOfRegionsToRemove);

My question is what's the best way to handle a call when the index is valid :
(between 0 (inclusive) and the number of Regions in the model (exclusive))
but the numberOfRegionsToRemove is invalid:
(index + regionsToRemove > the number of regions in the model)
Is it best to throw an exception like IllegalArgumentException or just to remove as many Regions as I can (all the regions from index to the end of the model)?
Sub-question: if I throw an exception what's the recommended way to unit test that the call threw the exception and left the model untouched (I'm using Java and JUnit here but I guess this isn't a Java specific question).

A: Typically, for structures like this, you have a remove method which takes an index and if that index is outside the bounds of the items in the structure, an exception is thrown.
That being said, you should be consistent with whatever that remove method that takes a single index does.  If it simply ignores incorrect indexes, then ignore it if your range exceeds (or even starts before) the indexes of the items in your structure.

A: I would say that an argument such as illegalArgumentException would be the best way to go here.  If the calling code was not passing a workable value, you wouldn't necessarily want to trust that they really wanted to remove what it had them do.

A: I agree with Mitchel and casperOne -- an Exception makes the most sense.
As far as unit testing is concerned, JUnit4 allows you to exceptions directly:
http://www.ibm.com/developerworks/java/library/j-junit4.html
You would need only to pass parameters which are guaranteed to cause the exception, and add the correct annotation (@Test(expected=IllegalArgumentException.class)) to the JUnit test method.
Edit: As Tom Martin mentioned, JUnit 4 is a decent-sized step away from JUnit 3.  It is, however, possible to also test exceptions using JUnit 3.  It's just not as easy.
One of the ways I've tested exceptions is by using a try/catch block within the class itself, and embedding Assert statements within it.
Here's a simple example -- it's not complete (e.g. regionModel is assumed to be instantiated), but it should get the idea across:
public void testRemoveRegionsInvalidInputs() {
  int originalSize = regionModel.length();
  int index = 0;
  int numberOfRegionsToRemove = 1,000; // > than regionModel's current size
  try {
    regionModel.removeRegions(index, numberOfRegionsToRemove);

    // Since the exception will immediately go into the 'catch' block this code will only run if the IllegalArgumentException wasn't thrown
    Assert.assertTrue("Exception not Thrown!", false);
  }
  catch (IllegalArgumentException e) {
     Assert.assertTrue("Exception thrown, but regionModel was modified", regionModel.length() == originalSize);
  }
  catch (Exception e) {
      Assert.assertTrue("Incorrect exception thrown", false);
  }
}


text:
Q: bower - when should I use dependency vs. devDependency when writing a library? Seems weird to me that I get dependency conflict on things I shouldn't. Lets take angular and angular-datepicker for example.
When I add a dependency on angular-datepicker, I get a conflict for another angular version.
In npm the resolved dependencies are used in runtime. so if angular-datepicker was to run in npm, it would have used its own version of angular at runtime. which makes sense.
However this is not the case in bower, since the runtime versions are shared, and angular-datepicker's angular version is only used for development, not for runtime.
the more libraries I add, the harder it gets to "satisfy" all.
seems to me like all the libraries should declare angular as a devDependency instead of a dependency - as they expect the project using them to be dependent on angular directly rather than use their angular.
but then, when should I use dependencies?
Can someone clarify this issue to me please.

A: You should use devDependency for parts of the app that you might need as a developer to build/test/compile/serve the app. Things like your test suite or your gulp/other task runners.
You should use dependency for anything that the client needs to run the compiled app. In your case, both Angular and Angular datepicker are dependencies.
One main difference is that if you run bower install -p (for production) you will only install into your bower_components directory and ignore devDependencies.
It sounds like what is happening is that your app is running one version of Angular and your Angular-datepicker plugin is running a different version of Angular. A good solution is to either update everything to the latest Angular version, or if that's not possible choose the version of your angular-datepicker plugin that is compatible with the version of Angular you're running.


text:
Q: java 8 - store method in HashMap and get return value from method in map I want to store methods pointer in map to execute them based on a string value. Аrom what I found, I can use Map<String, Runnable> to do it, but the problem is I want to get the return value from the method.
Say I have something like this:
private Map<String, Runnable> timeUnitsMap = new HashMap<String, Runnable>() {{
    timeUnitsMap.put("minutes", () -> config.getMinutesValues());
}}

The method config.getMinutesValues() is from another class.
How can I do int value = timeUnitsMap.get("minutes").run(); or to store something else in the map (instead of Runnable) in order to get the value from the function in the map?

A: Runnable doesn't return a value. You should use Supplier or Callable instead.
The primary difference between Supplier and Callable is that Callable allows you to throw a checked exception. You then have to handle the possibility of that exception everywhere you use the Callable. Supplier is probably simpler for your use case.
You would need to change your Map<String, Runnable> to a Map<String, Supplier<Integer>>. The lambda function itself wouldn't need changing.
@assylias pointed out in a comment that you could also use Map<String, IntSupplier>. Using an IntSupplier avoids boxing your int as an Integer.

A: Use Callable instead of Runnable.

A: You will need to use Callable instead of Runnable and also, you would need to override call() method.
You can get a clue from following snippet:
private Map<String, Callable<Integer>> timeUnitsMap = new HashMap<String, Callable<Integer>>(){
        {timeUnitsMap.put("minutes", () -> call());}};

and you would need to override call() method as well,
@Override
    public Integer call() throws Exception {
        return 1;
}


text:
Q: On what UNIX-like system / filesystem is the st_blocks field returned by stat() not a number of 512-byte units? I always assumed the st_blocks field returned by stat()/lstat()... system calls  and which du uses to get the disk usage of files was expressed in 512 bytes units.
Checking the POSIX specification, I now see POSIX makes no guarantee for that. The perl documentation for its own stat() function also warns against making that assumption.
In any case, as indicated by POSIX, that block size is not related to the st_blksize field returned by stat(), so has to be found elsewhere.
Checking the GNU du or GNU find source code, I see evidence HP/UX uses 1024 bytes units instead. GNU find adjusts its -printf %b output to always give a number of 512-byte units which is probably the source of my confusion.
Is there any other Unix-like system, still currently in use where st_blocks is not expressed in 512 byte units? Can that be filesystem dependant (as POSIX suggests)? I guess mounting an HP/UX NFS share could do it.

A: st_blksize is called "the optimum I/O size" and unrelated to the units used for st_blocks. The optimum I/O size of course is filesystem specific. This is a result from the fast filesystem development from Berlekey in 1981/1982. Before, there was no optimum block size in the available filesystem
st_blocks is expressed in units of DEV_BSIZE that indeed is 1024 on HP-UX. DEV_BSIZE is a platform specific constant. Later, when FFS was renamed to UFS, there was a second filesystem in BSD UNIX with different behavior related to indirect blocks and that required this new stat() field. Before, du did just know the algorithm for indirect blocks from the filesystem.
If you run a HP-UX NFS fileserver and other NFS clients, you get wrong reports from the HP-UX NFS server for df unless HP did fix their problem during the past 15 years, where I had no access to recent versions of HP-UX. I know of no other UNIX with similar NFS related bugs.
BTW: up to NFSv3, NFS assumes a blocksize of 512 and HP would need to convert their NFS reports in the server. NFSv4 does not make that implicit assumption, but HP-UX still reports wrong numbers.
I know no other UNIX that is based on a 1024 DEV_BSIZE.


text:
Q: Tool to visualize system monitoring log on a web server I am sure there must be many existing ones there, just want to figure out what's the best fit for our requirements.
Basically we have a log file which we dump system monitoring data such as memory usage, CPU with timestamps.
What we want is to have a web server that visualize the system monitoring data live. I think it's not hard to implement (basically grab a window of data and draw some plots and put it on the web). Just wondering if there are existing tiny tools that are easy to use and have very friendly UIs.
I know Ambari provides interfaces that can visualize your data on live, while our system is very small and no need to bother that.
Many thanks,
ausgoo

A: The best way I feel is to push the data to collectd and move the rrd to the graphite srever where you can view all the stats easily.


text:
Q: Using delimiter to get multiple words as one string? I don't really know how to explain what I'm asking but I'm having trouble using a delimiter to isolate a multi-worded string.
Example: For line
3 James De Santa 2.30 friend 2010

I am not sure how to write my delimiter to have
String firstName = scanner.next(); //This would be "James"
String lastName = scanner.next(); //This would be "De Santa"
String relationship = scanner.next(); //This would be "friend"

I've tried
scanner.useDelimiter("[^a-zA-z'-]+");

but that returns "De" and "Santa" as two separate strings.


text:
Q: Is there an operator to calculate percentage in Python? I've recently learned that the " % " sign is used to calculate the remainder of an integer in Python. However I was unable to determine if there's another operator or method to calculate percent in Python.
Like with " / " which will give you the quotient, if you just use a float for one of the integers, it will actually give you the answer like traditional division. So is there a method to work out percentage?

A: use of %
def percent(expression="1000*12%") -> float:
    if "%" in expression:
        expression = expression.replace("%","")
        a, b = expression.split("*")
        a, b = float(a), float(b)
    return a*b/100

>>> percent("1500*20%")
300.0

Another way
p = lambda x : x/100
p20 = p(20)

>>> 150*p20
30.0

A: Brian's answer (a custom function) is the correct and simplest thing to do in general.
But if you really wanted to define a numeric type with a (non-standard) '%' operator, like desk calculators do, so that 'X % Y' means X * Y / 100.0, then from Python 2.6 onwards you can redefine the mod() operator:
import numbers

class MyNumberClasswithPct(numbers.Real):
    def __mod__(self,other):
        """Override the builtin % to give X * Y / 100.0 """
        return (self * other)/ 100.0
    # Gotta define the other 21 numeric methods...
    def __mul__(self,other):
        return self * other # ... which should invoke other.__rmul__(self)
    #...

This could be dangerous if you ever use the '%' operator across a mixture of MyNumberClasswithPct with ordinary integers or floats.
What's also tedious about this code is you also have to define all the 21 other methods of an Integral or Real, to avoid the following annoying and obscure TypeError when you instantiate it
("Can't instantiate abstract class MyNumberClasswithPct with abstract methods __abs__,  __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mul__,  __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__,  __rpow__, __rtruediv__, __truediv__, __trunc__")

A: There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.

A: You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:
def percentage(part, whole):
  return 100 * float(part)/float(whole)

Or with a % at the end:
 def percentage(part, whole):
  Percentage = 100 * float(part)/float(whole)
  return str(Percentage) + "%"

Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer), you would write:
def percentage(percent, whole):
  return (percent * whole) / 100.0

A: I have found that the most useful case for me is to compute the calculations as ratios and then printing the results formatting them as percentages thanks to Python formatting options:
result = 1.0/2.0            # result is 0.5
print(f'{result:.0%}')      # prints "50%"

A: Very quickly and sortly-code implementation by using the lambda operator.
In [17]: percent = lambda part, whole:float(whole) / 100 * float(part)
In [18]: percent(5,400)
Out[18]: 20.0
In [19]: percent(5,435)
Out[19]: 21.75

A: def percent(part, whole):
    try:
        return 100 * float(part) / float(whole)
    except ZeroDivisionError:
        return 0

A: Just use this
score_in_percentage = round( score *100 , 2 )
print(f' {score_in_percentage}% ') #50%


text:
Q: "An instance of NSFetchedResultsController requires a non-nil fetchRequest and managedObjectContext" How to solve this ?
https://github.com/hamza5645/progress-tracker-.git
full code
Already have a NSFetchedResultsController and a managedObjectContext
in the homeViewModel

import Foundation
import CoreData

class HomeViewModel: NSObject, ObservableObject {

    private var fetchedResultsController:            NSFetchedResultsController<MyList>
    private(set) var context: NSManagedObjectContext

    @Published var myLists: [MyListViewModel] = []

    override init() {
        self.context = CoreDataManager.shared.context
        fetchedResultsController = NSFetchedResultsController(fetchRequest: MyList.all, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        super.init()
        fetchedResultsController.delegate = self

        do {
            try fetchedResultsController.performFetch()
            guard let myLists = fetchedResultsController.fetchedObjects else { return }
            self.myLists = myLists.map(MyListViewModel.init)

        } catch {
            print(error)
        }
    }

    func saveNewList(newListName: String, colorCode: String) {

        let myList = MyList(context: context)
        myList.name = newListName
        myList.colorCode = colorCode
        do {
            try myList.save()
        } catch {
            print(error)
        }

    }

}

extension HomeViewModel: NSFetchedResultsControllerDelegate {
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        guard let myLists = controller.fetchedObjects as? [MyList] else { return }
        self.myLists = myLists.map(MyListViewModel.init)
    }
}

A: The error is misleading:
Form the documentation

Using NSFetchedResultsController
Creating the Fetched Results Controller.
You typically create an instance of NSFetchedResultsController as an instance variable of a table view controller. When you initialize the fetch results controller, you provide four parameters:
A fetch request. This must contain at least one sort descriptor to order the results..
...

Add a sort descriptor.
Edit: And replace
self.context = CoreDataManager.shared.context
fetchedResultsController = NSFetchedResultsController(fetchRequest: MyList.all, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

with
let context = CoreDataManager.shared.context
self.context = context
fetchedResultsController = NSFetchedResultsController(fetchRequest: MyList.all, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

Actually you should get a accessing self before having called super error.


text:
Q: What is $\Re(e^i)$?
What is $\Re(e^i)$?

My book says answer is $e$.  Can that be right?
I know $e^{i \pi} = \cos \pi + i \sin \pi = -1$
So that would mean $e^i = \cos 1 + i \sin 1$ and the real part would be $\cos 1$.  That's not the book's answer.

A: You're right, $e^i=\cos 1+i \sin 1$. So the answer is $\cos 1$.


text:
Q: Why my service executes once and then it doesn't function even its running in the background? Here is my code of MapService class is there any solution for my problem?
public class MapService extends Service
    {
        GPSTracker gpsTracker;
        double lat,lon;
        SharedPreferences sharedPreferences;
        String phone,mrequestBody,url="";
        @Override
        public void onCreate() {//onCreate Method ,initializing .
            // TODO Auto-generated method stub
            super.onCreate();
            gpsTracker = new GPSTracker(MapService.this);
            sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            Notification notification = new Notification();
            startForeground(1, notification);
        }

//in this override function i have wrote my code to post location but it only executes once i guess the problem is somewhere here please give your valuable suggestions.
@Override
public int onStartCommand(Intent intent, int flags, int startId)
        {
//acquiring latitude and longitude
          lat=  gpsTracker.getLongitude();
           lon= gpsTracker.getLatitude();

           phone= sharedPreferences.getString("phone_number","");
            Toast.makeText(MapService.this, lat + " latitude ," + lon + " longitude ," + phone + " phone ", Toast.LENGTH_LONG).show();
    //        RequestQueue queue = Volley.newRequestQueue(this);
            final JSONObject jsonObject = new JSONObject();

            try {
                jsonObject.put("latitude", lat);
                jsonObject.put("longitude", lon);
                jsonObject.put("phone",phone);;
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
    //parsing json Onject to string
            mrequestBody = jsonObject.toString();
     Toast.makeText(this, url, Toast.LENGTH_SHORT).show();
                final JsonObjectRequest jsonObjReq = new JsonObjectRequest(
                        Request.Method.POST, url, null,
                        new Response.Listener<JSONObject>()
                        {
                            @Override
                            public void onResponse(JSONObject response)
                            {
                                Log.i("location", response.toString());
                                //pDialog.dismiss();
                                Toast.makeText(MapService.this, (String) String.valueOf(response), Toast.LENGTH_SHORT).show();
                            }
                        }, new Response.ErrorListener()
                {

    //Volley error response
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("Error: " + error.getMessage()
                        );
                      //  pDialog.dismiss();
                       Toast.makeText(MapService.this,"ServiceMap :"+error.getMessage(),Toast.LENGTH_LONG).show();
                    }
                })
                {
                    /**
                     * Passing some request headers
                     * */
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("content-type", "application/json");
                        return headers;
                    }
    //getbody function of volley POST request
                    @Override
                    public byte[] getBody() {
                        try {
                            return mrequestBody == null ? null : mrequestBody.getBytes("utf-8");
                        } catch (UnsupportedEncodingException uee) {
                            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                                    mrequestBody, "utf-8");
                            return null;

                        }
                    }
                };
    // Adding request to request queue
                Volley.newRequestQueue(this).add(jsonObjReq);
                return Service.START_NOT_STICKY;
        }

Here in below activity i'm calling my service to instantiate
Intent serviceIntent = new Intent(Service_Men_LoginActivity.this,MapService.class);
                              //serviceIntent.setAction("com.example.lenovo.khadam.MapService");

The Only problem is that it execute once all the toast in the MapService shown only once but i want this service to execute until i call its stopService Method.And i don't want this service to be a foreground service because no notification should appear to user .


text:
Q: nodejs + archiver, Why this zip archive downloader does not work (Unexpected end of archive)? I want to download multiple files using archiver+express. Server should send a .zip file in response to a post request from client.
The following code creates a zip archive, sends it, shows a save as dialog to user and let him open the archive. By default WinRAR opens the archive and lists file inside (only one file), with a ! 98I9ZOCR.zip:Unexpected end of archive error.
What is wrong?
server:
    var archive = archiver('zip');
    archive.on('error', function(err) {
        res.status(500).send({error: err.message});
    });
    //on stream closed we can end the request
    archive.on('end', function() {
        console.log('Archive wrote %d bytes', archive.pointer());
    });
    //set the archive name
    res.attachment('userarchive.zip');
    //this is the streaming magic
    archive.pipe(res);
    for (var fi in req.body.filename) {
        var _file = src + '/' + req.body.filename[fi];
        archive.file(_file, { name: p.basename(_file) });
    }
    archive.finalize();

client:
   $http({
        method: 'post',
        url: to,
        data: data
    }).success(function(data, status, headers, config){
        var file = new Blob([data], {type: 'application/zip'});
        window.location = URL.createObjectURL(file);
    }).error(function(data, status, headers, config){
        console.log('Error');
    });

A: It seems like you need to wait until the finalization is finished. The archive.finalize(); method returns a promise.
Here you're listening the "on end" event but not ending the request as the comment says
//on stream closed we can end the request
archive.on('end', function() {
        console.log('Archive wrote %d bytes', archive.pointer());
    });

Also, I've found that even after the promise that is returned from the archive.finalize() method is resolved the archiver may still be piping some data. I haven't found anything better than waiting after the finalize promise is resolved

A: I forgot to set the right response type:
responseType: 'arraybuffer'


text:
Q: laravel 5 mail::send() not working in controller It show error while executing my code on server...

page not working on submit the form
Controller Code

class SaveFormController extends Controller {
public function create(){
    return view('/join-our-team');
}
public function store(SaveFormRequest $request){
    $data   =   Input::all();
    Mail::send('emails.reply', $data, function($message){
        $message->from($data['email'] , $data['name']);
        $message->to('abc@asd.com' , 'team');
    });
    return redirect('/');
 }
}

My html code was

        @foreach($errors->all() as $error)

{{ $error }}

        @endforeach

    {!! Form::open(array('route' => 'applicant_store', 'class' => 'form')) !!}

        {!! Form::label('Your Name') !!}
        {!! Form::text('name', null,
            array('class'=>'form-control',
                  'placeholder'=>'Your name')) !!}

        {!! Form::label('Your E-mail Address') !!}
        {!! Form::text('email', null,
            array('class'=>'form-control',
                  'placeholder'=>'Your e-mail address')) !!}

        {!! Form::label('Your Education') !!}
        {!! Form::select('education', ['Post Graduate', 'Graduate', '12th'], null, ['class'=>'form-control'] ) !!}

        {!! Form::label('Your Contact No.') !!}
        {!! Form::text('phone', null,
            array('class'=>'form-control',
                  'placeholder'=>'Your 10 digit Mobile No.')) !!}

    {!! Form::label('Experience') !!}

            {!! Form::label('Years') !!}
            {!! Form::select('year',[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, '10+'],null, ['class'=>'form-control']) !!}

            {!! Form::label('Months') !!}
            {!! Form::select('month',[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],null, ['class'=>'form-control']) !!}

        {!! Form::label('Resume (doc,docx,pdf format)') !!}
        {!! Form::file('applicant_resume',['class'=>'form-control']) !!}

        {!! Form::submit('Submit Details',
          array('class'=>'btn btn-success')) !!}

    {!! Form::close() !!}

and my app/mail.php configuration is
<?php
return [
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.abc.com'),
'port' => env('MAIL_PORT', 587),
'from' => ['address' => 'my_mail', 'name' => 'team'],
'encryption' => 'tls',
'username' => env('my_email'),
'password' => env('my_pwd'),
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,
];

Cannot found the error after try diffetrent......
Please help me to get the solution..

A: Your problem is the data you're passing to the mail function.  The second parameter is for the data that is being sent to the view not within the function.  Change it to this
public function store(SaveFormRequest $request){
    $data   =   Input::all();
    Mail::send('emails.reply', $data, function($message) use($data) {
        $message->from($data['email'] , $data['name']);
        $message->to('abc@asd.com' , 'team');
    });
    return redirect('/');

A: if your html code and controller are ok than you just need to ..change the  file with like this...
config/mail.php
'driver' => env('MAIL_DRIVER', 'mail'),
'host' => env('MAIL_HOST', 'www.yourdomain.com'),
'port' => env('MAIL_PORT', 587),
'from' => ['address' => 'info@domain.com', 'name' => name'],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,

and change the .env file to
MAIL_DRIVER=mail
MAIL_HOST=www.yourdomain.com
MAIL_PORT=587
MAIL_USERNAME=email address
MAIL_PASSWORD=your email plassword
MAIL_ENCRYPTION=null

hope so it will work


text:
Q: low pass FIR filter - with no latency I'm using a FIR filter to oversample audio. It's a simple typical windowed sinc, i.e. a sinc function truncated and windowed. As usual it requires past and 'future' samples to work. in practical terms this means the audio output is delayed.
 The sinc function is an ideal low pass filter. My question what is the equivalent, except with no 'future' samples required. I guess this function is the same as the impulse response of a brick wall IIR filter. It will have a perfect brick-wall cuttoff, but will not have perfect phase response.

A: If you want a particular frequency response, then a minimum phase filter would provide the lowest "delay" or latency of IIR or FIR filter with that response.  An IIR filter with all its poles and zeros inside the unit circle would be a minimum phase filter.  A minimum phase filter is also not linear phase, so you'll have to release that constraint to reduce latency.  A FIR filter can be approximately converted to minimum phase either by cepstum techniques (see Oppenheim & Schafer), or by numerically solving for an IIR filter with a similar enough frequency response, flipping all the poles and zeros inside, and converting a suitably windowed impulse response back to a FIR filter.
Trying to get any less than minimum phase delay will flatten a filter's transition band(s) until, at "zero" delay, the filter would either have to reject nothing or reject everything, and thus become useless.


text:
Q: Getter methods in java with asynchronous connection needing a delay I'm making a series of connections asynchronously via MySQL, and I have a class which contains a bunch of easy-accesible static methods to update/remove/clear/get/etc data.
The issue I'm confronted with is that the getter methods won't return the proper value (practically ever) because they are returned before the async connection gets a chance to update the value to be returned.
Example:
public static int getSomething(final UUID user)
{
    Connection c = StatsMain.getInstance().getSQL().getConnection();

    PreparedStatement ps;

    try
    {
        ps = c.prepareStatement("select something from stats where uuid=?");
        ps.setString(1, user.toString());

        ResultSet result = ps.executeQuery();
        return result.getInt("something");
    }
    catch (SQLException e)
    {
        return false;
    }
}

(Not copy & pasted, but pretty close)
I realize I can use a 'callback' effect by passing an interface to the method and doing such, but that becomes very tedious when the database stores 10 values for a key.

A: Sounds like you're looking for Futures since Java 6 or CompletableFuture, which is new in Java 8

A: Solution 1:
The best method I've come up with is have a thread with a loop in it that waits for MySQL to return values and responds to each value.  This is rather like the callback in the get routine, but you only have the one loop.  Of course, the loop has to know what to do with each possible returned piece of data.
This means rethinking a bit how your program works.  Instead of: ask a question, get an answer, use the answer, you have two completely independent operations.  The first is: ask a question, then forget about it.  The second is: get an answer, then, knowing nothing about the question, use the answer.  It's a completely different approach, and you need to get your head around it before using it.
(One possible further advantage of this approach is that MySQL end can now send data without being prompted.  You have the option of feeding changes made by another user to your user in real time.)
Solution 2:
My other solution is simpler in some ways, but it can have you firing off lots of threads.  Just have your getSomething method block until it has the answer and returns.  To keep your program from hanging, just put the whole block of code that calls the method in its own thread.
Hybrid:
You can use both solutions together.  The first one makes for cleaner code, but the second lets you answer a specific question when you get the reply.  (If you get a "Customer Name" from the DB, and you have a dozen fields it could go in, it might help to know that you did ask for this field specifically, and that you asked because the user pushed a button to put the value in a specific text box on the screen.)
Lastly:
You can avoid a lot of multithreading headaches by using InvokeLater to put all changes to your data structures on your EventQueue.  This can nicely limit the synchronization problems.  (On the other hand, having 20 or 30 threads going at once can make good use of all your computer's cores, if you like to live dangerously.)
You may want to stick with synchronized calls, but if you do want to go asynchronous, this is how I'd do it.  It's not too bad once you get some basic tools written and get your brain to stop thinking synchronously.


text:
Q: Weird CSRF error in Django with Nginx and Gunicorn Background
When I try to access into my Django administration panel, I get Forbidden (403) CSRF verification failed. Request aborted., even if I disable the CSRF middleware. This affects all users, in different locations with different browsers. I've followed the steps to fix this error of several questions in stackoverflow, but still the same. This has been killing me for weeks.
Issue
I'm using https with Cloudflare (Free plan), but this error persist if I deactivate https. This occurs in mydomain.com/admin
Known facts

*

*I'm using Django 2.0 and gunicorn 19.0

*I've checked the cookies of my browser

*I've tried removing django.middleware.csrf.CsrfViewMiddleware

*This occurs just in the Django Admin dashboard, when CSRF middleware is enabled, the another POST or GET forms works fine.

*I'm logged into my Django Admin dashboard, and if I logout, I can login again with no problems, but if I try from another place, or with another user, the problem occurs again.

*Gunicorn config it's the default.

Configuration files
Settings.py
CSRF_TRUSTED_ORIGINS = ['.domain.com']
CSRF_COOKIE_DOMAIN = ['.domain.com', '127.0.0.1']
CSRF_COOKIE_SECURE = True
ALLOWED_HOSTS = ['127.0.0.1', 'domain.com', 'www.domain.com', '104.336.44.153', '.domain.com']

MIDDLEWARE = [
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Nginx
server {
    server_name domain.com;

    access_log off;

    location /static {
        alias /opt/myenv/myenv/static/;
    }

    location /descargas/dir/ {
        alias /opt/myenv/myenv/dir/;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }
}

Please help! Thanks for reading.

A: The CSRF cookie is set by CsrfViewMiddleware, so you should keep it.
I would try to change your MIDDLEWARE ordering:
MIDDLEWARE = [
 'django.middleware.security.SecurityMiddleware', # THE FIRST
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


text:
Q: phonegap sqlite database max size? What is max db size allowed using phonegap storage api?
What are the options in case the DB size will increase gradually as my users start using the app and adding data to it. ?

A: The database size is not limited to 5MB it can keep on increasing till the phone storage is capable of handling it.
Neither PhoneGap nor SQLite limits the size of the app.

A: I think 5MB WebSQL DB size limit of Chrome more information please check this group link


text:
Q: May I have an input for GET parameter in a form using POST method Is it possible that, a form contains multiple inputs, when submit the form, some input values go into post body while some go into the URL?
<form action=sample.php method=POST accept-charset=gbk>
  <input name=a />
  <input name=b />
</form>

And when submit, it POST b=someval to sample.php?a=itsval
——
I'm handling an old system. The backend read parameters some from get, some from post, and not using utf-8. No one can change its code.


text:
Q: What is dimension order of numpy shape for image data? I am using nibabel lib to load data from nii file. I read the document of the lib at http://nipy.org/nibabel/gettingstarted.html, and found that

This information is available without the need to load anything of the main image data into the memory. Of course there is also access to the image data as a NumPy array

This is my code to load the data and it shapes
import nibabel as nib
img = nib.load('example.nii')
data = img.get_data()
data = np.squeeze(data)
data = np.copy(data, order="C")
print data.shape

I got the result
128, 128, 64

What is order of data shape? Is it WidthxHeightxDepth? And my input must  arranged as depth, height, width. So I will use input=data.transpose(2,0,1). Is it right? Thanks all
Update: I found that the Numpy will read the image by order Height x Width x Depth as the reference http://www.python-course.eu/images/axis.jpeg

A: OK, here's my take:
Using scipy.ndimage.imread('img.jpg', mode='RGB'), the resulting array will always have this order: (H, W, D) i.e. (height, width, depth) because of the terminology that numpy uses for ndarrays (axis=0, axis=1, axis=2) or analogously (Y, X, Z) if one would like to visualize in 3 dimensions.
# read image
In [21]: img = scipy.ndimage.imread('suza.jpg', mode='RGB')

# image shape as (H, W, D)
In [22]: img.shape
Out[22]: (634, 1366, 3)

# transpose to shape as (D, H, W)
In [23]: tr_img = img.transpose((-1, 0, 1))

In [23]: tr_img.shape
Out[23]: (3, 634, 1366)

If you consider the img_shape as a tuple,
#  index    (0,   1,    2)
img_shape = (634, 1366, 3)
# or index  (-3,  -2,  -1)

Choose which one is a convenient way for you to remember.

NOTE: The scipy.ndimage.imread() API has been removed since Scipy 1.2.0. So, it is now recommended to use imageio.imread(), which reads the image and returns Array, a subclass of numpy array, following the same conventions discussed above.
# read image
$ img = imageio.imread('suza.jpg', format='jpg')

# convert the image to a numpy array
$ img_np = np.asarray(img)

PS: It should also be noted that libraries like tensorflow also (almost) follows the same convention as numpy.
tf.image_decode_jpeg()  returns:

A Tensor of type uint8. 3-D with shape [height, width, channels]


text:
Q: Error on mount through php "exec" I'm trying to mount an iscsi virtual disk, but if I execute the command through the exec function in php this give me that error: mount: special device /dev/sdf1 does not exist.
But if I run the command directly in the console it run well!!
What can I do?
I'm obtaining the /dev/sdf1 in a good way, and it exists, but only through php doesn't work.
Thanks
I'm running the command with sudo and run it in console as www-data user always with sudo, so, I suppose that is the same enviroment.
sudo mount -t ext3 /dev/sdf1 /san_disks/RIBS_2
The sudoers file has this lines:
www-data    ALL = (root) /usr/bin/iscsiadm, /bin/mount, /bin/umount
%www-data ALL=NOPASSWD: ALL

And it works in console.

A: This was happening because "/dev" wasn't updated. I made a sleep(1) and it works!!


text:
Q: How to copy structure inside the function in C? memcpy I'm student, so sorry for a stupid question if it's actually is. Didn't finish C lang module yet :c
So the memcpy(); in core.c file doesn't work like it should. Or maybe it just works in the way I don't need. The question is help to find a solution for the following task:
The idea is to have a function multiply(); which accepts nMatrix [4x4] and nVector [4] pointers. It suppose to make buffer(tempVector) for getting multiplied results and then memcpy the whole structure to nVector.
But instead beautiful multiplied vector result it gives garbage from the memory.
Also before go out of the scope I free the tempVector array to prevent any bad heap memory management. Unfortunately the nVector array is still depends on copied memory from tempVector.
I would appreciate any advice! :D
So that is the problem code part -
core.c
#include "core.h"
#include "init.h"
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <string.h>
#define vecLength 4

typedef struct Vector {
double * vector;
int N;
} Vector;

typedef struct Matrix {
double ** matrix;
int nRow;
int nCol;
} Matrix;
...
...
void multiply(Vector* nVector, Matrix* nMatrix)
    {
    Vector tempVector;
    vectorInit(&tempVector);
    for(int i = 0; i < nMatrix->nRow; i++)
        for(int j = 0; j < nMatrix->nCol; j++)
            tempVector.vector[i]+= nMatrix->matrix[i][j]*nVector->vector[j];

    memcpy(nVector,&tempVector,sizeof(Vector));
    vectorFree(&tempVector);
    }

main.c
int main(){
    ...
    ...
    Vector* v_Test;
    Matrix* m_Test;

    //Test structures memory allocation
    v_Test = (Vector*) malloc(sizeof(Vector));
    m_Test = (Matrix*) malloc(sizeof(Matrix));

    //Initialization of vector in structure
    vectorInit(v_Test);

    for(int i = 0; i < v_Test->N; i++)
        v_Test->vector[i]=i+1;

    //Print vector
    vectorPrint(v_Test);
    getch();

    //Initialization of matrix in structure
    matrixInit(m_Test);

    for(int i=0; i<m_Test->nCol; i++)
        for(int j=0; j<m_Test->nCol;j++)
            m_Test->matrix[i][j]=m_Test->nRow*i+j;

    //Print matrix
    matrixPrint(m_Test);
    getch();

    multiply(v_Test,m_Test);

    vectorPrint(v_Test);
    getch();

    vectorFree(v_Test);
    getch();

    matrixFree(m_Test);
    getch();
  }
...
...
}

A: Already found the solution by trying the last idea before upload. So when you call memcpy it just copies array pointer of the vector which will be deallocated in the next instruction vectorFree();. So to prevent that we just copy the actual array from tempVector to nVector structure!*
Solution in code:

memcpy(nVector->vector,tempVector.vector,vecLength*sizeof(double));

I still upload it cause I paid 45 min to write this question. And I hope it will help anyone in the future :)
Stay cool guys and have a wonderful day :D


text:
Q: Abrikosov and his fluxoids (why only one ?) In superconductivity, when we solve the ginzburg-landau equations relative to a 2 dimensional plane immersed in a magnetic field, we find that a periodic lattice of vortices is a solution. When we look at the higher critical magnetic field, we suppose that the plane is covered with vortices each having inside a flux equal to an integer n times the quantum flux $h/e$ and we assume just $n=1$. I can understand intuitively why this is the less energical configuration (it's just easier to make some holes somewhere else), but does someone know how to show it explicitly (actually, I didn't know how to calculate the free energy associate without having the complete solution which is an Infinite serie...) or know some reference that proves why should this state with multi-fluxoids be unstable ?
Thanks a lot if you can help !


text:
Q: Buildfire - Is there a way to direct people to another tab within the admin dashboard? In my admin dashboard I have a custom tab that is used for displaying access requests made by users within the widget.  I give the admin some options in this custom tab.  One of these options is to grant the request.  When the admin grants the requests however, they must then assign the user that requested access to a plugin so they can be redirected in the future.
I have this functionality set up in another tab and don't really want to replicate it in this custom tab if I don't have to.  Is there anyway to, on clicking of the grant access button, send the admin to the other tab with some data from previous tab?

A: Unfortunately There is no navigate to Tab feature. However you can actually navigate to other page directly which will take you there under the same tab (not ideal but will get the job done)
Or a much cleaner solution would be building a SPA architecture like the People or Places plugin with virtual tabs and breadcrumbs
https://github.com/BuildFire/sdk/wiki/How-to-use-Breadcrumbs
ref:

*

*https://github.com/BuildFire/peoplePlugin

*https://github.com/BuildFire/placesPlugin
Hope this helps


text:
Q: how to add information to json using Python in fast way I have geojson file that contains places. where "'parking': 0 " all the time.
'type': 'Feature',
'properties': {
 ...// Other fields
'latitude': -74.0121613846062,
'longitude': 40.7043040747924,
'parking': 0 }

I would like to update it from another csv file data set.
-------------------------------------------
 latitude    + Longitude + Possible_parking
-------------------------------------------
-74.012161      40.804        -1

-1: Impossible to park
1: Possible Parking
I would like to update the geojson file.
data = pd.read_csv("data/_all.csv")

geojson_in = open('data/input.json', 'r')
tracts_geojson = json.load(geojson_in)
geojson_in.close()

# For each record in the geojson file, add location information
for i, r in enumerate(tracts_geojson['features']):
    for x in range(len(data.latitude.values)):
        if ((r['properties']['latitude']==data["latitude"][x]) and (r['properties']['longitude']== data["longitude"][x])):
            r['properties']['parking'] = str(data['Possible_parking'][x])

The problem with script I am using is that it takes so long time (+24 hours now).
I don't wanna convert csv file to json directly, 'cause input.json contains other information that I can't find in CSV file.
Is there any pythonic way to do this faster ?

A: You are looping through your whole parking CSV rows for each feature in the JSON file; this is a N * M loop; a 600MB CSV file contains roughly 30 million parking space entries (at roughly 21 bytes per row), and you are looping through all 30 million per feature.
You want to load the whole CSV file into a dictionary:
import csv

with open(("data/_all.csv", 'rb') as incsv:
    reader = csv.reader(incsv)
    next(reader, None)  # skip presumed header
    parking = {(lat, long): park for lat, long, park in reader}

Use this instead of looping over the whole dataset for each JSON entry:
for feat in tracts_geojson['features']:
    lat, long = feat['properties']['latitude'], feat['properties']['longitude']
    if (lat, long) in parking:
        feat['properties']['parking'] = parking[lat, long]

Lookups in a dictionary take constant time; instead of 30 million loops per feature you now use one straight-forward lookup per feature.


text:
Q: Why it's not working my localhost when I run an Angular/React project? When I run npm start in a React or Angular project, the page stuck loading forever in blank.
I have tried to reinstall node, change ports and other things, and nothing. It's very strange. My OS is MacOS 10.14.6 and It started to fail suddenly days ago. And I have in my localhost mysql, apache and php running without problems.
There are not error messages.
-----EDIT-----
I tried to create new React and Angular apps too but localhost still not working.
-----EDIT 2-----
Sometimes, randomly in Safari incognito mode works, but I have disabled cache and try incognito mode on Chrome too, but nothing. Firefox is not working too.
I am trying the correct port and there are not messages in console.

A: FALSE ALARM
It was the antivirus but I don't know exactly why. Maybe was some extra security, but It's strange because localhost of Apache works for example.


text:
Q: SQLServer Campo Identity pula para 1001 Notei que uma das tabelas teve um saldo do 9 para 1001. A princípio imaginei que algum colega teria feito um teste no banco e excluído o registro na sequencia fazendo com que o número tivesse esse salto.
Agora aconteceu com uma outra tabela sem que ninguém tenha feito um insert com posterior exclusão. Alguém já teve esse problema? Essa é a tabela:
CREATE TABLE [dbo].[PcpsRota](
    [RotaId] [int] IDENTITY(1,1) NOT NULL,
    [EmpId] [int] NOT NULL,
    [RotaDes] [varchar](80) NOT NULL,
    [UsuId] [int] NOT NULL,
    [UsuDta] [datetime] NOT NULL,
    [UltUsuId] [int] NOT NULL,
    [UltDta] [datetime] NOT NULL,
    [RotaSit] [smallint] NOT NULL,
PRIMARY KEY CLUSTERED
(
    [RotaId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[PcpsRota] ADD  DEFAULT (getdate()) FOR [UltDta]
GO
ALTER TABLE [dbo].[PcpsRota] ADD  CONSTRAINT [DF_RotaSit]  DEFAULT ((2)) FOR [RotaSit]
GO
ALTER TABLE [dbo].[PcpsRota]  WITH CHECK ADD  CONSTRAINT [CHK_PcpsRota_UltimoUsuario_DeveSerInformado] CHECK  (([UltUsuId]>(0)))
GO
ALTER TABLE [dbo].[PcpsRota] CHECK CONSTRAINT [CHK_PcpsRota_UltimoUsuario_DeveSerInformado]
GO

A: A partir da versão SQL Server 2012, por motivos de performance, os valores IDENTITY são armazenados em cache e alguns desses valores podem ser perdidos durante uma falha no banco de dados ou quando o servidor reinicia, assim resultando em um gap na sequência dos valores. Esse é o comportamento padrão do SQL Server.
Se você não deseja esse comportamento, você tem duas opções:

*

*Usar uma SEQUENCE com a opção NOCACHE.
 CREATE SEQUENCE CountBy1
     START WITH 1
     INCREMENT BY 1
     NOCACHE;
 GO

 CREATE TABLE t1 (
 Id INT PRIMARY KEY DEFAULT NEXT VALUE FOR CountBy1,
 col INT NOT NULL);
 GO

*Ou, usar a trace flag 272.
Microsoft Docs: https://docs.microsoft.com/pt-br/previous-versions/sql/sql-server-2012/ms186775(v=sql.110)?redirectedfrom=MSDN


text:
Q: How to extract information from map in java I need to extract and use the departureTime and arrivalTime values stored inside of a linkedlist inside of a map for the next step in my assignment but I don't know the syntax or if it is even possible to extract just that set of information from the specific value in the map and store them as values or a new list.  Is this possible or should I abandon this method and take a different route?
public Info (String destination, double departureTime, double arrivalTime){
        this.destination = destination;
        this.departureTime = departureTime;
        this.arrivalTime = arrivalTime;
}

public class Route {
    Map<String,LinkedList<Info>> airportFlightMap = new HashMap<>();
    LinkedList<Info> destinations;
    private int array[];
    private int arraySize;
    private int heapSize;

    public Route(int arraySize) {
        array = new int [arraySize];
        this.arraySize = arraySize;
        heapSize = 0;
    }

    public void fillHash(String origin, String destination, double departureTime, double arrivalTime) {
        if(airportFlightMap.containsKey(origin)){
            destinations = airportFlightMap.get(origin);
            destinations.add(new Info(destination, departureTime/100, arrivalTime/100));
        }
        else{
            destinations = new LinkedList<>();
            destinations.add(new Info(destination, departureTime/100, arrivalTime/100));
            airportFlightMap.put(origin, destinations);
        }
    }

A: Entering something like this should fix it:
@Listener
public void sendPacket(EventSendPacket event) {
    if (event.getStage() == EventStageable.EventStage.PRE) {
        if (event.getPacket() instanceof CPacketPlayerDigging) {
            final Minecraft mc = Minecraft.getMinecraft();

            final CPacketPlayerDigging packet = (CPacketPlayerDigging) event.getPacket();
            if (packet.getAction() == CPacketPlayerDigging.Action.RELEASE_USE_ITEM) {
                if (mc.player.inventory.getCurrentItem().getItem() instanceof ItemBow && mc.player.getItemInUseMaxCount() >= 20) {
                    if (!mc.player.onGround) {
                        mc.player.connection.sendPacket(new CPacketPlayer.Position(mc.player.posX, mc.player.posY - 0.1f, mc.player.posZ, false));
                        mc.player.connection.sendPacket(new CPacketPlayer.Position(mc.player.posX, mc.player.posY - 10000f, mc.player.posZ, true));
                    }
                }
            }
        }
    }
}

A: To iterate over a map you can check this question. There are multple ways to do it.
Now, your structure is like this:
|------|-------|
| key1 | value |
|------|-------|
| key2 | value |
|------|-------|
| ...  |  ...  |
|------|-------|
| keyN | value |
|------|-------|

Where key is an String and value is a LinkedList<Info>. So you can think in this:
|------|-------|
| key1 | value | --> [][][][]...[]
|------|-------|
| key2 | value | --> [][][][]...[]
|------|-------|
| ...  |  ...  | -->   . . .
|------|-------|
| keyN | value | --> [][][][]...[]
|------|-------|

Iterating through the map is like iterate over every key. And then you can get the key or the value.
At this point, with this code:
airportFlightMap.forEach((k,v)->System.out.println("k = "+k));

You will print the key in console. Also, note that forEach has two values: k and v, that are key and value. So you can get each value for each key. That's mean you can iterate over each item into the map.
And, how to get an specific value? Is as easy as call get() method:
LinkedList<Info> value = airportFlightMap.get("key1");

Using get() you can retrieve the value asociated with the key passed into paramater.
So you can using this to get the value you want.
Example here:
airportFlightMap.forEach((key,value)->{
    // key is an string
    System.out.println("k = "+key);
    // value is the LinkedList associated with the key
    System.out.println("v = "+value.size());
});

To get the values departureTime and arrivalTime you only have to iterate over every list looking for that.
airportFlightMap.forEach((key,value)->{
    for(Info i : value) {
        // Do whatever you want with these values
        i.getArrivalTime());
        i.getDepartureTime());
    }
});

Also you can use lambda expresions if you want, but I suposse these high order functions are not easy to understand for a begginer.
But you can check this
As code example, you can use filter to search for a value in the whole list without iterate over every position:
airportFlightMap.forEach((key,value)->{
    Optional<Info> i = value.stream().filter(v -> v.getDepartureTime()==3).findFirst();
    if(i.isPresent()) {
        //Exists into key
    }else {
        //No exists into key
    }
});


text:
Q: Why i am getting a Number FormatException? I made a program on the code chef.I am getting a correct output on my eclipse ide and when i  submitted it the output shown on CodeChef ide is :
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Prog1.stop(Main.java:16)
at Prog1.main(Main.java:50)

Here is the question Link:https://www.codechef.com/problems/TEST
Here is my solution to the problem:
//life universe and EveryThing
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Prog1
{
 public static void stop() throws IOException
 {

   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   String s1=br.readLine();
   int x=Integer.parseInt(s1);
   int ar[]=new int[x];
   int k=0;
    for(int i=0;i<x;i++)
     {
       BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
       String s2=br1.readLine();
       int p=Integer.parseInt(s2);
       ar[k++]=p;
     }
   for(int m=0;m<x;m++)
    {
       System.out.println(ar[m]);
    }
   for(int y=0;y<x;)
    {
        if(ar[y]!=42)
        {
          System.out.println(ar[y]);
          y++;
        }
        else
        {
          break;
        }

    }

}
 public static void main(String s[]) throws IOException
 {
 stop();
 }
}

A: Cause:
You are doing Integer.parseInt(). That causes exception for  non valid strings and nulls  etc ..
Solution:
1) Have a null check
2) Try=Catch it and do necessary in catch.

A: The immediate cause is that you're passing null into Integer.parseInt. Next you need to work out why that's happening...
You're creating a new BufferedReader wrapping System.in on each iteration... that's likely to be reading more than just a single line, which means some of the lines of input are effectively being swallowed.
Just create one BufferedReader at the start, and use that for the whole program. You could also check whether the return value for readLine is null, but as that would indicate invalid data it's not awful to just let that throw in the way it already is doing...

A: first do a check if(s1!=null) then int x=Integer.parseInt(s1); use exception handling concept try catch.
            try{
                   if(s1!=null){
                       int x=Integer.parseInt(s1);
                   }
               }catch(NumberFormatException e){

               }


text:
Q: strings are missing when i try to print(response.text) I am learning & working with python from couple of days.
In my source code need to read the http contents.
I am trying to scrape http using request.get(httplink).
For debugging purpose i am trying to display all the contents of http using print(response.text).
But i could see few of the strings are not displayed when i run the code.
My question is print(response.text) will displays all the strings from the http page??Please someone answer to my question as i am not able to proceed further.

A: The text property of Response object is just content, but decoded according to headers. First of all try check out content field and find missing strings there. This is about output (console), i presume :)


text:
Q: How to set ScrollViewer or scroll (dynamically created grid)? Here I'm dynamically creating grid on form. The code is working fine but I want this grid in scroll viewer or scroll bar (vertical). Can any one tell me how to set scroll in this code.
   Grid DynamicGrid = new Grid();
        DynamicGrid.Width = 400;
        DynamicGrid.HorizontalAlignment = HorizontalAlignment.Right;
        DynamicGrid.VerticalAlignment = VerticalAlignment.Top;
        DynamicGrid.Margin = new Thickness(50);
        DynamicGrid.ShowGridLines = false;
        DynamicGrid.Background = new SolidColorBrush(Colors.LightSteelBlue);

        // Create Columns
        ColumnDefinition gridCol1 = new ColumnDefinition();
        DynamicGrid.ColumnDefinitions.Add(gridCol1);

        // Create Rows
        RowDefinition gridRow1 = new RowDefinition();
        gridRow1.Height = new GridLength(30);
        DynamicGrid.RowDefinitions.Add(gridRow1);

        TextBlock txtBlock2 = new TextBlock();
        txtBlock2.Text = "Age";
        txtBlock2.FontSize = 14;
        txtBlock2.FontWeight = FontWeights.Bold;
        txtBlock2.Foreground = new SolidColorBrush(Colors.Green);
        txtBlock2.VerticalAlignment = VerticalAlignment.Top;
        Grid.SetRow(txtBlock2, 0);
        Grid.SetColumn(txtBlock2, 1);

        TextBlock ageText = new TextBlock();
        ageText.Text = "33";
        ageText.FontSize = 12;
        ageText.FontWeight = FontWeights.Bold;
        Grid.SetRow(ageText, 1);
        Grid.SetColumn(ageText, 1);

        // Display grid into a Window
        window.Content = DynamicGrid;

A: I think the easiest way to do that is to include the Grid into a ScrollViewer:
ScrollViewer viewer = new ScrollViewer();
viewer.Content = DynamicGrid;
Window.Content = viewer;

Best regards,


text:
Q: SSIS execute sql commands stored in a column of a table
Error: error occurred while extracting the result into a variable of type (DBTYPE_WSTR). Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Using SSIS I have placed in a sql column commands that will convert a pdf to a blob they have been tested and work individually.  So I would like to query the table column pass it to a exec sql task and execute each command.  I have tried many different things currently I have a execute sql task resultset being set to "full result set"  in the ResultSet the name is set to 0 and variable is User::sqlcmds this goes into a foreach loop container with collection tab setting of ADO object source variable = User::sqlcmds  and Enumeration mode as Rows in the first table.  Variable Mappings tab has Variable = User::sqlcmdenu and Index set to 0.  Within the foreach container I have a execute sql task and the sqlstatement set to:
declare @sql nvarchar(max)
set @sql= CONVERT(NVARCHAR(4000),'  ' + ?)
exec sp_executesql @sql

Parameter mapping: Variable name=user::sqlcmds, Direction: Input, Datatype:NVARCHAR, parameter name inputsqlcmd.
what am I doing wrong?
Tried using data flow, now trying execute sql and foreach. neither works.

Error: error occurred while extracting the result into a variable of type (DBTYPE_WSTR). Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

A: Got it to work by going back to dataflow task:
oledb source has-> select convert(varchar(4000),cmd) cmd from attcmd
then used derived column to convert -> (DT_WSTR,4000)cmd   (this solves the non Unicode to Unicode problems).
this is input into oledb command with component properties tab set to ->
declare @sql nvarchar(max)
set @sql= CONVERT(NVARCHAR(4000),?)
exec sp_executesql @sql WITH RESULT SETS NONE
be sure to set column mapping of the input column to Param_0!
Data type of input column is DT_WSTR and Param_0 data type is Unicode string [DT_WSTR].


text:
Q: How do I use environment variables in a static site inside docker? I have a react app built with webpack that I want to deploy inside a docker container. I'm currently using the DefinePlugin to pass the api url for the app along with some other environment variables into the app during the build phase. The relevant part of my webpack config looks something like:
plugins: [
    new DefinePlugin({
        GRAPHQL_API_URL: JSON.stringify(process.env.GRAPHQL_API_URL),
        DEBUG: process.env.DEBUG,
        ...
    }),
    ...
]

Since this strategy requires the environment variables at build time, my docker file is a little icky, since I need to actually put the webpack build call as part of the CMD command:
FROM node:10.16.0-alpine

WORKDIR /usr/app/

COPY . ./

RUN npm install

# EXPOSE and serve -l ports should match
EXPOSE 3000
CMD npm run build && npm run serve -- -l 3000

I'd love for the build step in webpack to be a layer in the docker container (a RUN command), so I could potentially clean out all the source files after the build succeeds, and so start up is faster. Is there a standard strategy for dealing with this issue of using information from the docker environment when you are only serving static files?

A:
How do I use environment variables in a static site inside docker?

This question is broader than your specific problem I think. The generic answer to this is, you can't, by nature of the fact that the content is static. If you need the API URL to be dynamic and modifiable at runtime then there needs to be some feature to support that. I'm not familiar enough with webpack to know if this can work but there is a lot of information at the following link that might help you.
Passing environment-dependent variables in webpack

Is there a standard strategy for dealing with this issue of using information from the docker environment when you are only serving static files?

If you are happy to have the API URL baked into the image then the standard strategy with static content in general is to use a multistage build. This generates the static content and then copies it to a new base image, leaving behind any dependencies that were required for the build.
https://docs.docker.com/develop/develop-images/multistage-build/


text:
Q: Where can I find the C++11 standard papers?
Possible Duplicate:
Where do I find the current C or C++ standard documents?

Where can I find the full C++11 standard? I know features of it are floating around the internet but I can't seem to find the document itself.

A: IMO cppreference.com  can be a free alternative to buying the actual standard.

A: You can get the full, final standard directly from the ISO, or some national bodies.
You probably don't want to get in a hurry though. The ANSI (for one) normally re-publishes an official version with identical technical material -- basically the only change is saying "ANSI/ISO" on the the title page instead of just "ISO". At least for past versions, however, the price has been much more reasonable (~$30US instead of ~$400US).
Edit: As expected, the standard is now available for $30US.

A: If you don't really need and can't afford to shell out the money for the real thing, you can make do with the latest publicly available draft: N3242.

A: The standard is available from the ISO website for ~$400 or so.

A: It's an ISO standard, which you can purchase here: http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=50372


text:
Q: Reverse ordered list for jquery submitted comments Hey guys I have one more question lol. I am using a script that allows users to submit comments through jquery ajax, however when they are submitted, the submitted comments submit at the bottom of the other comments which are sorted in descending order (newest on top) when the page first loads (due to mysql query). Is there a way to make it submit on top through some sort of sorting javascript function?
  function prepare(response) {
      var d = new Date();
      count++;
      d.setTime(response.time*1000);

      var mytime = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
      var string = '
'
          + ''+mytime+''
          + ''+response.user+':'
          + ''+response.message+''
          +'
';

      return string;
    }
   function success(response, status)  {
          if(status == 'success') {
            lastTime = response.time;
            $('#daddy-shoutbox-list').append(prepare(response));
            $('input[name=message]').attr('value', '').focus();
            $('#list-'+count).fadeIn('slow');
            timeoutID = setTimeout(refresh, 3000);
          }
        }

A: Use prepend() instead of append().
$('#daddy-shoutbox-list').prepend(prepare(response));


text:
Q: what does th expression [1 : 2^nR] mesn in information theory? I find the below expression a lot in math, statistics and information theory m ∈ [1 : 2^nR]
expression is a text like the following:
a randomized encoder that generates a codeword X^n(m), m ∈ [1 : 2nR], according to a conditional pmf p(x^n|m)
Could some one explain it for me ?

A: The notation $(M,n)=(2^{nR},n)$ usually represents a binary code (not necessarily linear) with codewords of length $n$ and rate $R\in(0,1)$ which gives (up to a floor function) $2^{nR}$ codewords. Since we're interested in asymptotics we don't care about the floor function.
The codewords can be arranged so that they correspond to one of $2^{nR}$ messages with index $\{1,2,\ldots,2^{nR}\}$


text:
Q: SSL routines:tls_process_server_certificate:certificate verify failed:self signed certificate aioodbc I try to connect to my database using
import aioodbc

dsn = 'Driver=ODBC Driver 18 for SQL Server;Server=my_adress;Database=ML;UID=123;PWD=123;TrustServerCertificate=no'
        connect = partial(aioodbc.connect, dsn=dsn, echo=True, autocommit=True)

But after i have following error
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 18 for SQL Server]SSL Provider: [error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed:self signed certificate] (-1) (SQLDriverConnect)')

how to disable ssl verification ?


text:
Q: Convert int to string with dots java How do I convert int to string with dots seperating in a certain pattern?
example:
int number = 12312300:

would become
"123.123.0.0";

I've looked at DecimalFormat and split to divide, but to no success.
EDIT:
As menetioned by a few of you, here is a more detailed explanation.
the format will stay as XXX.XXX.X.X.
so ex:
int number = 12312300;

converted to String:
String = "123.123.0.0";
number++;

so next time the method gets called the number is:
int number = 12312301;

which again becomes when converted to String:
String = "123.123.0.1";

A: Use this function:
public void convert()
{
    int [] num = new int[3];
    String str = null;
    int number = 123012;
    for (int i=0; i <num.length;i++)
    {
     num[i] = number%10;
     number = number/10;
    }
    str = number+"."+num[2]+"."+num[1]+"."+num[0];
    System.out.println(str);
}

A: Convert to String with Integer.toString(number);
Then you can use the substring method of the String class to split your String into the seperate parts. Finally you can just add them together with the + operator. For example = ss1 + "." + ss2 + "." and so on.
String s = Integer.toString(number);
//change this part so it matches the format you want to achieve
s = s.substring(0,2) + "." + s.substring(3,5) "." + s.substring(6,6);

This would basically work, but if your String is not long enough, the substring method will throw an exception at runtime. So you'll have to check the size of the String first.


text:
Q: Finding solutions to polynomial modular equations like $(x+1)^6 - x^6 \equiv 0\ (\textrm{mod}\ 19)$ I'm more or less okay with linear modulo equations, and was wondering how to solve polynomial modulo equations like $(x+1)^6 - x^6 \equiv 0\ (\textrm{mod}\ 19)$.
The possible solutions are 2, 7, 9, 11 and 16 (found on an online calculator). What is the general method to solving such equations? A method better than just guess for all $x \leq 19$, since then it would be difficult if the modulo is big. Thanks!

A: there are six sixth roots of one $\pmod {19},$ those being the three cube roots of $1$ and the three cube roots of $-1.$  For each of these, solve $\frac{x+1}{x} \equiv t \pmod {19}$ where $t^6 \equiv 1 \pmod {19}.$ Or, for $t \neq 1,$ you see
$$ \frac{1}{x} \equiv t - 1 \pmod {19},  $$
$$ x \equiv \frac{1}{t-1} \pmod{19} $$
The cube roots of one are $1,7,11 \pmod {19}.$ For instance, $18 \cdot 19 = 342$ and $7^3 = 343.$ Then $7 \cdot 11 = 77 = 1 + 4 \cdot 19.$
The cube roots of $-1$ are therefore $18, 12, 8 \pmod {19}.$
multiplicative inverses
$$
\begin{array}{cccccccccccccccccc}
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 \\
1 & 10 & 13 & 5 & 4 & 16 & 11 & 12 & 17 & 2 & 8 & 9 & 3 & 15 & 14 & 6 & 9 & 18
\end{array}
$$


text:
Q: Wordpress class-wp-image-editor.php permission denied I just changed the directory of my WordPress instance. I copied all files via FTP into the new folder and also copied the database and edited the site URL and home entries.
Now the page don't show the images, but gives me this message:

Warning: imagejpeg() [function.imagejpeg]: Unable to open
  '/www/htdocs/serverID/wp-content/uploads/bfi_thumb/modell3-2xr5ffo5juzmz3rgn84d8g.jpg'
  for writing: Permission denied in
  /www/htdocs/w00db707/wp-includes/class-wp-image-editor.php on line 405

Everything else is looking good. Do you know whats wrong?

A: Two possibilities:

*

*The file/folder permissions for /wp-content/uploads/ need to be CHMOD to 0755 or 0777

*If the permissions are already set to 0755 or 0777, the owning user/group needs to match your HTTPD user (varies based on server configuration; sometimes the user is www-data, sometimes apache, if a Plesk environment it is the username you setup the subscription with)


text:
Q: How to check string is valid date or not irrespective of pattern/format? I have tried Date.parse(), Date() and many other solution but no proper solution yet without checking it's pattern using regex(or external package like moment.js) first.
Attaching screenshot of sample which should be invalid date
e.g. Test - 7


text:
Q: Jpgraph : how set label for group bar column chart in php here is  my jpgraph demo code:
<?php // content="text/plain; charset=utf-8"
// $Id: groupbarex1.php,v 1.2 2002/07/11 23:27:28 aditus Exp $
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_bar.php');

$datay1=array(35,160,0,0,0,0);
$datay2=array(35,190,190,190,190,190);
$datay3=array(20,70,70,140,230,260);

$graph = new Graph(450,200,'auto');
$graph->SetScale("textlin");
$graph->SetShadow();
$graph->img->SetMargin(40,30,40,40);
$graph->xaxis->SetTickLabels($gDateLocale->GetShortMonth());

$graph->xaxis->title->Set('Year 2002');
$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);

$graph->title->Set('Group bar plot');
$graph->title->SetFont(FF_FONT1,FS_BOLD);

$bplot1 = new BarPlot($datay1);
$bplot2 = new BarPlot($datay2);
$bplot3 = new BarPlot($datay3);

$bplot1->SetFillColor("orange");
$bplot2->SetFillColor("brown");
$bplot3->SetFillColor("darkgreen");

$gbarplot = new GroupBarPlot(array($bplot1,$bplot2,$bplot3));
$gbarplot->SetWidth(0.6);
$graph->Add($gbarplot);

$graph->Stroke();
?>

this code has no error and this is working perfectly...my problem is how can I set labels for this multi bars for identifying ...
How can I set A LABELS..

A: $graph->legend->SetPos(0.5,0.98,'center','bottom');
$bplot1->SetLegend("Pass");
$bplot2->SetLegend("---");
$bplot3->SetLegend("---");

$gbarplot = new GroupBarPlot(array($bplot1,$bplot2,$bplot3));
$gbarplot->SetWidth(0.6);
$graph->Add($gbarplot);

$graph->Stroke();

Write this line in your code. For more info please see this url:
Class Reference
With Example


text:
Q: How to reduce repeated VBA code I have an identical AfterUpdate event for 11 fields in my form. Is there any way to put the AfterUpdate code in a function or module and then call the function or module in each AfterUpdate event?
If a certain field is changed on the main form, I prompt the user with a message box saying they need to add a note in the subform describing the change. If the user clicks OK on the message box, it brings the focus to the note subform. If the user clicks Cancel, the change is undone in the main form.
Below is the code that is repeated for 11 fields:
Private Sub ID_AfterUpdate()

On Error GoTo StandardErrorHandling

Dim NoteReq As Integer

NoteReq = MsgBox("A change has been made to a protected field! " & _
"Please provide a note with a brief description of the change." _
, vbOKCancel, "A Note is Required!")

If Form.Dirty = True Then

    If NoteReq = vbCancel Then

        Me.Undo

    ElseIf NoteReq = vbOK Then

    'You may have to set focus to the subform then the control

    [Forms]![MainForm].[SubFormNotes].SetFocus

    DoCmd.GoToRecord , , acNewRec 'Go to new note record, not existing one

    End If

End If

ExitStandardErrorHandling:
Exit Sub

StandardErrorHandling:

MsgBox "The following error has occured:" & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & vbCrLf & _
            "Error Description: " & Err.Description & vbCrLf & vbCrLf _
             , vbCritical, "An Error has Occurred!"

Resume ExitStandardErrorHandling

End Sub

I know a function returns a value so if I put the above code in a function, and called the function within the AfterUpdate event of each field, how would I code it so that it returns a value? Or is there another way to cut down on the redundant code? Thanks!

A: Functions don't seem to need to return a value in my experience. I've made functions to do exactly this sort of thing - highlight a textbox by changing the BackColor when selected, make several buttons do a set process to another control that shares a tag, swap values between Active and Previous controls etc.
You should be able to create a function directly from that coding simply by replacing the first line with something along the lines of Function UpdateNote() and the last line with End Function, and then do a find and replace "sub" with "function"
Then you can call that function simply by putting exactly =UpdateNote() (or whatever you call the funtion) in the After Update event property (directly in the property list, not vba or macro).
You can even apply it to all the different field's properties at once, by selecting all 11 of them and pasting that =UpdateNote() in the After Update event property.
It definitely works, and is pretty neat and clean in my opinion. If there's a reason it's not ideal, I'm not aware of it...