Programs & Examples On #File exists

How to check if a file exists from a url

You can use the function file_get_contents();

if(file_get_contents('https://example.com/example.txt')) {
    //File exists
}

Verify if file exists or not in C#

These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.

The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)

Deleting a file in VBA

In VB its normally Dir to find the directory of the file. If it's not blank then it exists and then use Kill to get rid of the file.

test = Dir(Filename)
If Not test = "" Then
    Kill (Filename)
End If

Portable way to check if directory exists [Windows/Linux, C]

stat() works on Linux., UNIX and Windows as well:

#include <sys/types.h>
#include <sys/stat.h>

struct stat info;

if( stat( pathname, &info ) != 0 )
    printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR )  // S_ISDIR() doesn't exist on my windows 
    printf( "%s is a directory\n", pathname );
else
    printf( "%s is no directory\n", pathname );

How do I check whether a file exists without exceptions?

Although almost every possible way has been listed in (at least one of) the existing answers (e.g. Python 3.4 specific stuff was added), I'll try to group everything together.

Note: every piece of Python standard library code that I'm going to post, belongs to version 3.5.3.

Problem statement:

  1. Check file (arguable: also folder ("special" file) ?) existence
  2. Don't use try / except / else / finally blocks

Possible solutions:

  1. [Python 3]: os.path.exists(path) (also check other function family members like os.path.isfile, os.path.isdir, os.path.lexists for slightly different behaviors)

    os.path.exists(path)
    

    Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

    All good, but if following the import tree:

    • os.path - posixpath.py (ntpath.py)

      • genericpath.py, line ~#20+

        def exists(path):
            """Test whether a path exists.  Returns False for broken symbolic links"""
            try:
                st = os.stat(path)
            except os.error:
                return False
            return True
        

    it's just a try / except block around [Python 3]: os.stat(path, *, dir_fd=None, follow_symlinks=True). So, your code is try / except free, but lower in the framestack there's (at least) one such block. This also applies to other funcs (including os.path.isfile).

    1.1. [Python 3]: Path.is_file()

    • It's a fancier (and more pythonic) way of handling paths, but
    • Under the hood, it does exactly the same thing (pathlib.py, line ~#1330):

      def is_file(self):
          """
          Whether this path is a regular file (also True for symlinks pointing
          to regular files).
          """
          try:
              return S_ISREG(self.stat().st_mode)
          except OSError as e:
              if e.errno not in (ENOENT, ENOTDIR):
                  raise
              # Path doesn't exist or is a broken symlink
              # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
              return False
      
  2. [Python 3]: With Statement Context Managers. Either:

    • Create one:

      class Swallow:  # Dummy example
          swallowed_exceptions = (FileNotFoundError,)
      
          def __enter__(self):
              print("Entering...")
      
          def __exit__(self, exc_type, exc_value, exc_traceback):
              print("Exiting:", exc_type, exc_value, exc_traceback)
              return exc_type in Swallow.swallowed_exceptions  # only swallow FileNotFoundError (not e.g. TypeError - if the user passes a wrong argument like None or float or ...)
      
      • And its usage - I'll replicate the os.path.isfile behavior (note that this is just for demonstrating purposes, do not attempt to write such code for production):

        import os
        import stat
        
        
        def isfile_seaman(path):  # Dummy func
            result = False
            with Swallow():
                result = stat.S_ISREG(os.stat(path).st_mode)
            return result
        
    • Use [Python 3]: contextlib.suppress(*exceptions) - which was specifically designed for selectively suppressing exceptions


    But, they seem to be wrappers over try / except / else / finally blocks, as [Python 3]: The with statement states:

    This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

  3. Filesystem traversal functions (and search the results for matching item(s))


    Since these iterate over folders, (in most of the cases) they are inefficient for our problem (there are exceptions, like non wildcarded globbing - as @ShadowRanger pointed out), so I'm not going to insist on them. Not to mention that in some cases, filename processing might be required.

  4. [Python 3]: os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True) whose behavior is close to os.path.exists (actually it's wider, mainly because of the 2nd argument)

    • user permissions might restrict the file "visibility" as the doc states:

      ...test if the invoking user has the specified access to path. mode should be F_OK to test the existence of path...

    os.access("/tmp", os.F_OK)

    Since I also work in C, I use this method as well because under the hood, it calls native APIs (again, via "${PYTHON_SRC_DIR}/Modules/posixmodule.c"), but it also opens a gate for possible user errors, and it's not as Pythonic as other variants. So, as @AaronHall rightly pointed out, don't use it unless you know what you're doing:

    Note: calling native APIs is also possible via [Python 3]: ctypes - A foreign function library for Python, but in most cases it's more complicated.

    (Win specific): Since vcruntime* (msvcr*) .dll exports a [MS.Docs]: _access, _waccess function family as well, here's an example:

    Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os, ctypes
    >>> ctypes.CDLL("msvcrt")._waccess(u"C:\\Windows\\System32\\cmd.exe", os.F_OK)
    0
    >>> ctypes.CDLL("msvcrt")._waccess(u"C:\\Windows\\System32\\cmd.exe.notexist", os.F_OK)
    -1
    

    Notes:

    • Although it's not a good practice, I'm using os.F_OK in the call, but that's just for clarity (its value is 0)
    • I'm using _waccess so that the same code works on Python3 and Python2 (in spite of unicode related differences between them)
    • Although this targets a very specific area, it was not mentioned in any of the previous answers


    The Lnx (Ubtu (16 x64)) counterpart as well:

    Python 3.5.2 (default, Nov 17 2016, 17:05:23)
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os, ctypes
    >>> ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6").access(b"/tmp", os.F_OK)
    0
    >>> ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6").access(b"/tmp.notexist", os.F_OK)
    -1
    

    Notes:

    • Instead hardcoding libc's path ("/lib/x86_64-linux-gnu/libc.so.6") which may (and most likely, will) vary across systems, None (or the empty string) can be passed to CDLL constructor (ctypes.CDLL(None).access(b"/tmp", os.F_OK)). According to [man7]: DLOPEN(3):

      If filename is NULL, then the returned handle is for the main program. When given to dlsym(), this handle causes a search for a symbol in the main program, followed by all shared objects loaded at program startup, and then all shared objects loaded by dlopen() with the flag RTLD_GLOBAL.

      • Main (current) program (python) is linked against libc, so its symbols (including access) will be loaded
      • This has to be handled with care, since functions like main, Py_Main and (all the) others are available; calling them could have disastrous effects (on the current program)
      • This doesn't also apply to Win (but that's not such a big deal, since msvcrt.dll is located in "%SystemRoot%\System32" which is in %PATH% by default). I wanted to take things further and replicate this behavior on Win (and submit a patch), but as it turns out, [MS.Docs]: GetProcAddress function only "sees" exported symbols, so unless someone declares the functions in the main executable as __declspec(dllexport) (why on Earth the regular person would do that?), the main program is loadable but pretty much unusable
  5. Install some third-party module with filesystem capabilities

    Most likely, will rely on one of the ways above (maybe with slight customizations).
    One example would be (again, Win specific) [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions, which is a Python wrapper over WINAPIs.

    But, since this is more like a workaround, I'm stopping here.

  6. Another (lame) workaround (gainarie) is (as I like to call it,) the sysadmin approach: use Python as a wrapper to execute shell commands

    • Win:

      (py35x64_test) e:\Work\Dev\StackOverflow\q000082831>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" -c "import os; print(os.system('dir /b \"C:\\Windows\\System32\\cmd.exe\" > nul 2>&1'))"
      0
      
      (py35x64_test) e:\Work\Dev\StackOverflow\q000082831>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" -c "import os; print(os.system('dir /b \"C:\\Windows\\System32\\cmd.exe.notexist\" > nul 2>&1'))"
      1
      
    • Nix (Lnx (Ubtu)):

      [cfati@cfati-ubtu16x64-0:~]> python3 -c "import os; print(os.system('ls \"/tmp\" > /dev/null 2>&1'))"
      0
      [cfati@cfati-ubtu16x64-0:~]> python3 -c "import os; print(os.system('ls \"/tmp.notexist\" > /dev/null 2>&1'))"
      512
      

Bottom line:

  • Do use try / except / else / finally blocks, because they can prevent you running into a series of nasty problems. A counter-example that I can think of, is performance: such blocks are costly, so try not to place them in code that it's supposed to run hundreds of thousands times per second (but since (in most cases) it involves disk access, it won't be the case).

Final note(s):

  • I will try to keep it up to date, any suggestions are welcome, I will incorporate anything useful that will come up into the answer

check if file exists in php

Based on your comment to Haim, is this a file on your own server? If so, you need to use the file system path, not url (e.g. file_exists( '/path/to/images/thumbnail.jpg' )).

VBA check if file exists

something like this

best to use a workbook variable to provide further control (if needed) of the opened workbook

updated to test that file name was an actual workbook - which also makes the initial check redundant, other than to message the user than the Textbox is blank

Dim strFile As String
Dim WB As Workbook
strFile = Trim(TextBox1.Value)
Dim DirFile As String
If Len(strFile) = 0 Then Exit Sub

DirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFile
If Len(Dir(DirFile)) = 0 Then
  MsgBox "File does not exist"
Else
 On Error Resume Next
 Set WB = Workbooks.Open(DirFile)
 On Error GoTo 0
 If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical
End If

How to access pandas groupby dataframe by key

Wes McKinney (pandas' author) in Python for Data Analysis provides the following recipe:

groups = dict(list(gb))

which returns a dictionary whose keys are your group labels and whose values are DataFrames, i.e.

groups['foo']

will yield what you are looking for:

     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

Android Studio shortcuts like Eclipse

Alt+enter is a 'fast solving problems option'. If you try it over class name after writing 'implements XXXX' it will suggest you to autoimplemnt that methods.

The correct shortcut for 'Organice imports' is Ctrl+Alt+O

You can find a really good Android Studio/IntellyJ shortcuts cheatsheet here: IntellyJ shortcut cheatsheet

------Hint-----

Give a try to Live Templates in Android Studio (It's like magic). Just press Ctrl+J

private constructor

It's common when you want to implement a singleton. The class can have a static "factory method" that checks if the class has already been instantiated, and calls the constructor if it hasn't.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use aliases on eloquent models modify your code like this:

Item
    ::from( 'items as items_alias' )
    ->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
    ->select( DB::raw( 'items_alias.*' ) )
    ->get();

This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result. Adding DB::raw prevents laravel from adding table prefixes to aliases.

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

if you are in dev mode with not valid certificate, why not just set weClient.setUseInsecureSSL(true). works for me

How do I reverse an int array in Java?

static int[] reverseArray(int[] a) {
     int ret[] = new int[a.length];
     for(int i=0, j=a.length-1; i<a.length && j>=0; i++, j--)
         ret[i] = a[j];
     return ret;
}

Predicate Delegates in C#

Simply -> they provide True/False values based on condition mostly used for querying. mostly used with delegates

consider example of list

List<Program> blabla= new List<Program>();
        blabla.Add(new Program("shubham", 1));
        blabla.Add(new Program("google", 3));
        blabla.Add(new Program("world",5));
        blabla.Add(new Program("hello", 5));
        blabla.Add(new Program("bye", 2));

contains names and ages. Now say we want to find names on condition So I Will use,

    Predicate<Program> test = delegate (Program p) { return p.age > 3; };
        List<Program> matches = blabla.FindAll(test);
        Action<Program> print = Console.WriteLine;
        matches.ForEach(print);

tried to Keep it Simple!

Centering a Twitter Bootstrap button

Wrap in a div styled with "text-center" class.

Tensorflow image reading & display

I used CIFAR10 format instead of STL10 and code came out like

filename_queue = tf.train.string_input_producer(filenames)
read_input = read_cifar10(filename_queue)
with tf.Session() as sess:       
    tf.train.start_queue_runners(sess=sess)
    result = sess.run(read_input.uint8image)        
img = Image.fromarray(result, "RGB")    
img.save('my.jpg')

The snippet is identical with mttk and Rosa Gronchi, but Somehow I wasn't able to show the image during run-time, so I saved as the JPG file.

How to hide/show div tags using JavaScript?

Have you tried

document.getElementById('body').style.display = "none";

instead of

document.getElementById('body').style.display = "hidden";?

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You also encounter this if you run an Application on a Scheduled Task in Non-Interactive mode.

As soon as you show a Dialog it throws the error:

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

You can see its a MessageBox causing the problem in the stack trace:

at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon,  MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)  

Solution

If you're running your app on a Scheduled Task send an email instead of showing a Dialog.

How can I extract substrings from a string in Perl?

You could do something like this:

my $data = <<END;
1) Scheme ID: abc-456-hu5t10 (High priority) *
2) Scheme ID: frt-78f-hj542w (Balanced)
3) Scheme ID: 23f-f974-nm54w (super formula run) *
END

foreach (split(/\n/,$data)) {
  $_ =~ /Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?/ || next;
  my ($id,$word,$star) = ($1,$2,$3);
  print "$id $word $star\n";
}

The key thing is the Regular expression:

Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?

Which breaks up as follows.

The fixed String "Scheme ID: ":

Scheme ID: 

Followed by one or more of the characters a-z, 0-9 or -. We use the brackets to capture it as $1:

([a-z0-9-]+)

Followed by one or more whitespace characters:

\s+

Followed by an opening bracket (which we escape) followed by any number of characters which aren't a close bracket, and then a closing bracket (escaped). We use unescaped brackets to capture the words as $2:

\(([^)]+)\)

Followed by some spaces any maybe a *, captured as $3:

\s*(\*)?

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal

itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));

I already added these params by xml but it didnot work correctly
and with this line all is ok

Test class with a new() call in it with Mockito

I am all for Eran Harel's solution and in cases where it isn't possible, Tomasz Nurkiewicz's suggestion for spying is excellent. However, it's worth noting that there are situations where neither would apply. E.g. if the login method was a bit "beefier":

public class TestedClass {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
        return lc;
    }
}

... and this was old code that could not be refactored to extract the initialization of a new LoginContext to its own method and apply one of the aforementioned solutions.

For completeness' sake, it's worth mentioning a third technique - using PowerMock to inject the mock object when the new operator is called. PowerMock isn't a silver bullet, though. It works by applying byte-code manipulation on the classes it mocks, which could be dodgy practice if the tested classes employ byte code manipulation or reflection and at least from my personal experience, has been known to introduce a performance hit to the test. Then again, if there are no other options, the only option must be the good option:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TestedClass.class)
public class TestedClassTest {

    @Test
    public void testLogin() {
        LoginContext lcMock = mock(LoginContext.class);
        whenNew(LoginContext.class).withArguments(anyString(), anyString()).thenReturn(lcMock);
        TestedClass tc = new TestedClass();
        tc.login ("something", "something else");
        // test the login's logic
    }
}

C# Debug - cannot start debugging because the debug target is missing

For those with this kind of problem - another solution: Pay attention also to Warnings when you build solution. For example, I had referenced a dll built with higher version of .NET (4.5.2) than my main project (4.5) After I referenced a dll built with 4.0 build process was successful.

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Parsing ISO 8601 date in Javascript

According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date methods and formatting to accomplish your goal:

function dateToString (date) {
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[date.getMonth()];
  var day = date.getDate();
  var year = date.getFullYear();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[date.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");

alert(dateToString(date));

You could even take it one step further and override the Date.toString() method:

function dateToString () { // No date argument this time
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[*this*.getMonth()];
  var day = *this*.getDate();
  var year = *this*.getFullYear();

  var hours = *this*.getHours();
  var minutes = *this*.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[*this*.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;

alert(date.toString());

Eclipse: stop code from running (java)

I have a .bat file on my quick task bar (windows) with:

taskkill /F /IM java.exe

It's very quick, but it may not be good in many situations!

How do I auto-hide placeholder text upon focus using css or jquery?

$("input[placeholder]").each(function () {
    $(this).attr("data-placeholder", this.placeholder);

    $(this).bind("focus", function () {
        this.placeholder = '';
    });
    $(this).bind("blur", function () {
        this.placeholder = $(this).attr("data-placeholder");
    });
});

The application may be doing too much work on its main thread

I had the same problem. Android Emulator worked perfectly on Android < 6.0. When I used emulator Nexus 5 (Android 6.0), the app worked very slow with I/Choreographer: Skipped frames in the logs.

So, I solved this problem by changing in Manifest file hardwareAccelerated option to true like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application android:hardwareAccelerated="true">
        ...
    </application>
</manifest>

Using a Python subprocess call to invoke a Python script

Windows? Unix?

Unix will need a shebang and exec attribute to work:

#!/usr/bin/env python

as the first line of script and:

chmod u+x script.py

at command-line or

call('python script.py'.split())

as mentioned previously.

Windows should work if you add the shell=True parameter to the "call" call.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

See the image for reference :- (Soruce :- Android Studio-Image Assets option and Android Office Site )

enter image description here

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

What is the difference between NULL, '\0' and 0?

A byte with a value of 0x00 is, on the ASCII table, the special character called NUL or NULL. In C, since you shouldn't embed control characters in your source code, this is represented in C strings with an escaped 0, i.e., \0.

But a true NULL is not a value. It is the absence of a value. For a pointer, it means the pointer has nothing to point to. In a database, it means there is no value in a field (which is not the same thing as saying the field is blank, 0, or filled with spaces).

The actual value a given system or database file format uses to represent a NULL isn't necessarily 0x00.

Best way to check if column returns a null value (from database to .net application)

System.Convert.IsDbNull][1](table.rows[0][0]);

IIRC, the (table.rows[0][0] == null) won't work, as DbNull.Value != null;

How to draw rounded rectangle in Android UI?

Right_click on the drawable and create new layout xml file in the name of for example button_background.xml. then copy and paste the following code. You can change it according your need.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="14dp" />
<solid android:color="@color/colorButton" />
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
<size
android:width="120dp"
android:height="40dp" />
</shape>

Now you can use it.

<Button
android:background="@drawable/button_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Just wrap the float, boolean, int or similar in an NSNumber.

For structs, I don't know of a handy solution, but you could make a separate ObjC class that owns such a struct.

HTML if image is not found

The best way to solve your problem:

<img id="currentPhoto" src="SomeImage.jpg" onerror="this.onerror=null; this.src='Default.jpg'" alt="" width="100" height="120">

onerror is a good thing for you :)

Just change the image file name and try yourself.

Simplest way to do a recursive self-join?

Using CTEs you can do it this way

DECLARE @Table TABLE(
        PersonID INT,
        Initials VARCHAR(20),
        ParentID INT
)

INSERT INTO @Table SELECT     1,'CJ',NULL
INSERT INTO @Table SELECT     2,'EB',1
INSERT INTO @Table SELECT     3,'MB',1
INSERT INTO @Table SELECT     4,'SW',2
INSERT INTO @Table SELECT     5,'YT',NULL
INSERT INTO @Table SELECT     6,'IS',5

DECLARE @PersonID INT

SELECT @PersonID = 1

;WITH Selects AS (
        SELECT *
        FROM    @Table
        WHERE   PersonID = @PersonID
        UNION ALL
        SELECT  t.*
        FROM    @Table t INNER JOIN
                Selects s ON t.ParentID = s.PersonID
)
SELECT  *
FROm    Selects

Maven build debug in Eclipse

The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

For anyone with the same issue as I had, I was calling a public method method1 from within another class. method1 then called another public method method2 within the same class. method2 was annotated with @Transactional, but method1 was not. All that method1 did was transform some arguments and directly call method2, so no DB operations here.

The issue got solved for me once I moved the @Transactional annotation to method1.

Not sure the reason for this, but this did it for me.

Deploying Java webapp to Tomcat 8 running in Docker container

Tomcat will only extract the war which is copied to webapps directory. Change Dockerfile as below:

FROM tomcat:8.0.20-jre8
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

You might need to access the url as below unless you have specified the webroot

http://192.168.59.103:8888/myapp/getData

Can a java lambda have more than 1 parameter?

For this case you could use interfaces from default library (java 1.8):

java.util.function.BiConsumer
java.util.function.BiFunction

There is a small (not the best) example of default method in interface:

default BiFunction<File, String, String> getFolderFileReader() {
    return (directory, fileName) -> {
        try {
            return FileUtils.readFile(directory, fileName);
        } catch (IOException e) {
            LOG.error("Unable to read file {} in {}.", fileName, directory.getAbsolutePath(), e);
        }
        return "";
    };
}}

How to have conditional elements and keep DRY with Facebook React's JSX?

Maybe it helps someone who comes across the question: All the Conditional Renderings in React It's an article about all the different options for conditional rendering in React.

Key takeaways of when to use which conditional rendering:

** if-else

  • is the most basic conditional rendering
  • beginner friendly
  • use if to opt-out early from a render method by returning null

** ternary operator

  • use it over an if-else statement
  • it is more concise than if-else

** logical && operator

  • use it when one side of the ternary operation would return null

** switch case

  • verbose
  • can only be inlined with self invoking function
  • avoid it, use enums instead

** enums

  • perfect to map different states
  • perfect to map more than one condition

** multi-level/nested conditional renderings

  • avoid them for the sake of readability
  • split up components into more lightweight components with their own simple conditional rendering
  • use HOCs

** HOCs

  • use them to shield away conditional rendering
  • components can focus on their main purpose

** external templating components

  • avoid them and be comfortable with JSX and JavaScript

How do I output the results of a HiveQL query to CSV?

This shell command prints the output format in csv to output.txt without the column headers.

$ hive --outputformat=csv2 -f 'hivedatascript.hql' --hiveconf hive.cli.print.header=false > output.txt

How to show empty data message in Datatables

By default the grid view will take care, just pass empty data set.

How to remove square brackets in string using regex?

here you go

var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

forcing web-site to show in landscape mode only

Try this It may be more appropriate for you

_x000D_
_x000D_
#container { display:block; }_x000D_
@media only screen and (orientation:portrait){_x000D_
  #container {  _x000D_
    height: 100vw;_x000D_
    -webkit-transform: rotate(90deg);_x000D_
    -moz-transform: rotate(90deg);_x000D_
    -o-transform: rotate(90deg);_x000D_
    -ms-transform: rotate(90deg);_x000D_
    transform: rotate(90deg);_x000D_
  }_x000D_
}_x000D_
@media only screen and (orientation:landscape){_x000D_
  #container {  _x000D_
     -webkit-transform: rotate(0deg);_x000D_
     -moz-transform: rotate(0deg);_x000D_
     -o-transform: rotate(0deg);_x000D_
     -ms-transform: rotate(0deg);_x000D_
     transform: rotate(0deg);_x000D_
  }_x000D_
}
_x000D_
<div id="container">_x000D_
    <!-- your html for your website -->_x000D_
    <H1>This text is always in Landscape Mode</H1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will automatically manage even rotation.

Jackson: how to prevent field serialization

The easy way is to annotate your getters and setters.

Here is the original example modified to exclude the plain text password, but then annotate a new method that just returns the password field as encrypted text.

class User {

    private String password;

    public void setPassword(String password) {
        this.password = password;
    }

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    @JsonProperty("password")
    public String getEncryptedPassword() {
        // encryption logic
    }
}

How to select into a variable in PL/SQL when the result might be null?

What about using MAX? That way if no data is found the variable is set to NULL, otherwise the maximum value.
Since you expect either 0 or 1 value, MAX should be OK to use.

v_column my_table.column%TYPE;
select MAX(column) into v_column from my_table where ...;

Ruby on Rails - Import Data from a CSV file

This can help. It has code examples too:

http://csv-mapper.rubyforge.org/

Or for a rake task for doing the same:

http://erikonrails.snowedin.net/?p=212

php - How do I fix this illegal offset type error

check $xml->entry[$i] exists and is an object before trying to get a property of it

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

How can I access Oracle from Python?

Here is how my code looks like. It also shows an example of how to use query parameters using a dictionary. It works on using Python 3.6:

import cx_Oracle

CONN_INFO = {
    'host': 'xxx.xx.xxx.x',
    'port': 12345,
    'user': 'SOME_SCHEMA',
    'psw': 'SECRETE',
    'service': 'service.server.com'
}

CONN_STR = '{user}/{psw}@{host}:{port}/{service}'.format(**CONN_INFO)

QUERY = '''
    SELECT
        *
    FROM
        USER
    WHERE
        NAME = :name
'''


class DB:
    def __init__(self):
        self.conn = cx_Oracle.connect(CONN_STR)

    def query(self, query, params=None):
        cursor = self.conn.cursor()
        result = cursor.execute(query, params).fetchall()
        cursor.close()
        return result


db = DB()
result = db.query(QUERY, {'name': 'happy'})

Verify object attribute value with mockito

You can refer the following:

Mockito.verify(mockedObject).someMethodOnMockedObject(eq(desiredObject))

This will verify whether method of mockedObject is called with desiredObject as parameter.

How to escape double quotes in JSON

To escape backslashes that cause problems for JSON data I use this function.

//escape backslash to avoid errors
var escapeJSON = function(str) {
    return str.replace(/\\/g,'\\');
};

how to rotate text left 90 degree and cell size is adjusted according to text in html

You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>.

Also make sure you change your id #rotate to a class since you have multiple.

A 4x3 table with the headers in the first column rotated by 90 degrees

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
  border-collapse: collapse;_x000D_
  border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
  visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
  /* FF3.5+ */_x000D_
  -moz-transform: rotate(-90.0deg);_x000D_
  /* Opera 10.5 */_x000D_
  -o-transform: rotate(-90.0deg);_x000D_
  /* Saf3.1+, Chrome */_x000D_
  -webkit-transform: rotate(-90.0deg);_x000D_
  /* IE6,IE7 */_x000D_
  filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
  /* IE8 */_x000D_
  -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
  /* Standard */_x000D_
  transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>10kg</div>_x000D_
    </td>_x000D_
    <td>B</td>_x000D_
    <td>C</td>_x000D_
    <td>D</td>_x000D_
    <td>E</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>20kg</div>_x000D_
    </td>_x000D_
    <td>G</td>_x000D_
    <td>H</td>_x000D_
    <td>I</td>_x000D_
    <td>J</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div class='rotate'>30kg</div>_x000D_
    </td>_x000D_
    <td>L</td>_x000D_
    <td>M</td>_x000D_
    <td>N</td>_x000D_
    <td>O</td>_x000D_
  </tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

JavaScript

The equivalent to the above in pure JavaScript is as follows:

jsFiddle

window.addEventListener('load', function () {
    var rotates = document.getElementsByClassName('rotate');
    for (var i = 0; i < rotates.length; i++) {
        rotates[i].style.height = rotates[i].offsetWidth + 'px';
    }
});

link_to method and click event in Rails

another solution is catching onClick event and for aggregate data to js function you can

.hmtl.erb

<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>

.js

// handle my-class click
$('a.my-class').on('click', function () {
  var link = $(this);
  var array = link.data('array');
});

Ajax Upload image

first in your ajax call include success & error function and then check if it gives you error or what?

your code should be like this

$(document).ready(function (e) {
    $('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#ImageBrowse").on("change", function() {
        $("#imageUploadForm").submit();
    });
});

How do I check in SQLite whether a table exists?

Use:

PRAGMA table_info(your_table_name)

If the resulting table is empty then your_table_name doesn't exist.

Documentation:

PRAGMA schema.table_info(table-name);

This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.

The table named in the table_info pragma can also be a view.

Example output:

cid|name|type|notnull|dflt_value|pk
0|id|INTEGER|0||1
1|json|JSON|0||0
2|name|TEXT|0||0

Portable way to check if directory exists [Windows/Linux, C]

With C++17 you can use std::filesystem::is_directory function (https://en.cppreference.com/w/cpp/filesystem/is_directory). It accepts a std::filesystem::path object which can be constructed with a unicode path.

Creating a "logical exclusive or" operator in Java

The following your code:

public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}

is superfluous.

Why not to write:

public static boolean logicalXOR(boolean x, boolean y) {
    return x != y;
}

?

Also, as javashlook said, there already is ^ operator.

!= and ^ work identically* for boolean operands (your case), but differently for integer operands.

* Notes:
1. They work identically for boolean (primitive type), but not Boolean (object type) operands. As Boolean (object type) values can have value null. And != will return false or true when one or both of its operands are null, while ^ will throw NullPointerException in this case.
2. Although they work identically, they have different precedence, e.g. when used with &: a & b != c & d will be treated as a & (b != c) & d, while a & b ^ c & d will be treated as (a & b) ^ (c & d) (offtopic: ouch, C-style precedence table sucks).

How to convert an XML file to nice pandas dataframe?

Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records. xmltodict handling xml load

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Emulate a 403 error page

I understand you have a scenario with ErrorDocument already defined within your apache conf or .htaccess and want to make those pages appear when manually sending a 4xx status code via php.

Unfortunately this is not possible with common methods because php sends header directly to user's browser (not to Apache web server) whereas ErrorDocument is a display handler for http status generated from Apache.

Programmatically change the src of an img tag

With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

document.querySelector('img[name="edit-save"]');

and change the src with

document.querySelector('img[name="edit-save"]').src = "..."

so you could achieve the desired effect with

var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
    this.src = "..." // this is the reference to the image itself
};

otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)

What's the fastest way to convert String to Number in JavaScript?

Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string. You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code. read the comments to understand better how the conversion is done.

// Here Im creating my variable as a string
var str = "258";


// here im printing the string variable: str
console.log ( str );


// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);


// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);

T-SQL Format integer to 2-digit string

here you go

select RIGHT(REPLICATE('0', 2) + CAST(2 AS VARCHAR(2)), 2)

should return 02

Unable to start Service Intent

In my case the 1 MB maximum cap for data transport by Intent. I'll just use Cache or Storage.

Angular - Use pipes in services and components

If you want to use your custom pipe in your components, you can add

@Injectable({
  providedIn: 'root'
})

annotation to your custom pipe. Then, you can use it as a service

How to access the first property of a Javascript object?

if someone prefers array destructuring

const [firstKey] = Object.keys(object);

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None

a = 10
print a 

del a       
print a      ## throws an error here because it's been deleted already.

The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del has no real effect, since those names would have been deleted as they went out of scope anyway.

Dynamically allocating an array of objects

The constructor of your A object allocates another object dynamically and stores a pointer to that dynamically allocated object in a raw pointer.

For that scenario, you must define your own copy constructor , assignment operator and destructor. The compiler generated ones will not work correctly. (This is a corollary to the "Law of the Big Three": A class with any of destructor, assignment operator, copy constructor generally needs all 3).

You have defined your own destructor (and you mentioned creating a copy constructor), but you need to define both of the other 2 of the big three.

An alternative is to store the pointer to your dynamically allocated int[] in some other object that will take care of these things for you. Something like a vector<int> (as you mentioned) or a boost::shared_array<>.

To boil this down - to take advantage of RAII to the full extent, you should avoid dealing with raw pointers to the extent possible.

And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling delete - delete handles that case by doing nothing so you don't have to clutter you code with the checks.

How to launch an EXE from Web page (asp.net)

You can see how iTunes does it by using Fiddler to follow the action when using the link: http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=80028216

  1. It downloads a js file
  2. On windows: the js file determines if iTunes was installed on the computer or not: looks for an activeX browser component if IE, or a browser plugin if FF
  3. If iTunes is installed then the browser is redirected to an URL with a special transport: itms://...
  4. The browser invokes the handler (provided by the iTunes exe). This includes starting up the exe if it is not already running.
  5. iTunes exe uses the rest of the special url to show a specific page to the user.

Note that the exe, when installed, installed URL protocol handlers for "itms" transport with the browsers.

Not a simple engineering project to duplicate, but definitely do-able. If you go ahead with this, please consider making the relevant software open source.

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

All you have to do is to edit the httpd-xampp.conf

from Require local to Require all granted in the LocationMatch tag.

That's it!

How can I check if my Element ID has focus?

This is a block element, in order for it to be able to receive focus, you need to add tabindex attribute to it, as in

<div id="myID" tabindex="1"></div>

Tabindex will allow this element to receive focus. Use tabindex="-1" (or indeed, just get rid of the attribute alltogether) to disallow this behaviour.

And then you can simply

if ($("#myID").is(":focus")) {...}

Or use the

$(document.activeElement)

As been suggested previously.

Android appcompat v7:23

Latest published version of the Support Library is 24.1.1, So you can use it like this,

compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'

Same as for other support components.

You can see the revisions here,
https://developer.android.com/topic/libraries/support-library/revisions.html

How to delete a cookie?

Here a good link on Quirksmode.

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

Failed to execute removeChild on Node

I was wraped it with <> </> as a parent when I changed it to normal , div , its worked fine

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

How to write JUnit test with Spring Autowire?

Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;

Also this looks wierd to me :

@ContextConfiguration("classpath*:conf/components.xml")

Here is an example that works fine for me :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {

    @Autowired
    OwnerService ownerService;

    @Before
    public void setup() {

        ownerService.cleanList();

    }

    @Test
    public void testOwners() {

        Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
        owner = ownerService.createOwner(owner);
        assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
        assertTrue("Check that Id exist: ", owner.getId() > 0);

        owner.setLastName("Larsson");
        ownerService.updateOwner(owner);
        owner = ownerService.getOwner(owner.getId());
        assertEquals("Name is changed", "Larsson", owner.getLastName());

    }

python multithreading wait till all threads finished

I prefer using list comprehension based on an input list:

inputs = [scriptA + argumentsA, scriptA + argumentsB, ...]
threads = [Thread(target=call_script, args=(i)) for i in inputs]
[t.start() for t in threads]
[t.join() for t in threads]

How to convert a date String to a Date or Calendar object?

In brief:

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try {
  Date date = formatter.parse("01/29/02");
} catch (ParseException e) {
  e.printStackTrace();
}

See SimpleDateFormat javadoc for more.

And to turn it into a Calendar, do:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

How do I override nested NPM dependency versions?

NPM shrinkwrap offers a nice solution to this problem. It allows us to override that version of a particular dependency of a particular sub-module.

Essentially, when you run npm install, npm will first look in your root directory to see whether a npm-shrinkwrap.json file exists. If it does, it will use this first to determine package dependencies, and then falling back to the normal process of working through the package.json files.

To create an npm-shrinkwrap.json, all you need to do is

 npm shrinkwrap --dev

code:

{
  "dependencies": {
    "grunt-contrib-connect": {
      "version": "0.3.0",
      "from": "[email protected]",
      "dependencies": {
        "connect": {
          "version": "2.8.1",
          "from": "connect@~2.7.3"
        }
      }
    }
  }
}

How to add elements to an empty array in PHP?

$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";

//OR

$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}

Load image with jQuery and append it to the DOM

$('<img src="'+ imgPath +'">').load(function() {
  $(this).width(some).height(some).appendTo('#some_target');
});

If you want to do for several images then:

function loadImage(path, width, height, target) {
    $('<img src="'+ path +'">').load(function() {
      $(this).width(width).height(height).appendTo(target);
    });
}

Use:

loadImage(imgPath, 800, 800, '#some_target');

What's the difference between event.stopPropagation and event.preventDefault?

TL;DR
event.preventDefault()
Prevents the browsers default behaviour (such as opening a link), but does not stop the event from bubbling up the DOM.

event.stopPropagation()
Prevents the event from bubbling up the DOM, but does not stop the browsers default behaviour.

return false;
Usually seen in jQuery code, it Prevents the browsers default behaviour, Prevents the event from bubbling up the DOM, and immediately Returns from any callback.

One should checkout this really nice & easy 4 min read with examples from where the above piece was copied from.

Are multi-line strings allowed in JSON?

This is a really old question, but I came across this on a search and I think I know the source of your problem.

JSON does not allow "real" newlines in its data; it can only have escaped newlines. See the answer from @YOU. According to the question, it looks like you attempted to escape line breaks in Python two ways: by using the line continuation character ("\") or by using "\n" as an escape.

But keep in mind: if you are using a string in python, special escaped characters ("\t", "\n") are translated into REAL control characters! The "\n" will be replaced with the ASCII control character representing a newline character, which is precisely the character that is illegal in JSON. (As for the line continuation character, it simply takes the newline out.)

So what you need to do is to prevent Python from escaping characters. You can do this by using a raw string (put r in front of the string, as in r"abc\ndef", or by including an extra slash in front of the newline ("abc\\ndef").

Both of the above will, instead of replacing "\n" with the real newline ASCII control character, will leave "\n" as two literal characters, which then JSON can interpret as a newline escape.

App.Config change value

That worked for me in WPF application:

string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();

How to get `DOM Element` in Angular 2?

Update (using renderer):

Note that the original Renderer service has now been deprecated in favor of Renderer2

as on Renderer2 official doc.

Furthermore, as pointed out by @GünterZöchbauer:

Actually using ElementRef is just fine. Also using ElementRef.nativeElement with Renderer2 is fine. What is discouraged is accessing properties of ElementRef.nativeElement.xxx directly.


You can achieve this by using elementRef as well as by ViewChild. however it's not recommendable to use elementRef due to:

  • security issue
  • tight coupling

as pointed out by official ng2 documentation.

1. Using elementRef (Direct Access):

export class MyComponent {    
constructor (private _elementRef : ElementRef) {
 this._elementRef.nativeElement.querySelector('textarea').focus();
 }
}

2. Using ViewChild (better approach):

<textarea  #tasknote name="tasknote" [(ngModel)]="taskNote" placeholder="{{ notePlaceholder }}" 
style="background-color: pink" (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea> // <-- changes id to local var


export class MyComponent implements AfterViewInit {
  @ViewChild('tasknote') input: ElementRef;

   ngAfterViewInit() {
    this.input.nativeElement.focus();

  }
}

3. Using renderer:

export class MyComponent implements AfterViewInit {
      @ViewChild('tasknote') input: ElementRef;
         constructor(private renderer: Renderer2){           
          }

       ngAfterViewInit() {
       //using selectRootElement instead of depreaced invokeElementMethod
       this.renderer.selectRootElement(this.input["nativeElement"]).focus();
      }

    }

Twitter Bootstrap - add top space between rows

Add to this class in the .css file:

.row {
    margin-left: -20px;
    *zoom: 1;
    margin-top: 50px;
}

or make a new class and add it to the element

.rowSpecificFormName td {
    margin-top: 50px;
}

TCPDF output without saving file

Hint - with a saving file:

$pdf->Output('sandbox/pdf/example.pdf', 'F');

Mysql adding user for remote access

An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.

Regex replace uppercase with lowercase letters

Regular expression

Find:\w+

Replace:\L$0

Sublime Text uses the Perl Compatible Regular Expressions (PCRE) engine from the Boost library to power regular expressions in search panels.

\L Converts everything up to lowercase

$0 Capture groups

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

function to remove duplicate characters in a string

public static void main(String[] args) {

    char[] str = { 'a', 'b', 'a','b','c','e','c' };

    for (int i = 1; i < str.length; i++) {
        for (int j = 0; j < i; j++) {
            if (str[i] == str[j]) {
                str[i] = ' ';
            }
        }

    }
    System.out.println(str);
}

What, exactly, is needed for "margin: 0 auto;" to work?

Complete rule for CSS:

  1. (display: block AND width not auto) OR display: table
  2. float: none
  3. position: relative

Changing file extension in Python

An elegant way using pathlib.Path:

from pathlib import Path
p = Path('mysequence.fasta')
p.rename(p.with_suffix('.aln'))

Load external css file like scripts in jquery which is compatible in ie also

    //load css first, then print <link> to header, and execute callback
    //just set var href above this..
    $.ajax({
          url: href,
          dataType: 'css',
          success: function(){                  
                $('<link rel="stylesheet" type="text/css" href="'+href+'" />').appendTo("head");
                //your callback
            }
    });

For Jquery 1.2.6 and above ( omitting the fancy attributes functions above ).

I am doing it this way because I think that this will ensure that your requested stylesheet is loaded by ajax before you try to stick it into the head. Therefore, the callback is executed after the stylesheet is ready.

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

You can either remove E_STRICT from error_reporting(), or you can simply make your method static, if you need to call it statically. As far as I know, there is no (strict) way to have a method that can be invoked both as static and non-static method. Also, which is more annoying, you cannot have two methods with the same name, one being static and the other non-static.

How to test if JSON object is empty in Java

obj.length() == 0

is what I would do.

Delete ActionLink with confirm dialog

<%= Html.ActionLink("Delete", "Delete",
    new { id = item.storyId }, 
    new { onclick = "return confirm('Are you sure you wish to delete this article?');" })     %>

The above code only works for Html.ActionLink.

For

Ajax.ActionLink

use the following code:

<%= Ajax.ActionLink(" ", "deleteMeeting", new { id = Model.eventID, subid = subItem.ID, fordate = forDate, forslot = forslot }, new AjaxOptions
                                            {
                                                Confirm = "Are you sure you wish to delete?",
                                                UpdateTargetId = "Appointments",
                                                HttpMethod = "Get",
                                                InsertionMode = InsertionMode.Replace,
                                                LoadingElementId = "div_loading"
                                            }, new { @class = "DeleteApointmentsforevent" })%>

The 'Confirm' option specifies javascript confirm box.

Split Strings into words with multiple word boundary delimiters

got same problem as @ooboo and find this topic @ghostdog74 inspired me, maybe someone finds my solution usefull

str1='adj:sg:nom:m1.m2.m3:pos'
splitat=':.'
''.join([ s if s not in splitat else ' ' for s in str1]).split()

input something in space place and split using same character if you dont want to split at spaces.

How to force deletion of a python object?

In general, to make sure something happens no matter what, you use

from exceptions import NameError

try:
    f = open(x)
except ErrorType as e:
    pass # handle the error
finally:
    try:
        f.close()
    except NameError: pass

finally blocks will be run whether or not there is an error in the try block, and whether or not there is an error in any error handling that takes place in except blocks. If you don't handle an exception that is raised, it will still be raised after the finally block is excecuted.

The general way to make sure a file is closed is to use a "context manager".

http://docs.python.org/reference/datamodel.html#context-managers

with open(x) as f:
    # do stuff

This will automatically close f.

For your question #2, bar gets closed on immediately when it's reference count reaches zero, so on del foo if there are no other references.

Objects are NOT created by __init__, they're created by __new__.

http://docs.python.org/reference/datamodel.html#object.new

When you do foo = Foo() two things are actually happening, first a new object is being created, __new__, then it is being initialized, __init__. So there is no way you could possibly call del foo before both those steps have taken place. However, if there is an error in __init__, __del__ will still be called because the object was actually already created in __new__.

Edit: Corrected when deletion happens if a reference count decreases to zero.

Determine .NET Framework version for dll

The simplest way: just open the .dll in any text editor. Look at one of the last lines: enter image description here

How to check the function's return value if true or false

ValidateForm returns boolean,not a string.
When you do this if(ValidateForm() == 'false'), is the same of if(false == 'false'), which is not true.

function post(url, formId) {
    if(!ValidateForm()) {
        // False
    } else {
        // True
    }
}

How do I set browser width and height in Selenium WebDriver?

It's easy. Here is the full code.

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("Your URL")
driver.set_window_size(480, 320)

Make sure chrome driver is in your system path.

Why is the Java main method static?

Applets, midlets, servlets and beans of various kinds are constructed and then have lifecycle methods called on them. Invoking main is all that is ever done to the main class, so there is no need for a state to be held in an object that is called multiple times. It's quite normal to pin main on another class (although not a great idea), which would get in the way of using the class to create the main object.

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

Find package name for Android apps to use Intent to launch Market app from web

You can search the app online in the Google Play Store. When found, check the url, for example, https://play.google.com/store/apps/details?id=lutey.FTPServer&hl=en

The id parameter corresponds to the package name of the application. In the case of the url in the example, the package name is lutey.FTPServer.

How to resize the jQuery DatePicker control

with out changing the css file you can also change the calendar size  by putting the the following code in to ur <head>.....</head> tag:


<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Icon trigger</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style type="text/css">
.ui-widget { font-family: Lucida Grande, Lucida Sans, Arial, sans-serif; font-size: 0.6em; }
</style>

<script>



$(function() {

$( "#datepicker" ).datepicker({
//font-size:10px;
 //numberOfMonths: 3,

showButtonPanel: true,
showOn: 'button',
buttonImage: "images/calendar1.gif",
buttonImageOnly: true
});
});
</script>

</head>

Change name of folder when cloning from GitHub?

git clone <Repo> <DestinationDirectory>

Clone the repository located at Repo into the folder called DestinationDirectory on the local machine.

Android studio - Failed to find target android-18

I had the same problem when trying out Android Studio. I already had projects running on the ADT under SDK 18. No need to hack the manifest files.

Fixed by:

export ANDROID_HOME= pathtobundle/adt-bundle-linux-x86_64-20130729/sdk

If you don't have the ADT installed, and just want the SDK, it seems like a good solution is to install everything and then point Android Studio to the just the packaged SDK.

cd pathtobundle

wget http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20130729.zip

unzip *.zip

As someone else said, you may need to run the SDK Manager to install the desired packages before running Studio.

How can I copy a Python string?

I'm just starting some string manipulations and found this question. I was probably trying to do something like the OP, "usual me". The previous answers did not clear up my confusion, but after thinking a little about it I finally "got it".

As long as a, b, c, d, and e have the same value, they reference to the same place. Memory is saved. As soon as the variable start to have different values, they get start to have different references. My learning experience came from this code:

import copy
a = 'hello'
b = str(a)
c = a[:]
d = a + ''
e = copy.copy(a)

print map( id, [ a,b,c,d,e ] )

print a, b, c, d, e

e = a + 'something'
a = 'goodbye'
print map( id, [ a,b,c,d,e ] )
print a, b, c, d, e

The printed output is:

[4538504992, 4538504992, 4538504992, 4538504992, 4538504992]

hello hello hello hello hello

[6113502048, 4538504992, 4538504992, 4538504992, 5570935808]

goodbye hello hello hello hello something

How do you set the document title in React?

you should set document title in the life cycle of 'componentWillMount':

componentWillMount() {
    document.title = 'your title name'
  },

docker: "build" requires 1 argument. See 'docker build --help'

The following command worked for me. Docker file was placed in my-app-master folder.

docker build -f my-app-master/Dockerfile -t my-app-master .

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

How to update core-js to core-js@3 dependency?

How about reinstalling the node module? Go to the root directory of the project and remove the current node modules and install again.

These are the commands : rm -rf node_modules npm install

OR

npm uninstall -g react-native-cli and

npm install -g react-native-cli

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

http://msdn.microsoft.com/en-us/library/ms143316.aspx

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

Changing API level Android Studio

For android studio users:

  1. right click the App directory
  2. choose the "module setting" option
  3. change the ADK Platform as what you need
  4. Click Apply

The gradle will rebuild the project automatically.

Html.Textbox VS Html.TextboxFor

IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view.

You can do the same things with both, but you should use typed views and TextboxFor when possible.

Most efficient way to see if an ArrayList contains an object in Java

You could use a Comparator with Java's built-in methods for sorting and binary search. Suppose you have a class like this, where a and b are the fields you want to use for sorting:

class Thing { String a, b, c, d; }

You would define your Comparator:

Comparator<Thing> comparator = new Comparator<Thing>() {
  public int compare(Thing o1, Thing o2) {
    if (o1.a.equals(o2.a)) {
      return o1.b.compareTo(o2.b);
    }
    return o1.a.compareTo(o2.a);
  }
};

Then sort your list:

Collections.sort(list, comparator);

And finally do the binary search:

int i = Collections.binarySearch(list, thingToFind, comparator);

Docker compose, running containers in net:host

Just print

network_mode: "host"

How to make custom error pages work in ASP.NET MVC 4

I do something that requires less coding than the other solutions posted.

First, in my web.config, I have the following:

<customErrors mode="On" defaultRedirect="~/ErrorPage/Oops">
   <error redirect="~/ErrorPage/Oops/404" statusCode="404" />
   <error redirect="~/ErrorPage/Oops/500" statusCode="500" />
</customErrors>

And the controller (/Controllers/ErrorPageController.cs) contains the following:

public class ErrorPageController : Controller
{
    public ActionResult Oops(int id)
    {
        Response.StatusCode = id;

        return View();
    }
}

And finally, the view contains the following (stripped down for simplicity, but it can conta:

_x000D_
_x000D_
@{ ViewBag.Title = "Oops! Error Encountered"; }_x000D_
_x000D_
<section id="Page">_x000D_
  <div class="col-xs-12 well">_x000D_
    <table cellspacing="5" cellpadding="3" style="background-color:#fff;width:100%;" class="table-responsive">_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td valign="top" align="left" id="tableProps">_x000D_
            <img width="25" height="33" src="~/Images/PageError.gif" id="pagerrorImg">_x000D_
          </td>_x000D_
          <td width="360" valign="middle" align="left" id="tableProps2">_x000D_
            <h1 style="COLOR: black; FONT: 13pt/15pt verdana" id="errortype"><span id="errorText">@Response.Status</span></h1>_x000D_
          </td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td width="400" colspan="2" id="tablePropsWidth"><font style="COLOR: black; FONT: 8pt/11pt verdana">Possible causes:</font>_x000D_
          </td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td width="400" colspan="2" id="tablePropsWidth2">_x000D_
            <font style="COLOR: black; FONT: 8pt/11pt verdana" id="LID1">_x000D_
                            <hr>_x000D_
                            <ul>_x000D_
                                <li id="list1">_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Baptist explanation: </strong>There_x000D_
                                        must be sin in your life. Everyone else opened it fine.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Presbyterian explanation: </strong>It's_x000D_
                                        not God's will for you to open this link.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong> Word of Faith explanation:</strong>_x000D_
                                        You lack the faith to open this link. Your negative words have prevented_x000D_
                                        you from realizing this link's fulfillment.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Charismatic explanation: </strong>Thou_x000D_
                                        art loosed! Be commanded to OPEN!<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Unitarian explanation:</strong> All_x000D_
                                        links are equal, so if this link doesn't work for you, feel free to_x000D_
                                        experiment with other links that might bring you joy and fulfillment.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Buddhist explanation:</strong> .........................<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Episcopalian explanation:</strong>_x000D_
                                        Are you saying you have something against homosexuals?<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Christian Science explanation: </strong>There_x000D_
                                        really is no link.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Atheist explanation: </strong>The only_x000D_
                                        reason you think this link exists is because you needed to invent it.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Church counselor's explanation:</strong>_x000D_
                                        And what did you feel when the link would not open?_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                            </ul>_x000D_
                            <p>_x000D_
                                <br>_x000D_
                            </p>_x000D_
                            <h2 style="font:8pt/11pt verdana; color:black" id="ietext">_x000D_
                                <img width="16" height="16" align="top" src="~/Images/Search.gif">_x000D_
                                HTTP @Response.StatusCode - @Response.StatusDescription <br>_x000D_
                            </h2>_x000D_
                        </font>_x000D_
          </td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

It's just as simple as that. It could be easily extended to offer more detailed error info, but ELMAH handles that for me & the statusCode & statusDescription is all that I usually need.

java: use StringBuilder to insert at the beginning

you can use strbuilder.insert(0,i);

The import org.junit cannot be resolved

If you are using Java 9 or above you may need to require the junit dependency in your module-info.java

module myModule {
    requires junit;
}

Is it possible to create static classes in PHP (like in C#)?

In addition to Greg's answer, I would recommend to set the constructor private so that it is impossible to instantiate the class.

So in my humble opinion this is a more complete example based on Greg's one:

<?php

class Hello
{
    /**
     * Construct won't be called inside this class and is uncallable from
     * the outside. This prevents instantiating this class.
     * This is by purpose, because we want a static class.
     */
    private function __construct() {}
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>

Swift - How to hide back button in navigation item?

According to the documentation for UINavigationItem :

self.navigationItem.setHidesBackButton(true, animated: true)

Determining 32 vs 64 bit in C++

template<int> void DoMyOperationHelper();

template<> void DoMyOperationHelper<4>() 
{
  // do 32-bits operations
}

template<> void DoMyOperationHelper<8>() 
{
  // do 64-bits operations
}

// helper function just to hide clumsy syntax
inline void DoMyOperation() { DoMyOperationHelper<sizeof(size_t)>(); }

int main()
{
  // appropriate function will be selected at compile time 
  DoMyOperation(); 

  return 0;
}

How to make ConstraintLayout work with percentage values?

You can currently do this in a couple of ways.

One is to create guidelines (right-click the design area, then click add vertical/horizontal guideline). You can then click the guideline's "header" to change the positioning to be percentage based. Finally, you can constrain views to guidelines.

Another way is to position a view using bias (percentage) and to then anchor other views to that view.

That said, we have been thinking about how to offer percentage based dimensions. I can't make any promise but it's something we would like to add.

Difference between PACKETS and FRAMES

Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data, segment, packet, frame and bit. And the term PDU (Protocol Data Unit) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.

When we come to your question, we can call all of them by using the general term PDU, but if you want to call them specifically at a given layer:

  • Data: PDU of Application, Presentation and Session Layers
  • Segment: PDU of Transport Layer
  • Packet: PDU of network Layer
  • Frame: PDU of data-link Layer
  • Bit: PDU of physical Layer

Here is a diagram, since a picture is worth a thousand words: a picture is worth a thousand words

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Visual Studio SignTool.exe Not Found

Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.

Set session variable in laravel

I think your question ultimately can be boiled down to this:

Where can I set a long-lived value that is accessible globally in my application?

The obvious answer is that it depends. What it depends on are a couple of factors:

  • Will the value ever be different, or is it going to be the same for everybody?
  • How long exactly is long-lived? (Forever? A Day? One browsing 'session'?)

Config

If the value is the same for everyone and will seldom change, the best place to probably put it is in a configuration file somewhere underneath app/config, e.g. app/config/companyname.php:

<?php
return [
    'somevalue' => 10,
];

You could access this value from anywhere in your application via Config::get('companyname.somevalue')

Session

If the value you are intending to store is going to be different for each user, the most logical place to put it is in Session. This is what you allude to in your question, but you are using incorrect syntax. The correct syntax to store a variable in Session is:

Session::put('somekey', 'somevalue');

The correct syntax to retrieve it back out later is:

Session::get('somekey');

As far as when to perform these operations, that's a little up to you. I would probably choose a route filter if on Laravel 4.x or Middleware if using Laravel 5. Below is an example of using a route filter that leverages another class to actually come up with the value:

// File: ValueMaker.php (saved in some folder that can be autoloaded)
class ValueMaker
{
    public function makeValue()
    {
        return 42;
    }
}

// File: app/filters.php is probably the best place
Route::filter('set_value', function() {
    $valueMaker = app()->make('ValueMaker');
    Session::put('somevalue', $valueMaker->makeValue());
});

// File: app/routes.php
Route::group(['before' => 'set_value'], function() {
   // Value has already been 'made' by this point. 
   return View::make('view')
       ->with('value', Session::get('somevalue'))
   ;
});

How to use z-index in svg elements?

Move to front by transform:TranslateZ

Warning: Only works in FireFox

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160" style="width:160px; height:160px;">
    <g style="transform-style: preserve-3d;">
        <g id="one" style="transform-style: preserve-3d;">
            <circle fill="green" cx="100" cy="105" r="20" style="transform:TranslateZ(1px);"></circle>
        </g>
        <g id="two" style="transform-style: preserve-3d;">
            <circle fill="orange" cx="100" cy="95" r="20"></circle>
        </g>
    </g>
</svg>
_x000D_
_x000D_
_x000D_

Getting a directory name from a filename

Why does it have to be so complicated?

#include <windows.h>

int main(int argc, char** argv)         // argv[0] = C:\dev\test.exe
{
    char *p = strrchr(argv[0], '\\');
    if(p) p[0] = 0;

    printf(argv[0]);                    // argv[0] = C:\dev
}

push_back vs emplace_back

A nice code for the push_back and emplace_back is shown here.

http://en.cppreference.com/w/cpp/container/vector/emplace_back

You can see the move operation on push_back and not on emplace_back.

Oracle "(+)" Operator

That's Oracle specific notation for an OUTER JOIN, because the ANSI-89 format (using a comma in the FROM clause to separate table references) didn't standardize OUTER joins.

The query would be re-written in ANSI-92 syntax as:

   SELECT ...
     FROM a
LEFT JOIN b ON b.id = a.id

This link is pretty good at explaining the difference between JOINs.


It should also be noted that even though the (+) works, Oracle recommends not using it:

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions, which do not apply to the FROM clause OUTER JOIN syntax:

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

How about this:

$ seq 1 100000 | tail -n +10000 | head -n 10
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009

It uses tail to output from the 10,000th line and onwards and then head to only keep 10 lines.

The same (almost) result with sed:

$ seq 1 100000 | sed -n '10000,10010p'
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010

This one has the advantage of allowing you to input the line range directly.

You can't specify target table for update in FROM clause

You can make this in three steps:

CREATE TABLE test2 AS
SELECT PersId 
FROM pers p
WHERE (
  chefID IS NOT NULL 
  OR gehalt < (
    SELECT MAX (
      gehalt * 1.05
    )
    FROM pers MA
    WHERE MA.chefID = p.chefID
  )
)

...

UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE PersId
IN (
  SELECT PersId
  FROM test2
)
DROP TABLE test2;

or

UPDATE Pers P, (
  SELECT PersId
  FROM pers p
  WHERE (
   chefID IS NOT NULL 
   OR gehalt < (
     SELECT MAX (
       gehalt * 1.05
     )
     FROM pers MA
     WHERE MA.chefID = p.chefID
   )
 )
) t
SET P.gehalt = P.gehalt * 1.05
WHERE p.PersId = t.PersId

Trying to get property of non-object - CodeIgniter

In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.

In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.

Trying to get property of non-object

For Example:

if (!empty($this->xml_data->thing1->thing2))
{
   foreach ($this->xml_data->thing1->thing2 as $thing)
   {

   }
}

How to playback MKV video in web browser?

HTML5 does not support .mkv / Matroska files but you can use this code...

<video>
    <source src="video.mkv" type="video/mp4">
</video>

But it depends on the browser as to whether it will play or not. This method is known to work with Chrome.

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

Jquery how to find an Object by attribute in an Array

you should pass reference on item in grep function:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(item){
      return item.purpose == purposeName;
    });
};

Example

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

In chrome to set the value you need to do YYYY-MM-DD i guess because this worked : http://jsfiddle.net/HudMe/6/

So to make it work you need to set the date as 2012-10-01

How to set the custom border color of UIView programmatically?

Swift 5.2, UIView+Extension

extension UIView {
    public func addViewBorder(borderColor:CGColor,borderWith:CGFloat,borderCornerRadius:CGFloat){
        self.layer.borderWidth = borderWith
        self.layer.borderColor = borderColor
        self.layer.cornerRadius = borderCornerRadius

    }
}

You used this extension;

yourView.addViewBorder(borderColor: #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1), borderWith: 1.0, borderCornerRadius: 20)

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.


1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

How to set env variable in Jupyter notebook

If you are using systemd I just found out that you seem to have to add them to the systemd unit file. This on Ubuntu 16. Putting them into the .profile and .bashrc (even the /etc/profile) resulted in the ENV Vars not being available in the juypter notebooks.

I had to edit:

/lib/systemd/system/jupyer-notebook.service

and put in the variable i wanted to read in the unit file like:

Environment=MYOWN_VAR=theVar

and only then could I read it from within juypter notebook.

What is href="#" and why is it used?

The href attribute defines the URL of the resource of a link. If the anchor tag does not have href tag then it will not become hyperlink. The href attribute have the following values:

1. Absolute path: move to another site like href="http://www.google.com"
2. Relative path: move to another page within the site like herf ="defaultpage.aspx"
3. Move to an element with a specified id within the page like href="#bottom"
4. href="javascript:void(0)", it does not move anywhere.
5. href="#" , it does not move anywhere but scroll on the top of the current page.
6. href= "" , it will load the current page but some browsers causes forbidden errors.

Note: When we do not need to specified any url inside a anchor tag then use 
<a href="javascript:void(0)">Test1</a>

Refresh or force redraw the fragment

In my case, detach and attach worked:

 getSupportFragmentManager()
   .beginTransaction()
   .detach(contentFragment)
   .attach(contentFragment)
   .commit();

How can I get the class name from a C++ object?

An improvement for @Chubsdad answer,

//main.cpp

using namespace std;

int main(){
A a;
a.run();
}

//A.h
class A{
public:
 A(){};
 void run();
}

//A.cpp
#include <iostream>
#include <typeinfo>
void A::run(){
   cout << (string)typeid(this).name();
}

Which will print:

class A*

parsing JSONP $http.jsonp() response in angular.js

I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:

var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);

$http.jsonp(url, {jsonpCallbackParam: 'callback'})
    .then(function(data){
        console.log(data.found);
    });

Inserting a text where cursor is using Javascript/jquery

Use this, from here:

_x000D_
_x000D_
function insertAtCaret(areaId, text) {_x000D_
  var txtarea = document.getElementById(areaId);_x000D_
  if (!txtarea) {_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  var scrollPos = txtarea.scrollTop;_x000D_
  var strPos = 0;_x000D_
  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?_x000D_
    "ff" : (document.selection ? "ie" : false));_x000D_
  if (br == "ie") {_x000D_
    txtarea.focus();_x000D_
    var range = document.selection.createRange();_x000D_
    range.moveStart('character', -txtarea.value.length);_x000D_
    strPos = range.text.length;_x000D_
  } else if (br == "ff") {_x000D_
    strPos = txtarea.selectionStart;_x000D_
  }_x000D_
_x000D_
  var front = (txtarea.value).substring(0, strPos);_x000D_
  var back = (txtarea.value).substring(strPos, txtarea.value.length);_x000D_
  txtarea.value = front + text + back;_x000D_
  strPos = strPos + text.length;_x000D_
  if (br == "ie") {_x000D_
    txtarea.focus();_x000D_
    var ieRange = document.selection.createRange();_x000D_
    ieRange.moveStart('character', -txtarea.value.length);_x000D_
    ieRange.moveStart('character', strPos);_x000D_
    ieRange.moveEnd('character', 0);_x000D_
    ieRange.select();_x000D_
  } else if (br == "ff") {_x000D_
    txtarea.selectionStart = strPos;_x000D_
    txtarea.selectionEnd = strPos;_x000D_
    txtarea.focus();_x000D_
  }_x000D_
_x000D_
  txtarea.scrollTop = scrollPos;_x000D_
}
_x000D_
<textarea id="textareaid"></textarea>_x000D_
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
_x000D_
_x000D_
_x000D_

Back to previous page with header( "Location: " ); in PHP

Just try this in Javascript:

 $previous = "javascript:history.go(-1)";

Or you can try it in PHP:

if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];
}

Convert output of MySQL query to utf8

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

MySQL CURRENT_TIMESTAMP on create and on update

Guess this is a old post but actually i guess mysql supports 2 TIMESTAMP in its recent editions mysql 5.6.25 thats what im using as of now.

Converting a string to a date in JavaScript

var date = new Date(year, month, day);

or

var date = new Date('01/01/1970');

date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.

Play audio from a stream using C#

The SoundPlayer class can do this. It looks like all you have to do is set its Stream property to the stream, then call Play.

edit
I don't think it can play MP3 files though; it seems limited to .wav. I'm not certain if there's anything in the framework that can play an MP3 file directly. Everything I find about that involves either using a WMP control or interacting with DirectX.

Push git commits & tags simultaneously

Update August 2020

As mentioned originally in this answer by SoBeRich, and in my own answer, as of git 2.4.x

git push --atomic origin <branch name> <tag>

(Note: this actually work with HTTPS only with Git 2.24)

Update May 2015

As of git 2.4.1, you can do

git config --global push.followTags true

If set to true enable --follow-tags option by default.
You may override this configuration at time of push by specifying --no-follow-tags.

As noted in this thread by Matt Rogers answering Wes Hurd:

--follow-tags only pushes annotated tags.

git tag -a -m "I'm an annotation" <tagname>

That would be pushed (as opposed to git tag <tagname>, a lightweight tag, which would not be pushed, as I mentioned here)

Update April 2013

Since git 1.8.3 (April 22d, 2013), you no longer have to do 2 commands to push branches, and then to push tags:

The new "--follow-tags" option tells "git push" to push relevant annotated tags when pushing branches out.

You can now try, when pushing new commits:

git push --follow-tags

That won't push all the local tags though, only the one referenced by commits which are pushed with the git push.

Git 2.4.1+ (Q2 2015) will introduce the option push.followTags: see "How to make “git push” include tags within a branch?".

Original answer, September 2010

The nuclear option would be git push --mirror, which will push all refs under refs/.

You can also push just one tag with your current branch commit:

git push origin : v1.0.0 

You can combine the --tags option with a refspec like:

git push origin --tags :

(since --tags means: All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line)


You also have this entry "Pushing branches and tags with a single "git push" invocation"

A handy tip was just posted to the Git mailing list by Zoltán Füzesi:

I use .git/config to solve this:

[remote "origin"]
    url = ...
    fetch = +refs/heads/*:refs/remotes/origin/*
    push = +refs/heads/*
    push = +refs/tags/*

With these lines added git push origin will upload all your branches and tags. If you want to upload only some of them, you can enumerate them.

Haven't tried it myself yet, but it looks like it might be useful until some other way of pushing branches and tags at the same time is added to git push.
On the other hand, I don't mind typing:

$ git push && git push --tags

Beware, as commented by Aseem Kishore

push = +refs/heads/* will force-pushes all your branches.

This bit me just now, so FYI.


René Scheibe adds this interesting comment:

The --follow-tags parameter is misleading as only tags under .git/refs/tags are considered.
If git gc is run, tags are moved from .git/refs/tags to .git/packed-refs. Afterwards git push --follow-tags ... does not work as expected anymore.

How to format JSON in notepad++

Here are the steps to install JSToolNPP plugin on your Notepad++.

  1. Download 64bit version from Sourceforge or the 32bit version if you are on a 32-bit OS.

    64bit - JSToolNPP.1.21.0.uni.64.zip: Download from SourceForget.net
    
  2. Notepad++ before installation

does not show JSTool in the Plugins menu.

  1. Unzip the downloaded JSToolNPP.1.21.0.uni.64 and copy the JSMinNPP.dll and place it under C:\Program Files\Notepad++\plugins.

  2. Close Notepad++ and reopen it. If you have downloaded an incompatible dll, then it will complain, else it will open successfully. If it complains about incompatibility, go back to STEP 1 and download the correct bit version as per your OS. Check Plugins in Notepad++.

JSTool is now located in the Plugins menu.

  1. Paste a sample unformatted but valid JSON data in Notepad++.

  2. Select all text in Notepad++ (CTRL+A) and format using Plugins -> JSTool -> JSFormat.

NOTE: On side note, if you do not want to install any plugins like this, I would recommend using the following 2 best online formatters.

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

Using python webdriver right click operation

from selenium import webdriver

from selenium.webdriver import ActionChains

import time

driver = webdriver.Chrome()

driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html")
button=driver.find_element_by_xpath("//body[@class='wy-body-for-nav']")

action=ActionChains(driver)
action.context_click(button).perform()

Changing the "tick frequency" on x or y axis in matplotlib?

if you just want to set the spacing a simple one liner with minimal boilerplate:

plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1))

also works easily for minor ticks:

plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(1))

a bit of a mouthfull, but pretty compact

Deserializing a JSON into a JavaScript object

If you paste the string in server-side into the html don't need to do nothing:

For plain java in jsp:

var jsonObj=<%=jsonStringInJavaServlet%>;

For jsp width struts:

var jsonObj=<s:property value="jsonStringInJavaServlet" escape="false" escapeHtml="false"/>;

What does 'var that = this;' mean in JavaScript?

From Crockford

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

JS Fiddle

function usesThis(name) {
    this.myName = name;

    function returnMe() {
        return this;        //scope is lost because of the inner function
    }

    return {
        returnMe : returnMe
    }
}

function usesThat(name) {
    var that = this;
    this.myName = name;

    function returnMe() {
        return that;            //scope is baked in with 'that' to the "class"
    }

    return {
        returnMe : returnMe
    }
}

var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
      "UsesThis thinks it's called " + usesthis.returnMe().myName);

This alerts...

UsesThat thinks it's called Dave

UsesThis thinks it's called undefined

How to convert a char array to a string?

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

How do I revert an SVN commit?

Very old thread, however there is no answer for Intellij. To revert a single commit:

Go to: Subversion -> Integrate Directory...

integrate directory view

comparing two strings in ruby

From what you printed, it seems var2 is an array containing one string. Or actually, it appears to hold the result of running .inspect on an array containing one string. It would be helpful to show how you are initializing them.

irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]

How to split the filename from a full path in batch?

Parse a filename from the fully qualified path name (e.g., c:\temp\my.bat) to any component (e.g., File.ext).

Single line of code:

For %%A in ("C:\Folder1\Folder2\File.ext") do (echo %%~fA)

You can change out "C:\Folder1\Folder2\File.ext" for any full path and change "%%~fA" for any of the other options you will find by running "for /?" at the command prompt.

Elaborated Code

set "filename=C:\Folder1\Folder2\File.ext"
For %%A in ("%filename%") do (
    echo full path: %%~fA
    echo drive: %%~dA
    echo path: %%~pA
    echo file name only: %%~nA
    echo extension only: %%~xA
    echo expanded path with short names: %%~sA
    echo attributes: %%~aA
    echo date and time: %%~tA
    echo size: %%~zA
    echo drive + path: %%~dpA
    echo name.ext: %%~nxA
    echo full path + short name: %%~fsA)

Standalone Batch Script
Save as C:\cmd\ParseFn.cmd.

Add C:\cmd to your PATH environment variable and use it to store all of you reusable batch scripts.

@echo off
@echo ::___________________________________________________________________::
@echo ::                                                                   ::
@echo ::                              ParseFn                              ::
@echo ::                                                                   ::
@echo ::                           Chris Advena                            ::
@echo ::___________________________________________________________________::
@echo.

::
:: Process arguements
::
if "%~1%"=="/?" goto help
if "%~1%"=="" goto help
if "%~2%"=="/?" goto help
if "%~2%"=="" (
    echo !!! Error: ParseFn requires two inputs. !!!
    goto help)

set in=%~1%
set out=%~2%
:: echo "%in:~3,1%"   "%in:~0,1%"
if "%in:~3,1%"=="" (
    if "%in:~0,1%"=="/" (
    set in=%~2%
    set out=%~1%)
)

::
:: Parse filename
::
set "ret="
For %%A in ("%in%") do (
    if "%out%"=="/f" (set ret=%%~fA)
    if "%out%"=="/d" (set ret=%%~dA)
    if "%out%"=="/p" (set ret=%%~pA)
    if "%out%"=="/n" (set ret=%%~nA)
    if "%out%"=="/x" (set ret=%%~xA)
    if "%out%"=="/s" (set ret=%%~sA)
    if "%out%"=="/a" (set ret=%%~aA)
    if "%out%"=="/t" (set ret=%%~tA)
    if "%out%"=="/z" (set ret=%%~zA)
    if "%out%"=="/dp" (set ret=%%~dpA)
    if "%out%"=="/nx" (set ret=%%~nxA)
    if "%out%"=="/fs" (set ret=%%~fsA)
)
echo ParseFn result: %ret%
echo.

goto end
:help
@echo off
:: @echo ::___________________________________________________________________::
:: @echo ::                                                                   ::
:: @echo ::                           ParseFn Help                            ::
:: @echo ::                                                                   ::
:: @echo ::                           Chris Advena                            ::
:: @echo ::___________________________________________________________________::
@echo.
@echo ParseFn parses a fully qualified path name (e.g., c:\temp\my.bat)
@echo into the requested component, such as drive, path, filename, 
@echo extenstion, etc.
@echo.
@echo Syntax: /switch filename
@echo where,
@echo   filename is a fully qualified path name including drive, 
@echo   folder(s), file name, and extension
@echo.
@echo   Select only one switch:
@echo       /f - fully qualified path name
@echo       /d - drive letter only
@echo       /p - path only
@echo       /n - file name only
@echo       /x - extension only
@echo       /s - expanded path contains short names only
@echo       /a - attributes of file
@echo       /t - date/time of file
@echo       /z - size of file
@echo      /dp - drive + path
@echo      /nx - file name + extension
@echo      /fs - full path + short name
@echo.

:end
:: @echo ::___________________________________________________________________::
:: @echo ::                                                                   ::
:: @echo ::                         ParseFn finished                          ::
:: @echo ::___________________________________________________________________::
:: @echo.

Is there a way to access an iteration-counter in Java's for-each loop?

Idiomatic Solution:

final Set<Double> doubles; // boilerplate
final Iterator<Double> iterator = doubles.iterator();
for (int ordinal = 0; iterator.hasNext(); ordinal++)
{
    System.out.printf("%d:%f",ordinal,iterator.next());
    System.out.println();
}

this is actually the solution that Google suggests in the Guava discussion on why they did not provide a CountingIterator.

Random string generation with upper case letters and digits

I would like to suggest you next option:

import crypt
n = 10
crypt.crypt("any sring").replace('/', '').replace('.', '').upper()[-n:-1]

Paranoic mode:

import uuid
import crypt
n = 10
crypt.crypt(str(uuid.uuid4())).replace('/', '').replace('.', '').upper()[-n:-1]

implement addClass and removeClass functionality in angular2

You can basically switch the class using [ngClass]

for example

<button [ngClass]="{'active': selectedItem === 'item1'}" (click)="selectedItem = 'item1'">Button One</button>
<button [ngClass]="{'active': selectedItem === 'item2'}" (click)="selectedItem = 'item2'">Button Two</button>

Radio buttons and label to display in same line

you might have a width specified for your input tags somewhere in your css.

add a class="radio" to your radio boxes and an input.radio {width: auto;} to your css.

How to get current date in jquery?

function createDate() {
            var date    = new Date(),
                yr      = date.getFullYear(),
                month   = date.getMonth()+1,
                day     = date.getDate(),
                todayDate = yr + '-' + month + '-' + day;
            console.log("Today date is :" + todayDate);

How to fix div on scroll

On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.

Note: To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/

$(document).ready(function () {
  var $obj = $('#comment');
  var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0));

  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $obj.addClass('fixed');
    } else {
      // otherwise remove it
      $obj.removeClass('fixed');
    }
  });
});

How to schedule a task to run when shutting down windows

I had to also enable "Specify maximum wait time for group policy scripts" and "Display instructions in shutdown scripts as they run" to make it work for me as I explain here.

Iterating over JSON object in C#

This worked for me, converts to nested JSON to easy to read YAML

    string JSONDeserialized {get; set;}
    public int indentLevel;

    private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
    {
        bool bSuccess = false;
        indentLevel++;

        foreach (string strKey in dict.Keys)
        {
            string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
            JSONDeserialized+="\r\n" + strOutput;

            object o = dict[strKey];
            if (o is Dictionary<string, object>)
            {
                JSONDictionarytoYAML((Dictionary<string, object>)o);
            }
            else if (o is ArrayList)
            {
                foreach (object oChild in ((ArrayList)o))
                {
                    if (oChild is string)
                    {
                        strOutput = ((string)oChild);
                        JSONDeserialized += strOutput + ",";
                    }
                    else if (oChild is Dictionary<string, object>)
                    {
                        JSONDictionarytoYAML((Dictionary<string, object>)oChild);
                        JSONDeserialized += "\r\n";  
                    }
                }
            }
            else
            {
                strOutput = o.ToString();
                JSONDeserialized += strOutput;
            }
        }

        indentLevel--;

        return bSuccess;

    }

usage

        Dictionary<string, object> JSONDic = new Dictionary<string, object>();
        JavaScriptSerializer js = new JavaScriptSerializer();

          try {

            JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
            JSONDeserialized = "";

            indentLevel = 0;
            DisplayDictionary(JSONDic); 

            return JSONDeserialized;

        }
        catch (Exception)
        {
            return "Could not parse input JSON string";
        }

How to find the size of integer array

If the array is a global, static, or automatic variable (int array[10];), then sizeof(array)/sizeof(array[0]) works.

If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);) or passed as a function argument (void f(int array[])), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0]) compiles just fine even for the second case, but it will silently produce the wrong result.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

This is how I managed to do what I was trying to do:

[Test]
public void TransferHandlesDisconnect()
{
    // ... set up config here
    var methodTester = new Mock<Transfer>(configInfo);
    methodTester.CallBase = true;
    methodTester
        .Setup(m => 
            m.GetFile(
                It.IsAny<IFileConnection>(), 
                It.IsAny<string>(), 
                It.IsAny<string>()
            ))
        .Throws<System.IO.IOException>();

    methodTester.Object.TransferFiles("foo1", "foo2");
    Assert.IsTrue(methodTester.Object.Status == TransferStatus.TransferInterrupted);
}

If there is a problem with this method, I would like to know; the other answers suggest I am doing this wrong, but this was exactly what I was trying to do.

Java: Enum parameter in method

Sure, you could use an enum. Would something like the following work?

enum Alignment {
    LEFT,
    RIGHT
}

private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }

If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.

Retrieve all values from HashMap keys in an ArrayList Java

Java 8 solution for produce string like "key1: value1,key2: value2"

private static String hashMapToString(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.joining(","));

}

and produce a list simple collect as list

private static List<String> hashMapToList(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.toList());

}

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

How can I suppress the newline after a print statement?

Because python 3 print() function allows end="" definition, that satisfies the majority of issues.

In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:

from pprint import PrettyPrinter

class CommaEndingPrettyPrinter(PrettyPrinter):
    def pprint(self, object):
        self._format(object, self._stream, 0, 0, {}, 0)
        # this is where to tell it what you want instead of the default "\n"
        self._stream.write(",\n")

def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
    """Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
    printer = CommaEndingPrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth)
    printer.pprint(object)

Now, when I do:

comma_ending_prettyprint(row, stream=outfile)

I get what I wanted (substitute what you want -- Your Mileage May Vary)

Input group - two inputs close to each other

working workaround:

<div class="input-group">
    <input type="text" class="form-control input-sm" value="test1" />
    <span class="input-group-btn" style="width:0px;"></span>
    <input type="text" class="form-control input-sm" value="test2" />
</div>

downside: no border-collapse between the two text-fields, but they keep next to each other

http://jsfiddle.net/EfC26/

Update

thanks to Stalinko

This technique allows to glue more than 2 inputs. Border-collapsing is achieved using "margin-left: -1px" (-2px for the 3rd input and so on)

<div class="input-group">
  <input type="text" class="form-control input-sm" value="test1" />
  <span class="input-group-btn" style="width:0px;"></span>
  <input type="text" class="form-control input-sm" value="test2" style="margin-left:-1px" />
  <span class="input-group-btn" style="width:0px;"></span>
  <input type="text" class="form-control input-sm" value="test2" style="margin-left:-2px" />
</div>

http://jsfiddle.net/yLvk5mn1/1/

R: Break for loop

your break statement should break out of the for (in in 1:n).

Personally I am always wary with break statements and double check it by printing to the console to double check that I am in fact breaking out of the right loop. So before you test add the following statement, which will let you know if you break before it reaches the end. However, I have no idea how you are handling the variable n so I don't know if it would be helpful to you. Make a n some test value where you know before hand if it is supposed to break out or not before reaching n.

for (in in 1:n)
{
    if (in == n)         #add this statement
    {
        "sorry but the loop did not break"
    }

    id_novo <- new_table_df$ID[in]
    if(id_velho==id_novo)
    {
        break
    }
    else if(in == n)
    {
        sold_df <- rbind(sold_df,old_table_df[out,])
    }
}

jQuery Get Selected Option From Dropdown

Use the jQuery.val() function for select elements, too:

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

_x000D_
_x000D_
$(function() {_x000D_
  $("#aioConceptName").on("change", function() {_x000D_
    $("#debug").text($("#aioConceptName").val());_x000D_
  }).trigger("change");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<select id="aioConceptName">_x000D_
  <option>choose io</option>_x000D_
  <option>roma</option>_x000D_
  <option>totti</option>_x000D_
</select>_x000D_
<div id="debug"></div>
_x000D_
_x000D_
_x000D_

MySQL "WITH" clause

Have you ever tried Temporary Table? This solved my convern:

create temporary table abc (
column1 varchar(255)
column2 decimal
);
insert into abc
select ...
or otherwise
insert into abc
values ('text', 5.5), ('text2', 0815.8);

Then you can use this table in every select in this session:

select * from abc inner join users on ...;

How to use hex() without 0x in Python?

Use this code:

'{:x}'.format(int(line))

it allows you to specify a number of digits too:

'{:06x}'.format(123)
# '00007b'

For Python 2.6 use

'{0:x}'.format(int(line))

or

'{0:06x}'.format(int(line))

Serialize and Deserialize Json and Json Array in Unity

You can use Newtonsoft.Json just add Newtonsoft.dll to your project and use below script

using System;
using Newtonsoft.Json;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{

    [Serializable]
    public class Person
    {
        public string id;
        public string name;
    }
    public Person[] person;

    private void Start()
    {
       var myjson = JsonConvert.SerializeObject(person);

        print(myjson);

    }
}

enter image description here

another solution is using JsonHelper

using System;
using Newtonsoft.Json;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{

    [Serializable]
    public class Person
    {
        public string id;
        public string name;
    }
    public Person[] person;

    private void Start()
    {
        var myjson = JsonHelper.ToJson(person);

        print(myjson);

    }
}

enter image description here

How should a model be structured in MVC?

Disclaimer: the following is a description of how I understand MVC-like patterns in the context of PHP-based web applications. All the external links that are used in the content are there to explain terms and concepts, and not to imply my own credibility on the subject.

The first thing that I must clear up is: the model is a layer.

Second: there is a difference between classical MVC and what we use in web development. Here's a bit of an older answer I wrote, which briefly describes how they are different.

What a model is NOT:

The model is not a class or any single object. It is a very common mistake to make (I did too, though the original answer was written when I began to learn otherwise), because most frameworks perpetuate this misconception.

Neither is it an Object-Relational Mapping technique (ORM) nor an abstraction of database tables. Anyone who tells you otherwise is most likely trying to 'sell' another brand-new ORM or a whole framework.

What a model is:

In proper MVC adaptation, the M contains all the domain business logic and the Model Layer is mostly made from three types of structures:

  • Domain Objects

    A domain object is a logical container of purely domain information; it usually represents a logical entity in the problem domain space. Commonly referred to as business logic.

    This would be where you define how to validate data before sending an invoice, or to compute the total cost of an order. At the same time, Domain Objects are completely unaware of storage - neither from where (SQL database, REST API, text file, etc.) nor even if they get saved or retrieved.

  • Data Mappers

    These objects are only responsible for the storage. If you store information in a database, this would be where the SQL lives. Or maybe you use an XML file to store data, and your Data Mappers are parsing from and to XML files.

  • Services

    You can think of them as "higher level Domain Objects", but instead of business logic, Services are responsible for interaction between Domain Objects and Mappers. These structures end up creating a "public" interface for interacting with the domain business logic. You can avoid them, but at the penalty of leaking some domain logic into Controllers.

    There is a related answer to this subject in the ACL implementation question - it might be useful.

The communication between the model layer and other parts of the MVC triad should happen only through Services. The clear separation has a few additional benefits:

  • it helps to enforce the single responsibility principle (SRP)
  • provides additional 'wiggle room' in case the logic changes
  • keeps the controller as simple as possible
  • gives a clear blueprint, if you ever need an external API

 

How to interact with a model?

Prerequisites: watch lectures "Global State and Singletons" and "Don't Look For Things!" from the Clean Code Talks.

Gaining access to service instances

For both the View and Controller instances (what you could call: "UI layer") to have access these services, there are two general approaches:

  1. You can inject the required services in the constructors of your views and controllers directly, preferably using a DI container.
  2. Using a factory for services as a mandatory dependency for all of your views and controllers.

As you might suspect, the DI container is a lot more elegant solution (while not being the easiest for a beginner). The two libraries, that I recommend considering for this functionality would be Syfmony's standalone DependencyInjection component or Auryn.

Both the solutions using a factory and a DI container would let you also share the instances of various servers to be shared between the selected controller and view for a given request-response cycle.

Alteration of model's state

Now that you can access to the model layer in the controllers, you need to start actually using them:

public function postLogin(Request $request)
{
    $email = $request->get('email');
    $identity = $this->identification->findIdentityByEmailAddress($email);
    $this->identification->loginWithPassword(
        $identity,
        $request->get('password')
    );
}

Your controllers have a very clear task: take the user input and, based on this input, change the current state of business logic. In this example the states that are changed between are "anonymous user" and "logged in user".

Controller is not responsible for validating user's input, because that is part of business rules and controller is definitely not calling SQL queries, like what you would see here or here (please don't hate on them, they are misguided, not evil).

Showing user the state-change.

Ok, user has logged in (or failed). Now what? Said user is still unaware of it. So you need to actually produce a response and that is the responsibility of a view.

public function postLogin()
{
    $path = '/login';
    if ($this->identification->isUserLoggedIn()) {
        $path = '/dashboard';
    }
    return new RedirectResponse($path); 
}

In this case, the view produced one of two possible responses, based on the current state of model layer. For a different use-case you would have the view picking different templates to render, based on something like "current selected of article" .

The presentation layer can actually get quite elaborate, as described here: Understanding MVC Views in PHP.

But I am just making a REST API!

Of course, there are situations, when this is a overkill.

MVC is just a concrete solution for Separation of Concerns principle. MVC separates user interface from the business logic, and it in the UI it separated handling of user input and the presentation. This is crucial. While often people describe it as a "triad", it's not actually made up from three independent parts. The structure is more like this:

MVC separation

It means, that, when your presentation layer's logic is close to none-existent, the pragmatic approach is to keep them as single layer. It also can substantially simplify some aspects of model layer.

Using this approach the login example (for an API) can be written as:

public function postLogin(Request $request)
{
    $email = $request->get('email');
    $data = [
        'status' => 'ok',
    ];
    try {
        $identity = $this->identification->findIdentityByEmailAddress($email);
        $token = $this->identification->loginWithPassword(
            $identity,
            $request->get('password')
        );
    } catch (FailedIdentification $exception) {
        $data = [
            'status' => 'error',
            'message' => 'Login failed!',
        ]
    }

    return new JsonResponse($data);
}

While this is not sustainable, when you have complicate logic for rendering a response body, this simplification is very useful for more trivial scenarios. But be warned, this approach will become a nightmare, when attempting to use in large codebases with complex presentation logic.

 

How to build the model?

Since there is not a single "Model" class (as explained above), you really do not "build the model". Instead you start from making Services, which are able to perform certain methods. And then implement Domain Objects and Mappers.

An example of a service method:

In the both approaches above there was this login method for the identification service. What would it actually look like. I am using a slightly modified version of the same functionality from a library, that I wrote .. because I am lazy:

public function loginWithPassword(Identity $identity, string $password): string
{
    if ($identity->matchPassword($password) === false) {
        $this->logWrongPasswordNotice($identity, [
            'email' => $identity->getEmailAddress(),
            'key' => $password, // this is the wrong password
        ]);

        throw new PasswordMismatch;
    }

    $identity->setPassword($password);
    $this->updateIdentityOnUse($identity);
    $cookie = $this->createCookieIdentity($identity);

    $this->logger->info('login successful', [
        'input' => [
            'email' => $identity->getEmailAddress(),
        ],
        'user' => [
            'account' => $identity->getAccountId(),
            'identity' => $identity->getId(),
        ],
    ]);

    return $cookie->getToken();
}

As you can see, at this level of abstraction, there is no indication of where the data was fetched from. It might be a database, but it also might be just a mock object for testing purposes. Even the data mappers, that are actually used for it, are hidden away in the private methods of this service.

private function changeIdentityStatus(Entity\Identity $identity, int $status)
{
    $identity->setStatus($status);
    $identity->setLastUsed(time());
    $mapper = $this->mapperFactory->create(Mapper\Identity::class);
    $mapper->store($identity);
}

Ways of creating mappers

To implement an abstraction of persistence, on the most flexible approaches is to create custom data mappers.

Mapper diagram

From: PoEAA book

In practice they are implemented for interaction with specific classes or superclasses. Lets say you have Customer and Admin in your code (both inheriting from a User superclass). Both would probably end up having a separate matching mapper, since they contain different fields. But you will also end up with shared and commonly used operations. For example: updating the "last seen online" time. And instead of making the existing mappers more convoluted, the more pragmatic approach is to have a general "User Mapper", which only update that timestamp.

Some additional comments:

  1. Database tables and model

    While sometimes there is a direct 1:1:1 relationship between a database table, Domain Object, and Mapper, in larger projects it might be less common than you expect:

    • Information used by a single Domain Object might be mapped from different tables, while the object itself has no persistence in the database.

      Example: if you are generating a monthly report. This would collect information from different of tables, but there is no magical MonthlyReport table in the database.

    • A single Mapper can affect multiple tables.

      Example: when you are storing data from the User object, this Domain Object could contain collection of other domain objects - Group instances. If you alter them and store the User, the Data Mapper will have to update and/or insert entries in multiple tables.

    • Data from a single Domain Object is stored in more than one table.

      Example: in large systems (think: a medium-sized social network), it might be pragmatic to store user authentication data and often-accessed data separately from larger chunks of content, which is rarely required. In that case you might still have a single User class, but the information it contains would depend of whether full details were fetched.

    • For every Domain Object there can be more than one mapper

      Example: you have a news site with a shared codebased for both public-facing and the management software. But, while both interfaces use the same Article class, the management needs a lot more info populated in it. In this case you would have two separate mappers: "internal" and "external". Each performing different queries, or even use different databases (as in master or slave).

  2. A view is not a template

    View instances in MVC (if you are not using the MVP variation of the pattern) are responsible for the presentational logic. This means that each View will usually juggle at least a few templates. It acquires data from the Model Layer and then, based on the received information, chooses a template and sets values.

    One of the benefits you gain from this is re-usability. If you create a ListView class, then, with well-written code, you can have the same class handing the presentation of user-list and comments below an article. Because they both have the same presentation logic. You just switch templates.

    You can use either native PHP templates or use some third-party templating engine. There also might be some third-party libraries, which are able to fully replace View instances.

  3. What about the old version of the answer?

    The only major change is that, what is called Model in the old version, is actually a Service. The rest of the "library analogy" keeps up pretty well.

    The only flaw that I see is that this would be a really strange library, because it would return you information from the book, but not let you touch the book itself, because otherwise the abstraction would start to "leak". I might have to think of a more fitting analogy.

  4. What is the relationship between View and Controller instances?

    The MVC structure is composed of two layers: ui and model. The main structures in the UI layer are views and controller.

    When you are dealing with websites that use MVC design pattern, the best way is to have 1:1 relation between views and controllers. Each view represents a whole page in your website and it has a dedicated controller to handle all the incoming requests for that particular view.

    For example, to represent an opened article, you would have \Application\Controller\Document and \Application\View\Document. This would contain all the main functionality for UI layer, when it comes to dealing with articles (of course you might have some XHR components that are not directly related to articles).

how to get a list of dates between two dates in java

Here is my method for getting dates between two dates, including / w.o. including business days. It also takes source and desired date format as parameter.

public static List<String> getAllDatesBetweenTwoDates(String stdate,String enddate,String givenformat,String resultformat,boolean onlybunessdays) throws ParseException{
        DateFormat sdf;
        DateFormat sdf1;
        List<Date> dates = new ArrayList<Date>();
        List<String> dateList = new ArrayList<String>();
          SimpleDateFormat checkformat = new SimpleDateFormat(resultformat); 
          checkformat.applyPattern("EEE");  // to get Day of week
        try{
            sdf = new SimpleDateFormat(givenformat);
            sdf1 = new SimpleDateFormat(resultformat);
            stdate=sdf1.format(sdf.parse(stdate));
            enddate=sdf1.format(sdf.parse(enddate));

            Date  startDate = (Date)sdf1.parse( stdate); 
            Date  endDate = (Date)sdf1.parse( enddate);
            long interval = 24*1000 * 60 * 60; // 1 hour in millis
            long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
            long curTime = startDate.getTime();
            while (curTime <= endTime) {
                dates.add(new Date(curTime));
                curTime += interval;
            }
            for(int i=0;i<dates.size();i++){
                Date lDate =(Date)dates.get(i);
                String ds = sdf1.format(lDate);   
                if(onlybunessdays){
                    String day= checkformat.format(lDate); 
                    if(!day.equalsIgnoreCase("Sat") && !day.equalsIgnoreCase("Sun")){
                          dateList.add(ds);
                    }
                }else{
                      dateList.add(ds);
                }

                //System.out.println(" Date is ..." + ds);

            }


        }catch(ParseException e){
            e.printStackTrace();
            throw e;
        }finally{
            sdf=null;
            sdf1=null;
        }
        return dateList;
    }

And the method call would be like :

public static void main(String aregs[]) throws Exception {
        System.out.println(getAllDatesBetweenTwoDates("2015/09/27","2015/10/05","yyyy/MM/dd","dd-MM-yyyy",false));
    }

You can find the demo code : Click Here

Updating state on props change in React Form

It's quite clearly from their docs:

If you used componentWillReceiveProps for re-computing some data only when a prop changes, use a memoization helper instead.

Use: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization

What is the meaning of @_ in Perl?

@ is used for an array.

In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function:

sub Average{

    # Get total number of arguments passed.
    $n = scalar(@_);
    $sum = 0;

    foreach $item (@_){

        # foreach is like for loop... It will access every
        # array element by an iterator
        $sum += $item;
    }

    $average = $sum / $n;

    print "Average for the given numbers: $average\n";
}

Function call

Average(10, 20, 30);

If you observe the above code, see the foreach $item(@_) line... Here it passes the input parameter.

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

jQuery .search() to any string

search() is a String method.

You are executing the attr function on every <li> element. You need to invoke each and use the this reference within.

Example:

$('li').each(function() {
    var isFound = $(this).attr('title').search(/string/i);
    //do something based on isFound...
});

python's re: return True if string contains regex pattern

Here's a function that does what you want:

import re

def is_match(regex, text):
    pattern = re.compile(regex, text)
    return pattern.search(text) is not None

The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.

Examples:

>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Centering in CSS Grid

You can use flexbox to center your text. By the way no need for extra containers because text is considered as anonymous flex item.

From flexbox specs:

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space (i.e. characters that can be affected by the white-space property) is not rendered (just as if it were display:none).

So just make grid items as flex containers (display: flex), and add align-items: center and justify-content: center to center both vertically and horizontally.

Also performed optimization of HTML and CSS:

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-template-rows: 100vh;_x000D_
  _x000D_
  font-family: Raleway;_x000D_
  font-size: large;_x000D_
}_x000D_
_x000D_
.left_bg,_x000D_
.right_bg {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
  background-color: #3498db;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
  background-color: #ecf0f1;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left_bg">Review my stuff</div>_x000D_
  <div class="right_bg">Hire me!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the use of a private static variable in Java?

When in a static method you use a variable, the variable have to be static too as an example:

private static int a=0;  
public static void testMethod() {  
        a=1;  
}

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This error is caused by:

Y = Dataset.iloc[:,18].values

Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.

How to use regex in String.contains() method in Java

If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -

    private static final validPattern =   "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
    Pattern pattern = Pattern.compile(validPattern);
    Matcher matcher = pattern.matcher(inputString);
    System.out.print(matcher.find()); // should print true or false.

Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.

Find and replace words/lines in a file

This is the sort of thing I'd normally use a scripting language for. It's very useful to have the ability to perform these sorts of transformations very simply using something like Ruby/Perl/Python (insert your favorite scripting language here).

I wouldn't normally use Java for this since it's too heavyweight in terms of development cycle/typing etc.

Note that if you want to be particular in manipulating XML, it's advisable to read the file as XML and manipulate it as such (the above scripting languages have very useful and simple APIs for doing this sort of work). A simple text search/replace can invalidate your file in terms of character encoding etc. As always, it depends on the complexity of your search/replace requirements.

Seeding the random number generator in Javascript

Here's the adopted version of Jenkins hash, borrowed from here

export function createDeterministicRandom(): () => number {
  let seed = 0x2F6E2B1;
  return function() {
    // Robert Jenkins’ 32 bit integer hash function
    seed = ((seed + 0x7ED55D16) + (seed << 12))  & 0xFFFFFFFF;
    seed = ((seed ^ 0xC761C23C) ^ (seed >>> 19)) & 0xFFFFFFFF;
    seed = ((seed + 0x165667B1) + (seed << 5))   & 0xFFFFFFFF;
    seed = ((seed + 0xD3A2646C) ^ (seed << 9))   & 0xFFFFFFFF;
    seed = ((seed + 0xFD7046C5) + (seed << 3))   & 0xFFFFFFFF;
    seed = ((seed ^ 0xB55A4F09) ^ (seed >>> 16)) & 0xFFFFFFFF;
    return (seed & 0xFFFFFFF) / 0x10000000;
  };
}

You can use it like this:

const deterministicRandom = createDeterministicRandom()
deterministicRandom()
// => 0.9872818551957607

deterministicRandom()
// => 0.34880331158638

403 Forbidden error when making an ajax Post request in Django framework

Make sure you aren't caching the page/view that your form is showing up on. It could be caching your CSRF_TOKEN. Happened to me!

C++/CLI Converting from System::String^ to std::string

I spent hours trying to convert a windows form listbox ToString value to a standard string so that I could use it with fstream to output to a txt file. My Visual Studio didn't come with marshal header files which several answers I found said to use. After so much trial and error I finally found a solution to the problem that just uses System::Runtime::InteropServices:

void MarshalString ( String ^ s, string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars = 
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

//this is the code to use the function:
scheduleBox->SetSelected(0,true);
string a = "test";
String ^ c = gcnew String(scheduleBox->SelectedItem->ToString());
MarshalString(c, a);
filestream << a;

And here is the MSDN page with the example: http://msdn.microsoft.com/en-us/library/1b4az623(v=vs.80).aspx

I know it's a pretty simple solution but this took me HOURS of troubleshooting and visiting several forums to finally find something that worked.

Getting values from query string in an url using AngularJS $location

If your $location.search() is not working, then make sure you have the following:

1) html5Mode(true) is configured in app's module config

appModule.config(['$locationProvider', function($locationProvider) {
   $locationProvider.html5Mode(true);
}]);

2) <base href="/"> is present in your HTML

<head>
  <base href="/">
  ...
</head>

References:

  1. base href="/"
  2. html5Mode