Programs & Examples On #Vertical partitioning

Removing viewcontrollers from navigation stack

Using setViewControllers function from UINavigationController is the best way. There is also animated parameter to enable animation.

func setViewControllers(_ viewControllers: [UIViewController], animated: Bool)

Example in swift for question

func goToFifthVC() {

    var currentVCStack = self.navigationController?.viewControllers
    currentVCStack?.removeSubrange(2...3)

    let fifthVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "fifthVC")
    currentVCStack?.append(fifthVC)

    self.navigationController?.setViewControllers(currentVCStack!, animated: true)
}

I tried other ways like [tempVC removeFromParentViewController];. It make weird behaviour, removed ViewController navigation still showing when pop back like reported by @robin-ellerkmann

Calling a class function inside of __init__

If I'm not wrong, both functions are part of your class, you should use it like this:

class MyClass():
    def __init__(self, filename):
        self.filename = filename 

        self.stat1 = None
        self.stat2 = None
        self.stat3 = None
        self.stat4 = None
        self.stat5 = None
        self.parse_file()

    def parse_file(self):
        #do some parsing
        self.stat1 = result_from_parse1
        self.stat2 = result_from_parse2
        self.stat3 = result_from_parse3
        self.stat4 = result_from_parse4
        self.stat5 = result_from_parse5

replace your line:

parse_file() 

with:

self.parse_file()

How do I mock an autowired @Value field in Spring with Mockito?

You can use the magic of Spring's ReflectionTestUtils.setField in order to avoid making any modifications whatsoever to your code.

The comment from Michal Stochmal provides an example:

use ReflectionTestUtils.setField(bean, "fieldName", "value"); before invoking your bean method during test.

Check out this tutorial for even more information, although you probably won't need it since the method is very easy to use

UPDATE

Since the introduction of Spring 4.2.RC1 it is now possible to set a static field without having to supply an instance of the class. See this part of the documentation and this commit.

Mysql service is missing

Go to

C:\Program Files\MySQL\MySQL Server 5.2\bin

then Open MySQLInstanceConfig file

then complete the wizard.

Click finish

Solve the problem

I think this is the best way to change the port number also.

It works for me

ExecuteNonQuery: Connection property has not been initialized.

just try this..

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

How to use Tomcat 8 in Eclipse?

I follow Jason's step, but not works.

And then I find the WTP Update site http://download.eclipse.org/webtools/updates/.

Help -> Install new software -> Add > WTP:http://download.eclipse.org/webtools/updates/ -> OK

Then Help -> Check for update, just works, I don't know whether Jason's affect this .

Converting String to "Character" array in Java

I used the StringReader class in java.io. One of it's functions read(char[] cbuf) reads a string's contents into an array.

String str = "hello";
char[] array = new char[str.length()];
StringReader read = new StringReader(str);

try {
    read.read(array); //Reads string into the array. Throws IOException
} catch (IOException e) {
    e.printStackTrace();
}

for (int i = 0; i < str.length(); i++) {
        System.out.println("array["+i+"] = "+array[i]);
}

Running this gives you the output:

array[0] = h
array[1] = e
array[2] = l
array[3] = l
array[4] = o

Interview question: Check if one string is a rotation of other string

Join string1 with string2 and use KMP algorithm to check whether string2 is present in newly formed string. Because time complexity of KMP is lesser than substr.

What is a Windows Handle?

A HANDLE is a context-specific unique identifier. By context-specific, I mean that a handle obtained from one context cannot necessarily be used in any other aribtrary context that also works on HANDLEs.

For example, GetModuleHandle returns a unique identifier to a currently loaded module. The returned handle can be used in other functions that accept module handles. It cannot be given to functions that require other types of handles. For example, you couldn't give a handle returned from GetModuleHandle to HeapDestroy and expect it to do something sensible.

The HANDLE itself is just an integral type. Usually, but not necessarily, it is a pointer to some underlying type or memory location. For example, the HANDLE returned by GetModuleHandle is actually a pointer to the base virtual memory address of the module. But there is no rule stating that handles must be pointers. A handle could also just be a simple integer (which could possibly be used by some Win32 API as an index into an array).

HANDLEs are intentionally opaque representations that provide encapsulation and abstraction from internal Win32 resources. This way, the Win32 APIs could potentially change the underlying type behind a HANDLE, without it impacting user code in any way (at least that's the idea).

Consider these three different internal implementations of a Win32 API that I just made up, and assume that Widget is a struct.

Widget * GetWidget (std::string name)
{
    Widget *w;

    w = findWidget(name);

    return w;
}
void * GetWidget (std::string name)
{
    Widget *w;

    w = findWidget(name);

    return reinterpret_cast<void *>(w);
}
typedef void * HANDLE;

HANDLE GetWidget (std::string name)
{
    Widget *w;

    w = findWidget(name);

    return reinterpret_cast<HANDLE>(w);
}

The first example exposes the internal details about the API: it allows the user code to know that GetWidget returns a pointer to a struct Widget. This has a couple of consequences:

  • the user code must have access to the header file that defines the Widget struct
  • the user code could potentially modify internal parts of the returned Widget struct

Both of these consequences may be undesirable.

The second example hides this internal detail from the user code, by returning just void *. The user code doesn't need access to the header that defines the Widget struct.

The third example is exactly the same as the second, but we just call the void * a HANDLE instead. Perhaps this discourages user code from trying to figure out exactly what the void * points to.

Why go through this trouble? Consider this fourth example of a newer version of this same API:

typedef void * HANDLE;

HANDLE GetWidget (std::string name)
{
    NewImprovedWidget *w;

    w = findImprovedWidget(name);

    return reinterpret_cast<HANDLE>(w);
}

Notice that the function's interface is identical to the third example above. This means that user code can continue to use this new version of the API, without any changes, even though the "behind the scenes" implementation has changed to use the NewImprovedWidget struct instead.

The handles in these example are really just a new, presumably friendlier, name for void *, which is exactly what a HANDLE is in the Win32 API (look it up at MSDN). It provides an opaque wall between the user code and the Win32 library's internal representations that increases portability, between versions of Windows, of code that uses the Win32 API.

How to detect orientation change?

I like checking the orientation notification because you can add this feature in any class, no needs to be a view or a view controller. Even in your app delegate.

SWIFT 5:

    //ask the system to start notifying when interface change
    UIDevice.current.beginGeneratingDeviceOrientationNotifications()
    //add the observer
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(orientationChanged(notification:)),
        name: UIDevice.orientationDidChangeNotification,
        object: nil)

than caching the notification

    @objc func orientationChanged(notification : NSNotification) {
        //your code there
    }

ImportError: No module named 'MySQL'

The silly mistake I had done was keeping mysql.py in same dir. Try renaming mysql.py to another name so python don't consider that as module.

using scp in terminal

I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.

scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop

The username@remotecomputer is the same string you used with ssh initially.

Break or return from Java 8 stream forEach?

public static void main(String[] args) {
    List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");
    AtomicBoolean yes = new AtomicBoolean(true);
    list.stream().takeWhile(value -> yes.get()).forEach(value -> {
        System.out.println("prior cond" + value);
        if (value.equals("two")) {
            System.out.println(value);
            yes.set(false);
        }

    });
    //System.out.println("Hello World");
}

Ternary operator ?: vs if...else

They are the same, however, the ternary operator can be used in places where it is difficult to use a if/else:

printf("Total: %d item%s", cnt, cnt != 1 ? "s" : "");

Doing that statement with an if/else, would generate a very different compiled code.


Update after 8 years...

Actually, I think this would be better:

printf(cnt == 1 ? "Total: %d item" : "Total: %d items", cnt);

(actually, I'm pretty sure you can replace the "%d" in the first string with "one")

Unable to begin a distributed transaction

For me, it relate to Firewall setting. Go to your firewall setting, allow DTC Service and it worked.enter image description here

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

Bash script to run php script

A previous poster said..

If you have PHP installed as a command line tool… your shebang (#!) line needs to look like this: #!/usr/bin/php

While this could be true… just because you can type in php does NOT necessarily mean that's where php is going to be... /usr/bin/php is A common location… but as with any shebang… it needs to be tailored to YOUR env.

a quick way to find out WHERE YOUR particular executable is located on your $PATH, try.. ?which -a php ENTER, which for me looks like..

php is /usr/local/php5/bin/php
php is /usr/bin/php
php is /usr/local/bin/php
php is /Library/WebServer/CGI-Executables/php

The first one is the default i'd get if I just typed in php at a command prompt… but I can use any of them in a shebang, or directly… You can also combine the executable name with env, as is often seen, but I don't really know much about / trust that. XOXO.

Tools: replace not replacing in Android manifest

I was receiving a similar error on a project I was importing:

Multiple entries with same key: android:icon=REPLACE and tools:icon=REPLACE

Fixed after changing the below line within the application tag:

tools:replace="icon, label, theme"

to

tools:replace="android:icon, android:label, android:theme"

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

<a href="page.html" onclick="return false" style="cursor:default;">page link</a>

How to vertically center <div> inside the parent element with CSS?

If you know the height, you can use absolute positioning with a negative margin-top like so:

#Login {
    width:400px;
    height:400px;
    position:absolute;
    top:50%;
    left:50%;
    margin-left:-200px; /* width / -2 */
    margin-top:-200px; /* height / -2 */
}

Otherwise, there's no real way to vertically center a div with just CSS

The following untracked working tree files would be overwritten by merge, but I don't care

The only commands that worked for me were:

git fetch --all
git reset --hard origin/{{your branch name}}

Difference between h:button and h:commandButton

h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:

<h:form>
    <h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>

this code generates the follwing html:

<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">

whereas the h:button is simpler and just used for static or rule based navigation as follows

<h:button outcome="page.xhtml" value="button"/>

the generated html is

 <title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />

CSS Div width percentage and padding without breaking layout

Try removing the position from header and add overflow to container:

#container {
    position:relative;
    width:80%;
    height:auto;
    overflow:auto;
}
#header {
    width:80%;
    height:50px;
    padding:10px;
}

python: restarting a loop

Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).

Count number of days between two dates

None of the previous answers (to this date) gives the correct difference in days between two dates.

The one that comes closest is by thatdankent. A full answer would convert to_i and then divide:

(Time.now.to_i - 23.hours.ago.to_i) / 86400
>> 0

(Time.now.to_i - 25.hours.ago.to_i) / 86400
>> 1

(Time.now.to_i - 1.day.ago.to_i) / 86400
>> 1

In the question's specific example, one should not parse to Date if the time passed is relevant. Use Time.parse instead.

How to handle calendar TimeZones using Java?

public static Calendar convertToGmt(Calendar cal) {

    Date date = cal.getTime();
    TimeZone tz = cal.getTimeZone();

    log.debug("input calendar has date [" + date + "]");

    //Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT 
    long msFromEpochGmt = date.getTime();

    //gives you the current offset in ms from GMT at the current date
    int offsetFromUTC = tz.getOffset(msFromEpochGmt);
    log.debug("offset is " + offsetFromUTC);

    //create a new calendar in GMT timezone, set to this date and add the offset
    Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    gmtCal.setTime(date);
    gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);

    log.debug("Created GMT cal with date [" + gmtCal.getTime() + "]");

    return gmtCal;
}

Here's the output if I pass the current time ("12:09:05 EDT" from Calendar.getInstance()) in:

DEBUG - input calendar has date [Thu Oct 23 12:09:05 EDT 2008]
DEBUG - offset is -14400000
DEBUG - Created GMT cal with date [Thu Oct 23 08:09:05 EDT 2008]

12:09:05 GMT is 8:09:05 EDT.

The confusing part here is that Calendar.getTime() returns you a Date in your current timezone, and also that there is no method to modify the timezone of a calendar and have the underlying date rolled also. Depending on what type of parameter your web service takes, your may just want to have the WS deal in terms of milliseconds from epoch.

How to output HTML from JSP <%! ... %> block?

You can do something like this:

<%!
String myMethod(String input) {
    return "test " + input;
}
%>

<%= myMethod("1 2 3") %>

This will output test 1 2 3 to the page.

Build android release apk on Phonegap 3.x CLI

i got this to work by copy pasting the signed app in the same dir as zipalign. It seems that aapt.exe could not find the source file even when given the path. i.e. this did not work zipalign -f -v 4 C:...\CordovaApp-release-unsigned.apk C:...\destination.apk it reached aapt.exeCordovaApp-release-unsigned.apk , froze and upon hitting return 'aapt.exeCordovaApp-release-unsigned.apk' is not recognized as an internal or external command, operable program or batch file. And this did zipalign -f -v 4 CordovaApp-release-unsigned.apk myappname.apk

How to retrieve records for last 30 minutes in MS SQL?

Use:

SELECT * 
FROM [Janus999DB].[dbo].[tblCustomerPlay] 
WHERE DatePlayed <  GetDate() 
AND DatePlayed > dateadd(minute, -30, GetDate())

Add new value to an existing array in JavaScript

There are several ways:

Instantiating the array:

var arr;

arr = new Array(); // empty array

// ---

arr = [];          // empty array

// ---

arr = new Array(3);
alert(arr.length);  // 3
alert(arr[0]); // undefined

// ---

arr = [3];
alert(arr.length);  // 1
alert(arr[0]); // 3

Pushing to the array:

arr = [3];     // arr == [3]
arr[1] = 4;    // arr == [3, 4]
arr[2] = 5;    // arr == [3, 4, 5]
arr[4] = 7;    // arr == [3, 4, 5, undefined, 7]

// ---

arr = [3];
arr.push(4);        // arr == [3, 4]
arr.push(5);        // arr == [3, 4, 5]
arr.push(6, 7, 8);  // arr == [3, 4, 5, 6, 7, 8]

Using .push() is the better way to add to an array, since you don't need to know how many items are already there, and you can add many items in one function call.

Change x axes scale in matplotlib

This is not so much an answer to your original question as to one of the queries you had in the body of your question.

A little preamble, so that my naming doesn't seem strange:

import matplotlib
from matplotlib import rc
from matplotlib.figure import Figure
ax = self.figure.add_subplot( 111 )

As has been mentioned you can use ticklabel_format to specify that matplotlib should use scientific notation for large or small values:

ax.ticklabel_format(style='sci',scilimits=(-3,4),axis='both')

You can affect the way that this is displayed using the flags in rcParams (from matplotlib import rcParams) or by setting them directly. I haven't found a more elegant way of changing between '1e' and 'x10^' scientific notation than:

ax.xaxis.major.formatter._useMathText = True

This should give you the more Matlab-esc, and indeed arguably better appearance. I think the following should do the same:

rc('text', usetex=True)

SQL update fields of one table from fields of another one

Not necessarily what you asked, but maybe using postgres inheritance might help?

CREATE TABLE A (
    ID            int,
    column1       text,
    column2       text,
    column3       text
);

CREATE TABLE B (
    column4       text
) INHERITS (A);

This avoids the need to update B.

But be sure to read all the details.

Otherwise, what you ask for is not considered a good practice - dynamic stuff such as views with SELECT * ... are discouraged (as such slight convenience might break more things than help things), and what you ask for would be equivalent for the UPDATE ... SET command.

How to read single Excel cell value

using Microsoft.Office.Interop.Excel;

string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.ActiveSheet;

//Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();

wb.Close();

This example used the 'Microsoft Excel 15.0 Object Library' but may be compatible with earlier versions of Interop and other libraries.

How to get N rows starting from row M from sorted table in T-SQL

Probably good for small results, works in all versions of TSQL:

SELECT 
        * 
FROM
     (SELECT TOP (N) * 
      FROM 
            (SELECT TOP (M + N - 1) 
             FROM 
                   Table
             ORDER BY 
                      MyColumn) qasc
      ORDER BY 
               MyColumn DESC) qdesc
 ORDER BY 
         MyColumn

How to count objects in PowerShell?

@($output).Count does not always produce correct results. I used the ($output | Measure).Count method.

I found this with VMware Get-VmQuestion cmdlet:

$output = Get-VmQuestion -VM vm1
@($output).Count

The answer it gave is one, whereas

$output

produced no output (the correct answer was 0 as produced with the Measure method).

This only seemed to be the case with 0 and 1. Anything above 1 was correct with limited testing.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

you will get a No mapping found for HTTP request with URI error

if you scanned the wrong package

e.g your controller is in my.package.abc but you mistakenly put

<context:component-scan base-package="my.package.efg*" />

or

@ComponentScan("my.package.efg*")

which in the sense, your controller doesn't get scanned into the web application context, when request comes in not just url, but the entire class is not found!

How to identify a strong vs weak relationship on ERD?

The relationship Room to Class is considered weak (non-identifying) because the primary key components CID and DATE of entity Class doesn't contain the primary key RID of entity Room (in this case primary key of Room entity is a single component, but even if it was a composite key, one component of it also fulfills the condition).

However, for instance, in the case of the relationship Class and Class_Ins we see that is a strong (identifying) relationship because the primary key components EmpID and CID and DATE of Class_Ins contains a component of the primary key Class (in this case it contains both components CID and DATE).

How can I rotate an HTML <div> 90 degrees?

you can use css3 property writing-mode writing-mode: tb-rl

css-tricks

mozilla

How do I execute external program within C code in linux with arguments?

system() executes a shell which is then responsible for parsing the arguments and executing the desired program. To execute the program directly, use fork() and exec() (which is what system() uses to execute the shell as well as what the shell itself uses to execute commands).

#include <unistd.h>

int main() {
     if (fork() == 0) {
          /*
           * fork() returns 0 to the child process
           * and the child's PID to the parent.
           */
          execl("/path/to/foo", "foo", "arg1", "arg2", "arg3", 0);
          /*
           * We woundn't still be here if execl() was successful,
           * so a non-zero exit value is appropriate.
           */
          return 1;
     }

     return 0;
}

How to calculate the width of a text string of a specific font and font-size?

This is for swift 2.3 Version. You can get the width of string.

var sizeOfString = CGSize()
if let font = UIFont(name: "Helvetica", size: 14.0)
    {
        let finalDate = "Your Text Here"
        let fontAttributes = [NSFontAttributeName: font] // it says name, but a UIFont works
        sizeOfString = (finalDate as NSString).sizeWithAttributes(fontAttributes)
    }

Convert python datetime to timestamp in milliseconds

For Python2.7

You can format it into seconds and then multiply by 1000 to convert to millisecond.

from datetime import datetime

d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s')
d_in_ms = int(d)*1000
print(d_in_ms)

print(datetime.fromtimestamp(float(d)))

Output:

1482206922000
2016-12-20 09:38:42

Wait for shell command to complete

This is what I use to have VB wait for process to complete before continuing. I did not write this and do not take credit.

It was offered in some other open forum and works very well for me:

The following declarations are needed for the RunShell subroutine:

Option Explicit

Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long

Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Const PROCESS_QUERY_INFORMATION = &H400

Private Const STATUS_PENDING = &H103&

'then in your subroutine where you need to shell:

RunShell (path and filename or command, as quoted text)

Create a new TextView programmatically then display it below another TextView

If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.

Complete code:

String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);        
for( int i = 0; i < textArray.length; i++ )
{
    TextView textView = new TextView(this);
    textView.setText(textArray[i]);
    linearLayout.addView(textView);
}

Maximum on http header values?

If you are going to use any DDOS provider like Akamai, they have a maximum limitation of 8k in the response header size. So essentially try to limit your response header size below 8k.

Connection refused on docker container

I had the same problem. I was using Docker Toolbox on Windows Home. Instead of localhost I had to use http://192.168.99.100:8080/.

You can get the correct IP address using the command:

docker-machine ip

The above command returned 192.168.99.100 for me.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

Easy with recursion.

public static string GetStandardExcelColumnName(int columnNumberOneBased)
{
  int baseValue = Convert.ToInt32('A');
  int columnNumberZeroBased = columnNumberOneBased - 1;

  string ret = "";

  if (columnNumberOneBased > 26)
  {
    ret = GetStandardExcelColumnName(columnNumberZeroBased / 26) ;
  }

  return ret + Convert.ToChar(baseValue + (columnNumberZeroBased % 26) );
}

Tool to Unminify / Decompress JavaScript

Pretty Diff will beautify (pretty print) JavaScript in a way that conforms to JSLint and JSHint white space algorithms.

How can I check if an InputStream is empty without reading from it?

If the InputStream you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:

input.mark(1);
final int bytesRead = input.read(new byte[1]);
input.reset();
if (bytesRead != -1) {
    //stream not empty
} else {
    //stream empty
} 

If you don't control what kind of InputStream you're using, you can use the markSupported() method to check whether mark/reset will work on the stream, and fall back to the available() method or the java.io.PushbackInputStream method otherwise.

Running CMD command in PowerShell

For those who may need this info:

I figured out that you can pretty much run a command that's in your PATH from a PS script, and it should work.

Sometimes you may have to pre-launch this command with cmd.exe /c

Examples

Calling git from a PS script

I had to repackage a git client wrapped in Chocolatey (for those who may not know, it's a kind of app-store for Windows) which massively uses PS scripts.

I found out that, once git is in the PATH, commands like

$ca_bundle = git config --get http.sslCAInfo

will store the location of git crt file in $ca_bundle variable.

Looking for an App

Another example that is a combination of the present SO post and this SO post is the use of where command

$java_exe = cmd.exe /c where java

will store the location of java.exe file in $java_exe variable.

Jquery - How to get the style display attribute "none / block"

this is the correct answer

$('#theid').css('display') == 'none'

You can also use following line to find if it is display block or none

$('.deal_details').is(':visible')

Django datetime issues (default=datetime.now())

The datetime.now() is evaluated when the class is created, not when new record is being added to the database.

To achieve what you want define this field as:

date = models.DateTimeField(auto_now_add=True)

This way the date field will be set to current date for each new record.

concatenate two strings

You need to use the string concatenation operator +

String both = name + "-" + dest;

VBA using ubound on a multidimensional array

ubound(arr, 1) 

and

ubound(arr, 2) 

ImportError in importing from sklearn: cannot import name check_build

>>> from sklearn import preprocessing, metrics, cross_validation

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    from sklearn import preprocessing, metrics, cross_validation
  File "D:\Python27\lib\site-packages\sklearn\__init__.py", line 31, in <module>
    from . import __check_build
ImportError: cannot import name __check_build
>>> ================================ RESTART ================================
>>> from sklearn import preprocessing, metrics, cross_validation
>>> 

So, simply try to restart the shell!

Failed loading english.pickle with nltk.data.load

The main reason why you see that error is nltk couldn't find punkt package. Due to the size of nltk suite, all available packages are not downloaded by default when one installs it.

You can download punkt package like this.

import nltk
nltk.download('punkt')

from nltk import word_tokenize,sent_tokenize

If you do not pass any argument to the download function, it downloads all packages i.e chunkers, grammars, misc, sentiment, taggers, corpora, help, models, stemmers, tokenizers.

nltk.download()

The above function saves packages to a specific directory. You can find that directory location from comments here. https://github.com/nltk/nltk/blob/67ad86524d42a3a86b1f5983868fd2990b59f1ba/nltk/downloader.py#L1051

How to SELECT the last 10 rows of an SQL table which has no ID field?

If you want to retrieve last 10 records from sql use LIMIT. Suppose the data base contains 20 records.Use the below query

SELECT * FROM TABLE_NAME LIMIT 10,20;

where 10,20 is the offset value.Where 10 represent starting limit and 20 is the ending limit.

i.e 20 -10=10 records

HTTP GET with request body

Create a Requestfactory class

import java.net.URI;

import javax.annotation.PostConstruct;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RequestFactory {
    private RestTemplate restTemplate = new RestTemplate();

    @PostConstruct
    public void init() {
        this.restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory());
    }

    private static final class HttpComponentsClientHttpRequestWithBodyFactory extends HttpComponentsClientHttpRequestFactory {
        @Override
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (httpMethod == HttpMethod.GET) {
                return new HttpGetRequestWithEntity(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
    }

    private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
        public HttpGetRequestWithEntity(final URI uri) {
            super.setURI(uri);
        }

        @Override
        public String getMethod() {
            return HttpMethod.GET.name();
        }
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }
}

and @Autowired where ever you require and use, Here is one sample code GET request with RequestBody

 @RestController
 @RequestMapping("/v1/API")
public class APIServiceController {
    
    @Autowired
    private RequestFactory requestFactory;
    

    @RequestMapping(method = RequestMethod.GET, path = "/getData")
    public ResponseEntity<APIResponse> getLicenses(@RequestBody APIRequest2 APIRequest){
        APIResponse response = new APIResponse();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Gson gson = new Gson();
        try {
            StringBuilder createPartUrl = new StringBuilder(PART_URL).append(PART_URL2);
            
            HttpEntity<String> entity = new HttpEntity<String>(gson.toJson(APIRequest),headers);
            ResponseEntity<APIResponse> storeViewResponse = requestFactory.getRestTemplate().exchange(createPartUrl.toString(), HttpMethod.GET, entity, APIResponse.class); //.getForObject(createLicenseUrl.toString(), APIResponse.class, entity);
    
            if(storeViewResponse.hasBody()) {
                response = storeViewResponse.getBody();
            }
            return new ResponseEntity<APIResponse>(response, HttpStatus.OK);
        }catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<APIResponse>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
    }
}

How to calculate the time interval between two time strings

I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

But looks neat for me :)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

Regarding to the question you still need to use datetime.strptime() as others said earlier.

What is the native keyword in Java for?

  • native is a keyword in java, it indicates platform dependent.
  • native methods are acts as interface between Java(JNI) and other programming languages.

How to play YouTube video in my Android application?

Use YouTube Android Player API.

activity_main.xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.example.andreaskonstantakos.vfy.MainActivity">

<com.google.android.youtube.player.YouTubePlayerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="visible"
    android:layout_centerHorizontal="true"
    android:id="@+id/youtube_player"
    android:layout_alignParentTop="true" />

<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="195dp"
android:visibility="visible"
android:id="@+id/button" />


</RelativeLayout>

MainActivity.java:

package com.example.andreaskonstantakos.vfy;


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;



public class MainActivity extends YouTubeBaseActivity {

YouTubePlayerView youTubePlayerView;
Button button;
YouTubePlayer.OnInitializedListener onInitializedListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
     button = (Button) findViewById(R.id.button);


     onInitializedListener = new YouTubePlayer.OnInitializedListener(){

         @Override
         public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

            youTubePlayer.loadVideo("Hce74cEAAaE");

             youTubePlayer.play();
     }

         @Override
         public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

         }
     };

    button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

youTubePlayerView.initialize(PlayerConfig.API_KEY,onInitializedListener);
        }
    });
}
}

and the PlayerConfig.java class:

    package com.example.andreaskonstantakos.vfy;

/**
 * Created by Andreas Konstantakos on 13/4/2017.
 */

public class PlayerConfig {

PlayerConfig(){}

public static final String API_KEY = 
"xxxxx";
}

Replace the "Hce74cEAAaE" with your video ID from https://www.youtube.com/watch?v=Hce74cEAAaE. Get your API_KEY from Console.developers.google.com and also replace it on the PlayerConfig.API_KEY. For any further information you can follow the following tutorial step by step: https://www.youtube.com/watch?v=3LiubyYpEUk

How to center content in a bootstrap column?

Bootstrap naming conventions carry styles of their own, col-XS-1 refers to a column being 8.33% of the containing element wide. Your text, would most likely expand far beyond the specified width, and couldn't possible be centered within it. If you wanted it to constrain to the div, you could use something like css word-break.

For centering the content within an element large enough to expand beyond the text, you have two options.

Option 1: HTML Center Tag

<div class="row">
  <div class="col-xs-1 center-block">
    <center>
      <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
    </center>
  </div>
</div>

Option 2: CSS Text-Align

<div class="row">
  <div class="col-xs-1 center-block" style="text-align:center;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

If you wanted everything to constrain to the width of the column

<div class="row">
  <div class="col-xs-1 center-block" style="text-align:center;word-break:break-all;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

UPDATE - Using Bootstrap's text-center class

<div class="row">
  <div class="col-xs-1 center-block text-center">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

FlexBox Method

<div class="row">
  <div class="flexBox" style="
    display: flex;
    flex-flow: row wrap;
    justify-content: center;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

http://jsfiddle.net/usth0kd2/13/

How to install a Notepad++ plugin offline?

Here are the steps that worked for me:

  1. Download the plugin and extract the plugin dll file.
  2. Place the plugin.dll file under plugin folder of notepad++ installation. For me it was : C:\Program Files\Notepad++\plugins
  3. Go to Notepad++ then : Settings -> Import -> Import plugin (import the plugin).
  4. Notepad++ will show the restart message / Sometimes it may not show it.
  5. Restart the notepad++.
  6. Should see new plugin under the Plugins menu. ALL DONE!!

Javascript/Jquery to change class onclick?

Just using this will add "mynewclass" to the element with the id myElement and revert it on the next call.

<div id="showhide" class="meta-info" onclick="changeclass(this);">

function changeclass(element) {
    $(element).toggleClass('mynewclass');
}

Or for a slighly more jQuery way (you would run this after the DOM is loaded)

<div id="showhide" class="meta-info">

$('#showhide').click(function() {
    $(this).toggleClass('mynewclass');
});

See a working example of this here: http://jsfiddle.net/S76WN/

Preserve line breaks in angularjs

Just use the css style "white-space: pre-wrap" and you should be good to go. I've had the same issue where I need to handle error messages for which the line breaks and white spaces are really particular. I just added this inline where I was binding the data and it works like Charm!

jQuery Mobile Page refresh mechanism

I found this thread looking to create an ajax page refresh button with jQuery Mobile.

@sgissinger had the closest answer to what I was looking for, but it was outdated.

I updated for jQuery Mobile 1.4

function refreshPage() {
  jQuery.mobile.pageContainer.pagecontainer('change', window.location.href, {
    allowSamePageTransition: true,
    transition: 'none',
    reloadPage: true 
    // 'reload' parameter not working yet: //github.com/jquery/jquery-mobile/issues/7406
  });
}

// Run it with .on
$(document).on( "click", '#refresh', function() {
  refreshPage();
});

Detecting locked tables (locked by LOCK TABLE)

You can create your own lock with GET_LOCK(lockName,timeOut)

If you do a GET_LOCK(lockName, 0) with a 0 time out before you lock the tables and then follow that with a RELEASE_LOCK(lockName) then all other threads performing a GET_LOCK() will get a value of 0 which will tell them that the lock is being held by another thread.

However this won't work if you don't have all threads calling GET_LOCK() before locking tables. The documentation for locking tables is here

Hope that helps!

jQuery checkbox check/uncheck

Use prop() instead of attr() to set the value of checked. Also use :checkbox in find method instead of input and be specific.

Live Demo

$("#news_list tr").click(function() {
    var ele = $(this).find('input');
    if(ele.is(':checked')){
        ele.prop('checked', false);
        $(this).removeClass('admin_checked');
    }else{
        ele.prop('checked', true);
        $(this).addClass('admin_checked');
    }
});

Use prop instead of attr for properties like checked

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method

Block direct access to a file over http but allow php script access

That is how I prevented direct access from URL to my ini files. Paste the following code in .htaccess file on root. (no need to create extra folder)

<Files ~ "\.ini$">
  Order allow,deny
  Deny from all
</Files>

my settings.ini file is on the root, and without this code is accessible www.mydomain.com/settings.ini

How does MySQL process ORDER BY and LIMIT in a query?

You could add [asc] or [desc] at the end of the order by to get the earliest or latest records

For example, this will give you the latest records first

ORDER BY stamp DESC

Append the LIMIT clause after ORDER BY

'Conda' is not recognized as internal or external command

In addition to adding C:\Users\yourusername\Anaconda3 and C:\Users\yourusername\Anaconda3\Scripts, as recommended by Raja (above), also add C:\Users\yourusername\Anaconda3\Library\bin to your path variable. This will prevent an SSL error that is bound to happen if you're performing this on a fresh install of Anaconda.

SQL Server, division returns zero

Because it's an integer. You need to declare them as floating point numbers or decimals, or cast to such in the calculation.

How to Generate a random number of fixed length using JavaScript?

In case you also want the first digit to be able to be 0 this is my solution:

_x000D_
_x000D_
const getRange = (size, start = 0) => Array(size).fill(0).map((_, i) => i + start);_x000D_
_x000D_
const getRandomDigit = () => Math.floor(Math.random() * 10);_x000D_
_x000D_
const generateVerificationCode = () => getRange(6).map(getRandomDigit).join('');_x000D_
_x000D_
console.log(generateVerificationCode())
_x000D_
_x000D_
_x000D_

Java: how to use UrlConnection to post request with authorization?

I don't see anywhere in the code where you specify that this is a POST request. Then again, you need a java.net.HttpURLConnection to do that.

In fact, I highly recommend using HttpURLConnection instead of URLConnection, with conn.setRequestMethod("POST"); and see if it still gives you problems.

remove first element from array and return the array minus the first element

Try this

    var myarray = ["item 1", "item 2", "item 3", "item 4"];

    //removes the first element of the array, and returns that element apart from item 1.
    myarray.shift(); 
    console.log(myarray); 

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

If this is your own collection class rather than a built in one, you need to override its toString method. Eclipse calls that function for any objects for which it does not have a hard-wired formatting.

How to install Selenium WebDriver on Mac OS

Mac already has Python and a package manager called easy_install, so open Terminal and type

sudo easy_install selenium

Install specific version using laravel installer

Via composer installing specific version 7.*

composer create-project --prefer-dist laravel/laravel:^7.0 project_name

To install specific version 6.* and below use the following command:

composer create-project --prefer-dist laravel/laravel project_name "6.*"

C# Enum - How to Compare Value

Comparision:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}

or shorter version:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

Proper way to exit command line program?

if you do ctrl-z and then type exit it will close background applications.

Ctrl+Q is another good way to kill the application.

link button property to open in new tab?

This is not perfect, but it works.

<asp:LinkButton id="lbnkVidTtile1" runat="Server" 
    CssClass="bodytext" Text='<%# Eval("newvideotitle") %>'
    OnClientClick="return PostToNewWindow();"  />

<script type="text/javascript">
function PostToNewWindow()
{
    originalTarget = document.forms[0].target;
    document.forms[0].target='_blank';
    window.setTimeout("document.forms[0].target=originalTarget;",300);
    return true;
}
</script>

Need to remove href values when printing in Chrome

I encountered a similar problem only with a nested img in my anchor:

<a href="some/link">
   <img src="some/src">
</a>

When I applied

@media print {
   a[href]:after {
      content: none !important;
   }
}

I lost my img and the entire anchor width for some reason, so instead I used:

@media print {
   a[href]:after {
      visibility: hidden;
   }
}

which worked perfectly.

Bonus tip: inspect print preview

How to make an anchor tag refer to nothing?

If you don't want to have it point to anything, you probably shouldn't be using the <a> (anchor) tag.

If you want something to look like a link but not act like a link, it's best to use the appropriate element (such as <span>) and then style it using CSS:

<span class="fake-link" id="fake-link-1">Am I a link?</span>

.fake-link {
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}

Also, given that you tagged this question "jQuery", I am assuming that you want to attach a click event hander. If so, just do the same thing as above and then use something like the following JavaScript:

$('#fake-link-1').click(function() {
    /* put your code here */
});

How to serialize object to CSV file?

For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.

EDIT

According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !

By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.

I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.

Creating a new column based on if-elif-else condition

df.loc[df['A'] == df['B'], 'C'] = 0
df.loc[df['A'] > df['B'], 'C'] = 1
df.loc[df['A'] < df['B'], 'C'] = -1

Easy to solve using indexing. The first line of code reads like so, if column A is equal to column B then create and set column C equal to 0.

insert password into database in md5 format?

use MD5,

$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";

but MD5 is insecure. Use SHA2.

How to change fontFamily of TextView in Android

It's the same as android:typeface.

built-in fonts are:

  • normal
  • sans
  • serif
  • monospace

See android:typeface.

Capture Video of Android's Screen

If you want to record the user navigation so you can test UI and other things, I recommend you to use TestFairy

It allows you to send the apk to some test users by email and see a video with all the sessions in the app and even the app crashes and device stats.

Detect enter press in JTextField

Add an event for KeyPressed.

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
  if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
      // Enter was pressed. Your code goes here.
   }
} 

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Difference between == (equal) and === (identical equal)

PHP provides two comparison operators to check equality of two values. The main difference between of these two is that '==' checks if the values of the two operands are equal or not. On the other hand, '===' checks the values as well as the type of operands are equal or not.

== (Equal)

=== (Identical equal)

Example =>

<?php 
    $val1 = 1234;
    $val2 = "1234";
    var_dump($val1 == $val2);// output => bool(true)
    //It checks only operands value
?> 


<?php 
    $val1 = 1234;
    $val2 = "1234";
    var_dump($val1 === $val2);// output => bool(false)
    //First it checks type then operands value
?> 

if we type cast $val2 to (int)$val2 or (string)$val1 then it returns true

   <?php 
        $val1 = 1234;
        $val2 = "1234";
        var_dump($val1 === (int)$val2);// output => bool(true)
        //First it checks type then operands value
    ?> 

OR

  <?php 
        $val1 = 1234;
        $val2 = "1234";
        var_dump($val1 === (int)$val2);// output => bool(true)
        //First it checks type then operands value
    ?> 

Best way to check for null values in Java?

We can use Object.requireNonNull static method of Object class. Implementation is below

public void someMethod(SomeClass obj) {
    Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}

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

Yes, that is a good question. I don't understand it fully yet, but:

I understand that ENTRYPOINT is the binary that is being executed. You can overide entrypoint by --entrypoint="".

docker run -t -i --entrypoint="/bin/bash" ubuntu

CMD is the default argument to container. Without entrypoint, default argument is command that is executed. With entrypoint, cmd is passed to entrypoint as argument. You can emulate a command with entrypoint.

# no entrypoint
docker run ubuntu /bin/cat /etc/passwd

# with entry point, emulating cat command
docker run --entrypoint="/bin/cat" ubuntu /etc/passwd

So, main advantage is that with entrypoint you can pass arguments (cmd) to your container. To accomplish this, you need to use both:

# Dockerfile
FROM ubuntu
ENTRYPOINT ["/bin/cat"]

and

docker build -t=cat .

then you can use:

docker run cat /etc/passwd
#              ^^^^^^^^^^^
#                   CMD
#          ^^^      
#          image (tag)- using the default ENTRYPOINT

Alternate background colors for list items

This is set background color on even and odd li:

  li:nth-child(odd) { background: #ffffff; }
  li:nth-child(even) { background: #80808030; }

How to create a function in SQL Server

This will work for most of the website names :

SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....

Improve SQL Server query performance on large tables

There are a few issues with this query (and this apply to every query).

Lack of index

Lack of index on er101_upd_date_iso column is most important thing as Oded has already mentioned.

Without matching index (which lack of could cause table scan) there is no chance to run fast queries on big tables.

If you cannot add indexes (for various reasons including there is no point in creating index for just one ad-hoc query) I would suggest a few workarounds (which can be used for ad-hoc queries):

1. Use temporary tables

Create temporary table on subset (rows and columns) of data you are interested in. Temporary table should be much smaller that original source table, can be indexed easily (if needed) and can cached subset of data which you are interested in.

To create temporary table you can use code (not tested) like:

-- copy records from last month to temporary table
INSERT INTO
   #my_temporary_table
SELECT
    *
FROM
    er101_acct_order_dtl WITH (NOLOCK)
WHERE 
    er101_upd_date_iso > DATEADD(month, -1, GETDATE())

-- you can add any index you need on temp table
CREATE INDEX idx_er101_upd_date_iso ON #my_temporary_table(er101_upd_date_iso)

-- run other queries on temporary table (which can be indexed)
SELECT TOP 100
    * 
FROM 
    #my_temporary_table 
ORDER BY 
    er101_upd_date_iso DESC

Pros:

  • Easy to do for any subset of data.
  • Easy to manage -- it's temporary and it's table.
  • Doesn't affect overall system performance like view.
  • Temporary table can be indexed.
  • You don't have to care about it -- it's temporary :).

Cons:

  • It's snapshot of data -- but probably this is good enough for most ad-hoc queries.

2. Common table expression -- CTE

Personally I use CTE a lot with ad-hoc queries -- it's help a lot with building (and testing) a query piece by piece.

See example below (the query starting with WITH).

Pros:

  • Easy to build starting from big view and then selecting and filtering what really you need.
  • Easy to test.

Cons:

  • Some people dislike CDE -- CDE queries seem to be long and difficult to understand.

3. Create views

Similar to above, but create views instead of temporary tables (if you play often with the same queries and you have MS SQL version which supports indexed views.

You can create views or indexed views on subset of data you are interested in and run queries on view -- which should contain only interesting subset of data much smaller than the whole table.

Pros:

  • Easy to do.
  • It's up to date with source data.

Cons:

  • Possible only for defined subset of data.
  • Could be inefficient for large tables with high rate of updates.
  • Not so easy to manage.
  • Can affect overall system performance.
  • I am not sure indexed views are available in every version of MS SQL.

Selecting all columns

Running star query (SELECT * FROM) on big table is not good thing...

If you have large columns (like long strings) it takes a lot of time to read them from disk and pass by network.

I would try to replace * with column names which you really need.

Or, if you need all columns try to rewrite query to something like (using common data expression):

;WITH recs AS (
    SELECT TOP 100 
        id as rec_id -- select primary key only
    FROM 
        er101_acct_order_dtl 
    ORDER BY 
        er101_upd_date_iso DESC
)
SELECT
    er101_acct_order_dtl.*
FROM
    recs
    JOIN
      er101_acct_order_dtl
    ON
      er101_acct_order_dtl.id = recs.rec_id
ORDER BY 
    er101_upd_date_iso DESC 

Dirty reads

Last thing which could speed up the ad-hoc query is allowing dirty reads with table hint WITH (NOLOCK).

Instead of hint you can set transaction isolation level to read uncommited:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

or set proper SQL Management Studio setting.

I assume for ad-hoc queries dirty reads is good enough.

What are advantages of Artificial Neural Networks over Support Vector Machines?

If you want to use a kernel SVM you have to guess the kernel. However, ANNs are universal approximators with only guessing to be done is the width (approximation accuracy) and height (approximation efficiency). If you design the optimization problem correctly you do not over-fit (please see bibliography for over-fitting). It also depends on the training examples if they scan correctly and uniformly the search space. Width and depth discovery is the subject of integer programming.

Suppose you have bounded functions f(.) and bounded universal approximators on I=[0,1] with range again I=[0,1] for example that are parametrized by a real sequence of compact support U(.,a) with the property that there exists a sequence of sequences with

lim sup { |f(x) - U(x,a(k) ) | : x } =0

and you draw examples and tests (x,y) with a distribution D on IxI.

For a prescribed support, what you do is to find the best a such that

sum {  ( y(l) - U(x(l),a) )^{2} | : 1<=l<=N } is minimal

Let this a=aa which is a random variable!, the over-fitting is then

average using D and D^{N} of ( y - U(x,aa) )^{2}

Let me explain why, if you select aa such that the error is minimized, then for a rare set of values you have perfect fit. However, since they are rare the average is never 0. You want to minimize the second although you have a discrete approximation to D. And keep in mind that the support length is free.

How to center an image horizontally and align it to the bottom of the container?

wouldn't

margin-left:auto;
margin-right:auto;

added to the .image_block a img do the trick?
Note that that won't work in IE6 (maybe 7 not sure)
there you will have to do on .image_block the container Div

text-align:center;

position:relative; could be a problem too.

Insert some string into given string at given index in Python

There are several ways to do this:

One way is to use slicing:

>>> a="line=Name Age Group Class Profession"
>>> b=a.split()
>>> b[2:2]=[b[2]]*3
>>> b
['line=Name', 'Age', 'Group', 'Group', 'Group', 'Group', 'Class', 'Profession']
>>> a=" ".join(b)
>>> a
'line=Name Age Group Group Group Group Class Profession'

Another would be to use regular expressions:

>>> import re
>>> a=re.sub(r"(\S+\s+\S+\s+)(\S+\s+)(.*)", r"\1\2\2\2\2\3", a)
>>> a
'line=Name Age Group Group Group Group Class Profession'

Chart creating dynamically. in .net, c#

You need to attach the Form1_Load handler to the Load event:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Random rnd = new Random();
            Chart mych = new Chart();
            mych.Height = 100;
            mych.Width = 100;
            mych.BackColor = SystemColors.Highlight;
            mych.Series.Add("duck");

            mych.Series["duck"].SetDefault(true);
            mych.Series["duck"].Enabled = true;
            mych.Visible = true;

            for (int q = 0; q < 10; q++)
            {
                int first = rnd.Next(0, 10);
                int second = rnd.Next(0, 10);
                mych.Series["duck"].Points.AddXY(first, second);
                Debug.WriteLine(first + "  " + second);
            }

            Controls.Add(mych);
        }
    }
}

Text on image mouseover?

And if you come from even further in the future you can use the title property on div tags now to provide tooltips:

<div title="Tooltip text">Hover over me</div>

Let's just hope you're not using a browser from the past.

_x000D_
_x000D_
<div title="Tooltip text">Hover over me</div>
_x000D_
_x000D_
_x000D_

How do I execute multiple SQL Statements in Access' Query Editor?

You might find it better to use a 3rd party program to enter the queries into Access such as WinSQL I think from memory WinSQL supports multiple queries via it's batch feature.

I ultimately found it easier to just write a program in perl to do bulk INSERTS into an Access via ODBC. You could use vbscript or any language that supports ODBC though.

You can then do anything you like and have your own complicated logic to handle the importing.

Android EditText delete(backspace) key event

Belated but it may help new visitors, use TextWatcher() instead will help alot and also it will work for both soft and hard keyboard as well.

 editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    //Here it means back button is pressed and edit text is now empty
                } else {
                   //Here edit text has some text
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

Changing background colour of tr element on mouseover

You could try:

tr:hover {
    background-color: #000;
}

tr:hover td {
    background-color: transparent; /* or #000 */
}

JS Fiddle demo.

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

How to scanf only integer and repeat reading if the user enters non-numeric characters?

char check1[10], check2[10];
int foo;

do{
  printf(">> ");
  scanf(" %s", check1);
  foo = strtol(check1, NULL, 10); // convert the string to decimal number
  sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number

If the input is number, you can use foo as your input.

sorting a vector of structs

Yes: you can sort using a custom comparison function:

std::sort(info.begin(), info.end(), my_custom_comparison);

my_custom_comparison needs to be a function or a class with an operator() overload (a functor) that takes two data objects and returns a bool indicating whether the first is ordered prior to the second (i.e., first < second). Alternatively, you can overload operator< for your class type data; operator< is the default ordering used by std::sort.

Either way, the comparison function must yield a strict weak ordering of the elements.

How to ignore SSL certificate errors in Apache HttpClient 4.0

We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.

some method to call when making post requests....

SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
    HttpPost postRequest = new HttpPost(url);

continue your request in the normal form

How can I hide an HTML table row <tr> so that it takes up no space?

You can set <tr id="result_tr" style="display: none;"> and then show it back with JavaScript:

var result_style = document.getElementById('result_tr').style;
result_style.display = 'table-row';

No space left on device

Such difference between the output of du -sh and df -h may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

In this approach only one statement is executed when the UPDATE is successful.

-- For each row in source
BEGIN TRAN    

UPDATE target
SET <target_columns> = <source_values>
WHERE <target_expression>

IF (@@ROWCOUNT = 0)
   INSERT target (<target_columns>)
VALUES (<source_values>)

COMMIT

Call angularjs function using jquery/javascript

Try this:

const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
     scope.myfunction('test');
});

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

Swift convert unix time to date and time

For me: Converting timestamps coming from API to a valid date :

`let date = NSDate.init(fromUnixTimestampNumber: timesTamp /* i.e 1547398524000 */) as Date?`

Using Google Translate in C#

Google Translate Kit, an open source library http://ggltranslate.codeplex.com/

Translator gt = new Translator();
/*using cache*/
DemoWriter dw = new DemoWriter();
gt.KeyGen = new SimpleKeyGen();
gt.CacheManager = new SimleCacheManager();
gt.Writer = dw;
Translator.TranslatedPost post = gt.GetTranslatedPost("Hello world", LanguageConst.ENGLISH, LanguageConst.CHINESE);
Translator.TranslatedPost post2 = gt.GetTranslatedPost("I'm Jeff", LanguageConst.ENGLISH, LanguageConst.CHINESE);
this.result.InnerHtml = "<p>" + post.text +post2.text+ "</p>";
dw.WriteToFile();

Strings in C, how to get subString

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

int main ()
{
        char someString[]="abcdedgh";
        char otherString[]="00000";
        memcpy (otherString, someString, 5);
        printf ("someString: %s\notherString: %s\n", someString, otherString);
        return 0;
}

You will not need stdio.h if you don't use the printf statement and putting constants in all but the smallest programs is bad form and should be avoided.

Javascript ES6/ES5 find in array and change

An other approach is to use splice.

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

N.B : In case you're working with reactive frameworks, it will update the "view", your array "knowing" you've updated it.

Answer :

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

let foundIndex = items.findIndex(element => element.id === item.id)
items.splice(foundIndex, 1, item)

And in case you want to only change a value of an item, you can use find function :

// Retrieve item and assign ref to updatedItem
let updatedItem = items.find((element) => { return element.id === item.id })

// Modify object property
updatedItem.aProp = ds.aProp

How to schedule a periodic task in Java?

my servlet contains this as a code how to keep this in scheduler if a user presses accept

if(bt.equals("accept")) {
    ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
    String lat=request.getParameter("latlocation");
    String lng=request.getParameter("lnglocation");
    requestingclass.updatelocation(lat,lng);
}

Convert Json String to C# Object List

using dynamic variable in C# is the simplest.

Newtonsoft.Json.Linq has class JValue that can be used. Below is a sample code which displays Question id and text from the JSON string you have.

        string jsonString = "[{\"Question\":{\"QuestionId\":49,\"QuestionText\":\"Whats your name?\",\"TypeId\":1,\"TypeName\":\"MCQ\",\"Model\":{\"options\":[{\"text\":\"Rahul\",\"selectedMarks\":\"0\"},{\"text\":\"Pratik\",\"selectedMarks\":\"9\"},{\"text\":\"Rohit\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":true,\"selectedOption\":\"1\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"02\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"\",\"S8\":\"\",\"S9\":\"Pratik\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"},{\"Question\":{\"QuestionId\":51,\"QuestionText\":\"Are you smart?\",\"TypeId\":3,\"TypeName\":\"True-False\",\"Model\":{\"options\":[{\"text\":\"True\",\"selectedMarks\":\"7\"},{\"text\":\"False\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":false,\"selectedOption\":\"3\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"01\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"True\",\"S8\":\"\",\"S9\":\"\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"}]";
        dynamic myObject = JValue.Parse(jsonString);
        foreach (dynamic questions in myObject)
        {
            Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString());
        }
        Console.Read();

Output from the code => Output from the code

android download pdf from url then open it with a pdf reader

Hi the problem is in FileDownloader class

 urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.

Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)

Attaching the working code with screenshots.

enter image description here

enter image description here

MainActivity.java

package com.example.downloadread;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void download(View v)
    {
        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}

FileDownloader.java

package com.example.downloadread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="download"
        android:onClick="download" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="38dp"
        android:text="view"
        android:onClick="view" />

</RelativeLayout>

String.format() to format double in java

If you want to format it with manually set symbols, use this:

DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", decimalFormatSymbols);
System.out.println(decimalFormat.format(1237516.2548)); //1,237,516.25

Locale-based formatting is preferred, though.

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

You have to change the extends Activity to extends AppCompactActivity then try set and getSupportActionBar()

Html helper for <input type="file" />

To use BeginForm, here's the way to use it:

 using(Html.BeginForm("uploadfiles", 
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})

How to get just the responsive grid from Bootstrap 3?

Checkout zirafa/bootstrap-grid-only. It contains only the bootstrap grid and responsive utilities that you need (no reset or anything), and simplifies the complexity of working directly with the LESS files.

Excel Reference To Current Cell

I found the best way to handle this (for me) is to use the following:

Dim MyString as String
MyString = Application.ThisCell.Address
Range(MyString).Select

Hope this helps.

Getting JSONObject from JSONArray

start from

JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");

you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array member

Iterating

for(int i = 0; i < deletedtrs_array.length(); i++){
    JSONObject obj = deletedtrs_array.getJSONObject(i);
    Log.d("Item no."+i, obj.toString());

    // create object of type DeletedTrsWrapper like this
    DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);

    // String company_id = obj.getString("companyid");
    // String username = obj.getString("username");
    // String date = obj.getString("date");
    // int report_id = obj.getInt("reportid");
}

Own object type

class DeletedTrsWrapper {

    public String company_id;
    public String username;
    public String date;
    public int report_id;

    public DeletedTrsWrapper(JSONObject obj){
        company_id = obj.getString("companyid");
        username = obj.getString("username");
        date = obj.getString("date");
        report_id = obj.getInt("reportid");
    }
}

Normalizing a list of numbers in Python

If working with data, many times pandas is the simple key

This particular code will put the raw into one column, then normalize by column per row. (But we can put it into a row and do it by row per column, too! Just have to change the axis values where 0 is for row and 1 is for column.)

import pandas as pd


raw = [0.07, 0.14, 0.07]  

raw_df = pd.DataFrame(raw)
normed_df = raw_df.div(raw_df.sum(axis=0), axis=1)
normed_df

where normed_df will display like:

    0
0   0.25
1   0.50
2   0.25

and then can keep playing with the data, too!

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

Outputs after two seconds:

101

Excel VBA For Each Worksheet Loop

Try to slightly modify your code:

Sub forEachWs()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call resizingColumns(ws)
    Next
End Sub

Sub resizingColumns(ws As Worksheet)
    With ws
        .Range("A:A").ColumnWidth = 20.14
        .Range("B:B").ColumnWidth = 9.71
        .Range("C:C").ColumnWidth = 35.86
        .Range("D:D").ColumnWidth = 30.57
        .Range("E:E").ColumnWidth = 23.57
        .Range("F:F").ColumnWidth = 21.43
        .Range("G:G").ColumnWidth = 18.43
        .Range("H:H").ColumnWidth = 23.86
        .Range("i:I").ColumnWidth = 27.43
        .Range("J:J").ColumnWidth = 36.71
        .Range("K:K").ColumnWidth = 30.29
        .Range("L:L").ColumnWidth = 31.14
        .Range("M:M").ColumnWidth = 31
        .Range("N:N").ColumnWidth = 41.14
        .Range("O:O").ColumnWidth = 33.86
    End With
End Sub

Note, resizingColumns routine takes parametr - worksheet to which Ranges belongs.

Basically, when you're using Range("O:O") - code operats with range from ActiveSheet, that's why you should use With ws statement and then .Range("O:O").

And there is no need to use global variables (unless you are using them somewhere else)

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

Margin while printing html page

I'd personally suggest using a different unit of measurement than px. I don't think that pixels have much relevance in terms of print; ideally you'd use:

  • point (pt)
  • centimetre (cm)

I'm sure there are others, and one excellent article about print-css can be found here: Going to Print, by Eric Meyer.

Importing a csv into mysql via command line

You can simply import by

mysqlimport --ignore-lines=1 --lines-terminated-by='\n' --fields-terminated-by=',' --fields-enclosed-by='"' --verbose --local -uroot -proot db_name csv_import.csv

Note: Csv File name and Table name should be same

How to query all the GraphQL type fields without writing a long query?

GraphQL query format was designed in order to allow:

  1. Both query and result shape be exactly the same.
  2. The server knows exactly the requested fields, thus the client downloads only essential data.

However, according to GraphQL documentation, you may create fragments in order to make selection sets more reusable:

# Only most used selection properties

fragment UserDetails on User {
    id,
    username
} 

Then you could query all user details by:

FetchUsers {
    users() {
        ...UserDetails
    }
}

You can also add additional fields alongside your fragment:

FetchUserById($id: ID!) {
    users(id: $id) {
        ...UserDetails
        count
    }
}

Using WGET to run a cronjob PHP

If you want get output only when php fail:

php -r 'echo file_get_contents(http://www.example.com/cronit.php);'

This way you receive an email from cronjob only when the script fails and not whenever the php is called.

Java method to swap primitives

I think this is the closest you can get to a simple swap, but it does not have a straightforward usage pattern:

int swap(int a, int b) {  // usage: y = swap(x, x=y);
   return a;
}

y = swap(x, x=y);

It relies on the fact that x will pass into swap before y is assigned to x, then x is returned and assigned to y.

You can make it generic and swap any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

c = swap(a, a=b, b=c)

Create a string and append text to it

Another way to do this is to add the new characters to the string as follows:

Dim str As String

str = ""

To append text to your string this way:

str = str & "and this is more text"

Find the last time table was updated

Why not just run this: No need for special permissions

SELECT
    name, 
    object_id, 
    create_date, 
    modify_date
FROM
    sys.tables 
WHERE 
    name like '%yourTablePattern%'
ORDER BY
    modify_date

Find an object in array?

Swift 2 or later

You can combine indexOf and map to write a "find element" function in a single line.

let array = [T(name: "foo"), T(name: "Foo"), T(name: "FOO")]
let foundValue = array.indexOf { $0.name == "Foo" }.map { array[$0] }
print(foundValue) // Prints "T(name: "Foo")"

Using filter + first looks cleaner, but filter evaluates all the elements in the array. indexOf + map looks complicated, but the evaluation stops when the first match in the array is found. Both the approaches have pros and cons.

replace all occurrences in a string

As explained here, you can use:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

... which you can then call using:

var str = "50.000.000";
alert(replaceall(str,'.',''));

The function will alert "50000000"

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

How to Apply global font to whole HTML document

Best practice I think is to set the font to the body:

body {
    font: normal 10px Verdana, Arial, sans-serif;
}

and if you decide to change it for some element it could be easily overwrited:

h2, h3 {
    font-size: 14px;
}

jQuery function after .append

$('#root').append(child);
// do your work here

Append doesn't have callbacks, and this is code that executes synchronously - there is no risk of it NOT being done

How to show full object in Chrome console?

I wrote a function to conveniently print things to the console.

// function for debugging stuff
function print(...x) {
    console.log(JSON.stringify(x,null,4));
}

// how to call it
let obj = { a: 1, b: [2,3] };
print('hello',123,obj);

will output in console:

[
    "hello",
    123,
    {
        "a": 1,
        "b": [
            2,
            3
        ]
    }
]

How to create a GUID/UUID in Python

If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.

Ex:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')

How does the Spring @ResponseBody annotation work?

Further to this, the return type is determined by

  1. What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.

  2. What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.

If there is a choice it picks one - in this example, it happens to be JSON.

This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.

Differences between JDK and Java SDK

My initial guess would be that the Java SDK is for building the JVM while the JDK is for building apps for the JVM.

Edit: Although this looks to be incorrect at the moment. Sun are in the process of opensourcing the JVM (perhaps they've even finished, now) so I wouldn't be too surprised if my answer does become correct... But at the moment, the SDK and JDK are the same thing.

How can I put strings in an array, split by new line?

There is quite a mix of direct and indirect answers on this page and some good advice in comments, but there isn't an answer that represents what I would write in my own project.

PHP Escape Sequence \R documentation: https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break,\r\n

Code: (Demo)

$string = '
My text1

My text2


My text3


';

var_export(
    preg_split('/\R+/', $string, 0, PREG_SPLIT_NO_EMPTY)
);

Output:

array (
  0 => 'My text1',
  1 => 'My text2',
  2 => 'My text3',
)

The OP makes no mention of trimming horizontal whitespace characters from the lines, so there is no expectation of removing \s or \h while exploding on variable (system agnostic) new lines.

While PHP_EOL is sensible advice, it lacks the flexibility appropriately explode the string when the newline sequence is coming from another operating system.

Using a non-regex explode will tend to be less direct because it will require string preparations. Furthermore, there may be mopping up after the the explosions if there are unwanted blank lines to remove.

Using \R+ (one or more consecutive newline sequences) and the PREG_SPLIT_NO_EMPTY function flag will deliver a gap-less, indexed array in a single, concise function call. Some people have a bias against regular expressions, but this is a perfect case for why regex should be used. If performance is a concern for valid reasons (e.g. you are processing hundreds of thousands of points of data), then go ahead and invest in benchmarking and micro-optimization. Beyond that, just use this one-line of code so that your code is brief, robust, and direct.

Store a closure as a variable in Swift

Closures can be declared as typealias as below

typealias Completion = (Bool, Any, Error) -> Void

If you want to use in your function anywhere in code; you can write like normal variable

func xyz(with param1: String, completion: Completion) {
}

How to "grep" out specific line ranges of a file

Try using sed as mentioned on http://linuxcommando.blogspot.com/2008/03/using-sed-to-extract-lines-in-text-file.html. For example use

sed '2,4!d' somefile.txt

to print from the second line to the fourth line of somefile.txt. (And don't forget to check http://www.grymoire.com/Unix/Sed.html, sed is a wonderful tool.)

How to tell if a string is not defined in a Bash shell script

~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO=""
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO="a"
~> if [ -z $FOO ]; then echo "EMPTY"; fi
~> 

-z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed here or, with clearer explanations, here.

Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.

Alternate word:

~$ unset FOO
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
~$ FOO=""
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
DEFINED

Default value:

~$ FOO=""
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
~$ unset FOO
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
UNDEFINED

Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.

What is the regex for "Any positive integer, excluding 0"

^\d*[1-9]\d*$

this can include all positive values, even if it is padded by Zero in the front

Allows

1

01

10

11 etc

do not allow

0

00

000 etc..

Biggest differences of Thrift vs Protocol Buffers?

It's also important to note that not all supported languages compair consistently with thrift or protobuf. At this point it's a matter of the modules implementation in addition to the underlying serialization. Take care to check benchmarks for whatever language you plan to use.

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

To make a batch file for its current directory and sub directories:

cd %~dp0
attrib -h -r -s /s /d /l *.*

Capitalize words in string

My solution:

String.prototype.toCapital = function () {
    return this.toLowerCase().split(' ').map(function (i) {
        if (i.length > 2) {
            return i.charAt(0).toUpperCase() + i.substr(1);
        }

        return i;
    }).join(' ');
};

Example:

'álL riGht'.toCapital();
// Returns 'Áll Right'

svn: E155004: ..(path of resource).. is already locked

For me it's worked with svn cleanup in Eclipse.

Problems with entering Git commit message with Vim

Have you tried just going: git commit -m "Message here"

So in your case:

git commit -m "Form validation added"

After you've added your files of course.

HTML tag <a> want to add both href and onclick working

You already have what you need, with a minor syntax change:

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

<script type="text/javascript">
    function theFunction () {
        // return true or false, depending on whether you want to allow the `href` property to follow through or not
    }
</script>

The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)

Detecting installed programs via registry

An application does not need to have any registry entry. In fact, many applications do not need to be installed at all. U3 USB sticks are a good example; the programs on them just run from the file system.

As noted, most good applications can be found via their uninstall registry key though. This is actually a pair of keys, per-user and per-machine (HKCU/HKLM - Piskvor mentioned only the HKLM one). It does not (always) give you the install directory, though.

If it's in HKCU, then you have to realise that HKEY_CURRENT_USER really means "Current User". Other users have their own HKCU entries, and their own installed software. You can't find that. Reading every HKEY_USERS hive is a disaster on corporate networks with roaming profiles. You really don't want to fetch 1000 accounts from your remote [US|China|Europe] office.

Even if an application is installed, and you know where, it may not have the same "version" notion you have. The best source is the "version" resource in the executables. That's indeed a plural, so you have to find all of them, extract version resources from all and in case of a conflict decid on something reasonable.

So - good luck. There are dozes of ways to fail.

functional way to iterate over range (ES6/7)

Here's an approach using generators:

function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;
}

Then you can write

console.log(...square(7));

Another idea is:

[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.

Alternatively, we could write

Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write

Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is

[...1e4+''].map((_, i) => i*i)

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

ooh! neat question.

Matlab's for loop takes a matrix as input and iterates over its columns. Matlab also handles practically everything by value (no pass-by-reference) so I would expect that it takes a snapshot of the for-loop's input so it's immutable.

here's an example which may help illustrate:

>> A = zeros(4); A(:) = 1:16

A =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

>> i = 1; for col = A; disp(col'); A(:,i) = i; i = i + 1; end;
     1     2     3     4

     5     6     7     8

     9    10    11    12

    13    14    15    16

>> A

A =

     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4

Rails - How to use a Helper Inside a Controller

My problem resolved with Option 1. Probably the simplest way is to include your helper module in your controller:

class ApplicationController < ActionController::Base
  include ApplicationHelper

...

Converting integer to string in Python

>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5

CSS Input with width: 100% goes outside parent's bound

I tried these solutions but never got a conclusive result. In the end I used proper semantic markup with a fieldset. It saved having to add any width calculations and any box-sizing.

It also allows you to set the form width as you require and the inputs remain within the padding you need for your edges.

In this example I have put a border on the form and fieldset and an opaque background on the legend and fieldset so you can see how they overlap and sit with each other.

<html>
  <head>
  <style>
    form {
      width: 300px;
      margin: 0 auto;
      border: 1px solid;
    }
    fieldset {
      border: 0;
      margin: 0;
      padding: 0 20px 10px;
      border: 1px solid blue;
      background: rgba(0,0,0,.2);
    }
    legend {
      background: rgba(0,0,0,.2);
      width: 100%;
      margin: 0 -20px;
      padding: 2px 20px;
      color: $col1;
      border: 0;
    }
    input[type="email"],
    input[type="password"],
    button {
      width: 100%;
      margin: 0 0 10px;
      padding: 0 10px;
    }
    input[type="email"],
    input[type="password"] {
      line-height: 22px;
      font-size: 16px;
    }
    button {
    line-height: 26px;
    font-size: 20px;
    }
  </style>
  </head>
  <body>
  <form>
      <fieldset>
          <legend>Log in</legend>
          <p>You may need some content here, a message?</p>
          <input type="email" id="email" name="email" placeholder="Email" value=""/>
          <input type="password" id="password" name="password" placeholder="password" value=""/>
          <button type="submit">Login</button>
      </fieldset>
  </form>
  </body>
</html>

How do you declare string constants in C?

One advantage (albeit very slight) of defining string constants is that you can concatenate them at compile time:

#define HELLO "hello"
#define WORLD "world"

puts( HELLO WORLD );

Not sure that's really an advantage, but it is a technique that cannot be used with const char *'s.

Chrome ignores autocomplete="off"

to anyone looking for a solution to this, I finally figure it out.

Chrome only obey's the autocomplete="off" if the page is a HTML5 page (I was using XHTML).

I converted my page to HTML5 and the problem went away (facepalm).

Returning a file to View/Download in ASP.NET MVC

FileVirtualPath --> Research\Global Office Review.pdf

public virtual ActionResult GetFile()
{
    return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

For those coming here with a Mac:

I had the same issue and the problem was, I created an emulator with API Level 29 but removed that SDK and installed 28 instead. The emulator that was not able to be launched anymore.

Therefore check the AVD Manager if your emulator really can be launched.

How do you make Git work with IntelliJ?

Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works

Create session factory in Hibernate 4

Configuration hibConfiguration = new Configuration()
            .addResource("wp4core/hibernate/config/table.hbm.xml")
            .configure();       

serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(hibConfiguration.getProperties())
            .buildServiceRegistry();

sessionFactory = hibConfiguration.buildSessionFactory(serviceRegistry);
session = sessionFactory.withOptions().openSession();

How to count occurrences of a column value efficiently in SQL?

Here's another solution. this one uses very simple syntax. The first example of the accepted solution did not work on older versions of Microsoft SQL (i.e 2000)

SELECT age, count(*)
FROM Students 
GROUP by age
ORDER BY age

What is a typedef enum in Objective-C?

You can use in the below format, Raw default value starting from 0, so

  • kCircle is 0,
  • kRectangle is 1,
  • kOblateSpheroid is 2.

You can assign your own specific start value.

typedef enum : NSUInteger {
    kCircle, // for your value; kCircle = 5, ...
    kRectangle,
    kOblateSpheroid
} ShapeType;

ShapeType circleShape = kCircle;
NSLog(@"%lu", (unsigned long) circleShape); // prints: 0

Howto? Parameters and LIKE statement SQL

you have to do:

LIKE '%' + @param + '%'

How to get function parameter names/values dynamically?

Below is the code taken from AngularJS which uses the technique for its dependency injection mechanism.

And here is an explanation of it taken from http://docs.angularjs.org/tutorial/step_05

Angular's dependency injector provides services to your controller when the controller is being constructed. The dependency injector also takes care of creating any transitive dependencies the service may have (services often depend upon other services).

Note that the names of arguments are significant, because the injector uses these to look up the dependencies.

/**
 * @ngdoc overview
 * @name AUTO
 * @description
 *
 * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
 */

var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(.+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
  var $inject,
      fnText,
      argDecl,
      last;

  if (typeof fn == 'function') {
    if (!($inject = fn.$inject)) {
      $inject = [];
      fnText = fn.toString().replace(STRIP_COMMENTS, '');
      argDecl = fnText.match(FN_ARGS);
      forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
        arg.replace(FN_ARG, function(all, underscore, name){
          $inject.push(name);
        });
      });
      fn.$inject = $inject;
    }
  } else if (isArray(fn)) {
    last = fn.length - 1;
    assertArgFn(fn[last], 'fn')
    $inject = fn.slice(0, last);
  } else {
    assertArgFn(fn, 'fn', true);
  }
  return $inject;
}

How to get the new value of an HTML input after a keypress has modified it?

You can try this code (requires jQuery):

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#foo').keyup(function(e) {
                var v = $('#foo').val();
                $('#debug').val(v);
            })
        });
    </script>
</head>
<body>
    <form>
        <input type="text" id="foo" value="bar"><br>
        <textarea id="debug"></textarea>
    </form>
</body>
</html>

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

How to make blinking/flashing text with CSS 3

<style>
    .class1{
        height:100px;
        line-height:100px;
        color:white;
        font-family:Bauhaus 93;
        padding:25px;
        background-color:#2a9fd4;
        border:outset blue;
        border-radius:25px;
        box-shadow:10px 10px green;
        font-size:45px;
    }
     .class2{
        height:100px;
        line-height:100px;
        color:white;
        font-family:Bauhaus 93;
        padding:25px;
        background-color:green;
        border:outset blue;
        border-radius:25px;
        box-shadow:10px 10px green;
        font-size:65px;
    }
</style>
<script src="jquery-3.js"></script>
<script>
    $(document).ready(function () {
        $('#div1').addClass('class1');
        var flag = true;

        function blink() {
            if(flag)
            {
                $("#div1").addClass('class2');
                flag = false;
            }
            else
            { 
                if ($('#div1').hasClass('class2'))
                    $('#div1').removeClass('class2').addClass('class1');
                flag = true;
            }
        }
        window.setInterval(blink, 1000);
    });
</script>

jQuery Validate - Enable validation for hidden fields

This worked for me within an ASP.NET site. To enable validation on some hidden fields use this code

$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";

To enable validation for all elements of form use this one $("form").data("validator").settings.ignore = "";

Note that use them within $(document).ready(function() { })

How do I import modules or install extensions in PostgreSQL 9.1+?

Postgrseql 9.1 provides for a new command CREATE EXTENSION. You should use it to install modules.

Modules provided in 9.1 can be found here.. The include,

adminpack , auth_delay , auto_explain , btree_gin , btree_gist
, chkpass , citext , cube , dblink , dict_int
, dict_xsyn , dummy_seclabel , earthdistance , file_fdw , fuzzystrmatch
, hstore , intagg , intarray , isn , lo
, ltree , oid2name , pageinspect , passwordcheck , pg_archivecleanup
, pgbench , pg_buffercache , pgcrypto , pg_freespacemap , pgrowlocks
, pg_standby , pg_stat_statements , pgstattuple , pg_test_fsync , pg_trgm
, pg_upgrade , seg , sepgsql , spi , sslinfo , tablefunc
, test_parser , tsearch2 , unaccent , uuid-ossp , vacuumlo
, xml2

If for instance you wanted to install earthdistance, simply use this command:

CREATE EXTENSION earthdistance;

If you wanted to install an extension with a hyphen in its name, like uuid-ossp, you need to enclose the extension name in double quotes:

CREATE EXTENSION "uuid-ossp";

MySQL select one column DISTINCT, with corresponding other columns

Keep in mind when using the group by and order by that MySQL is the ONLY database that allows for columns to be used in the group by and/or order by piece that are not part of the select statement.

So for example: select column1 from table group by column2 order by column3

That will not fly in other databases like Postgres, Oracle, MSSQL, etc. You would have to do the following in those databases

select column1, column2, column3 from table group by column2 order by column3

Just some info in case you ever migrate your current code to another database or start working in another database and try to reuse code.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()

    if not ret:
        cap = cv.VideoCapture(camera_url)
        continue

    # do your processing here

And it works perfectly!

Running Python code in Vim

Think about using shebang line, so you will be able to use it with still any language, not only Python.

Adding shebang:

Add this to first line of your script:

#!/usr/bin/env python3

or this, if you are using Python 2:

#!/usr/bin/env python2

Vim keymap:

Add this to your ~/.vimrc:

nmap <F7> :w<cr>:!clear;"%:p"<cr>

Make file executable:

Type in Vim:

:!chmod +x %

or in terminal:

chmod +x script_name.py

Explanation:

When F7 is pressed in normal mode, Vim will try to execute current file as bash script. Then bash interpreter will see shebang line and understand, that this file should be passed to Python (or any other programm if needed).

Also you will be able to run your script from terminal using it's name:

./script_name.py

instead of this way (that will work too):

python3 script_name.py

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

Android changing Floating Action Button color

just use,

app:backgroundTint="@color/colorPrimary"

dont use,

android:backgroundTint="@color/colorPrimary"

How can change width of dropdown list?

try the !important argument to make sure the CSS is not conflicting with any other styles you have specified. Also using a reset.css is good before you add your own styles.

select#wgmstr {
    max-width: 50px;
    min-width: 50px;
    width: 50px !important;
}

or

<select name="wgtmsr" id="wgtmsr" style="width: 50px !important; min-width: 50px; max-width: 50px;">

PHP how to get the base domain/url?

2 lines to solve it

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$myDomain = preg_replace('/^www\./', '', parse_url($actual_link, PHP_URL_HOST));

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

For Loop on Lua

By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:

Way1

names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end

Way2

names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end

Way1 uses the table index/key , on your table names each element has a key starting from 1, for example:

names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John

So you just make i go from 1 to 3.

On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:

names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end

prints the following:

1   John
2   Joe
myKey   myValue

Can't access to HttpContext.Current

This is because you are referring to property of controller named HttpContext. To access the current context use full class name:

System.Web.HttpContext.Current

However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current as being deprecated inside ASP.NET MVC. The correct way to access current context is

this.ControllerContext.HttpContext

or if you are inside a Controller, just use member

this.HttpContext

How to delete images from a private docker registry?

Problem 1

You mentioned it was your private docker registry, so you probably need to check Registry API instead of Hub registry API doc, which is the link you provided.

Problem 2

docker registry API is a client/server protocol, it is up to the server's implementation on whether to remove the images in the back-end. (I guess)

DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)

Detailed explanation

Below I demo how it works now from your description as my understanding for your questions.

I run a private docker registry. I use the default one, and listen on port 5000.

docker run -d -p 5000:5000 registry

Then I tag the local image and push into it.

$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
Sending image list
Pushing repository localhost:5000/ubuntu (1 tags)
511136ea3c5a: Image successfully pushed
d7ac5e4f1812: Image successfully pushed
2f4b4d6a4a06: Image successfully pushed
83ff768040a0: Image successfully pushed
6c37f792ddac: Image successfully pushed
e54ca5efa2e9: Image successfully pushed
Pushing tag for rev [e54ca5efa2e9] on {http://localhost:5000/v1/repositories/ubuntu/tags/latest}

After that I can use Registry API to check it exists in your private docker registry

$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags
{"latest": "e54ca5efa2e962582a223ca9810f7f1b62ea9b5c3975d14a5da79d3bf6020f37"}

Now I can delete the tag using that API !!

$ curl -X DELETE localhost:5000/v1/repositories/ubuntu/tags/latest
true

Check again, the tag doesn't exist in my private registry server

$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags/latest
{"error": "Tag not found"}

Server.UrlEncode vs. HttpUtility.UrlEncode

I had significant headaches with these methods before, I recommend you avoid any variant of UrlEncode, and instead use Uri.EscapeDataString - at least that one has a comprehensible behavior.

Let's see...

HttpUtility.UrlEncode(" ") == "+" //breaks ASP.NET when used in paths, non-
                                  //standard, undocumented.
Uri.EscapeUriString("a?b=e") == "a?b=e" // makes sense, but rarely what you
                                        // want, since you still need to
                                        // escape special characters yourself

But my personal favorite has got to be HttpUtility.UrlPathEncode - this thing is really incomprehensible. It encodes:

  • " " ==> "%20"
  • "100% true" ==> "100%%20true" (ok, your url is broken now)
  • "test A.aspx#anchor B" ==> "test%20A.aspx#anchor%20B"
  • "test A.aspx?hmm#anchor B" ==> "test%20A.aspx?hmm#anchor B" (note the difference with the previous escape sequence!)

It also has the lovelily specific MSDN documentation "Encodes the path portion of a URL string for reliable HTTP transmission from the Web server to a client." - without actually explaining what it does. You are less likely to shoot yourself in the foot with an Uzi...

In short, stick to Uri.EscapeDataString.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

As mentioned earlier, you'll create the add and delete commands. You can use svn move on both your working copy or the repository url. If you use your working copy, the changes won't be committed - you'll need to commit in a separate operation.

If you svn move a URL, you'll need to supply a --message, and the changes will be reflected in the repository immediately.

How to check certificate name and alias in keystore files?

In order to get all the details I had to add the -v option to romaintaz answer:

keytool -v -list -keystore <FileName>.keystore

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.

Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.

Syntax

ALTER TRIGGER trigger Name DISABLE;

ALTER TRIGGER trigger_Name ENABLE;

How can I make the cursor turn to the wait cursor?

Building on the previous, my preferred approach (since this is a frequently performed action) is to wrap the wait cursor code in an IDisposable helper class so it can be used with using() (one line of code), take optional parameters, run the code within, then clean up (restore cursor) afterwards.

public class CursorWait : IDisposable
{
    public CursorWait(bool appStarting = false, bool applicationCursor = false)
    {
        // Wait
        Cursor.Current = appStarting ? Cursors.AppStarting : Cursors.WaitCursor;
        if (applicationCursor) Application.UseWaitCursor = true;
    }

    public void Dispose()
    {
        // Reset
        Cursor.Current = Cursors.Default;
        Application.UseWaitCursor = false;
    }
}

Usage:

using (new CursorWait())
{
    // Perform some code that shows cursor
}

What is [Serializable] and when should I use it?

Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.

It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.

It has NOTHING to do with XML or JSON serialization.

Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.

Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

How to choose the id generation strategy when using JPA and Hibernate

Basically, you have two major choices:

  • You can generate the identifier yourself, in which case you can use an assigned identifier.
  • You can use the @GeneratedValue annotation and Hibernate will assign the identifier for you.

For the generated identifiers you have two options:

  • UUID identifiers.
  • Numerical identifiers.

For numerical identifiers you have three options:

  • IDENTITY
  • SEQUENCE
  • TABLE

IDENTITY is only a good choice when you cannot use SEQUENCE (e.g. MySQL) because it disables JDBC batch updates.

SEQUENCE is the preferred option, especially when used with an identifier optimizer like pooled or pooled-lo.

TABLE is to be avoided since it uses a separate transaction to fetch the identifier and row-level locks which scales poorly.

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

My complete code as below is working well:

package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmail
{
public static void main(String [] args)
{    
    // Sender's email ID needs to be mentioned
     String from = "[email protected]";
     String pass ="test123";
    // Recipient's email ID needs to be mentioned.
   String to = "[email protected]";

   String host = "smtp.gmail.com";

   // Get system properties
   Properties properties = System.getProperties();
   // Setup mail server
   properties.put("mail.smtp.starttls.enable", "true");
   properties.put("mail.smtp.host", host);
   properties.put("mail.smtp.user", from);
   properties.put("mail.smtp.password", pass);
   properties.put("mail.smtp.port", "587");
   properties.put("mail.smtp.auth", "true");

   // Get the default Session object.
   Session session = Session.getDefaultInstance(properties);

   try{
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));

      // Set Subject: header field
      message.setSubject("This is the Subject Line!");

      // Now set the actual message
      message.setText("This is actual message");

      // Send message
      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      System.out.println("Sent message successfully....");
   }catch (MessagingException mex) {
      mex.printStackTrace();
   }
}
}

executing shell command in background from script

This works because the it's a static variable. You could do something much cooler like this:

filename="filename"
extension="txt"
for i in {1..20}; do
    eval "filename${i}=${filename}${i}.${extension}"
    touch filename${i}
    echo "this rox" > filename${i}
done

This code will create 20 files and dynamically set 20 variables. Of course you could use an array, but I'm just showing you the feature :). Note that you can use the variables $filename1, $filename2, $filename3... because they were created with evaluate command. In this case I'm just creating files, but you could use to create dynamically arguments to the commands, and then execute in background.

SQL Last 6 Months

In MySQL

where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month

SQLFiddle demo

In SQL Server

where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)

SQLFiddle demo