Programs & Examples On #Wx.textctrl

wx.textctrl refers to wxTextCtrl, which is a text control in wxWidgets that allows text to be displayed and edited

Working copy XXX locked and cleanup failed in SVN

Today I have experienced above issue saying

svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)

And here is my solution, got working

  1. Closed Xcode IDE, from where I was trying to commit changes.
  2. On Mac --> Go to Terminal --> type below command

svn cleanup <Dir path of my SVN project code>

exmaple:

svn cleanup /Users/Ramdhan/SVN_Repo/ProjectName

  1. Hit enter and wait for cleanup done.
  2. Go To XCode IDE and Clean and Build project
  3. Now I can commit my all changes and take update as well.

Hope this will help.

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

Root certificates issued by CAs are just self-signed certificates (which may in turn be used to issue intermediate CA certificates). They have not much special about them, except that they've managed to be imported by default in many browsers or OS trust anchors.

While browsers and some tools are configured to look for the trusted CA certificates (some of which may be self-signed) in location by default, as far as I'm aware the openssl command isn't.

As such, any server that presents the full chain of certificate, from its end-entity certificate (the server's certificate) to the root CA certificate (possibly with intermediate CA certificates) will have a self-signed certificate in the chain: the root CA.

openssl s_client -connect myweb.com:443 -showcerts doesn't have any particular reason to trust Verisign's root CA certificate, and because it's self-signed you'll get "self signed certificate in certificate chain".

If your system has a location with a bundle of certificates trusted by default (I think /etc/pki/tls/certs on RedHat/Fedora and /etc/ssl/certs on Ubuntu/Debian), you can configure OpenSSL to use them as trust anchors, for example like this:

openssl s_client -connect myweb.com:443 -showcerts -CApath /etc/ssl/certs

getActivity() returns null in Fragment function

Call getActivity() method inside the onActivityCreated()

Finding a branch point with Git?

Not quite a solution to the question but I thought it was worth noting the the approach I use when I have a long-living branch:

At the same time I create the branch, I also create a tag with the same name but with an -init suffix, for example feature-branch and feature-branch-init.

(It is kind of bizarre that this is such a hard question to answer!)

Check if item is in an array / list

Use a lambda function.

Let's say you have an array:

nums = [0,1,5]

Check whether 5 is in nums in Python 3.X:

(len(list(filter (lambda x : x == 5, nums))) > 0)

Check whether 5 is in nums in Python 2.7:

(len(filter (lambda x : x == 5, nums)) > 0)

This solution is more robust. You can now check whether any number satisfying a certain condition is in your array nums.

For example, check whether any number that is greater than or equal to 5 exists in nums:

(len(filter (lambda x : x >= 5, nums)) > 0)

How can I send an inner <div> to the bottom of its parent <div>?

Here is way to avoid absolute divs and tables if you know parent's height:

<div class="parent">
    <div class="child"> <a href="#">Home</a>
    </div>
</div>

CSS:

.parent {
    line-height:80px;
    border: 1px solid black;
}
.child {
    line-height:normal;
    display: inline-block;
    vertical-align:bottom;
    border: 1px solid red;
}

JsFiddle:

Example

jQuery UI dialog positioning

you can use $(this).offset(), position is related to the parent

React.js: Set innerHTML vs dangerouslySetInnerHTML

You can bind to dom directly

<div dangerouslySetInnerHTML={{__html: '<p>First &middot; Second</p>'}}></div>

Remove json element

All the answers are great, and it will do what you ask it too, but I believe the best way to delete this, and the best way for the garbage collector (if you are running node.js) is like this:

var json = { <your_imported_json_here> };
var key = "somekey";
json[key] = null;
delete json[key];

This way the garbage collector for node.js will know that json['somekey'] is no longer required, and will delete it.

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

What can I use for good quality code coverage for C#/.NET?

TestCocoon is also pretty nice. It is in active development and has a user community:

  • Open source (GPL 3)
  • Supports C/C++/C# cross platform (Linux, Windows, and Mac)
  • CoverageScanner - Instrumentation during the Generation
  • CoverageBrowser - View, Analysis and Management of Code Coverage Result

However, TestCocoon is no longer developed and its creators are now producing a commercial software for C/C++.

Change an image with onclick()

How about this? It doesn't require so much coding.

_x000D_
_x000D_
$(".plus").click(function(){
 $(this).toggleClass("minus")  ; 
})
_x000D_
.plus{
    background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_blue.png");
    width:130px;
    height:130px;
    background-repeat:no-repeat;
}

.plus.minus{
    background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_minus.png");
    width:130px;
    height:130px;
    background-repeat:no-repeat;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#"><div class="plus">CHANGE</div></a>
_x000D_
_x000D_
_x000D_

No module named _sqlite3

I had the same problem with Python 3.5 on Ubuntu while using pyenv.

If you're installing the python using pyenv, it's listed as one of the common build problems. To solve it, remove the installed python version, install the requirements (for this particular case libsqlite3-dev), then reinstall the python version.

What is the Oracle equivalent of SQL Server's IsNull() function?

Also use NVL2 as below if you want to return other value from the field_to_check:

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

How to force open links in Chrome not download them?

To make certain file types OPEN on your computer, instead of Chrome Downloading...

You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE.

Now the file type will always OPEN using your default program.

To reset this feature, go to Settings / Advance Settings and under the "Download.." section, there's a button to reset 'all' Auto Downloads

Hope this helps.. :-)

Visual Instructions found here:

http://www.presentermedia.com/blog/2013/10/my-file-automatically-opens-instead-of-saving-with-chrome/

Find records from one table which don't exist in another

SELECT t1.ColumnID,
CASE 
    WHEN NOT EXISTS( SELECT t2.FieldText  
                     FROM Table t2 
                     WHERE t2.ColumnID = t1.ColumnID) 
    THEN t1.FieldText
    ELSE t2.FieldText
END FieldText       
FROM Table1 t1, Table2 t2

How to debug Spring Boot application with Eclipse?

With eclipse or any other IDE, just right click on your main spring boot application and click "debug as java application"

Receiving JSON data back from HTTP request

If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method.

The HttpClient class documentation includes this example:

  HttpClient client = new HttpClient();
  HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
  response.EnsureSuccessStatusCode();
  string responseBody = await response.Content.ReadAsStringAsync();

window.location.href not working

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

Regex any ASCII character

. stands for any char, so you write your regex like this:

xxx.+xxx

Compare two Lists for differences

I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.

If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.

Here is how to do it in Linq:

List<Employee> listA = new List<Employee>();
        List<Employee> listB = new List<Employee>();

        listA.Add(new Employee() { Id = 1, Name = "Bill" });
        listA.Add(new Employee() { Id = 2, Name = "Ted" });

        listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
        listB.Add(new Employee() { Id = 3, Name = "Jim" });

        var identicalQuery = from employeeA in listA
                             join employeeB in listB on employeeA.Id equals employeeB.Id
                             select new { EmployeeA = employeeA, EmployeeB = employeeB };

        foreach (var queryResult in identicalQuery)
        {
            Console.WriteLine(queryResult.EmployeeA.Name);
            Console.WriteLine(queryResult.EmployeeB.Name);
        }

Command to open file with git

A simple solution to the problem is nano index.html and git or any other terminal will open the file right on the terminal, then you edit from there.

You see commands at the bottom of the edit page on how to save.

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

You can use .on() to capture multiple events and then test for touch on the screen, e.g.:

$('#selector')
.on('touchstart mousedown', function(e){
  e.preventDefault();
  var touch = e.touches[0];
  if(touch){
    // Do some stuff
  }
  else {
    // Do some other stuff
  }
});

Getting Hour and Minute in PHP

Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use date_default_timezone_set() then use one of the supported timezones.

Sending simple message body + file attachment using Linux Mailx

On RHEL Linux, I had trouble getting my message in the body of the email instead of as an attachment . Using od -cx, I found that the body of my email contained several /r. I used a perl script to strip the /r, and the message was correctly inserted into the body of the email.

mailx -s "subject text" [email protected] < 'body.txt'

The text file body.txt contained the char \r, so I used perl to strip \r.

cat body.txt | perl success.pl > body2.txt
mailx -s "subject text" [email protected] < 'body2.txt'

This is success.pl

    while (<STDIN>) {
        my $currLine = $_;
        s?\r??g;
        print
    }
;

set gvim font in .vimrc file

I am trying to set this in .vimrc file like below

For GUI specific settings use the .gvimrc instead of .vimrc, which on Windows is either $HOME\_gvimrc or $VIM\_gvimrc.

Check the :help .gvimrc for details. In essence, on start-up VIM reads the .vimrc. After that, if GUI is activated, it also reads the .gvimrc. IOW, all VIM general settings should be kept in .vimrc, all GUI specific things in .gvimrc. (But if you do no use console VIM then you can simply forget about the .vimrc.)

set guifont=Consolas\ 10

The syntax is wrong. After :set guifont=* you can always check the proper syntax for the font using :set guifont?. VIM Windows syntax is :set guifont=Consolas:h10. I do not see precise specification for that, though it is mentioned in the :help win32-faq.

Netbeans - class does not have a main method

It was most likely that you capitalized 'm' in 'main' to 'Main'

This happened to me this instant but I fixed it thanks to the various source code examples given by all those that responded. Thank you.

MySql Inner Join with WHERE clause

You could only write one where clause.

 SELECT table1.f_id  FROM table1
 INNER JOIN table2
 ON table2.f_id = table1.f_id
 where table1.f_com_id = '430' AND      
 table1.f_status = 'Submitted' AND table2.f_type = 'InProcess'

How can a query multiply 2 cell for each row MySQL?

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable

Jackson overcoming underscores in favor of camel-case

Annotating all model classes looks to me as an overkill and Kenny's answer didn't work for me https://stackoverflow.com/a/43271115/4437153. The result of serialization was still camel case.

I realised that there is a problem with my spring configuration, so I had to tackle that problem from another side. Hopefully someone finds it useful, but if I'm doing something against springs' rules then please let me know.

Solution for Spring MVC 5.2.5 and Jackson 2.11.2

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);           

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
    }
}

ORACLE IIF Statement

Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:

DECODE Function:

SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee

CASE Function:

SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee

How do I read the first line of a file using cat?

You don't need cat.

head -1 file

will work fine.

Maven project version inheritance - do I have to specify the parent version?

eFox's answer worked for a single project, but not when I was referencing a module from another one (the pom.xml were still stored in my .m2 with the property instead of the version).

However, it works if you combine it with the flatten-maven-plugin, since it generates the poms with the correct version, not the property.

The only option I changed in the plug-in definition is the outputDirectory, it's empty by default, but I prefer to have it in target, which is set in my .gitignore configuration:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>flatten-maven-plugin</artifactId>
   <version>1.0.1</version>
   <configuration>
      <updatePomFile>true</updatePomFile>
      <outputDirectory>target</outputDirectory>
   </configuration>
   <executions>
      <execution>
         <id>flatten</id>
         <phase>process-resources</phase>
         <goals>
            <goal>flatten</goal>
         </goals>
      </execution>
   </executions>
</plugin>

The plug-in configuration goes in the parent pom.xml

How does one extract each folder name from a path?

I wrote the following method which works for me.

protected bool isDirectoryFound(string path, string pattern)
    {
        bool success = false;

        DirectoryInfo directories = new DirectoryInfo(@path);
        DirectoryInfo[] folderList = directories.GetDirectories();

        Regex rx = new Regex(pattern);

        foreach (DirectoryInfo di in folderList)
        {
            if (rx.IsMatch(di.Name))
            {
                success = true;
                break;
            }
        }

        return success;
    }

The lines most pertinent to your question being:

DirectoryInfo directories = new DirectoryInfo(@path); DirectoryInfo[] folderList = directories.GetDirectories();

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Use .gitattributes instead, with the following setting:

# Ignore all differences in line endings
*        -crlf

.gitattributes would be found in the same directory as your global .gitconfig. If .gitattributes doesn't exist, add it to that directory. After adding/changing .gitattributes you will have to do a hard reset of the repository in order to successfully apply the changes to existing files.

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

Changing default encoding of Python?

First: reload(sys) and setting some random default encoding just regarding the need of an output terminal stream is bad practice. reload often changes things in sys which have been put in place depending on the environment - e.g. sys.stdin/stdout streams, sys.excepthook, etc.

Solving the encode problem on stdout

The best solution I know for solving the encode problem of print'ing unicode strings and beyond-ascii str's (e.g. from literals) on sys.stdout is: to take care of a sys.stdout (file-like object) which is capable and optionally tolerant regarding the needs:

  • When sys.stdout.encoding is None for some reason, or non-existing, or erroneously false or "less" than what the stdout terminal or stream really is capable of, then try to provide a correct .encoding attribute. At last by replacing sys.stdout & sys.stderr by a translating file-like object.

  • When the terminal / stream still cannot encode all occurring unicode chars, and when you don't want to break print's just because of that, you can introduce an encode-with-replace behavior in the translating file-like object.

Here an example:

#!/usr/bin/env python
# encoding: utf-8
import sys

class SmartStdout:
    def __init__(self, encoding=None, org_stdout=None):
        if org_stdout is None:
            org_stdout = getattr(sys.stdout, 'org_stdout', sys.stdout)
        self.org_stdout = org_stdout
        self.encoding = encoding or \
                        getattr(org_stdout, 'encoding', None) or 'utf-8'
    def write(self, s):
        self.org_stdout.write(s.encode(self.encoding, 'backslashreplace'))
    def __getattr__(self, name):
        return getattr(self.org_stdout, name)

if __name__ == '__main__':
    if sys.stdout.isatty():
        sys.stdout = sys.stderr = SmartStdout()

    us = u'aouäöü?zß²'
    print us
    sys.stdout.flush()

Using beyond-ascii plain string literals in Python 2 / 2 + 3 code

The only good reason to change the global default encoding (to UTF-8 only) I think is regarding an application source code decision - and not because of I/O stream encodings issues: For writing beyond-ascii string literals into code without being forced to always use u'string' style unicode escaping. This can be done rather consistently (despite what anonbadger's article says) by taking care of a Python 2 or Python 2 + 3 source code basis which uses ascii or UTF-8 plain string literals consistently - as far as those strings potentially undergo silent unicode conversion and move between modules or potentially go to stdout. For that, prefer "# encoding: utf-8" or ascii (no declaration). Change or drop libraries which still rely in a very dumb way fatally on ascii default encoding errors beyond chr #127 (which is rare today).

And do like this at application start (and/or via sitecustomize.py) in addition to the SmartStdout scheme above - without using reload(sys):

...
def set_defaultencoding_globally(encoding='utf-8'):
    assert sys.getdefaultencoding() in ('ascii', 'mbcs', encoding)
    import imp
    _sys_org = imp.load_dynamic('_sys_org', 'sys')
    _sys_org.setdefaultencoding(encoding)

if __name__ == '__main__':
    sys.stdout = sys.stderr = SmartStdout()
    set_defaultencoding_globally('utf-8') 
    s = 'aouäöü?zß²'
    print s

This way string literals and most operations (except character iteration) work comfortable without thinking about unicode conversion as if there would be Python3 only. File I/O of course always need special care regarding encodings - as it is in Python3.

Note: plains strings then are implicitely converted from utf-8 to unicode in SmartStdout before being converted to the output stream enconding.

How to redirect to action from JavaScript method?

(This is more of a comment but I can't comment because of the low reputation, somebody might find these useful)

If you're in sth.com/product and you want to redirect to sth.com/product/index use

window.location.href = "index";

If you want to redirect to sth.com/home

window.location.href = "/home";

and if you want you want to redirect to sth.com/home/index

window.location.href = "/home/index";

Read all worksheets in an Excel workbook into an R list with data.frames

Since this is the number one hit to the question: Read multi sheet excel to list:

here is the openxlsx solution:

filename <-"myFilePath"

sheets <- openxlsx::getSheetNames(filename)
SheetList <- lapply(sheets,openxlsx::read.xlsx,xlsxFile=filename)
names(SheetList) <- sheets

Python socket receive - incoming packets always have a different size

I know this is old, but I hope this helps someone.

Using regular python sockets I found that you can send and receive information in packets using sendto and recvfrom

# tcp_echo_server.py
import socket

ADDRESS = ''
PORT = 54321

connections = []
host = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host.setblocking(0)
host.bind((ADDRESS, PORT))
host.listen(10)  # 10 is how many clients it accepts

def close_socket(connection):
    try:
        connection.shutdown(socket.SHUT_RDWR)
    except:
        pass
    try:
        connection.close()
    except:
        pass

def read():
    for i in reversed(range(len(connections))):
        try:
            data, sender = connections[i][0].recvfrom(1500)
            return data
        except (BlockingIOError, socket.timeout, OSError):
            pass
        except (ConnectionResetError, ConnectionAbortedError):
            close_socket(connections[i][0])
            connections.pop(i)
    return b''  # return empty if no data found

def write(data):
    for i in reversed(range(len(connections))):
        try:
            connections[i][0].sendto(data, connections[i][1])
        except (BlockingIOError, socket.timeout, OSError):
            pass
        except (ConnectionResetError, ConnectionAbortedError):
            close_socket(connections[i][0])
            connections.pop(i)

# Run the main loop
while True:
    try:
        con, addr = host.accept()
        connections.append((con, addr))
    except BlockingIOError:
        pass

    data = read()
    if data != b'':
        print(data)
        write(b'ECHO: ' + data)
        if data == b"exit":
            break

# Close the sockets
for i in reversed(range(len(connections))):
    close_socket(connections[i][0])
    connections.pop(i)
close_socket(host)

The client is similar

# tcp_client.py
import socket

ADDRESS = "localhost"
PORT = 54321

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDRESS, PORT))
s.setblocking(0)

def close_socket(connection):
    try:
        connection.shutdown(socket.SHUT_RDWR)
    except:
        pass
    try:
        connection.close()
    except:
        pass

def read():
    """Read data and return the read bytes."""
    try:
        data, sender = s.recvfrom(1500)
        return data
    except (BlockingIOError, socket.timeout, AttributeError, OSError):
        return b''
    except (ConnectionResetError, ConnectionAbortedError, AttributeError):
        close_socket(s)
        return b''

def write(data):
    try:
        s.sendto(data, (ADDRESS, PORT))
    except (ConnectionResetError, ConnectionAbortedError):
        close_socket(s)

while True:
    msg = input("Enter a message: ")
    write(msg.encode('utf-8'))

    data = read()
    if data != b"":
        print("Message Received:", data)

    if msg == "exit":
        break

close_socket(s)

How to retrieve a user environment variable in CMake (Windows)

Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.

If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.

You need to open a new command line prompt after you change the user settings.

The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.

Flask ImportError: No Module Named Flask

Another thing - if you're using python3, make sure you are starting your server with python3 server.py, not python server.py

shell script. how to extract string using regular expressions

Using bash regular expressions:

re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi

Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.

re="http://([^/]+)/"

This is the regular expression stored in a bash variable, re - i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:

  • http:// is just a string - the input string must contain this substring for the regular expression to match
  • [] Normally square brackets are used say "match any character within the brackets". So c[ao]t would match both "cat" and "cot". The ^ character within the [] modifies this to say "match any character except those within the square brackets. So in this case [^/] will match any character apart from "/".
  • The square bracket expression will only match one character. Adding a + to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+ matches 1 or more of the set of all characters, excluding "/".
  • Putting () parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.
  • Finally we do an exact match on "/" to make sure we match all the way to end of the fully qualified domain name and the following "/"

Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:

if [[ $name =~ $re ]]; then
    echo ${BASH_REMATCH[1]}
fi

In bash, the [[ ]] specify an extended conditional test, and may contain the =~ bash regular expression operator. In this case we test whether the input string $name matches the regular expression $re. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()), and we can access it using the BASH_REMATCH array:

  • Element 0 of this array ${BASH_REMATCH[0]} will be the entire string matched by the regular expression, i.e. "http://www.google.com/".
  • Subsequent elements of this array will be subsequent results of submatches. Note you can have multiple submatch () within a regular expression - The BASH_REMATCH elements will correspond to these in order. So in this case ${BASH_REMATCH[1]} will contain "www.google.com", which I think is the string you want.

Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~ operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.

This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.


Note that instead of setting the $re variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~ match operator.

How to read/write a boolean when implementing the Parcelable interface?

Here's how I'd do it...

writeToParcel:

dest.writeByte((byte) (myBoolean ? 1 : 0));     //if myBoolean == true, byte == 1

readFromParcel:

myBoolean = in.readByte() != 0;     //myBoolean == true if byte != 0

What port is a given program using?

most decent firewall programs should allow you to access this information. I know that Agnitum OutpostPro Firewall does.

Order columns through Bootstrap4

I'm using Bootstrap 3, so i don't know if there is an easier way to do it Bootstrap 4 but this css should work for you:

.pull-right-xs {
    float: right;
}

@media (min-width: 768px) {
   .pull-right-xs {
      float: left;
   }
}

...and add class to second column:

<div class="row">
    <div class="col-xs-3 col-md-6">
        1
    </div>
    <div class="col-xs-3 col-md-6 pull-right-xs">
        2
    </div>
    <div class="col-xs-6 col-md-12">
        3
    </div>
</div>

EDIT:

Ohh... it looks like what i was writen above is exacly a .pull-xs-right class in Bootstrap 4 :X Just add it to second column and it should work perfectly.

System.Timers.Timer vs System.Threading.Timer

One important difference not mentioned above which might catch you out is that System.Timers.Timer silently swallows exceptions, whereas System.Threading.Timer doesn't.

For example:

var timer = new System.Timers.Timer { AutoReset = false };
timer.Elapsed += (sender, args) =>
{
    var z = 0;
    var i = 1 / z;
};
timer.Start();

vs

var timer = new System.Threading.Timer(x =>
{
    var z = 0;
    var i = 1 / z;
}, null, 0, Timeout.Infinite);

MySQL - UPDATE query based on SELECT Query

UPDATE
    `table1` AS `dest`,
    (
        SELECT
            *
        FROM
            `table2`
        WHERE
            `id` = x
    ) AS `src`
SET
    `dest`.`col1` = `src`.`col1`
WHERE
    `dest`.`id` = x
;

Hope this works for you.

Why use pointers?

One use of pointers (I won't mention things already covered in other people's posts) is to access memory that you haven't allocated. This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices.

Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:

unsigned char *pVideoMemory = (unsigned char *)0xA0000000;

Many embedded devices still use this technique.

Android Studio update -Error:Could not run build action using Gradle distribution

I have run into a similar problem on Mac.

Looking at the log under Help -> Show logs in Finder I found the following entry.

You have JVM property "https.proxyHost" set to "127.0.0.1".
This may lead to incorrect behaviour. Proxy should be set in Settings | HTTP Proxy
This JVM property is old and its usage is not recommended by Oracle.
(Note: It could have been assigned by some code dynamically.)

and it turned out I had Charles as a network proxy running. Shutting down Charles solved the problem.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to create separate AngularJS controller files?

For brevity, here's an ES2015 sample that doesn't rely on global variables

// controllers/example-controller.js

export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
  // something... 
}

// controllers/another-controller.js

export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
  // functionality... 
}

// app.js

import angular from "angular";

import {
  ExampleControllerName,
  ExampleController
} = "./controllers/example-controller";

import {
  AnotherControllerName,
  AnotherController
} = "./controllers/another-controller";

angular.module("myApp", [/* deps */])
  .controller(ExampleControllerName, ExampleController)
  .controller(AnotherControllerName, AnotherController)

How to return a PNG image from Jersey REST service method to the browser

If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:

@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage>  {
  @Override
  public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return type == BufferedImage.class;
  }

  @Override
  public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return -1; // not used in JAX-RS 2
  }

  @Override
  public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
    ImageIO.write(image, mt.getSubtype(), out);
  } 
}

This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.

Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:

@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
  BufferedImage image = ...;
  return Response.ok(image).build();
}

A couple of advantages to this approach:

  • It writes to the response OutputSteam rather than an intermediary BufferedOutputStream
  • It supports both png and jpg output (depending on the media types allowed by the resource method)

Plotting categorical data with pandas and matplotlib

You might find useful mosaic plot from statsmodels. Which can also give statistical highlighting for the variances.

from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);

enter image description here

But beware of the 0 sized cell - they will cause problems with labels.

See this answer for details

How to test web service using command line curl

From the documentation on http://curl.haxx.se/docs/httpscripting.html :

HTTP Authentication

curl --user name:password http://www.example.com 

Put a file to a HTTP server with curl:

curl --upload-file uploadfile http://www.example.com/receive.cgi

Send post data with curl:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi

Add CSS class to a div in code behind

To ADD classes to html elements see how to add css class to html generic control div?. There are answers similar to those given here but showing how to add classes to html elements.

Python - Check If Word Is In A String

As you are asking for a word and not for a string, I would like to present a solution which is not sensitive to prefixes / suffixes and ignores case:

#!/usr/bin/env python

import re


def is_word_in_text(word, text):
    """
    Check if a word is in a text.

    Parameters
    ----------
    word : str
    text : str

    Returns
    -------
    bool : True if word is in text, otherwise False.

    Examples
    --------
    >>> is_word_in_text("Python", "python is awesome.")
    True

    >>> is_word_in_text("Python", "camelCase is pythonic.")
    False

    >>> is_word_in_text("Python", "At the end is Python")
    True
    """
    pattern = r'(^|[^\w]){}([^\w]|$)'.format(word)
    pattern = re.compile(pattern, re.IGNORECASE)
    matches = re.search(pattern, text)
    return bool(matches)


if __name__ == '__main__':
    import doctest
    doctest.testmod()

If your words might contain regex special chars (such as +), then you need re.escape(word)

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Just for others reference, I seemed to have this issue too if I tried to load a URL that had whitespace at the end (was being pulled from user input).

mysql query order by multiple items

Sort by picture and then by activity:

SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;

Making a Bootstrap table column fit to content

Make a class that will fit table cell width to content

.table td.fit, 
.table th.fit {
    white-space: nowrap;
    width: 1%;
}

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Well if you know the order of your words.. you can use:

SELECT `name` FROM `table` WHERE `name` REGEXP 'Stylus.+2100'

Also you can use:

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%' AND `name` LIKE '%2100%'

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

How to run server written in js with Node.js

Just go on that directory of your JS file from cmd and write node jsFile.js or even node jsFile; both will work fine.

Setting timezone in Python

>>> import os, time
>>> time.strftime('%X %x %Z')
'12:45:20 08/19/09 CDT'
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'18:45:39 08/19/09 BST'

To get the specific values you've listed:

>>> year = time.strftime('%Y')
>>> month = time.strftime('%m')
>>> day = time.strftime('%d')
>>> hour = time.strftime('%H')
>>> minute = time.strftime('%M')

See here for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.

How to select records from last 24 hours using SQL?

MySQL :

SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(NOW(), INTERVAL 24 HOUR)

The INTERVAL can be in YEAR, MONTH, DAY, HOUR, MINUTE, SECOND

For example, In the last 10 minutes

SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(NOW(), INTERVAL 10 MINUTE)

file_get_contents() how to fix error "Failed to open stream", "No such file"

You may try using this

<?php
$json = json_decode(file_get_contents('./prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=*key*'));
print_r($json);
?>

The "./" allows to search url from current directory. You may use

chdir($_SERVER["DOCUMENT_ROOT"]);

to change current working directory to root of your website if path is relative from root directory.

How to generate a simple popup using jQuery

First the CSS - tweak this however you like:

a.selected {
  background-color:#1F75CC;
  color:white;
  z-index:100;
}

.messagepop {
  background-color:#FFFFFF;
  border:1px solid #999999;
  cursor:default;
  display:none;
  margin-top: 15px;
  position:absolute;
  text-align:left;
  width:394px;
  z-index:50;
  padding: 25px 25px 20px;
}

label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  text-indent: -15px;
}

.messagepop p, .messagepop.div {
  border-bottom: 1px solid #EFEFEF;
  margin: 8px 0;
  padding-bottom: 8px;
}

And the JavaScript:

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });    
}

$(function() {
  $('#contact').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect($(this));               
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('#contact'));
    return false;
  });
});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

And finally the html:

<div class="messagepop pop">
  <form method="post" id="new_message" action="/messages">
    <p><label for="email">Your email or name</label><input type="text" size="30" name="email" id="email" /></p>
    <p><label for="body">Message</label><textarea rows="6" name="body" id="body" cols="35"></textarea></p>
    <p><input type="submit" value="Send Message" name="commit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
  </form>
</div>

<a href="/contact" id="contact">Contact Us</a>

Here is a jsfiddle demo and implementation.

Depending on the situation you may want to load the popup content via an ajax call. It's best to avoid this if possible as it may give the user a more significant delay before seeing the content. Here couple changes that you'll want to make if you take this approach.

HTML becomes:

<div>
    <div class="messagepop pop"></div> 
    <a href="/contact" id="contact">Contact Us</a>
</div>

And the general idea of the JavaScript becomes:

$("#contact").on('click', function() {
    if($(this).hasClass("selected")) {
        deselect();               
    } else {
        $(this).addClass("selected");
        $.get(this.href, function(data) {
            $(".pop").html(data).slideFadeToggle(function() { 
                $("input[type=text]:first").focus();
            });
        }
    }
    return false;
});

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

Where can I find Android source code online?

I stumbled across Android XRef the other day and found it useful, especially since it is backed by OpenGrok which offers insanely awesome and blindingly fast search.

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

Error: Cannot invoke an expression whose type lacks a call signature

This error can be caused when you are requesting a value from something and you put parenthesis at the end, as if it is a function call, yet the value is correctly retrieved without ending parenthesis. For example, if what you are accessing is a Property 'get' in Typescript.

private IMadeAMistakeHere(): void {
    let mynumber = this.SuperCoolNumber();
}

private IDidItCorrectly(): void {
    let mynumber = this.SuperCoolNumber;
}

private get SuperCoolNumber(): number {
    let response = 42;
    return response;
};

How to Ping External IP from Java Android

Use this Code: this method works on 4.3+ and also for below versions too.

   try {

         Process process = null;

        if(Build.VERSION.SDK_INT <= 16) {
            // shiny APIS 
               process = Runtime.getRuntime().exec(
                    "/system/bin/ping -w 1 -c 1 " + url);


        } 
        else 
        {

                   process = new ProcessBuilder()
                 .command("/system/bin/ping", url)
                 .redirectErrorStream(true)
                 .start();

            }



        BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));

        StringBuffer output = new StringBuffer();
        String temp;

        while ( (temp = reader.readLine()) != null)//.read(buffer)) > 0)
        {
            output.append(temp);
            count++;
        }

        reader.close();


        if(count > 0)
            str = output.toString();

        process.destroy();
     } catch (IOException e) {
         e.printStackTrace();
    }

    Log.i("PING Count", ""+count);
    Log.i("PING String", str);

How to get the Google Map based on Latitude on Longitude?

this is the javascript to display google map by passing your longitude and latitude.

<script>
    function initialize() {
      var myLatlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }

    function loadScript() {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
      document.body.appendChild(script);
    }

    window.onload = loadScript;


</script>

When should I use git pull --rebase?

I would like to provide a different perspective on what "git pull --rebase" actually means, because it seems to get lost sometimes.

If you've ever used Subversion (or CVS), you may be used to the behavior of "svn update". If you have changes to commit and the commit fails because changes have been made upstream, you "svn update". Subversion proceeds by merging upstream changes with yours, potentially resulting in conflicts.

What Subversion just did, was essentially "pull --rebase". The act of re-formulating your local changes to be relative to the newer version is the "rebasing" part of it. If you had done "svn diff" prior to the failed commit attempt, and compare the resulting diff with the output of "svn diff" afterwards, the difference between the two diffs is what the rebasing operation did.

The major difference between Git and Subversion in this case is that in Subversion, "your" changes only exist as non-committed changes in your working copy, while in Git you have actual commits locally. In other words, in Git you have forked the history; your history and the upstream history has diverged, but you have a common ancestor.

In my opinion, in the normal case of having your local branch simply reflecting the upstream branch and doing continuous development on it, the right thing to do is always "--rebase", because that is what you are semantically actually doing. You and others are hacking away at the intended linear history of a branch. The fact that someone else happened to push slightly prior to your attempted push is irrelevant, and it seems counter-productive for each such accident of timing to result in merges in the history.

If you actually feel the need for something to be a branch for whatever reason, that is a different concern in my opinion. But unless you have a specific and active desire to represent your changes in the form of a merge, the default behavior should, in my opinion, be "git pull --rebase".

Please consider other people that need to observe and understand the history of your project. Do you want the history littered with hundreds of merges all over the place, or do you want only the select few merges that represent real merges of intentional divergent development efforts?

Set the table column width constant regardless of the amount of text in its cells?

I found KAsun's answer works better using vw instead of px like so:

<td><div style="width: 10vw" >...............</div></td>

This was the only styling I needed to adjust the column width

Create a folder if it doesn't already exist

You can try also:

$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

What is the javascript filename naming convention?

I generally prefer hyphens with lower case, but one thing not yet mentioned is that sometimes it's nice to have the file name exactly match the name of a single module or instantiable function contained within.

For example, I have a revealing module declared with var knockoutUtilityModule = function() {...} within its own file named knockoutUtilityModule.js, although objectively I prefer knockout-utility-module.js.

Similarly, since I'm using a bundling mechanism to combine scripts, I've taken to defining instantiable functions (templated view models etc) each in their own file, C# style, for maintainability. For example, ProductDescriptorViewModel lives on its own inside ProductDescriptorViewModel.js (I use upper case for instantiable functions).

How to serialize object to CSV file?

Worth mentioning that the handlebar library https://github.com/jknack/handlebars.java can trivialize many transformation tasks include toCSV.

Javascript dynamic array of strings

var junk=new Array();
junk.push('This is a string.');

Et cetera.

Creating a very simple linked list

A linked list is a node-based data structure. Each node designed with two portions (Data & Node Reference).Actually, data is always stored in Data portion (Maybe primitive data types eg Int, Float .etc or we can store user-defined data type also eg. Object reference) and similarly Node Reference should also contain the reference to next node, if there is no next node then the chain will end.

This chain will continue up to any node doesn't have a reference point to the next node.

Please find the source code from my tech blog - http://www.algonuts.info/linked-list-program-in-java.html

package info.algonuts;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

class LLNode {
    int nodeValue;
    LLNode childNode;

    public LLNode(int nodeValue) {
        this.nodeValue = nodeValue;
        this.childNode = null;
    }
}

class LLCompute {
    private static LLNode temp;
    private static LLNode previousNode;
    private static LLNode newNode;
    private static LLNode headNode;

    public static void add(int nodeValue) {
        newNode = new LLNode(nodeValue);
        temp = headNode;
        previousNode = temp;
        if(temp != null)
        {   compute();  }
        else
        {   headNode = newNode; }   //Set headNode
    }

    private static void compute() {
        if(newNode.nodeValue < temp.nodeValue) {    //Sorting - Ascending Order
            newNode.childNode = temp;
            if(temp == headNode) 
            {   headNode = newNode; }
            else if(previousNode != null) 
            {   previousNode.childNode = newNode;   }
        }
        else
        {
            if(temp.childNode == null)
            {   temp.childNode = newNode;   }
            else
            {
                previousNode = temp;
                temp = temp.childNode;
                compute();
            }
        }
    }

    public static void display() {
        temp = headNode;
        while(temp != null) {
            System.out.print(temp.nodeValue+" ");
            temp = temp.childNode;
        }
    }
}

public class LinkedList {
    //Entry Point
    public static void main(String[] args) {
        //First Set Input Values
        List <Integer> firstIntList = new ArrayList <Integer>(Arrays.asList(50,20,59,78,90,3,20,40,98));   
        Iterator<Integer> ptr  = firstIntList.iterator();
        while(ptr.hasNext()) 
        {   LLCompute.add(ptr.next());  }
        System.out.println("Sort with first Set Values");
        LLCompute.display();
        System.out.println("\n");

        //Second Set Input Values
        List <Integer> secondIntList = new ArrayList <Integer>(Arrays.asList(1,5,8,100,91));   
        ptr  = secondIntList.iterator();
        while(ptr.hasNext()) 
        {   LLCompute.add(ptr.next());  }
        System.out.println("Sort with first & Second Set Values");
        LLCompute.display();
        System.out.println();
    }
}

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

How to kill MySQL connections

No, there is no built-in MySQL command for that. There are various tools and scripts that support it, you can kill some connections manually or restart the server (but that will be slower).

Use SHOW PROCESSLIST to view all connections, and KILL the process ID's you want to kill.

You could edit the timeout setting to have the MySQL daemon kill the inactive processes itself, or raise the connection count. You can even limit the amount of connections per username, so that if the process keeps misbehaving, the only affected process is the process itself and no other clients on your database get locked out.

If you can't connect yourself anymore to the server, you should know that MySQL always reserves 1 extra connection for a user with the SUPER privilege. Unless your offending process is for some reason using a username with that privilege...

Then after you can access your database again, you should fix the process (website) that's spawning that many connections.

Populating spinner directly in the layout xml

Define this in your String.xml file and name the array what you want, such as "Weight"

<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>

and this code in your layout.xml

<Spinner 
        android:id="@+id/fromspin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:entries="@array/Weight"
 />

In your java file, getActivity is used in fragment; if you write that code in activity, then remove getActivity.

a = (Spinner) findViewById(R.id.fromspin);

 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
                R.array.weight, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        a.setAdapter(adapter);
        a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
                    if (!b.getText().toString().isEmpty()) {
                        float value1 = Float.parseFloat(b.getText().toString());
                        float kg = value1;
                        c.setText(Float.toString(kg));
                        float gram = value1 * 1000;
                        d.setText(Float.toString(gram));
                        float carat = value1 * 5000;
                        e.setText(Float.toString(carat));
                        float ton = value1 / 908;
                        f.setText(Float.toString(ton));
                    }

                }



            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
        // Inflate the layout for this fragment
        return v;
    }

Responding with a JSON object in Node.js (converting object/array to JSON string)

Per JamieL's answer to another post:

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.

Example:

res.json({"foo": "bar"});

Filter dict to contain only certain keys?

Code 1:

dict = { key: key * 10 for key in range(0, 100) }
d1 = {}
for key, value in dict.items():
    if key % 2 == 0:
        d1[key] = value

Code 2:

dict = { key: key * 10 for key in range(0, 100) }
d2 = {key: value for key, value in dict.items() if key % 2 == 0}

Code 3:

dict = { key: key * 10 for key in range(0, 100) }
d3 = { key: dict[key] for key in dict.keys() if key % 2 == 0}

All pieced of code performance are measured with timeit using number=1000, and collected 1000 times for each piece of code.

enter image description here

For python 3.6 the performance of three ways of filter dict keys almost the same. For python 2.7 code 3 is slightly faster.

Bootstrap carousel multiple frames at once

I had the same problem and the solutions described here worked well. But I wanted to support window size (and layout) changes. The result is a small library that solves all the calculation. Check it out here: https://github.com/SocialbitGmbH/BootstrapCarouselPageMerger

To make the script work, you have to add a new <div> wrapper with the class .item-content directly into your .item <div>. Example:

<div class="carousel slide multiple" id="very-cool-carousel" data-ride="carousel">
    <div class="carousel-inner" role="listbox">
        <div class="item active">
            <div class="item-content">
                First page
            </div>
        </div>
        <div class="item active">
            <div class="item-content">
                Second page
            </div>
        </div>
    </div>
</div>

Usage of this library:

socialbitBootstrapCarouselPageMerger.run('div.carousel');

To change the settings:

socialbitBootstrapCarouselPageMerger.settings.spaceCalculationFactor = 0.82;

Example:

As you can see, the carousel gets updated to show more controls when you resize the window. Check out the watchWindowSizeTimeout setting to control the timeout for reacting to window size changes.

how to add super privileges to mysql database?

In Sequel Pro, access the User Accounts window. Note that any MySQL administration program could be substituted in place of Sequel Pro.

Add the following accounts and privileges:

GRANT SUPER ON *.* TO 'user'@'%' IDENTIFIED BY PASSWORD

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

Python convert set to string and vice versa

Use repr and eval:

>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])

Note that eval is not safe if the source of string is unknown, prefer ast.literal_eval for safer conversion:

>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])

help on repr:

repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.

Copy every nth line from one sheet to another

Add new column and fill it with ascending numbers. Then filter by ([column] mod 7 = 0) or something like that (don't have Excel in front of me to actually try this);

If you can't filter by formula, add one more column and use the formula =MOD([column; 7]) in it then filter zeros and you'll get all seventh rows.

Effect of NOLOCK hint in SELECT statements

In addition to what is said above, you should be very aware that nolock actually imposes the risk of you not getting rows that has been committed before your select.

See http://blogs.msdn.com/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

You need to load the helper before loading the view somewhere in your controller.

But I think here you want to use the function site_url()

Before you load your view, basically anywhere inside the method in your controller, add this to your code :

$this->load->helper('url');

Then use the function site_url().

JavaFX "Location is required." even though it is in the same package

In my case all of the above were not the problem at all.

My problem was solved when I replaced :

getClass().getResource("ui_layout.fxml")

with :

getClass().getClassLoader().getResource("ui_layout.fxml")

Using Java with Microsoft Visual Studio 2012

Using Visual Studio IDE for porting Java to C#:

Currently I am using Visual Studio IDE environment for porting codes from Java to C#. Why? Java has a huge libraries and C# enables the access to the UWP ecosystem.

For supporting editing and debugging as well as examining Java Bytecode (disassembly), you could try:

For supporting Android (Java/C++) development, you could try:

The process cannot access the file because it is being used by another process (File is created but contains nothing)

You are writing to the file prior to closing your filestream:

using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
   str.BaseStream.Seek(0,SeekOrigin.End); 
   str.Write("mytext.txt.........................");
   str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
   string addtext="this line is added"+Environment.NewLine;

   str.Flush();

}

File.AppendAllText(path,addtext);  //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);

The above code should work, using the methods you are currently using. You should also look into the using statement and wrap your streams in a using block.

Call JavaScript function from C#

You can call javascript functions from c# using Jering.Javascript.NodeJS, an open-source library by my organization:

string javascriptModule = @"
module.exports = (callback, x, y) => {  // Module must export a function that takes a callback as its first parameter
    var result = x + y; // Your javascript logic
    callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";

// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });

// result == 8
Assert.Equal(8, result);

The library supports invoking directly from .js files as well. Say you have file C:/My/Directory/exampleModule.js containing:

module.exports = (callback, message) => callback(null, message);

You can invoke the exported function:

string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });

// result == "test"
Assert.Equal("test", result);

What happens to a declared, uninitialized variable in C? Does it have a value?

The basic answer is, yes it is undefined.

If you are seeing odd behavior because of this, it may depended on where it is declared. If within a function on the stack then the contents will more than likely be different every time the function gets called. If it is a static or module scope it is undefined but will not change.

Angular bootstrap datepicker date format does not format ng-model value

The format specified through datepicker-popup is just the format for the displayed date. The underlying ngModel is a Date object. Trying to display it will show it as it's default, standard-compliant rapresentation.

You can show it as you want by using the date filter in the view, or, if you need it to be parsed in the controller, you can inject $filter in your controller and call it as $filter('date')(date, format). See also the date filter docs.

Javascript - Open a given URL in a new tab by clicking a button

You can forget about using JavaScript because the browser controls whether or not it opens in a new tab. Your best option is to do something like the following instead:

<form action="http://www.yoursite.com/dosomething" method="get" target="_blank">
    <input name="dynamicParam1" type="text"/>
    <input name="dynamicParam2" type="text" />
    <input type="submit" value="submit" />
</form>

This will always open in a new tab regardless of which browser a client uses due to the target="_blank" attribute.

If all you need is to redirect with no dynamic parameters you can use a link with the target="_blank" attribute as Tim Büthe suggests.

Dynamically adding properties to an ExpandoObject

Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given object.


    public static class dynamicHelper
        {
            public static ExpandoObject convertToExpando(object obj)
            {
                //Get Properties Using Reflections
                BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
                PropertyInfo[] properties = obj.GetType().GetProperties(flags);

                //Add Them to a new Expando
                ExpandoObject expando = new ExpandoObject();
                foreach (PropertyInfo property in properties)
                {
                    AddProperty(expando, property.Name, property.GetValue(obj));
                }

                return expando;
            }

            public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
            {
                //Take use of the IDictionary implementation
                var expandoDict = expando as IDictionary;
                if (expandoDict.ContainsKey(propertyName))
                    expandoDict[propertyName] = propertyValue;
                else
                    expandoDict.Add(propertyName, propertyValue);
            }
        }

Usage:

//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);

//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");

Get the latest record from mongodb collection

I need a query with constant time response

By default, the indexes in MongoDB are B-Trees. Searching a B-Tree is a O(logN) operation, so even find({_id:...}) will not provide constant time, O(1) responses.

That stated, you can also sort by the _id if you are using ObjectId for you IDs. See here for details. Of course, even that is only good to the last second.

You may to resort to "writing twice". Write once to the main collection and write again to a "last updated" collection. Without transactions this will not be perfect, but with only one item in the "last updated" collection it will always be fast.

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

I have faced this type of error. to call a function from the razor.

public ActionResult EditorAjax(int id, int? jobId, string type = ""){}

solved that by changing the line

from

<a href="/ScreeningQuestion/EditorAjax/5&jobId=2&type=additional" /> 

to

<a href="/ScreeningQuestion/EditorAjax/?id=5&jobId=2&type=additional" />

where my route.config is

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "RPMS.Controllers" } // Parameter defaults
        );

Linux/Unix command to determine if process is running?

None of the answers worked for me, so heres mine:

process="$(pidof YOURPROCESSHERE|tr -d '\n')"
if [[ -z "${process// }" ]]; then
  echo "Process is not running."
else
  echo "Process is running."
fi

Explanation:

|tr -d '\n'

This removes the carriage return created by the terminal. The rest can be explained by this post.

align textbox and text/labels in html?

I have found better option,

<style type="text/css">
    .form {
        margin: 0 auto;
        width: 210px;
    }
    .form label{
        display: inline-block;
        text-align: right;
        float: left;
    }
    .form input{
        display: inline-block;
        text-align: left;
        float: right;
    }
</style>

Demo here: https://jsfiddle.net/durtpwvx/

Get Android shared preferences value in activity/normal class

I tried this code, to retrieve shared preferences from an activity, and could not get it to work:

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.getAll();
    Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
    Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());

Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.

getPreferenceManager().setSharedPreferencesName("defaultPreferences");

After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.

Delete specific line number(s) from a text file using sed?

$ cat foo
1
2
3
4
5
$ sed -e '2d;4d' foo
1
3
5
$ 

Is it safe to delete the "InetPub" folder?

Don't delete the folder or you will create a registry problem. However, if you do not want to use IIS, search the web for turning it off. You might want to check out "www.blackviper.com" because he lists all Operating System "services" (Not "Computer Services" - both are in Administrator Tools) with extra information for what you can and cannot disable to change to manual. If I recall correctly, he had some IIS info and how to turn it off.

How can I auto hide alert box after it showing it?

tldr; jsFiddle Demo

This functionality is not possible with an alert. However, you could use a div

function tempAlert(msg,duration)
{
 var el = document.createElement("div");
 el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
 el.innerHTML = msg;
 setTimeout(function(){
  el.parentNode.removeChild(el);
 },duration);
 document.body.appendChild(el);
}

Use this like this:

tempAlert("close",5000);

Where should I put the log4j.properties file?

As already stated, log4j.properties should be in a directory included in the classpath, I want to add that in a mavenized project a good place can be src/main/resources/log4j.properties

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

  1. Go to Sql Server Management Studio >
  2. Object Explorer >
  3. Databases >
  4. Choose and expand your Database.
  5. Under your database right click on "Database Diagrams" and select "New Database Diagram".
  6. It will a open a new window. Choose tables to include in ER-Diagram (to select multiple tables press "ctrl" or "shift" button and select tables).
  7. Click add.
  8. Wait for it to complete. Done!

You can save generated diagram for future use.

screenshot

How do I use IValidatableObject?

Just to add a couple of points:

Because the Validate() method signature returns IEnumerable<>, that yield return can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.Enable)
    {
        // ...
        if (this.Prop1 > this.Prop2)
        {
            yield return new ValidationResult("Prop1 must be larger than Prop2");
        }

Also, if you are using MVC ModelState, you can convert the validation result failures to ModelState entries as follows (this might be useful if you are doing the validation in a custom model binder):

var resultsGroupedByMembers = validationResults
    .SelectMany(vr => vr.MemberNames
                        .Select(mn => new { MemberName = mn ?? "", 
                                            Error = vr.ErrorMessage }))
    .GroupBy(x => x.MemberName);

foreach (var member in resultsGroupedByMembers)
{
    ModelState.AddModelError(
        member.Key,
        string.Join(". ", member.Select(m => m.Error)));
}

Shell script current directory?

To print the current working Directory i.e. pwd just type command like:

echo "the PWD is : ${pwd}"

<ng-container> vs <template>

Edit : Now it is documented

<ng-container> to the rescue

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

(...)

The <ng-container> is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:

  if (someCondition) {
      statement1; 
      statement2;
      statement3;
     }

Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The <ng-container> satisfies a similar need in Angular templates.

Original answer:

According to this pull request :

<ng-container> is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.

<ng-container> is rendered as an HTML comment.

so this angular template :

<div>
    <ng-container>foo</ng-container>
<div>

will produce this kind of output :

<div>
    <!--template bindings={}-->foo
<div>

So ng-container is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.

<div>
    <ng-container *ngIf="true">
        <h2>Title</h2>
        <div>Content</div>
    </ng-container>
</div>

will then produce :

<div>
    <h2>Title</h2>
    <div>Content</div>
</div>

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

how to show only even or odd rows in sql server 2008?

Here’s a simple and straightforward answer to your question, (I think). I am using the TSQL2012 sample database and I am returning only even or odd rows based on “employeeID” in the “HR.Employees” table.

USE TSQL2012;
GO

Return only Even numbers of the employeeID:

SELECT *
FROM HR.Employees
WHERE (empid % 2) = 0;
GO

Return only Odd numbers of the employeeID:

SELECT *
FROM HR.Employees
WHERE (empid % 2) = 1;
GO

Hopefully, that’s the answer you were looking for.

How do I convert a calendar week into a date in Excel?

For ISO week numbers you can use this formula to get the Monday

=DATE(A2,1,-2)-WEEKDAY(DATE(A2,1,3))+B2*7

assuming year in A2 and week number in B2

it's the same as my answer here https://stackoverflow.com/a/10855872/1124287

Iteration ng-repeat only X times in AngularJs

Answer given by @mpm is not working it gives the error

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}

To avoid this along with

ng-repeat="t in getTimes(4)"

use

track by $index

like this

<div ng-repeat="t in getTimes(4) track by $index">TEXT</div>

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

The complexity of software application is not measured and is not written in big-O notation. It is only useful to measure algorithm complexity and to compare algorithms in the same domain. Most likely, when we say O(n), we mean that it's "O(n) comparisons" or "O(n) arithmetic operations". That means, you can't compare any pair of algorithms or applications.

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

yield from basically chains iterators in a efficient way:

# chain from itertools:
def chain(*iters):
    for it in iters:
        for item in it:
            yield item

# with the new keyword
def chain(*iters):
    for it in iters:
        yield from it

As you can see it removes one pure Python loop. That's pretty much all it does, but chaining iterators is a pretty common pattern in Python.

Threads are basically a feature that allow you to jump out of functions at completely random points and jump back into the state of another function. The thread supervisor does this very often, so the program appears to run all these functions at the same time. The problem is that the points are random, so you need to use locking to prevent the supervisor from stopping the function at a problematic point.

Generators are pretty similar to threads in this sense: They allow you to specify specific points (whenever they yield) where you can jump in and out. When used this way, generators are called coroutines.

Read this excellent tutorials about coroutines in Python for more details

How to print the current Stack Trace in .NET without any exception?

An alternative to System.Diagnostics.StackTrace is to use System.Environment.StackTrace which returns a string-representation of the stacktrace.

Another useful option is to use the $CALLER and $CALLSTACK debugging variables in Visual Studio since this can be enabled run-time without rebuilding the application.

Read and write a text file in typescript

First you will need to install node definitions for Typescript. You can find the definitions file here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

Once you've got file, just add the reference to your .ts file like this:

/// <reference path="path/to/node.d.ts" />

Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

/// <reference path="path/to/node.d.ts" />

class MyClass {

    // Here we import the File System module of node
    private fs = require('fs');

    constructor() { }

    createFile() {

        this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
            if (err) {
                return console.error(err);
            }
            console.log("File created!");
        });
    }

    showFile() {

        this.fs.readFile('file.txt', function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Asynchronous read: " + data.toString());
        });
    }
}

// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();

Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

> node myClass.js

ExecutorService that interrupts tasks after a timeout

What about this alternative idea :

  • two have two executors :
    • one for :
      • submitting the task, without caring about the timeout of the task
      • adding the Future resulted and the time when it should end to an internal structure
    • one for executing an internal job which is checking the internal structure if some tasks are timeout and if they have to be cancelled.

Small sample is here :

public class AlternativeExecutorService 
{

private final CopyOnWriteArrayList<ListenableFutureTask> futureQueue       = new CopyOnWriteArrayList();
private final ScheduledThreadPoolExecutor                scheduledExecutor = new ScheduledThreadPoolExecutor(1); // used for internal cleaning job
private final ListeningExecutorService                   threadExecutor    = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5)); // used for
private ScheduledFuture scheduledFuture;
private static final long INTERNAL_JOB_CLEANUP_FREQUENCY = 1000L;

public AlternativeExecutorService()
{
    scheduledFuture = scheduledExecutor.scheduleAtFixedRate(new TimeoutManagerJob(), 0, INTERNAL_JOB_CLEANUP_FREQUENCY, TimeUnit.MILLISECONDS);
}

public void pushTask(OwnTask task)
{
    ListenableFuture<Void> future = threadExecutor.submit(task);  // -> create your Callable
    futureQueue.add(new ListenableFutureTask(future, task, getCurrentMillisecondsTime())); // -> store the time when the task should end
}

public void shutdownInternalScheduledExecutor()
{
    scheduledFuture.cancel(true);
    scheduledExecutor.shutdownNow();
}

long getCurrentMillisecondsTime()
{
    return Calendar.getInstance().get(Calendar.MILLISECOND);
}

class ListenableFutureTask
{
    private final ListenableFuture<Void> future;
    private final OwnTask                task;
    private final long                   milliSecEndTime;

    private ListenableFutureTask(ListenableFuture<Void> future, OwnTask task, long milliSecStartTime)
    {
        this.future = future;
        this.task = task;
        this.milliSecEndTime = milliSecStartTime + task.getTimeUnit().convert(task.getTimeoutDuration(), TimeUnit.MILLISECONDS);
    }

    ListenableFuture<Void> getFuture()
    {
        return future;
    }

    OwnTask getTask()
    {
        return task;
    }

    long getMilliSecEndTime()
    {
        return milliSecEndTime;
    }
}

class TimeoutManagerJob implements Runnable
{
    CopyOnWriteArrayList<ListenableFutureTask> getCopyOnWriteArrayList()
    {
        return futureQueue;
    }

    @Override
    public void run()
    {
        long currentMileSecValue = getCurrentMillisecondsTime();
        for (ListenableFutureTask futureTask : futureQueue)
        {
            consumeFuture(futureTask, currentMileSecValue);
        }
    }

    private void consumeFuture(ListenableFutureTask futureTask, long currentMileSecValue)
    {
        ListenableFuture<Void> future = futureTask.getFuture();
        boolean isTimeout = futureTask.getMilliSecEndTime() >= currentMileSecValue;
        if (isTimeout)
        {
            if (!future.isDone())
            {
                future.cancel(true);
            }
            futureQueue.remove(futureTask);
        }
    }
}

class OwnTask implements Callable<Void>
{
    private long     timeoutDuration;
    private TimeUnit timeUnit;

    OwnTask(long timeoutDuration, TimeUnit timeUnit)
    {
        this.timeoutDuration = timeoutDuration;
        this.timeUnit = timeUnit;
    }

    @Override
    public Void call() throws Exception
    {
        // do logic
        return null;
    }

    public long getTimeoutDuration()
    {
        return timeoutDuration;
    }

    public TimeUnit getTimeUnit()
    {
        return timeUnit;
    }
}
}

What is the difference between server side cookie and client side cookie?

  1. Yes you can create cookies that can only be read on the server-side. These are called "HTTP Only" -cookies, as explained in other answers already

  2. No, there is no way (I know of) to create "cookies" that can be read only on the client-side. Cookies are meant to facilitate client-server communication.

  3. BUT, if you want something LIKE "client-only-cookies" there is a simple answer: Use "Local Storage".

Local Storage is actually syntactically simpler to use than cookies. A good simple summary of cookies vs. local storage can be found at:

https://courses.cs.washington.edu/courses/cse154/12au/lectures/slides/lecture21-client-storage.shtml#slide8

A point: You might use cookies created in JavaScript to store GUI-related things you only need on the client-side. BUT the cookie is sent to the server for EVERY request made, it becomes part of the http-request headers thus making the request contain more data and thus slower to send.

If your page has 50 resources like images and css-files and scripts then the cookie is (typically) sent with each request. More on this in Does every web request send the browser cookies?

Local storage does not have those data-transfer related disadvantages, it sends no data. It is great.

Early exit from function?

You can just use return.

function myfunction() {
     if(a == 'stop') 
         return;
}

This will send a return value of undefined to whatever called the function.

var x = myfunction();

console.log( x );  // console shows undefined

Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.

return false;
return true;
return "some string";
return 12345;

How do I negate a test with regular expressions in a bash script?

Yes you can negate the test as SiegeX has already pointed out.

However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:

[[ ":$PATH:" != *":$1:"* ]]

(Source)

How to deserialize JS date using Jackson?

This works for me - i am using jackson 2.0.4

ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);

Pass a javascript variable value into input type hidden value

<script type="text/javascript">
  function product(x,y)
  {
   return x*y;
  }
 document.getElementById('myvalue').value = product(x,y);
 </script>

 <input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">

How can I test a PDF document if it is PDF/A compliant?

Do you have Adobe PDFL or Acrobat Professional? You can use preflight operation if you do.

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

How do I run Python script using arguments in windows command line

import sys

def hello(a, b):
    print  'hello and that\'s your sum: {0}'.format(a + b)

if __name__ == '__main__':
    hello(int(sys.argv[1]), int(sys.argv[2]))

Moreover see @thibauts answer about how to call python script.

Python xticks in subplots

See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:

  • If you want to set the xticklabels:

    ax.set_xticks([1,4,5]) 
    ax.set_xticklabels([1,4,5], fontsize=12)
    
  • If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):

    ax.tick_params(axis="x", labelsize=12) 
    
  • To do it all at once:

    plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", 
             horizontalalignment="left")`
    

About "*.d.ts" in TypeScript

I could not comment and thus am adding this as an answer.
We had some pain trying to map existing types to a javascript library.

To map a .d.ts file to its javascript file you need to give the .d.ts file the same name as the javascript file, keep them in the same folder, and point the code that needs it to the .d.ts file.

eg: test.js and test.d.ts are in the testdir/ folder, then you import it like this in a react component:

import * as Test from "./testdir/test";

The .d.ts file was exported as a namespace like this:

export as namespace Test;

export interface TestInterface1{}
export class TestClass1{}

failed to push some refs to [email protected]

In my case, I had an invalid package name. I wasn't able to pick up on the error code right away, because I didn't scroll up far enough, but the error was:

remote:        $ NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client
remote: npm ERR! code EINVALIDPACKAGENAME // <-- this was hard to find
remote: npm ERR! Invalid package name "react-loader-spinne  r": name can only contain URL-friendly characters

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.

Here is my code in the view

@Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));

Now you can use this in the JavaScript file as:

 var url = $("#RedirectTo").val();
 location.href = url;

It worked like a charm fro me. I hope it helps you too.

Exit while loop by user hitting ENTER key

You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

How to get size of mysql database?

It can be determined by using following MySQL command

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema

Result

Database    Size (MB)
db1         11.75678253
db2         9.53125000
test        50.78547382

Get result in GB

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 / 1024 AS "Size (GB)" FROM information_schema.TABLES GROUP BY table_schema

How to set headers in http get request?

Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:

func yourHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("header_name", "header_value")
}

Tar error: Unexpected EOF in archive

I had a similar error, but in my case the cause was file renaming. I was creating a gzipped file file1.tar.gz and repeatedly updating it in another tarfile with tar -uvf ./combined.tar ./file1.tar.gz. I got the unexpected EOF error when after untarring combined.tar and trying to untar file1.tar.gz.

I noticed there was a difference in the output of file before and after tarring:

$file file1.tar.gz
file1.tar.gz: gzip compressed data, was "file1.tar", last modified: Mon Jul 29 12:00:00 2019, from Unix
$tar xvf combined.tar
$file file1.tar.gz
file1.tar.gz: gzip compressed data, was "file_old.tar", last modified: Mon Jul 29 12:00:00 2019, from Unix

So, it appears that the file had a different name when I originally created combined.tar, and using the tar update function doesn't overwrite the metadata for the gzipped filename. The solution was to recreate combined.tar from scratch instead of updating it.

I still don't know exactly what happened, since changing the name of a gzipped file doesn't normally break it.

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

Format number to always show 2 decimal places

Just run into this one of longest thread, below is my solution:

parseFloat(Math.round((parseFloat(num * 100)).toFixed(2)) / 100 ).toFixed(2)

Let me know if anyone can poke a hole

How to upload multiple files using PHP, jQuery and AJAX

HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" value="Upload File" id="upload"/>
</form>

Javascript

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

for ajax upload

$('#upload').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;

    for (; i < len; i++) {
        file = filedata.files[i];

        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {

            },       
            error: function(res) {

             }       
             });
            }
        });

PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

/** 
    Edit: $target_path variable need to be reinitialized and should 
    be inside for loop to avoid appending previous file name to new one. 
*/

Please use the script above script for ajax upload. It will work

How can I use an ES6 import in Node.js?

Back to Jonathan002's original question about

"... what version supports the new ES6 import statements?"

based on the article by Dr. Axel Rauschmayer, there is a plan to have it supported by default (without the experimental command line flag) in Node.js 10.x LTS. According to node.js's release plan as it is on 3/29, 2018, it's likely to become available after Apr 2018, while LTS of it will begin on October 2018.

Preprocessing in scikit learn - single sample - Depreciation warning

I faced the same issue and got the same deprecation warning. I was using a numpy array of [23, 276] when I got the message. I tried reshaping it as per the warning and end up in nowhere. Then I select each row from the numpy array (as I was iterating over it anyway) and assigned it to a list variable. It worked then without any warning.

array = []
array.append(temp[0])

Then you can use the python list object (here 'array') as an input to sk-learn functions. Not the most efficient solution, but worked for me.

How to delete a file after checking whether it exists

if (File.Exists(path))
{
    File.Delete(path);
}

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

Creating JSON on the fly with JObject

Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "@odata.etag". I prefer the indexer initializer syntax in my test cases:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = "2Pac"
};

Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = new JObject
    {
        ["Name"] = "2Pac",
        ["Age"] = 28
    }
};

With object initializer syntax, the above initialization would be:

JObject jsonObject = new JObject
{
    { "Date", DateTime.Now },
    { "Album", "Me Against The World" },
    { "Year", 1995 }, 
    { "Artist", new JObject
        {
            { "Name", "2Pac" },
            { "Age", 28 }
        }
    }
};

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

In my case the path of MySQL data folder had a special character "ç" and it make me get...

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist.

I'm have removed all special characters and everything works.

Enter key pressed event handler

The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.

One can get special keys like ENTER by overriding the IsInputKey method:

public class CustomTextBox : System.Windows.Forms.TextBox
{
    protected override bool IsInputKey(Keys keyData)
    {
        if (keyData == Keys.Return)
            return true;
        return base.IsInputKey(keyData);
    }
}

Then one can use the KeyDown event in the following way:

CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);

private void tb_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
          //Enter key is down

          //Capture the text
          if (sender is TextBox)
          {
              TextBox txb = (TextBox)sender;
              MessageBox.Show(txb.Text);
          }
    }
}

How to know the git username and email saved during configuration?

If you want to check or set the user name and email you can use the below command

Check user name

git config user.name

Set user name

git config user.name "your_name"

Check your email

git config user.email

Set/change your email

git config user.email "[email protected]"

List/see all configuration

git config --list

How to compare two vectors for equality element by element in C++?

According to the discussion here you can directly compare two vectors using

==

if (vector1 == vector2){
   //true
}
else{
   //false
}

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

For each error of the form:

npm WARN {something} requires a peer of {other thing} but none is installed. You must install peer dependencies yourself.

You should:

$ npm install --save-dev "{other thing}"

Note: The quotes are needed if the {other thing} has spaces, like in this example:

npm WARN [email protected] requires a peer of rollup@>=0.66.0 <2 but none was installed.

Resolved with:

$ npm install --save-dev "rollup@>=0.66.0 <2"

How to define global variable in Google Apps Script

I use this: if you declare var x = 0; before the functions declarations, the variable works for all the code files, but the variable will be declare every time that you edit a cell in the spreadsheet

Javascript/jQuery: Set Values (Selection) in a multiple Select

Just provide the jQuery val function with an array of values:

var values = "Test,Prof,Off";
$('#strings').val(values.split(','));

And to get the selected values in the same format:

values = $('#strings').val();

Set the text in a span

Use .text() instead, and change your selector:

$(".ui-datepicker-prev .ui-icon.ui-icon-circle-triangle-w").text('<<');

-- VIEW DEMO --

Why do we need boxing and unboxing in C#?

The best way to understand this is to look at lower-level programming languages C# builds on.

In the lowest-level languages like C, all variables go one place: The Stack. Each time you declare a variable it goes on the Stack. They can only be primitive values, like a bool, a byte, a 32-bit int, a 32-bit uint, etc. The Stack is both simple and fast. As variables are added they just go one on top of another, so the first you declare sits at say, 0x00, the next at 0x01, the next at 0x02 in RAM, etc. In addition, variables are often pre-addressed at compile-time, so their address is known before you even run the program.

In the next level up, like C++, a second memory structure called the Heap is introduced. You still mostly live in the Stack, but special ints called Pointers can be added to the Stack, that store the memory address for the first byte of an Object, and that Object lives in the Heap. The Heap is kind of a mess and somewhat expensive to maintain, because unlike Stack variables they don't pile linearly up and then down as a program executes. They can come and go in no particular sequence, and they can grow and shrink.

Dealing with pointers is hard. They're the cause of memory leaks, buffer overruns, and frustration. C# to the rescue.

At a higher level, C#, you don't need to think about pointers - the .Net framework (written in C++) thinks about these for you and presents them to you as References to Objects, and for performance, lets you store simpler values like bools, bytes and ints as Value Types. Underneath the hood, Objects and stuff that instantiates a Class go on the expensive, Memory-Managed Heap, while Value Types go in that same Stack you had in low-level C - super-fast.

For the sake of keeping the interaction between these 2 fundamentally different concepts of memory (and strategies for storage) simple from a coder's perspective, Value Types can be Boxed at any time. Boxing causes the value to be copied from the Stack, put in an Object, and placed on the Heap - more expensive, but, fluid interaction with the Reference world. As other answers point out, this will occur when you for example say:

bool b = false; // Cheap, on Stack
object o = b; // Legal, easy to code, but complex - Boxing!
bool b2 = (bool)o; // Unboxing!

A strong illustration of the advantage of Boxing is a check for null:

if (b == null) // Will not compile - bools can't be null
if (o == null) // Will compile and always return false

Our object o is technically an address in the Stack that points to a copy of our bool b, which has been copied to the Heap. We can check o for null because the bool's been Boxed and put there.

In general you should avoid Boxing unless you need it, for example to pass an int/bool/whatever as an object to an argument. There are some basic structures in .Net that still demand passing Value Types as object (and so require Boxing), but for the most part you should never need to Box.

A non-exhaustive list of historical C# structures that require Boxing, that you should avoid:

  • The Event system turns out to have a Race Condition in naive use of it, and it doesn't support async. Add in the Boxing problem and it should probably be avoided. (You could replace it for example with an async event system that uses Generics.)

  • The old Threading and Timer models forced a Box on their parameters but have been replaced by async/await which are far cleaner and more efficient.

  • The .Net 1.1 Collections relied entirely on Boxing, because they came before Generics. These are still kicking around in System.Collections. In any new code you should be using the Collections from System.Collections.Generic, which in addition to avoiding Boxing also provide you with stronger type-safety.

You should avoid declaring or passing your Value Types as objects, unless you have to deal with the above historical problems that force Boxing, and you want to avoid the performance hit of Boxing it later when you know it's going to be Boxed anyway.

Per Mikael's suggestion below:

Do This

using System.Collections.Generic;

var employeeCount = 5;
var list = new List<int>(10);

Not This

using System.Collections;

Int32 employeeCount = 5;
var list = new ArrayList(10);

Update

This answer originally suggested Int32, Bool etc cause boxing, when in fact they are simple aliases for Value Types. That is, .Net has types like Bool, Int32, String, and C# aliases them to bool, int, string, without any functional difference.

PHP file_get_contents() and setting request headers

You can use this variable to retrieve response headers after file_get_contents() function.

Code:

  file_get_contents("http://example.com");
  var_dump($http_response_header);

Output:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}

"/usr/bin/ld: cannot find -lz"

It means you asked it to include the library 'libz.a' or 'libz.so' containing a compression package, and although the compiler found some files, none of them was suitable for the build you are using.

You either need to change your build parameters or you need to get the correct library installed or you need to specify where the correct library is on the link command line with a -L/where/it/is/lib type option.

how to measure running time of algorithms in python

For small algorithms you can use the module timeit from python documentation:

def test():
    "Stupid test function"
    L = []
    for i in range(100):
        L.append(i)

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

Less accurately but still valid you can use module time like this:

from time import time
t0 = time()
call_mifuntion_vers_1()
t1 = time()
call_mifunction_vers_2()
t2 = time()

print 'function vers1 takes %f' %(t1-t0)
print 'function vers2 takes %f' %(t2-t1)

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

C#: New line and tab characters in strings

It depends on if you mean '\n' (linefeed) or '\r\n' (carriage return + linefeed). The former is not the Windows default and will not show properly in some text editors (like Notepad).

You can do

sb.Append(Environment.NewLine);
sb.Append("\t");

or

sb.Append("\r\n\t");

What is the easiest way to install BLAS and LAPACK for scipy?

pip install Cython

before

pip install sklearn

did the trick for me.

The best way to remove duplicate values from NSMutableArray in Objective-C?

need order

NSArray *yourarray = @[@"a",@"b",@"c"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourarray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
NSLog(@"%@",arrayWithoutDuplicates);

or don't need order

NSSet *set = [NSSet setWithArray:yourarray];
NSArray *arrayWithoutOrder = [set allObjects];
NSLog(@"%@",arrayWithoutOrder);

Warning: implode() [function.implode]: Invalid arguments passed

You can try

echo implode(', ', (array)$ret);

When is a CDATA section necessary within a script tag?

CDATA indicates that the contents within are not XML.

Here is an explanation on wikipedia

how to get domain name from URL

For a certain purpose I did this quick Python function yesterday. It returns domain from URL. It's quick and doesn't need any input file listing stuff. However, I don't pretend it works in all cases, but it really does the job I needed for a simple text mining script.

Output looks like this :

http://www.google.co.uk => google.co.uk
http://24.media.tumblr.com/tumblr_m04s34rqh567ij78k_250.gif => tumblr.com

def getDomain(url):    
        parts = re.split("\/", url)
        match = re.match("([\w\-]+\.)*([\w\-]+\.\w{2,6}$)", parts[2]) 
        if match != None:
            if re.search("\.uk", parts[2]): 
                match = re.match("([\w\-]+\.)*([\w\-]+\.[\w\-]+\.\w{2,6}$)", parts[2])
            return match.group(2)
        else: return ''  

Seems to work pretty well.
However, it has to be modified to remove domain extensions on output as you wished.

How can I convert an HTML element to a canvas element?

The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.

Disable Transaction Log

SQL Server requires a transaction log in order to function.

That said there are two modes of operation for the transaction log:

  • Simple
  • Full

In Full mode the transaction log keeps growing until you back up the database. In Simple mode: space in the transaction log is 'recycled' every Checkpoint.

Very few people have a need to run their databases in the Full recovery model. The only point in using the Full model is if you want to backup the database multiple times per day, and backing up the whole database takes too long - so you just backup the transaction log.

The transaction log keeps growing all day, and you keep backing just it up. That night you do your full backup, and SQL Server then truncates the transaction log, begins to reuse the space allocated in the transaction log file.

If you only ever do full database backups, you don't want the Full recovery mode.

HTML if image is not found

try PHP

if (file_exists('url/img/' . $Image)) {
    $show_img_URL = "Image.jpg";
} else {
    $show_img_URL = "Image_not_found.jpg";
}

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Initial bytes incorrect after Java AES/CBC decryption

This is an improvement over the accepted answer.

Changes:

(1) Using random IV and prepend it to the encrypted text

(2) Using SHA-256 to generate a key from a passphrase

(3) No dependency on Apache Commons

public static void main(String[] args) throws GeneralSecurityException {
    String plaintext = "Hello world";
    String passphrase = "My passphrase";
    String encrypted = encrypt(passphrase, plaintext);
    String decrypted = decrypt(passphrase, encrypted);
    System.out.println(encrypted);
    System.out.println(decrypted);
}

private static SecretKeySpec getKeySpec(String passphrase) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    return new SecretKeySpec(digest.digest(passphrase.getBytes(UTF_8)), "AES");
}

private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
    return Cipher.getInstance("AES/CBC/PKCS5PADDING");
}

public static String encrypt(String passphrase, String value) throws GeneralSecurityException {
    byte[] initVector = new byte[16];
    SecureRandom.getInstanceStrong().nextBytes(initVector);
    Cipher cipher = getCipher();
    cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));
    byte[] encrypted = cipher.doFinal(value.getBytes());
    return DatatypeConverter.printBase64Binary(initVector) +
            DatatypeConverter.printBase64Binary(encrypted);
}

public static String decrypt(String passphrase, String encrypted) throws GeneralSecurityException {
    byte[] initVector = DatatypeConverter.parseBase64Binary(encrypted.substring(0, 24));
    Cipher cipher = getCipher();
    cipher.init(Cipher.DECRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));
    byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted.substring(24)));
    return new String(original);
}

What is the equivalent of Java's final in C#?

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

comparing 2 strings alphabetically for sorting purposes

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

All return true.

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

In your case it works like so -

1 . "a?aaa" < "?a?b"

compares the first two "a" characters - all equal, lets move to the next character.

2 . "a?a??aa" < "a?b??"

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

How to convert byte array to string

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result);

How to get StackPanel's children to fill maximum space downward?

An alternative method is to use a Grid with one column and n rows. Set all the rows heights to Auto, and the bottom-most row height to 1*.

I prefer this method because I've found Grids have better layout performance than DockPanels, StackPanels, and WrapPanels. But unless you're using them in an ItemTemplate (where the layout is being performed for a large number of items), you'll probably never notice.

The term 'ng' is not recognized as the name of a cmdlet

You should update node js to latest version. Otherwise uninstall node js and install it again.

Java: Check if command line arguments are null

@jjnguy's answer is correct in most circumstances. You won't ever see a null String in the argument array (or a null array) if main is called by running the application is run from the command line in the normal way.

However, if some other part of the application calls a main method, it is conceivable that it might pass a null argument or null argument array.

However(2), this is clearly a highly unusual use-case, and it is an egregious violation of the implied contract for a main entry-point method. Therefore, I don't think you should bother checking for null argument values in main. In the unlikely event that they do occur, it is acceptable for the calling code to get a NullPointerException. After all, it is a bug in the caller to violate the contract.

how to add script inside a php code?

You could use PHP's file_get_contents();

<?php

   $script = file_get_contents('javascriptFile.js');
   echo "<script>".$script."</script>";

?>

For more information on the function:

http://php.net/manual/en/function.file-get-contents.php

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

In my case, I was using an TOMCAT 8 and updating to TOMCAT 9 fixed it:

  <modelVersion>4.0.0</modelVersion>
  <groupId>spring-boot-app</groupId>
  <artifactId>spring-boot-app</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <executions>
          <execution>
            <goals>
              <goal>java</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>com.example.Application</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <properties>
    <tomcat.version>9.0.37</tomcat.version>
  </properties>

Related issues:

  1. https://github.com/spring-projects/spring-boot/issues?q=missing+ServletWebServerFactory+bean
  2. https://github.com/spring-projects/spring-boot/issues/22013 - Spring Boot app as a module
  3. https://github.com/spring-projects/spring-boot/issues/19141 - Application fails to load when main class extends a base class annotated with @SpringBootApplication when spring-boot-starter-web is included as a dependency

Set the value of a variable with the result of a command in a Windows batch file

One needs to be somewhat careful, since the Windows batch command:

for /f "delims=" %%a in ('command') do @set theValue=%%a

does not have the same semantics as the Unix shell statement:

theValue=`command`

Consider the case where the command fails, causing an error.

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:

set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

In a nutshell:

  • CMD sets default command and/or parameters, which can be overwritten from command line when docker container runs.
  • ENTRYPOINT command and parameters will not be overwritten from command line. Instead, all command line arguments will be added after ENTRYPOINT parameters.

If you need more details or would like to see difference on example, there is a blog post that comprehensively compare CMD and ENTRYPOINT with lots of examples - http://goinbigdata.com/docker-run-vs-cmd-vs-entrypoint/

Searching a string in eclipse workspace

At the top level menus, select 'Search' -> 'File Search' Then near the bottom (in the scope) there is a choice to select the entire workspace.

For your "File search has encountered a problem", you need to refresh the files in your workspace, in the Project/Package Explorer, right click and select "Refresh" at any level (project, folder, file). This will sync your workspace with the underlying file system and prevent the problem.

Convert Time DataType into AM PM Format:

Try this:

select CONVERT(VARCHAR(5), ' 4:07PM', 108) + ' ' + RIGHT(CONVERT(VARCHAR(30), ' 4:07PM', 9),2) as ConvertedTime

Correct set of dependencies for using Jackson mapper

No, you can simply use com.fasterxml.jackson.databind.ObjectMapper. Most likely you forgot to fix your import-statements, delete all references to codehaus and you're golden.

Move an array element from one array position to another

Here's a one liner I found on JSPerf....

Array.prototype.move = function(from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);
};

which is awesome to read, but if you want performance (in small data sets) try...

 Array.prototype.move2 = function(pos1, pos2) {
    // local variables
    var i, tmp;
    // cast input parameters to integers
    pos1 = parseInt(pos1, 10);
    pos2 = parseInt(pos2, 10);
    // if positions are different and inside array
    if (pos1 !== pos2 && 0 <= pos1 && pos1 <= this.length && 0 <= pos2 && pos2 <= this.length) {
      // save element from position 1
      tmp = this[pos1];
      // move element down and shift other elements up
      if (pos1 < pos2) {
        for (i = pos1; i < pos2; i++) {
          this[i] = this[i + 1];
        }
      }
      // move element up and shift other elements down
      else {
        for (i = pos1; i > pos2; i--) {
          this[i] = this[i - 1];
        }
      }
      // put element from position 1 to destination
      this[pos2] = tmp;
    }
  }

I can't take any credit, it should all go to Richard Scarrott. It beats the splice based method for smaller data sets in this performance test. It is however significantly slower on larger data sets as Darwayne points out.

How to determine the screen width in terms of dp or dip at runtime in Android?

Your problem is with casting the float to an int, losing precision. You should also multiply with the factor and not divide.

Do this:

int dp = (int)(pixel*getResources().getDisplayMetrics().density);

Concatenating strings in Razor

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

typeof operator in C

Since typeof is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof and _Alignof are also seen as an operators.

And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.

size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;

can only be determined at run time.

Using HTML data-attribute to set CSS background-image url

If you wanted to keep it with just HTML and CSS you can use CSS Variables. Keep in mind, css variables aren't supported in IE.

<div class="thumb" style="--background: url('images/img.jpg')"></div> 
.thumb {
    background-image: var(--background);
}

Codepen: https://codepen.io/bruce13/pen/bJdoZW

Can you get the column names from a SqlDataReader?

You can get the column names from a DataReader.

Here is the important part:

  for (int col = 0; col < SqlReader.FieldCount; col++)
  {
    Console.Write(SqlReader.GetName(col).ToString());         // Gets the column name
    Console.Write(SqlReader.GetFieldType(col).ToString());    // Gets the column type
    Console.Write(SqlReader.GetDataTypeName(col).ToString()); // Gets the column database type
  }

How to remove all click event handlers using jQuery?

If you used...

$(function(){
    function myFunc() {
        // ... do something ...
    };
    $('#saveBtn').click(myFunc);
});

... then it will be easier to unbind later.

UIView's frame, bounds, center, origin, when to use what?

Marco's answer above is correct, but just to expand on the question of "under what context"...

frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.

center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.

bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds] on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.

Why is there an frame rectangle and an bounds rectangle in an UIView?

Hopefully this helps clarify the circumstances where each property might get used.

How to test if a string is JSON or not?

Use JSON.parse

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

How to replace part of string by position?

        string s = "ABCDEFG";
        string t = "st";
        s = s.Remove(4, t.Length);
        s = s.Insert(4, t);

Finding height in Binary Search Tree

enter image description here

According to "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, following is the definition of tree height:

The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf, and the height of a tree is the height of its root. The height of a tree is also equal to the largest depth of any node in the tree.

Following is my ruby solution. Most of the people forgot about height of empty tree or tree of single node in their implementation.

def height(node, current_height)
  return current_height if node.nil? || (node.left.nil? && node.right.nil?)
  return [height(node.left, current_height + 1), height(node.right, current_height + 1)].max if node.left && node.right
  return height(node.left, current_height + 1) if node.left
  return height(node.right, current_height + 1)
end