Programs & Examples On #Pngfix

Add property to an array of objects

or use map

Results.map(obj=> ({ ...obj, Active: 'false' }))

Edited to reflect comment by @adrianolsk to not mutate the original and instead return a new object for each.

Read the spec

Connection Strings for Entity Framework

Instead of using config files you can use a configuration database with a scoped systemConfig table and add all your settings there.

CREATE TABLE [dbo].[SystemConfig]  
    (  
      [Id] [int] IDENTITY(1, 1)  
                 NOT NULL ,  
      [AppName] [varchar](128) NULL ,  
      [ScopeName] [varchar](128) NOT NULL ,  
      [Key] [varchar](256) NOT NULL ,  
      [Value] [varchar](MAX) NOT NULL ,  
      CONSTRAINT [PK_SystemConfig_ID] PRIMARY KEY NONCLUSTERED ( [Id] ASC )  
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
               ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]  
    )  
ON  [PRIMARY]  

GO  

SET ANSI_PADDING OFF  
GO  

ALTER TABLE [dbo].[SystemConfig] ADD  CONSTRAINT [DF_SystemConfig_ScopeName]  DEFAULT ('SystemConfig') FOR [ScopeName]  
GO 

With such configuration table you can create rows like such: enter image description here

Then from your your application dal(s) wrapping EF you can easily retrieve the scoped configuration.
If you are not using dal(s) and working in the wire directly with EF, you can make an Entity from the SystemConfig table and use the value depending on the application you are on.

Convert String to Float in Swift

I found another way to take a input value of a UITextField and cast it to a float:

    var tempString:String?
    var myFloat:Float?

    @IBAction func ButtonWasClicked(_ sender: Any) {
       tempString = myUITextField.text
       myFloat = Float(tempString!)!
    }

How to remove commits from a pull request

People wouldn't like to see a wrong commit and a revert commit to undo changes of the wrong commit. This pollutes commit history.

Here is a simple way for removing the wrong commit instead of undoing changes with a revert commit.

  1. git checkout my-pull-request-branch

  2. git rebase -i HEAD~n // where n is the number of last commits you want to include in interactive rebase.

  3. Replace pick with drop for commits you want to discard.
  4. Save and exit.
  5. git push --force

Import CSV file into SQL Server

The best, quickest and easiest way to resolve the comma in data issue is to use Excel to save a comma separated file after having set Windows' list separator setting to something other than a comma (such as a pipe). This will then generate a pipe (or whatever) separated file for you that you can then import. This is described here.

Jquery selector input[type=text]')

$('input[type=text],select', '.sys');

for looping:

$('input[type=text],select', '.sys').each(function() {
   // code
});

What is SuppressWarnings ("unchecked") in Java?

The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.

Is unsigned integer subtraction defined behavior?

When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:

enter image description here

9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned, then modular arithmetic takes place.


Now look at the following operations storing the result as an unsigned int:

unsigned int five = 5, seven = 7;
unsigned int a = five - seven;      // a = (-2 % 2^32) = 4294967294 

int one = 1, six = 6;
unsigned int b = one - six;         // b = (-5 % 2^32) = 4294967291

When you want to make sure that the result is signed, then stored it into signed variable or cast it to signed. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs() function defined in stdlib.h:

int c = five - seven;       // c = -2
int d = abs(five - seven);  // d =  2

Be very careful, especially while writing conditions, because:

if (abs(five - seven) < seven)  // = if (2 < 7)
    // ...

if (five - seven < -1)          // = if (-2 < -1)
    // ...

if (one - six < 1)              // = if (-5 < 1)
    // ...

if ((int)(five - seven) < 1)    // = if (-2 < 1)
    // ...

but

if (five - seven < 1)   // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
    // ...

if (one - six < five)   // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
    // ...

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

What can you do if you need to make a change to a file, but don’t know the file’s encoding? If you know the encoding is ASCII-compatible and only want to examine or modify the ASCII parts, you can open the file with the surrogateescape error handler:

with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
    data = f.read()

Java ArrayList replace at specific index

Use the set() method: see doc

arraylist.set(index,newvalue);

Difference between static memory allocation and dynamic memory allocation

Static memory allocation. Memory allocated will be in stack.

int a[10];

Dynamic memory allocation. Memory allocated will be in heap.

int *a = malloc(sizeof(int) * 10);

and the latter should be freed since there is no Garbage Collector(GC) in C.

free(a);

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

What is the correct format to use for Date/Time in an XML file

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

Tensorflow: how to save/restore a model?

You can also check out examples in TensorFlow/skflow, which offers save and restore methods that can help you easily manage your models. It has parameters that you can also control how frequently you want to back up your model.

How to clear all input fields in a specific div with jQuery?

Fiddle: http://jsfiddle.net/simple/BdQvp/

You can do it like so:

I have added two buttons in the Fiddle to illustrate how you can insert or clear values in those input fields through buttons. You just capture the onClick event and call the function.

//Fires when the Document Loads, clears all input fields
$(document).ready(function() {
  $('.fetch_results').find('input:text').val('');    
});

//Custom Functions that you can call
function resetAllValues() {
  $('.fetch_results').find('input:text').val('');
}

function addSomeValues() {
  $('.fetch_results').find('input:text').val('Lala.');
}

Update:

Check out this great answer below by Beena as well for a more universal approach.

How to link an input button to a file select window?

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here's a working fiddle.

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.

Where should I put <script> tags in HTML markup?

Script blocks DOM load untill it's loaded and executed.

If you place scripts at the end of <body> all of DOM has chance to load and render (page will "display" faster). <script> will have access to all of those DOM elements.

In other hand placing it after <body> start or above will execute script (where there's still no DOM elements).

You are including jQuery which means you can place it wherever you wish and use .ready()

Eclipse error: "The import XXX cannot be resolved"

Try adding JRE System Library in the build path of your project.

If "0" then leave the cell blank

Use this

=IFERROR((H15+G16-F16)^2/(H15+G16-F16),"")

Logical operator in a handlebars.js {{#if}} conditional

One other alternative is to use function name in #if. The #if will detect if the parameter is function and if it is then it will call it and use its return for truthyness check. Below myFunction gets current context as this.

{{#if myFunction}}
  I'm Happy!
{{/if}}

Passing command line arguments in Visual Studio 2010?

Under Project->Properties->Debug, you should see a box for Command line arguments (This is in C# 2010, but it should basically be the same place)

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SSMS, "Query" menu item... "Results to"... "Results to File"

Shortcut = CTRL+shift+F

You can set it globally too

"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down

Edit: after comment

In SSMS, "Query" menu item... "SQLCMD" mode

This allows you to run "command line" like actions.

A quick test in my SSMS 2008

:OUT c:\foo.txt
SELECT * FROM sys.objects

Edit, Sep 2012

:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects

Database cluster and load balancing

From SQL Server point of view:

Clustering will give you an active - passive configuration. Meaning in a 2 node cluster, one of them will be the active (serving) and the other one will be passive (waiting to take over when the active node fails). It's a high availability from hardware point of view.

You can have an active-active cluster, but it will require multiple instances of SQL Server running on each node. (i.e. Instance 1 on Node A failing over to Instance 2 on Node B, and instance 1 on Node B failing over to instance 2 on Node A).

Load balancing (at least from SQL Server point of view) does not exists (at least in the same sense of web server load balancing). You can't balance load that way. However, you can split your application to run on some database on server 1 and also run on some database on server 2, etc. This is the primary mean of "load balancing" in SQL world.

React.js: Identifying different inputs with one onChange handler

You can track the value of each child input by creating a separate InputField component that manages the value of a single input. For example the InputField could be:

var InputField = React.createClass({
  getInitialState: function () {
    return({text: this.props.text})
  },
  onChangeHandler: function (event) {
     this.setState({text: event.target.value})
  }, 
  render: function () {
    return (<input onChange={this.onChangeHandler} value={this.state.text} />)
  }
})

Now the value of each input can be tracked within a separate instance of this InputField component without creating separate values in the parent's state to monitor each child component.

Bootstrap Carousel image doesn't align properly

It could have something to do with your styles. In my case, I am using a link within the parent "item" div, so I had to change my stylesheet to say the following:

.carousel .item a > img {
  display: block;
  line-height: 1;
}

under the preexisting boostrap code:

.carousel .item > img {
  display: block;
  line-height: 1;
}

and my image looks like:

<div class="active item" id="2"><a href="http://epdining.com/eats.php?place=TestRestaurant1"><img src="rimages/2.jpg"></a><div class="carousel-caption"><p>This restaurant is featured blah blah blah blah blah.</p></div></div>

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"

Explanation : [How it works]

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.

Hope it work

Other warning

objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int

Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"

[caution: It may void other warning of 64 Bits architecture conversion].

How to check if a number is a power of 2

Find if the given number is a power of 2.

#include <math.h>

int main(void)
{
    int n,logval,powval;
    printf("Enter a number to find whether it is s power of 2\n");
    scanf("%d",&n);
    logval=log(n)/log(2);
    powval=pow(2,logval);

    if(powval==n)
        printf("The number is a power of 2");
    else
        printf("The number is not a power of 2");

    getch();
    return 0;
}

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

What worked for me was to rename the project by removing the special characters.

Example: "project_marketplace" to "projectmarketplace"

In this case, I redid the project with react-native init and copied the src and package.json folder.

How can I check if my Element ID has focus?

Write below code in script and also add jQuery library

var getElement = document.getElementById('myID');

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')
            }
        });
    }

Thank you...

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

getApplication() vs. getApplicationContext()

Compare getApplication() and getApplicationContext().

getApplication returns an Application object which will allow you to manage your global application state and respond to some device situations such as onLowMemory() and onConfigurationChanged().

getApplicationContext returns the global application context - the difference from other contexts is that for example, an activity context may be destroyed (or otherwise made unavailable) by Android when your activity ends. The Application context remains available all the while your Application object exists (which is not tied to a specific Activity) so you can use this for things like Notifications that require a context that will be available for longer periods and independent of transient UI objects.

I guess it depends on what your code is doing whether these may or may not be the same - though in normal use, I'd expect them to be different.

Lazy Method for Reading Big File in Python?

f = ... # file-like object, i.e. supporting read(size) function and 
        # returning empty string '' when there is nothing to read

def chunked(file, chunk_size):
    return iter(lambda: file.read(chunk_size), '')

for data in chunked(f, 65536):
    # process the data

UPDATE: The approach is best explained in https://stackoverflow.com/a/4566523/38592

Where does Android app package gets installed on phone

You will find the application folder at:

/data/data/"your package name"

you can access this folder using the DDMS for your Emulator. you can't access this location on a real device unless you have a rooted device.

Complete list of reasons why a css file might not be working

I had the same problem - I changed my text encoding to UTF-16 on my index file and my css file would show up blank when I'd try to load the page in the browser. I figured out by much trial and error that your html and css files have to have the same encoding! I don't know if this would work for you but it did for me.

numbers not allowed (0-9) - Regex Expression in javascript

Simply:

/^([^0-9]*)$/

That pattern matches any number of characters that is not 0 through 9.

I recommend checking out http://regexpal.com/. It will let you easily test out a regex.

Change bullets color of an HTML list without using span

I really liked Marc's answer too - I needed a set of different colored ULs and obviously it would be easier just to use a class. Here is what I used for orange, for example:

ul.orange {
    list-style: none;
    padding: 0px;
}
ul.orange > li:before {
    content: '\25CF ';
    font-size: 15px;
    color: #F00;
    margin-right: 10px;
    padding: 0px;
    line-height: 15px;
}

Plus, I found that the hex code I used for "content:" was different than Marc's (that hex circle seemed to sit a bit too high). The one I used seems to sit perfectly in the middle. I also found several other shapes (squares, triangles, circles, etc.) right here

Equivalent of explode() to work with strings in MySQL

Use this function. It works like a charm. replace "|" with the char to explode/split and the values 1,2,3,etc are based on the number of entries in the data-set: Value_ONE|Value_TWO|Value_THREE.

SUBSTRING_INDEX(SUBSTRING_INDEX(`tblNAME`.`tblFIELD`, '|', 1), '|', -1) AS PSI,
SUBSTRING_INDEX(SUBSTRING_INDEX(`tblNAME`.`tblFIELD`, '|', 2), '|', -1) AS GPM,
SUBSTRING_INDEX(SUBSTRING_INDEX(`tblNAME`.`tblFIELD`, '|', 3), '|', -1) AS LIQUID

I hope this helps.

Is there any use for unique_ptr with array?

Scott Meyers has this to say in Effective Modern C++

The existence of std::unique_ptr for arrays should be of only intellectual interest to you, because std::array, std::vector, std::string are virtually always better data structure choices than raw arrays. About the only situation I can conceive of when a std::unique_ptr<T[]> would make sense would be when you're using a C-like API that returns a raw pointer to a heap array that you assume ownership of.

I think that Charles Salvia's answer is relevant though: that std::unique_ptr<T[]> is the only way to initialise an empty array whose size is not known at compile time. What would Scott Meyers have to say about this motivation for using std::unique_ptr<T[]>?

What is difference between sleep() method and yield() method of multi threading?

yield(): yield method is used to pause the execution of currently running process so that other waiting thread with the same priority will get CPU to execute.Threads with lower priority will not be executed on yield. if there is no waiting thread then this thread will start its execution.

join(): join method stops currently executing thread and wait for another to complete on which in calls the join method after that it will resume its own execution.

For detailed explanation, see this link.

Add a Progress Bar in WebView

Put a progress bar and the webview inside a relativelayout and set the properties for the progress bar as follows,

  1. Make its visibility as GONE.
  2. CENTRE it in the Relativelayout.

and then in onPageStarted() of the webclient make the progress bar visible so that it shows the progressbar when you have clicked on a link. In onPageFinished() make the progress bar visiblility as GONE so that it disappears when the page has finished loading... This will work fine for your scenario. Hope this helps...

php - add + 7 days to date format mm dd, YYYY

The "+1 month" issue with strtotime

As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

$dt = date("Y-m-d");
echo date( "Y-m-d", strtotime( "$dt +1 day" ) ); // PHP:  2009-03-04
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP:  2009-03-31

How do I add a border to an image in HTML?

Here is some HTML and CSS code that would solve your issue:

CSS

.ImageBorder
{
    border-width: 1px;
    border-color: Black;
}

HTML

<img src="MyImage.gif" class="ImageBorder" />

Difference between File.separator and slash in paths

As the gentlemen described the difference with variant details.

I would like to recommend the use of the Apache Commons io api, class FilenameUtils when dealing with files in a program with the possibility of deploying on multiple OSs.

Break when a value changes using the Visual Studio debugger

Update in 2019:

This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.

https://blogs.msdn.microsoft.com/visualstudio/2019/02/12/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/

Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!

Unable to load DLL 'SQLite.Interop.dll'

This is how I fixed it in my project.

It was working, and when a colleague submitted his changes, I received the "Unable to load DLL 'SQLite.Interop.dll'" exception.

Diffing the project's .csproj file, this was in the NON-WORKING version:

<ItemGroup>
     <Content Include="x64\SQLite.Interop.dll" />
     <Content Include="x86\SQLite.Interop.dll" />
</ItemGroup>

And this is what the WORKING version had:

<ItemGroup>
     <Content Include="x64\SQLite.Interop.dll">
          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
      <Content Include="x86\SQLite.Interop.dll">
          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
</ItemGroup>

After reverting back, I didn't receive the exception. The DLL files were dumped in the appropriate Debug\x64 (etc) folders.

Auto logout with Angularjs based on idle user

Played with Boo's approach, however don't like the fact that user got kicked off only once another digest is run, which means user stays logged in until he tries to do something within the page, and then immediatelly kicked off.

I am trying to force the logoff using interval which checks every minute if last action time was more than 30 minutes ago. I hooked it on $routeChangeStart, but could be also hooked on $rootScope.$watch as in Boo's example.

app.run(function($rootScope, $location, $interval) {

    var lastDigestRun = Date.now();
    var idleCheck = $interval(function() {
        var now = Date.now();            
        if (now - lastDigestRun > 30*60*1000) {
           // logout
        }
    }, 60*1000);

    $rootScope.$on('$routeChangeStart', function(evt) {
        lastDigestRun = Date.now();  
    });
});

SQL multiple column ordering

The other answers lack a concrete example, so here it goes:

Given the following People table:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826

If you execute the query below:

SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC

The result set will look like this:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706

Create a List of primitive int?

You can use primitive collections available in Eclipse Collections. Eclipse Collections has List, Set, Bag and Map for all primitives. The elements in the primitive collections are maintained as primitives and no boxing takes place.

You can initialize a IntList like this:

MutableIntList ints = IntLists.mutable.empty();

You can convert from a List<Integer> to IntList like this:

List<Integer> integers = new ArrayList<>();
MutableIntList ints = ListAdapter.adapt(integers).collectInt(each -> each);

Note: I am a contributor to Eclipse Collections.

Cannot enqueue Handshake after invoking quit

According to:

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

and

Note: If you're serving web requests, then you shouldn't be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.


From:

It says:

Server disconnects

You may lose the connection to a MySQL server due to network problems, the server timing you out, or the server crashing. All of these events are considered fatal errors, and will have the err.code = 'PROTOCOL_CONNECTION_LOST'. See the Error Handling section for more information.

The best way to handle such unexpected disconnects is shown below:

function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

As you can see in the example above, re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool freeing up space for a new connection to be created on the next getConnection call.


I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:

function initializeConnection(config) {
    function addDisconnectHandler(connection) {
        connection.on("error", function (error) {
            if (error instanceof Error) {
                if (error.code === "PROTOCOL_CONNECTION_LOST") {
                    console.error(error.stack);
                    console.log("Lost connection. Reconnecting...");

                    initializeConnection(connection.config);
                } else if (error.fatal) {
                    throw error;
                }
            }
        });
    }

    var connection = mysql.createConnection(config);

    // Add handlers.
    addDisconnectHandler(connection);

    connection.connect();
    return connection;
}

Initializing a connection:

var connection = initializeConnection({
    host: "localhost",
    user: "user",
    password: "password"
});

Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection, which was var connection = mysql.createConnection(config); to simply just

connection = mysql.createConnection(config);

The reason being that if connection is a global variable in your program, then the issue before was that you were making a new connection variable when handling an error signal. But in my nodejs code, I kept using the same global connection variable to run queries on, so the new connection would be lost in the local scope of the initalizeConnection method. But in the modification, it ensures that the global connection variable is reset This may be relevant if you're experiencing an issue known as

Cannot enqueue Query after fatal error

after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.

Could pandas use column as index?

Yes, with set_index you can make Locality your row index.

data.set_index('Locality', inplace=True)

If inplace=True is not provided, set_index returns the modified dataframe as a result.

Example:

> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                     ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> df
     Locality    2005    2006
0  ABBOTSFORD  427000  448000
1  ABERFELDIE  534000  600000

> df.set_index('Locality', inplace=True)
> df
              2005    2006
Locality                  
ABBOTSFORD  427000  448000
ABERFELDIE  534000  600000

> df.loc['ABBOTSFORD']
2005    427000
2006    448000
Name: ABBOTSFORD, dtype: int64

> df.loc['ABBOTSFORD'][2005]
427000

> df.loc['ABBOTSFORD'].values
array([427000, 448000])

> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]

Error: Unexpected value 'undefined' imported by the module

I had this error because I had an index.ts file in the root of my app that was exporting my app.component.ts. So I thought I could do the following:

import { AppComponent } from './';

This worked and gave me no red squiggly lines and even intellisense brings up AppComponent when you start typing it. But come to find out it was causing this error. After I changed it to:

import { AppComponent } from './app.component';

The error went away.

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

'module' object has no attribute 'DataFrame'

The most likely explanation is that either a file called 'pandas.py' is in the same directory as your script, or that another variable called 'pd' is used in your program.

How to get the nth occurrence in a string?

function getStringReminder(str, substr, occ) {
   let index = str.indexOf(substr);
   let preindex = '';
   let i = 1;
   while (index !== -1) {
      preIndex = index;
      if (occ == i) {
        break;
      }
      index = str.indexOf(substr, index + 1)
      i++;
   }
   return preIndex;
}
console.log(getStringReminder('bcdefgbcdbcd', 'bcd', 3));

Merging multiple PDFs using iTextSharp in c#.net

I found the answer:

Instead of the 2nd Method, add more files to the first array of input files.

public static void CombineMultiplePDFs(string[] fileNames, string outFile)
{
    // step 1: creation of a document-object
    Document document = new Document();
    //create newFileStream object which will be disposed at the end
    using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
    {
       // step 2: we create a writer that listens to the document
       PdfCopy writer = new PdfCopy(document, newFileStream );
       if (writer == null)
       {
           return;
       }

       // step 3: we open the document
       document.Open();

       foreach (string fileName in fileNames)
       {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(fileName);
           reader.ConsolidateNamedDestinations();

           // step 4: we add content
           for (int i = 1; i <= reader.NumberOfPages; i++)
           {                
               PdfImportedPage page = writer.GetImportedPage(reader, i);
               writer.AddPage(page);
           }

           PRAcroForm form = reader.AcroForm;
           if (form != null)
           {
               writer.CopyAcroForm(reader);
           }

           reader.Close();
       }

       // step 5: we close the document and writer
       writer.Close();
       document.Close();
   }//disposes the newFileStream object
}

Strange out of memory issue while loading an image to a Bitmap object

It seems that this is a very long running problem, with a lot of differing explanations. I took the advice of the two most common presented answers here, but neither one of these solved my problems of the VM claiming it couldn't afford the bytes to perform the decoding part of the process. After some digging I learned that the real problem here is the decoding process taking away from the NATIVE heap.

See here: BitmapFactory OOM driving me nuts

That lead me to another discussion thread where I found a couple more solutions to this problem. One is to callSystem.gc(); manually after your image is displayed. But that actually makes your app use MORE memory, in an effort to reduce the native heap. The better solution as of the release of 2.0 (Donut) is to use the BitmapFactory option "inPurgeable". So I simply added o2.inPurgeable=true; just after o2.inSampleSize=scale;.

More on that topic here: Is the limit of memory heap only 6M?

Now, having said all of this, I am a complete dunce with Java and Android too. So if you think this is a terrible way to solve this problem, you are probably right. ;-) But this has worked wonders for me, and I have found it impossible to run the VM out of heap cache now. The only drawback I can find is that you are trashing your cached drawn image. Which means if you go RIGHT back to that image, you are redrawing it each and every time. In the case of how my application works, that is not really a problem. Your mileage may vary.

Reading JSON from a file?

To add on this, today you are able to use pandas to import json:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html You may want to do a careful use of the orient parameter.

git - remote add origin vs remote set-url origin

if you have existing project and you would like to add remote repository url then you need to do following command

git init

if you would like to add readme.md file then you can create it and add it using below command.

git add README.md

make your first commit using below command

git commit -m "first commit"

Now you completed all local repository process, now how you add remote repository url ? check below command this is for ssh url, you can change it for https.

git remote add origin [email protected]:user-name/repository-name.git

How you push your first commit see below command :

git push -u origin master

How to get the selected date of a MonthCalendar control in C#

Using SelectionRange you will get the Start and End date.

private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
    var startDate = monthCalendar1.SelectionRange.Start.ToString("dd MMM yyyy");
    var endDate = monthCalendar1.SelectionRange.End.ToString("dd MMM yyyy");
}

If you want to update the maximum number of days that can be selected, then set MaxSelectionCount property. The default is 7.

// Only allow 21 days to be selected at the same time.
monthCalendar1.MaxSelectionCount = 21;

MySQL - Using COUNT(*) in the WHERE clause

Just academic version without having clause:

select *
from (
   select gid, count(*) as tmpcount from gd group by gid
) as tmp
where tmpcount > 10;

How do I check if there are duplicates in a flat list?

A more simple solution is as follows. Just check True/False with pandas .duplicated() method and then take sum. Please also see pandas.Series.duplicated — pandas 0.24.1 documentation

import pandas as pd

def has_duplicated(l):
    return pd.Series(l).duplicated().sum() > 0

print(has_duplicated(['one', 'two', 'one']))
# True
print(has_duplicated(['one', 'two', 'three']))
# False

C# DateTime to UTC Time without changing the time

Use the DateTime.ToUniversalTime method.

How to call window.alert("message"); from C#?

if you are using ajax in your page that require script manager Page.ClientScript
will not work, Try this and it would do the work:

ScriptManager.RegisterClientScriptBlock(this, GetType(),
            "alertMessage", @"alert('your Message ')", true);

Vim for Windows - What do I type to save and exit from a file?

Esc to make sure you exit insert mode, then :wq (colon w q) or ZZ (shift-Z shift-Z).

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

To resolve this problem in the query without changing either database, you can cast the expressions on other side of the "=" sign with

COLLATE SQL_Latin1_General_CP1_CI_AS

as suggested here.

Forward slash in Java Regex

There is actually a reason behind why all these are messed up. A little more digging deeper is done in this thread and might be helpful to understand the reason why "\\" behaves like this.

Reading HTTP headers in a Spring REST controller

Instead of taking the HttpServletRequest object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.

public class OAuth2ClientController {
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private HttpServletRequest request;

    @Autowired
    public OAuth2ClientController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("Content-Type"));

        return ResponseEntity.ok();
    }
}

How to draw lines in Java

You can use the getGraphics method of the component on which you would like to draw. This in turn should allow you to draw lines and make other things which are available through the Graphics class

How to fix a collation conflict in a SQL Server query?

if the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!

insert/delete/update trigger in SQL server

the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind

/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
                    EmpID int,
                    Activity varchar(20),
                    DoneBy varchar(50),
                    Date_Time datetime NOT NULL DEFAULT GETDATE()
                   );

select * from Emp_Audit*/

create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
    SET @activity = 'UPDATE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
    SET @activity = 'INSERT';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin 
    SET @activity = 'DELETE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from deleted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

How do I bind the enter key to a function in tkinter?

I found one good thing about using bind is that you get to know the trigger event: something like: "You clicked with event = [ButtonPress event state=Mod1 num=1 x=43 y=20]" due to the code below:

self.submit.bind('<Button-1>', self.parse)
def parse(self, trigger_event):
        print("You clicked with event = {}".format(trigger_event))

Comparing the following two ways of coding a button click:

btn = Button(root, text="Click me to submit", command=(lambda: reply(ent.get())))
btn = Button(root, text="Click me to submit")
btn.bind('<Button-1>', (lambda event: reply(ent.get(), e=event)))
def reply(name, e = None):
    messagebox.showinfo(title="Reply", message = "Hello {0}!\nevent = {1}".format(name, e))

The first one is using the command function which doesn't take an argument, so no event pass-in is possible. The second one is a bind function which can take an event pass-in and print something like "Hello Charles! event = [ButtonPress event state=Mod1 num=1 x=68 y=12]"

We can left click, middle click or right click a mouse which corresponds to the event number of 1, 2 and 3, respectively. Code:

btn = Button(root, text="Click me to submit")
buttonClicks = ["<Button-1>", "<Button-2>", "<Button-3>"]
for bc in buttonClicks:
    btn.bind(bc, lambda e : print("Button clicked with event = {}".format(e.num)))

Output:

Button clicked with event = 1
Button clicked with event = 2
Button clicked with event = 3

ASP.NET MVC 3 - redirect to another action

You have to write this code instead of return View(); :

return RedirectToAction("ActionName", "ControllerName");

How to show current user name in a cell?

Based on the instructions at the link below, do the following.

In VBA insert a new module and paste in this code:

Public Function UserName()
    UserName = Environ$("UserName")
End Function

Call the function using the formula:

=Username()

Based on instructions at:

https://support.office.com/en-us/article/Create-Custom-Functions-in-Excel-2007-2f06c10b-3622-40d6-a1b2-b6748ae8231f

How do I combine the first character of a cell with another cell in Excel?

Use following formula:

=CONCATENATE(LOWER(MID(A1,1,1)),LOWER( B1))

for

Josh Smith = jsmith

note that A1 contains name and B1 contains surname

What is an example of the simplest possible Socket.io example?

Maybe this may help you as well. I was having some trouble getting my head wrapped around how socket.io worked, so I tried to boil an example down as much as I could.

I adapted this example from the example posted here: http://socket.io/get-started/chat/

First, start in an empty directory, and create a very simple file called package.json Place the following in it.

{
"dependencies": {}
}

Next, on the command line, use npm to install the dependencies we need for this example

$ npm install --save express socket.io

This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}

Create a file called server.js This will obviously be our server run by node. Place the following code into it:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

http.listen(3001, function(){

  console.log('listening on *:3001');

});

//for testing, we're just going to send data to the client every second
setInterval( function() {

  /*
    our message we want to send to the client: in this case it's just a random
    number that we generate on the server
  */
  var msg = Math.random();
  io.emit('message', msg);
  console.log (msg);

}, 1000);

Create the last file called index.html and place the following code into it.

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

You can now test this very simple example and see some output similar to the following:

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653

If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.

GitHub: invalid username or password

  1. Control panel
  2. Credential manager
  3. Look for options webcredentials and windows credentials
  4. in either one you will find github credentials fix it with correct credentials
  5. open new instance of git bash you should be able to perform your git commands.

This worked for me, I was able to pull and push into my remote repo.

What are all codecs and formats supported by FFmpeg?

Codecs proper:

ffmpeg -codecs

Formats:

ffmpeg -formats

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

if you use 'Month' in to_char it right pads to 9 characters; you have to use the abbreviated 'MON', or to_char then trim and concatenate it to avoid this. See, http://www.techonthenet.com/oracle/functions/to_char.php

select trim(to_char(date_field, 'month')) || ' ' || to_char(date_field,'dd, yyyy')
  from ...

or

select to_char(date_field,'mon dd, yyyy')
  from ...  

Remove ALL styling/formatting from hyperlinks

if you state a.redLink{color:red;} then to keep this on hover and such add a.redLink:hover{color:red;} This will make sure no other hover states will change the color of your links

How do I set the proxy to be used by the JVM

The following shows how to set in Java a proxy with proxy user and proxy password from the command line, which is a very common case. You should not save passwords and hosts in the code, as a rule in the first place.

Passing the system properties in command line with -D and setting them in the code with System.setProperty("name", "value") is equivalent.

But note this

Example that works:

C:\temp>java -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps.proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit com.andreas.JavaNetHttpConnection

But the following does not work:

C:\temp>java com.andreas.JavaNetHttpConnection -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps=proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit

The only difference is the position of the system properties! (before and after the class)

If you have special characters in password, you are allowed to put it in quotes "@MyPass123%", like in the above example.

If you access an HTTPS service, you have to use https.proxyHost, https.proxyPort etc.

If you access an HTTP service, you have to use http.proxyHost, http.proxyPort etc.

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

Probably this information will help. I was on Ubuntu 18.04 and when I tried to install Krita, using the ppa method, I got this error:

This application failed to start because it could not find or load the Qt platform plugin "xcb" in "".

Available platform plugins are: linuxfb, minimal, minimalegl, offscreen, wayland-egl, wayland, xcb.

Reinstalling the application may fix this problem.

Aborted

I tried all the solutions that I found in this thread and other webs without any success.

Finally, I found a post where the author mention that is possible to activate the debugging tool of qt5 using this simple command:

export QT_DEBUG_PLUGINS=1

After adding this command I run again krita I got the same error, however this time I knew the cause of that error.

libxcb-xinerama.so.0: cannot open shared object file: No such file or directory.

This error prevents to the "xcb" to load properly. So, the solution will be install the `libxcb-xinerama.so.0" right? However, when I run the command:

sudo apt install libxcb-xinerama

The lib was already installed. Now what Teo? Well, then I used an old trick :) Yeah, that one --reinstall

sudo apt install --reinstall libxcb-xinerama

TLDR: This last command solved my problem.

Flutter: Setting the height of the AppBar

You can use the toolbarHeight property of Appbar, it does exactly what you want.

pandas GroupBy columns with NaN (missing) values

This is mentioned in the Missing Data section of the docs:

NA groups in GroupBy are automatically excluded. This behavior is consistent with R

One workaround is to use a placeholder before doing the groupby (e.g. -1):

In [11]: df.fillna(-1)
Out[11]: 
   a   b
0  1   4
1  2  -1
2  3   6

In [12]: df.fillna(-1).groupby('b').sum()
Out[12]: 
    a
b    
-1  2
4   1
6   3

That said, this feels pretty awful hack... perhaps there should be an option to include NaN in groupby (see this github issue - which uses the same placeholder hack).

However, as described in another answer, "from pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using dropna=False"

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Regards Örvar

Convert categorical data in pandas dataframe

For converting categorical data in column C of dataset data, we need to do the following:

from sklearn.preprocessing import LabelEncoder 
labelencoder= LabelEncoder() #initializing an object of class LabelEncoder
data['C'] = labelencoder.fit_transform(data['C']) #fitting and transforming the desired categorical column.

How to test my servlet using JUnit

Updated Feb 2018: OpenBrace Limited has closed down, and its ObMimic product is no longer supported.

Here's another alternative, using OpenBrace's ObMimic library of Servlet API test-doubles (disclosure: I'm its developer).

package com.openbrace.experiments.examplecode.stackoverflow5434419;

import static org.junit.Assert.*;
import com.openbrace.experiments.examplecode.stackoverflow5434419.YourServlet;
import com.openbrace.obmimic.mimic.servlet.ServletConfigMimic;
import com.openbrace.obmimic.mimic.servlet.http.HttpServletRequestMimic;
import com.openbrace.obmimic.mimic.servlet.http.HttpServletResponseMimic;
import com.openbrace.obmimic.substate.servlet.RequestParameters;
import org.junit.Before;
import org.junit.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Example tests for {@link YourServlet#doPost(HttpServletRequest,
 * HttpServletResponse)}.
 *
 * @author Mike Kaufman, OpenBrace Limited
 */
public class YourServletTest {

    /** The servlet to be tested by this instance's test. */
    private YourServlet servlet;

    /** The "mimic" request to be used in this instance's test. */
    private HttpServletRequestMimic request;

    /** The "mimic" response to be used in this instance's test. */
    private HttpServletResponseMimic response;

    /**
     * Create an initialized servlet and a request and response for this
     * instance's test.
     *
     * @throws ServletException if the servlet's init method throws such an
     *     exception.
     */
    @Before
    public void setUp() throws ServletException {
        /*
         * Note that for the simple servlet and tests involved:
         * - We don't need anything particular in the servlet's ServletConfig.
         * - The ServletContext isn't relevant, so ObMimic can be left to use
         *   its default ServletContext for everything.
         */
        servlet = new YourServlet();
        servlet.init(new ServletConfigMimic());
        request = new HttpServletRequestMimic();
        response = new HttpServletResponseMimic();
    }

    /**
     * Test the doPost method with example argument values.
     *
     * @throws ServletException if the servlet throws such an exception.
     * @throws IOException if the servlet throws such an exception.
     */
    @Test
    public void testYourServletDoPostWithExampleArguments()
            throws ServletException, IOException {

        // Configure the request. In this case, all we need are the three
        // request parameters.
        RequestParameters parameters
            = request.getMimicState().getRequestParameters();
        parameters.set("username", "mike");
        parameters.set("password", "xyz#zyx");
        parameters.set("name", "Mike");

        // Run the "doPost".
        servlet.doPost(request, response);

        // Check the response's Content-Type, Cache-Control header and
        // body content.
        assertEquals("text/html; charset=ISO-8859-1",
            response.getMimicState().getContentType());
        assertArrayEquals(new String[] { "no-cache" },
            response.getMimicState().getHeaders().getValues("Cache-Control"));
        assertEquals("...expected result from dataManager.register...",
            response.getMimicState().getBodyContentAsString());

    }

}

Notes:

  • Each "mimic" has a "mimicState" object for its logical state. This provides a clear distinction between the Servlet API methods and the configuration and inspection of the mimic's internal state.

  • You might be surprised that the check of Content-Type includes "charset=ISO-8859-1". However, for the given "doPost" code this is as per the Servlet API Javadoc, and the HttpServletResponse's own getContentType method, and the actual Content-Type header produced on e.g. Glassfish 3. You might not realise this if using normal mock objects and your own expectations of the API's behaviour. In this case it probably doesn't matter, but in more complex cases this is the sort of unanticipated API behaviour that can make a bit of a mockery of mocks!

  • I've used response.getMimicState().getContentType() as the simplest way to check Content-Type and illustrate the above point, but you could indeed check for "text/html" on its own if you wanted (using response.getMimicState().getContentTypeMimeType()). Checking the Content-Type header the same way as for the Cache-Control header also works.

  • For this example the response content is checked as character data (with this using the Writer's encoding). We could also check that the response's Writer was used rather than its OutputStream (using response.getMimicState().isWritingCharacterContent()), but I've taken it that we're only concerned with the resulting output, and don't care what API calls produced it (though that could be checked too...). It's also possible to retrieve the response's body content as bytes, examine the detailed state of the Writer/OutputStream etc.

There are full details of ObMimic and a free download at the OpenBrace website. Or you can contact me if you have any questions (contact details are on the website).

Format ints into string of hex

The most recent and in my opinion preferred approach is the f-string:

''.join(f'{i:02x}' for i in [1, 15, 255])

Format options

The old format style was the %-syntax:

['%02x'%i for i in [1, 15, 255]]

The more modern approach is the .format method:

 ['{:02x}'.format(i) for i in [1, 15, 255]]

More recently, from python 3.6 upwards we were treated to the f-string syntax:

[f'{i:02x}' for i in [1, 15, 255]]

Format syntax

Note that the f'{i:02x}' works as follows.

  • The first part before : is the input or variable to format.
  • The x indicates that the string should be hex. f'{100:02x}' is '64' and f'{100:02d}' is '1001'.
  • The 02 indicates that the string should be left-filled with 0's to length 2. f'{100:02x}' is '64' and f'{100:30x}' is ' 64'.

How to create an integer array in Python?

two ways:

x = [0] * 10
x = [0 for i in xrange(10)]

Edit: replaced range by xrange to avoid creating another list.

Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.

Why can't non-default arguments follow default arguments?

All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the interpreter to decide which values match which arguments if mixed modes were allowed. A SyntaxError is raised if the arguments are not given in the correct order:

Let us take a look at keyword arguments, using your function.

def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y

Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:

func1("ok a", "ok b", 1)  # Is 1 assigned to x or ?
func1(1)                  # Is 1 assigned to a or ?
func1(1, 2)               # ?

How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

Reference O'Reilly - Core-Python
Where as this function make use of the default arguments syntactically correct for above function calls. Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.

How to scroll to top of a div using jQuery?

Or, for less code, inside your click you place:

setTimeout(function(){ 

$('#DIV_ID').scrollTop(0);

}, 500);

Add class to an element in Angular 4

you can try this without any java script you can do that just by using CSS

img:active,
img:focus,
img:hover{ 
border: 10px solid red !important
}

of if your case is to add any other css class by clicking you can use query selector like

<img id="image1" ng-click="changeClass(id)" >
<img id="image2" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >

in controller first search for any image with red border and remove it then by passing the image id add the border class to that image

$scope.changeClass = function(id){
angular.element(document.querySelector('.some-class').removeClass('.some-class');
angular.element(document.querySelector(id)).addClass('.some-class');
}

How to read file using NPOI

It might be helpful to rely on the Workbook factory to instantiate the workbook object since the factory method will do the detection of xls or xlsx for you. Reference: http://apache-poi.1045710.n5.nabble.com/How-to-check-for-valid-excel-files-using-POI-without-checking-the-file-extension-td2341055.html

IWorkbook workbook = WorkbookFactory.Create(inputStream);

If you're not sure of the Sheet's name but you are sure of the index (0 based), you can grab the sheet like this:

ISheet sheet = workbook.GetSheetAt(sheetIndex);

You can then iterate through the rows using code supplied by the accepted answer from mj82

Convert String to Double - VB

Try looking at Double.TryParse() if you are using .NET 1.1/2.0/3.0/3.5/4.0/4.5

Squaring all elements in a list

Use numpy.

import numpy as np
b = list(np.array(a)**2)

Moment js date time comparison

You should be able to compare them directly.

var date = moment("2013-03-24")
var now = moment();

if (now > date) {
   // date is past
} else {
   // date is future
}

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  _x000D_
  $('.compare').click(function(e) {_x000D_
  _x000D_
    var date = $('#date').val();_x000D_
  _x000D_
    var now = moment();_x000D_
    var then = moment(date);_x000D_
  _x000D_
    if (now > then) {_x000D_
      $('.result').text('Date is past');_x000D_
    } else {_x000D_
      $('.result').text('Date is future');_x000D_
    }_x000D_
_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<input type="text" name="date" id="date" value="2014-12-18"  placeholder="yyyy-mm-dd">_x000D_
<button class="compare">Compare date to current date</button>_x000D_
<br>_x000D_
<div class="result"></div>
_x000D_
_x000D_
_x000D_

How to make div fixed after you scroll to that div?

<script>
if($(window).width() >= 1200){
    (function($) {
        var element = $('.to_move_content'),
            originalY = element.offset().top;

        // Space between element and top of screen (when scrolling)
        var topMargin = 10;

        // Should probably be set in CSS; but here just for emphasis
        element.css('position', 'relative');

        $(window).on('scroll', function(event) {
            var scrollTop = $(window).scrollTop();

            element.stop(false, false).animate({
                top: scrollTop < originalY
                    ? 0
                    : scrollTop - originalY + topMargin
            }, 0);
        });
    })(jQuery);
}

Try this ! just add class .to_move_content to you div

Reload browser window after POST without prompting user to resend POST data

This is an older post, but I do have a better solution. Create a form containing all of your post values as hidden fields and give the form a name such as:

<form name="RefreshForm" method="post" action="http://yoursite/yourscript">
    <input type="hidden" name="postVariable" value="PostData">
</form>

Then all you need to do in your setTimeout is RefreshForm.submit();

Cheers!

Different CURRENT_TIMESTAMP and SYSDATE in oracle

CURRENT_DATE and CURRENT_TIMESTAMP return the current date and time in the session time zone.

SYSDATE and SYSTIMESTAMP return the system date and time - that is, of the system on which the database resides.

If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS* and CURRENT_* functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.

You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.

How do I determine if my python shell is executing in 32bit or 64bit?

platform.architecture() notes say:

Note: On Mac OS X (and perhaps other platforms), executable files may be universal files containing multiple architectures.

To get at the “64-bitness” of the current interpreter, it is more reliable to query the sys.maxsize attribute:

import sys
is_64bits = sys.maxsize > 2**32

Access Controller method from another controller in Laravel 5

This approach also works with same hierarchy of Controller files:

$printReport = new PrintReportController;

$prinReport->getPrintReport();

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I Had the same problem.

The solution for me is:

You must have the same version of: Microsoft.ReportViewer.ProcessingObjectModel registred in C:\Windows\assembly\GAC_MSIL\Microsoft.ReportViewer.ProcessingObjectModel, like you have registraded in web.config in developer server:

enter image description here

In my case i was only registred the 13. version in my prodution server and i have the 12. version in developer server.

the solution is install the version 12. in the prodution server too

the version 12. :

https://download.microsoft.com/download/A/1/2/A129F694-233C-4C7C-860F-F73139CF2E01/ENU/x86/ReportViewer.msi

Then now i have the version 12. in the prodution and the report work fine.

*** Remember to reset your IIS after instalation

enter image description here

Can I dispatch an action in reducer?

Starting another dispatch before your reducer is finished is an anti-pattern, because the state you received at the beginning of your reducer will not be the current application state anymore when your reducer finishes. But scheduling another dispatch from within a reducer is NOT an anti-pattern. In fact, that is what the Elm language does, and as you know Redux is an attempt to bring the Elm architecture to JavaScript.

Here is a middleware that will add the property asyncDispatch to all of your actions. When your reducer has finished and returned the new application state, asyncDispatch will trigger store.dispatch with whatever action you give to it.

// This middleware will just add the property "async dispatch" to all actions
const asyncDispatchMiddleware = store => next => action => {
  let syncActivityFinished = false;
  let actionQueue = [];

  function flushQueue() {
    actionQueue.forEach(a => store.dispatch(a)); // flush queue
    actionQueue = [];
  }

  function asyncDispatch(asyncAction) {
    actionQueue = actionQueue.concat([asyncAction]);

    if (syncActivityFinished) {
      flushQueue();
    }
  }

  const actionWithAsyncDispatch =
    Object.assign({}, action, { asyncDispatch });

  const res = next(actionWithAsyncDispatch);

  syncActivityFinished = true;
  flushQueue();

  return res;
};

Now your reducer can do this:

function reducer(state, action) {
  switch (action.type) {
    case "fetch-start":
      fetch('wwww.example.com')
        .then(r => r.json())
        .then(r => action.asyncDispatch({ type: "fetch-response", value: r }))
      return state;

    case "fetch-response":
      return Object.assign({}, state, { whatever: action.value });;
  }
}

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

I work for a large corporation and encountered this same error, but needed a different work around. My issue was related to proxy settings. I had my proxy set up so I needed to set my no_proxy to whitelist AWS before I was able to get everything to work. You can set it in your bash script as well if you don't want to muddy up your Python code with os settings.

Python:

import os
os.environ["NO_PROXY"] = "s3.amazonaws.com"

Bash:

export no_proxy = "s3.amazonaws.com"

Edit: The above assume a US East S3 region. For other regions: use s3.[region].amazonaws.com where region is something like us-east-1 or us-west-2

How can I center an image in Bootstrap?

Three ways to align img in the center of its parent.

  1. img is an inline element, text-center aligns inline elements in the center of its container should the container be a block element.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col text-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. mx-auto centers block elements. In order to so, change display of the img from inline to block with d-block class.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Use d-flex and justify-content-center on its parent.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col d-flex justify-content-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting RSA private key from PEM BASE64 Encoded private key file

Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.

How to import set of icons into Android Studio project

what u need to do is icons downloaded from material design, open that folder there are lots of icons categories specified, open any of it choose any icon and go to this folder -> drawable-anydpi-v21. this folder contains xml files copy any xml file and paste it to this location -> C:\Users\Username\AndroidStudioProjects\ur project name\app\src\main\res\drawable. That's it !! now you can use the icon in ur project.

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

The number of method references in a .dex file cannot exceed 64k API 17

This error can also occur when you load all google play services apis when you only using afew.

As stated by google:"In versions of Google Play services prior to 6.5, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit.

From version 6.5, you can instead selectively compile Google Play service APIs into your app."

For example when your app needs play-services-maps ,play-services-location .You need to add only the two apis in your build.gradle file at app level as show below:

compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'

Instead of:

compile 'com.google.android.gms:play-services:10.2.1'

For full documentation and list of google play services apis click here

Two versions of python on linux. how to make 2.7 the default

Enter the command

which python

//output:
/usr/bin/python

cd /usr/bin
ls -l

Here you can see something like this

lrwxrwxrwx 1 root   root            9 Mar  7 17:04  python -> python2.7

your default python2.7 is soft linked to the text 'python'

So remove the softlink python

sudo rm -r python

then retry the above command

ls -l

you can see the softlink is removed

-rwxr-xr-x 1 root   root      3670448 Nov 12 20:01  python2.7

Then create a new softlink for python3.6

ln -s /usr/bin/python3.6 python

Then try the command python in terminal

//output:
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux

Type help, copyright, credits or license for more information.

Dataset - Vehicle make/model/year (free)

Apparently there is not much out there. And a lot of doubt that someone would be willing to provide such a repository. So I solved the problem myself, and am sharing my dataset with anyone else who finds themselves facing the same problem.

https://github.com/n8barr/automotive-model-year-data

Initializing C# auto-properties

You can do it via the constructor of your class:

public class foo {
  public foo(){
    Bar = "bar";
  }
  public string Bar {get;set;}
}

If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):

public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  }
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  }
  public string Bar {get; set;}
  public string Baz {get; set;}
}

If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.

The name 'model' does not exist in current context in MVC3

I was facing the same issue and then I find a solution. The solution is:

  1. Close Visual Studio
  2. Delete the SUO file
  3. Restart Visual Studio

The .suo file is a hidden file in the same folder where the .svn solution file exists. Hope, it'll work!

How do I get LaTeX to hyphenate a word that contains a dash?

multi\hskip0pt-\hskip0pt disciplinary

You can e.g. define like

\def\:{\hskip0pt}

and then write

multi\:-\:disciplinary

Note that the babel Russian language package has its own set of dashes that do not prohibit hyphenation, "~ (double quotation+tilde) for example.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

Convert Little Endian to Big Endian

one more suggestion :

unsigned int a = 0xABCDEF23;
a = ((a&(0x0000FFFF)) << 16) | ((a&(0xFFFF0000)) >> 16);
a = ((a&(0x00FF00FF)) << 8) | ((a&(0xFF00FF00)) >>8);
printf("%0x\n",a);

How do I change a tab background color when using TabLayout?

Have you tried checking the API?

You will need to create a listener for the OnTabSelectedListener event, then when a user selects any tab you should check if it is the correct one, then change the background color using tabLayout.setBackgroundColor(int color), or if it is not the correct tab make sure you change back to the normal color again with the same method.

Turning off hibernate logging console output

For those who don't want elegant solutions, just a quick and dirty way to stop those messages, here is a solution that worked for me (I use Hibernate 4.3.6 and Eclipse and no answers provided above (or found on the internet) worked; neither log4j config files nor setting the logging level programatically)

public static void main(String[] args) {
    //magical - do not touch
    @SuppressWarnings("unused")
    org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.WARNING); //or whatever level you need

    ...
}

I used it in a tutorial program downloaded from this site

@RequestBody and @ResponseBody annotations in Spring

package com.programmingfree.springshop.controller;

import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.programmingfree.springshop.dao.UserShop;
import com.programmingfree.springshop.domain.User;


@RestController
@RequestMapping("/shop/user")
public class SpringShopController {

 UserShop userShop=new UserShop();

 @RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
 public User getUser(@PathVariable int id) {
  User user=userShop.getUserById(id);
  return user;
 }


 @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
 public List<User> getAllUsers() {
  List<User> users=userShop.getAllUsers();
  return users;
 }


}

In the above example they going to display all user and particular id details now I want to use both id and name,

1) localhost:8093/plejson/shop/user <---this link will display all user details
2) localhost:8093/plejson/shop/user/11 <----if i use 11 in link means, it will display particular user 11 details

now I want to use both id and name

localhost:8093/plejson/shop/user/11/raju <-----------------like this it means we can use any one in this please help me out.....

Refused to load the script because it violates the following Content Security Policy directive

It was solved with:

script-src 'self' http://xxxx 'unsafe-inline' 'unsafe-eval';

Javascript foreach loop on associative array object

This is very simple approach. The Advantage is you can get keys as well:

for (var key in array) {
    var value = array[key];
    console.log(key, value);
}

For ES6:

array.forEach(value => {
  console.log(value)
})  

For ES6: (If you want value, index and the array itself)

array.forEach((value, index, self) => {
  console.log(value, index, self)
})  

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

What's the difference between IFrame and Frame?

iframes are used a lot to include complete pages. When those pages are hosted on another domain you get problems with cross side scripting and stuff. There are ways to fix this.

Frames were used to divide your page into multiple parts (for example, a navigation menu on the left). Using them is no longer recommended.

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

How do I get the last word in each line with bash

there are many ways. as awk solutions shows, it's the clean solution

sed solution is to delete anything till the last space. So if there is no space at the end, it should work

sed 's/.* //g' <file>

you can avoid sed also and go for a while loop.

while read line
do [ -z "$line" ] && continue ;
echo $line|rev|cut -f1 -d' '|rev
done < file

it reads a line, reveres it, cuts the first (i.e. last in the original) and restores back

the same can be done in a pure bash way

while read line
do [ -z "$line" ] && continue ;
echo ${line##* }
done < file

it is called parameter expansion

How to add RSA key to authorized_keys file?

I know I am replying too late but for anyone else who needs this, run following command from your local machine

cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

this has worked perfectly fine. All you need to do is just to replace

[email protected]

with your own user for that particular host

What is the difference between Normalize.css and Reset CSS?

Well from its description it appears it tries to make the user agent's default style consistent across all browsers rather than stripping away all the default styling as a reset would.

Preserves useful defaults, unlike many CSS resets.

Is there a Visual Basic 6 decompiler?

For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

If you want to avoid the mem cost of using the exec command, I believe you can do better with xargs. I think the following is a more efficient alternative to

find foo -type f ! -name '*Music*' -exec cp {} bar \; # new proc for each exec



find . -maxdepth 1 -name '*Music*' -prune -o -print0 | xargs -0 -i cp {} dest/

Docker compose port mapping

If you want to bind to the redis port from your nodejs container you will have to expose that port in the redis container:

version: '2'
services:
  nodejs:
    build:
      context: .
      dockerfile: DockerFile
    ports:
      - "4000:4000"
    links:
      - redis

  redis:
    build:
      context: .
      dockerfile: Dockerfile-redis
    expose:
      - "6379"

The expose tag will let you expose ports without publishing them to the host machine, but they will be exposed to the containers networks.

https://docs.docker.com/compose/compose-file/#expose

The ports tag will be mapping the host port with the container port HOST:CONTAINER

https://docs.docker.com/compose/compose-file/#ports

Run MySQLDump without Locking Tables

When using MySQL Workbench, at Data Export, click in Advanced Options and uncheck the "lock-tables" options.

enter image description here

Cannot find Microsoft.Office.Interop Visual Studio

Just doing like @Kjartan.

Steps are as follows:

  1. Right click your C# project name in Visual Studio's "Solution Explorer";

  2. Then, select "add -> Reference -> COM -> Type Libraries " in order;

  3. Find the "Microsoft Office 16.0 Object Library", and add it to reference (Note: the version number may vary with the OFFICE you have installed);

  4. After doing this, you will see "Microsoft.Office.Interop.Word" under the "Reference" item in your project.

How can I use numpy.correlate to do autocorrelation?

To answer your first question, numpy.correlate(a, v, mode) is performing the convolution of a with the reverse of v and giving the results clipped by the specified mode. The definition of convolution, C(t)=? -8 < i < 8 aivt+i where -8 < t < 8, allows for results from -8 to 8, but you obviously can't store an infinitely long array. So it has to be clipped, and that is where the mode comes in. There are 3 different modes: full, same, & valid:

  • "full" mode returns results for every t where both a and v have some overlap.
  • "same" mode returns a result with the same length as the shortest vector (a or v).
  • "valid" mode returns results only when a and v completely overlap each other. The documentation for numpy.convolve gives more detail on the modes.

For your second question, I think numpy.correlate is giving you the autocorrelation, it is just giving you a little more as well. The autocorrelation is used to find how similar a signal, or function, is to itself at a certain time difference. At a time difference of 0, the auto-correlation should be the highest because the signal is identical to itself, so you expected that the first element in the autocorrelation result array would be the greatest. However, the correlation is not starting at a time difference of 0. It starts at a negative time difference, closes to 0, and then goes positive. That is, you were expecting:

autocorrelation(a) = ? -8 < i < 8 aivt+i where 0 <= t < 8

But what you got was:

autocorrelation(a) = ? -8 < i < 8 aivt+i where -8 < t < 8

What you need to do is take the last half of your correlation result, and that should be the autocorrelation you are looking for. A simple python function to do that would be:

def autocorr(x):
    result = numpy.correlate(x, x, mode='full')
    return result[result.size/2:]

You will, of course, need error checking to make sure that x is actually a 1-d array. Also, this explanation probably isn't the most mathematically rigorous. I've been throwing around infinities because the definition of convolution uses them, but that doesn't necessarily apply for autocorrelation. So, the theoretical portion of this explanation may be slightly wonky, but hopefully the practical results are helpful. These pages on autocorrelation are pretty helpful, and can give you a much better theoretical background if you don't mind wading through the notation and heavy concepts.

Mutex lock threads

Q1.) Assuming process B tries to take ownership of the same mutex you locked in process A (you left that out of your pseudocode) then no, process B cannot access sharedResource while the mutex is locked since it will sit waiting to lock the mutex until it is released by process A. It will return from the mutex_lock() function when the mutex is locked (or when an error occurs!)

Q2.) In Process B, ensure you always lock the mutex, access the shared resource, and then unlock the mutex. Also, check the return code from the mutex_lock( pMutex ) routine to ensure that you actually own the mutex, and ONLY unlock the mutex if you have locked it. Do the same from process A.

Both processes should basically do the same thing when accessing the mutex.
lock() If the lock succeeds, then { access sharedResource unlock() }

Q3.) Yes, there are lots of diagrams: =) https://www.google.se/search?q=mutex+thread+process&rlz=1C1AFAB_enSE487SE487&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&ei=ErodUcSmKqf54QS6nYDoAw&biw=1200&bih=1730&sei=FbodUbPbB6mF4ATarIBQ

What is the difference between int, Int16, Int32 and Int64?

int

It is a primitive data type defined in C#.

It is mapped to Int32 of FCL type.

It is a value type and represent System.Int32 struct.

It is signed and takes 32 bits.

It has minimum -2147483648 and maximum +2147483647 value.

Int16

It is a FCL type.

In C#, short is mapped to Int16.

It is a value type and represent System.Int16 struct.

It is signed and takes 16 bits.

It has minimum -32768 and maximum +32767 value.

Int32

It is a FCL type.

In C#, int is mapped to Int32.

It is a value type and represent System.Int32 struct.

It is signed and takes 32 bits.

It has minimum -2147483648 and maximum +2147483647 value.

Int64

It is a FCL type.

In C#, long is mapped to Int64.

It is a value type and represent System.Int64 struct.

It is signed and takes 64 bits.

It has minimum –9,223,372,036,854,775,808 and maximum 9,223,372,036,854,775,807 value.

I cannot access tomcat admin console?

Notice that the http code response status you are getting is an HTTP 404. The 404 or Not Found error message is a response code indicating that the client was able to communicate with a given server, but the server could not find what was requested.

If you have got an 403 Forbidden vs 401 Unauthorized HTTP responses then it might make a sense to review your tomcat-users.xml.

Resuming: check the manager resources and files of your server installation, some file/directory might be missing, or the path to the manager resources has been changed.

how to pass command line arguments to main method dynamically

If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program ArgsTest.java:

package test;

import java.io.IOException;

    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);
            }

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));

        }
    }

If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
  pro1
  pro2
  pro3
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2

How to check if multiple array keys exists

<?php

function check_keys_exists($keys_str = "", $arr = array()){
    $return = false;
    if($keys_str != "" and !empty($arr)){
        $keys = explode(',', $keys_str);
        if(!empty($keys)){
            foreach($keys as $key){
                $return = array_key_exists($key, $arr);
                if($return == false){
                    break;
                }
            }
        }
    }
    return $return;
}

//run demo

$key = 'a,b,c';
$array = array('a'=>'aaaa','b'=>'ccc','c'=>'eeeee');

var_dump( check_keys_exists($key, $array));

php $_POST array empty upon form submission

same issue here!

i was trying to connect to my local server code via post request in postman, and this problem wasted my time alot!

for anyone who uses local project (e.g. postman): use your IPv4 address (type ipconfig in cmd) instead of the "localhost" keyword. in my case:

before:

localhost/app/login

after:

192.168.1.101/app/login

SQLException : String or binary data would be truncated

Simply Used this: MessageBox.Show(cmd4.CommandText.ToString()); in c#.net and this will show you main query , Copy it and run in database .

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why does my 'git branch' have no master?

I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add . and then git commit and the master branch will be created.

Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.

How do I run Java .class files?

You need to set the classpath to find your compiled class:

java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2

PHP check if date between two dates

You are comparing the dates as strings, which won't work because the comparison is lexicographical. It's the same issue as when sorting a text file, where a line 20 would appear after a line 100 because the contents are not treated as numbers but as sequences of ASCII codes. In addition, the dates created are all wrong because you are using a string format string where a timestamp is expected (second argument).

Instead of this you should be comparing timestamps of DateTime objects, for instance:

 $paymentDate = date_create();
 $contractDateBegin = date_create_from_format('d/m/Y', '01/01/2001');
 $contractDateEnd = date_create_from_format('d/m/Y', '01/01/2015');

Your existing conditions will then work correctly.

How to change a package name in Eclipse?

create a new package, drag and drop the class into it and now you are able to rename the new package

What do the different readystates in XMLHttpRequest mean, and how can I use them?

  • 0 : UNSENT Client has been created. open() not called yet.
  • 1 : OPENED open() has been called.
  • 2 : HEADERS_RECEIVED send() has been called, and headers and status are available.
  • 3 : LOADING Downloading; responseText holds partial data.
  • 4 : DONE The operation is complete.

(From https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState)

React JS get current date

You can use the react-moment package

-> https://www.npmjs.com/package/react-moment

Put in your file the next line:

import moment from "moment";

date_create: moment().format("DD-MM-YYYY hh:mm:ss")

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Sort matrix according to first column in R

Read the data:

foo <- read.table(text="1 349
  1 393
  1 392
  4 459
  3 49
  3 32
  2 94")

And sort:

foo[order(foo$V1),]

This relies on the fact that order keeps ties in their original order. See ?order.

How to access PHP session variables from jQuery function in a .js file?

I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :

In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing : <p id="sessionOrigin"><?=$_SESSION['origin'];?></p>

In your js, using jQuery you can access it like so : $("#sessionOrigin").text();

EDIT: or even better, put it in a hidden input

<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>

What does the 'b' character do in front of a string literal?

Here's an example where the absence of b would throw a TypeError exception in Python 3.x

>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

Adding a b prefix would fix the problem.

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

Counting inversions in an array

I had a question similar to this for homework actually. I was restricted that it must have O(nlogn) efficiency.

I used the idea you proposed of using Mergesort, since it is already of the correct efficiency. I just inserted some code into the merging function that was basically: Whenever a number from the array on the right is being added to the output array, I add to the total number of inversions, the amount of numbers remaining in the left array.

This makes a lot of sense to me now that I've thought about it enough. Your counting how many times there is a greater number coming before any numbers.

hth.

jQuery: Change button text on click

This should work for you:

    $('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
});

How to find index position of an element in a list when contains returns true

Here is an example:

List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2

View/edit ID3 data for MP3 files

ID3.NET implemented ID3v1.x and ID3v2.3 and supports read/write operations on the ID3 section in MP3 files. There's also a NuGet package available.

how to replace an entire column on Pandas.DataFrame

If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning. Your example:

df = df.assign(B=df1['E'])

How do I reverse an int array in Java?

In case of Java 8 we can also use IntStream to reverse the array of integers as:

int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
                      .toArray(); //Output: [5, 4, 3, 2, 1]

How do I compare a value to a backslash?

Try like this:

if message.value[0] == "/" or message.value[0] == "\\":
  do_stuff

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

Rubymine: How to make Git ignore .idea files created by Rubymine

Add .idea/* to your exclusion list to prevent tracking of all .idea files, directories, and sub-resources.

JUnit test for System.out.println()

If you were using Spring Boot (you mentioned that you're working with an old application, so you probably aren't but it might be of use to others), then you could use org.springframework.boot.test.rule.OutputCapture in the following manner:

@Rule
public OutputCapture outputCapture = new OutputCapture();

@Test
public void out() {
    System.out.print("hello");
    assertEquals(outputCapture.toString(), "hello");
}

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

Find the most frequent number in a NumPy array

Also if you want to get most frequent value(positive or negative) without loading any modules you can use the following code:

lVals = [1,2,3,1,2,1,1,1,3,2,2,1]
print max(map(lambda val: (lVals.count(val), val), set(lVals)))

How can I make XSLT work in chrome?

I had the same problem on localhost. Running around the Internet looking for the answer and I approve that adding --allow-file-access-from-files works. I work on Mac, so for me I had to go through terminal sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files and enter your password (if you have one).

Another small thing - nothing will work unless you add to your .xml file the reference to your .xsl file as follows <?xml-stylesheet type="text/xsl" href="<path to file>"?>. Another small thing I didn't realise immediately - you should be opening your .xml file in browser, no the .xsl.

How to create and handle composite primary key in JPA

Key class:

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

Entity class:

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

How can I duplicate it with another Version?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s

On a server using a logon script, tell the logon to run the batch file. Jason

When does a process get SIGABRT (signal 6)?

You can send any signal to any process using the kill(2) interface:

kill -SIGABRT 30823

30823 was a dash process I started, so I could easily find the process I wanted to kill.

$ /bin/dash
$ Aborted

The Aborted output is apparently how dash reports a SIGABRT.

It can be sent directly to any process using kill(2), or a process can send the signal to itself via assert(3), abort(3), or raise(3).

C# adding a character in a string

Inserting Space in emailId field after every 8 characters

public string BreakEmailId(string emailId) {
    string returnVal = string.Empty;
    if (emailId.Length > 8) {           
        for (int i = 0; i < emailId.Length; i += 8) {
            returnVal += emailId.Substring(i, 8) + " ";
        }
    }

    return returnVal;
}

Convert a string to integer with decimal in Python

How about this?

>>> s = '23.45678'
>>> int(float(s))
23

Or...

>>> int(Decimal(s))
23

Or...

>>> int(s.split('.')[0])
23

I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.

Copy directory to another directory using ADD command

Indeed ADD go /usr/local/ will add content of go folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR to /usr/local/ then add your directory to it like:

WORKDIR /usr/local/
COPY go go/

or

WORKDIR /usr/local/go
COPY go ./

But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . . and exclude all unwanted directories and files in .dockerignore, let's say I got folders and files:

- src 
- tmp 
- dist 
- assets 
- go 
- justforfun 
- node_modules 
- scripts 
- .dockerignore 
- Dockerfile 
- headache.lock 
- package.json 

and I want to add src assets package.json justforfun go so:

in Dockerfile:

FROM galaxy:latest

WORKDIR /usr/local/
COPY . .

in .dockerignore file:

node_modules
headache.lock
tmp
dist

Or for more fun (or you like to confuse more people make them suffer as well :P) can be:

*
!src 
!assets 
!go 
!justforfun 
!scripts 
!package.json 

In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".

It is a late answer but adding more ways to do the same covering even more cases.

Extracting time from POSIXct

Here's an update for those looking for a tidyverse method to extract hh:mm::ss.sssss from a POSIXct object. Note that time zone is not included in the output.

library(hms)
as_hms(times)

What's the right way to decode a string that has special HTML entities in it?

Don’t use the DOM to do this. Using the DOM to decode HTML entities (as suggested in the currently accepted answer) leads to differences in cross-browser results.

For a robust & deterministic solution that decodes character references according to the algorithm in the HTML Standard, use the he library. From its README:

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.

Here’s how you’d use it:

he.decode("We&#39;re unable to complete your request at this time.");
? "We're unable to complete your request at this time."

Disclaimer: I'm the author of the he library.

See this Stack Overflow answer for some more info.

Implementation difference between Aggregation and Composition in Java

The difference is that any composition is an aggregation and not vice versa.

Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you mean "shared".

Further from UML standard:

composite - Indicates that the property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (parts).

So, University to cathedras association is a composition, because cathedra doesn't exist out of University (IMHO)

Precise semantics of shared aggregation varies by application area and modeler.

I.e., all other associations can be drawn as shared aggregations, if you are only following to some principles of yours or of somebody else. Also look here.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

Keep it Simple!

Simpler and a Standard solution to increment the number and to retain the dot at the end. Even if you get the css right, it will not work if your HTML is not correct. see below.

CSS

ol {
  counter-reset: item;
}
ol li {
  display: block;
}
ol li:before {
  content: counters(item, ". ") ". ";
  counter-increment: item;
}

SASS

ol {
    counter-reset: item;
    li {
        display: block;
        &:before {
            content: counters(item, ". ") ". ";
            counter-increment: item
        }
    }
}

HTML Parent Child

If you add the child make sure the it is under the parent li.

<!-- WRONG -->
<ol>
    <li>Parent 1</li> <!-- Parent is Individual. Not hugging -->
        <ol> 
            <li>Child</li>
        </ol>
    <li>Parent 2</li>
</ol>

<!-- RIGHT -->
<ol>
    <li>Parent 1 
        <ol> 
            <li>Child</li>
        </ol>
    </li> <!-- Parent is Hugging the child -->
    <li>Parent 2</li>
</ol>

How to convert JSON to XML or XML to JSON?

You can do these conversions also with the .NET Framework:

JSON to XML: by using System.Runtime.Serialization.Json

var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));

XML to JSON: by using System.Web.Script.Serialization

var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));

private static Dictionary<string, object> GetXmlData(XElement xml)
{
    var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
    if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
    else if (!xml.IsEmpty) attr.Add("_value", xml.Value);

    return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}

Trees in Twitter Bootstrap

If someone wants vertical version of the treeview from Harsh's answer, you can save some time:

http://jsfiddle.net/Fh47n/

.tree li {
    margin: 0px 0;

    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}

.tree li::before{
    content: '';
    position: absolute; 
    top: 0;
    width: 1px; 
    height: 100%;
    right: auto; 
    left: -20px;
    border-left: 1px solid #ccc;
    bottom: 50px;
}
.tree li::after{
    content: '';
    position: absolute; 
    top: 30px; 
    width: 25px; 
    height: 20px;
    right: auto; 
    left: -20px;
    border-top: 1px solid #ccc;
}
.tree li a{
    display: inline-block;
    border: 1px solid #ccc;
    padding: 5px 10px;
    text-decoration: none;
    color: #666;
    font-family: arial, verdana, tahoma;
    font-size: 11px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

/*Remove connectors before root*/
.tree > ul > li::before, .tree > ul > li::after{
    border: 0;
}
/*Remove connectors after last child*/
.tree li:last-child::before{ 
      height: 30px;
}

/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
    background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after, 
.tree li a:hover+ul li::before, 
.tree li a:hover+ul::before, 
.tree li a:hover+ul ul::before{
    border-color:  #94a0b4;
}

Creating a constant Dictionary in C#

Why not use namespaces or classes to nest your values? It may be imperfect, but it is very clean.

public static class ParentClass
{
    // here is the "dictionary" class
    public static class FooDictionary
    {
        public const string Key1 = "somevalue";
        public const string Foobar = "fubar";
    }
}

Now you can access .ParentClass.FooDictionary.Key1, etc.

How to write string literals in python without having to escape them?

if string is a variable, use the .repr method on it:

>>> s = '\tgherkin\n'

>>> s
'\tgherkin\n'

>>> print(s)
    gherkin

>>> print(s.__repr__())
'\tgherkin\n'

Java Replace Character At Specific Position Of String?

Use StringBuilder:

StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

I looked to MS to find the answers. The first solution assumes the user account running the application process has access to the shared folder or drive (Same domain). Make sure your DNS is resolved or try using IP address. Simply do the following:

 DirectoryInfo di = new DirectoryInfo(PATH);
 var files = di.EnumerateFiles("*.*", SearchOption.AllDirectories);

If you want across different domains .NET 2.0 with credentials follow this model:

WebRequest req = FileWebRequest.Create(new Uri(@"\\<server Name>\Dir\test.txt"));

        req.Credentials = new NetworkCredential(@"<Domain>\<User>", "<Password>");
        req.PreAuthenticate = true;

        WebResponse d = req.GetResponse();
        FileStream fs = File.Create("test.txt");

        // here you can check that the cast was successful if you want. 
        fs = d.GetResponseStream() as FileStream;
        fs.Close();

How to change color of the back arrow in the new material theme?

Looking at the Toolbar and TintManager source, drawable/abc_ic_ab_back_mtrl_am_alpha is tinted with the value of the style attribute colorControlNormal.

I did try setting this in my project (with <item name="colorControlNormal">@color/my_awesome_color</item> in my theme), but it's still black for me.

Update:

Found it. You need to set the actionBarTheme attribute (not actionBarStyle) with colorControlNormal.

Eg:

<style name="MyTheme" parent="Theme.AppCompat.Light">        
    <item name="actionBarTheme">@style/MyApp.ActionBarTheme</item>
    <item name="actionBarStyle">@style/MyApp.ActionBar</item>
    <!-- color for widget theming, eg EditText. Doesn't effect ActionBar. -->
    <item name="colorControlNormal">@color/my_awesome_color</item>
    <!-- The animated arrow style -->
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="MyApp.ActionBarTheme" parent="@style/ThemeOverlay.AppCompat.ActionBar">       
    <!-- THIS is where you can color the arrow! -->
    <item name="colorControlNormal">@color/my_awesome_color</item>
</style>

<style name="MyApp.ActionBarStyle" parent="@style/Widget.AppCompat.Light.ActionBar">
    <item name="elevation">0dp</item>      
    <!-- style for actionBar title -->  
    <item name="titleTextStyle">@style/ActionBarTitleText</item>
    <!-- style for actionBar subtitle -->  
    <item name="subtitleTextStyle">@style/ActionBarSubtitleText</item>

    <!-- 
    the actionBarTheme doesn't use the colorControlNormal attribute
    <item name="colorControlNormal">@color/my_awesome_color</item>
     -->
</style>

How do I get the absolute directory of a file in bash?

Take a look at realpath which is available on GNU/Linux, FreeBSD and NetBSD, but not OpenBSD 6.8. I use something like:

CONTAININGDIR=$(realpath ${FILEPATH%/*})

to do what it sounds like you're trying to do.

Resize command prompt through commands

You can use /start /max [your batch] it will fill the screen with the program it oppose to /min

Integer value in TextView

Consider using String#format with proper format specifications (%d or %f) instead.

int value = 10;

textView.setText(String.format("%d",value));

This will handle fraction separator and locale specific digits properly

How to get GET (query string) variables in Express.js on Node.js?

Whitequark responded nicely. But with the current versions of Node.js and Express.js it requires one more line. Make sure to add the 'require http' (second line). I've posted a fuller example here that shows how this call can work. Once running, type http://localhost:8080/?name=abel&fruit=apple in your browser, and you will get a cool response based on the code.

var express = require('express');
var http = require('http');
var app = express();

app.configure(function(){
    app.set('port', 8080);
});

app.get('/', function(req, res){
  res.writeHead(200, {'content-type': 'text/plain'});
  res.write('name: ' + req.query.name + '\n');
  res.write('fruit: ' + req.query.fruit + '\n');
  res.write('query: ' + req.query + '\n');
  queryStuff = JSON.stringify(req.query);
  res.end('That\'s all folks'  + '\n' + queryStuff);
});

http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
})

HTML img scaling

Adding max-width: 100%; to the img tag works for me.

How do I make a request using HTTP basic authentication with PHP curl?

If the authorization type is Basic auth and data posted is json then do like this

<?php

$data = array("username" => "test"); // data u want to post                                                                   
$data_string = json_encode($data);                                                                                   
 $api_key = "your_api_key";   
 $password = "xxxxxx";                                                                                                                 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://xxxxxxxxxxxxxxxxxxxxxxx");    
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($ch, CURLOPT_POST, true);                                                                   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(   
    'Accept: application/json',
    'Content-Type: application/json')                                                           
);             

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}                                                                                                      
$errors = curl_error($ch);                                                                                                            
$result = curl_exec($ch);
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);  
echo $returnCode;
var_dump($errors);
print_r(json_decode($result, true));

Print a variable in hexadecimal in Python

Convert the string to an integer base 16 then to hexadecimal.

print hex(int(string, base=16))

These are built-in functions.

http://docs.python.org/2/library/functions.html#int

Example

>>> string = 'AA'
>>> _int = int(string, base=16)
>>> _hex = hex(_int)
>>> print _int
170
>>> print _hex
0xaa
>>> 

How to uncheck checkbox using jQuery Uniform library

checkbox that act like radio btn

$(".checkgroup").live('change',function() { var previous=this.checked; $(".checkgroup).attr("checked", false); $(this).attr("checked", previous); });

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

To trigger an event you basically just call the event handler for that element. Slight change from your code.

var a = document.getElementById("element");
var evnt = a["onclick"];

if (typeof(evnt) == "function") {
    evnt.call(a);
}

How do I create an average from a Ruby array?

Some benchmarking of top solutions (in order of most efficient):

Large Array:

array = (1..10_000_000).to_a

Benchmark.bm do |bm|
  bm.report { array.instance_eval { reduce(:+) / size.to_f } }
  bm.report { array.sum.fdiv(array.size) }
  bm.report { array.sum / array.size.to_f }
  bm.report { array.reduce(:+).to_f / array.size }
  bm.report { array.reduce(:+).try(:to_f).try(:/, array.size) }
  bm.report { array.inject(0.0) { |sum, el| sum + el }.to_f / array.size }
  bm.report { array.reduce([ 0.0, 0 ]) { |(s, c), e| [ s + e, c + 1 ] }.reduce(:/) }
end


    user     system      total        real
0.480000   0.000000   0.480000   (0.473920)
0.500000   0.000000   0.500000   (0.502158)
0.500000   0.000000   0.500000   (0.508075)
0.510000   0.000000   0.510000   (0.512600)
0.520000   0.000000   0.520000   (0.516096)
0.760000   0.000000   0.760000   (0.767743)
1.530000   0.000000   1.530000   (1.534404)

Small Arrays:

array = Array.new(10) { rand(0.5..2.0) }

Benchmark.bm do |bm|
  bm.report { 1_000_000.times { array.reduce(:+).to_f / array.size } }
  bm.report { 1_000_000.times { array.sum / array.size.to_f } }
  bm.report { 1_000_000.times { array.sum.fdiv(array.size) } }
  bm.report { 1_000_000.times { array.inject(0.0) { |sum, el| sum + el }.to_f / array.size } }
  bm.report { 1_000_000.times { array.instance_eval { reduce(:+) / size.to_f } } }
  bm.report { 1_000_000.times { array.reduce(:+).try(:to_f).try(:/, array.size) } }
  bm.report { 1_000_000.times { array.reduce([ 0.0, 0 ]) { |(s, c), e| [ s + e, c + 1 ] }.reduce(:/) } }
end


    user     system      total        real
0.760000   0.000000   0.760000   (0.760353)
0.870000   0.000000   0.870000   (0.876087)
0.900000   0.000000   0.900000   (0.901102)
0.920000   0.000000   0.920000   (0.920888)
0.950000   0.000000   0.950000   (0.952842)
1.690000   0.000000   1.690000   (1.694117)
1.840000   0.010000   1.850000   (1.845623)

Get loop count inside a Python FOR loop

Try using itertools.count([n])

jQuery - select the associated label element of a input field

As long and your input and label elements are associated by their id and for attributes, you should be able to do something like this:

$('.input').each(function() { 
   $this = $(this);
   $label = $('label[for="'+ $this.attr('id') +'"]');
   if ($label.length > 0 ) {
       //this input has a label associated with it, lets do something!
   }
});

If for is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.

How to Call Controller Actions using JQuery in ASP.NET MVC

You can start reading from here jQuery.ajax()

Actually Controller Action is a public method which can be accessed through Url. So any call of an Action from an Ajax call, either MicrosoftMvcAjax or jQuery can be made. For me, jQuery is the simplest one. It got a lots of examples in the link I gave above. The typical example for an ajax call is like this.

$.ajax({
    // edit to add steve's suggestion.
    //url: "/ControllerName/ActionName",
    url: '<%= Url.Action("ActionName", "ControllerName") %>',
    success: function(data) {
         // your data could be a View or Json or what ever you returned in your action method 
         // parse your data here
         alert(data);
    }
});

More examples can be found in here

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

There are two options to handle/avoid this situation.

  1. Before re-running the application just terminate the previous connection.
  • Open the console --> right click --> terminate all.
  1. If you forgot to perform action mention on step 1 then
  • Figure out the port used by your application, you could see it the stack trace in the console window
  • Figure out the process id associated to port by executing netstat -aon command in cmd
  • Kill that process and re-run the application.