Programs & Examples On #Datafeed

Sending HTTP POST Request In Java

Call HttpURLConnection.setRequestMethod("POST") and HttpURLConnection.setDoOutput(true); Actually only the latter is needed as POST then becomes the default method.

jQuery .val change doesn't change input value

Changing the value property does not change the defaultValue. In the code (retrieved with .html() or innerHTML) the value attribute will contain the defaultValue, not the value property.

TabLayout tab selection

If it so happens that your default tab is the first one(0) and you happen to switch to a fragment, then you must manually replace the fragment for the first time. This is because the tab is selected before the listener gets registered.

private TabLayout mTabLayout;

...

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_tablayout, container, false);
    mTabLayout = view.findViewById(R.id.sliding_tabs);
    mTabLayout.addOnTabSelectedListener(mOnTabSelectedListener);

    getActivity().getSupportFragmentManager().beginTransaction()
        .replace(R.id.tabContent, MyFirstFragment.newInstance()).commit();
    return view;
}

Alternatively, you can consider calling getTabAt(0).select() and overriding onTabReselected like so:

@Override
public void onTabReselected(TabLayout.Tab tab) {
    // Replace the corresponding tab fragment.
}

This would work because you are essentially replacing the fragment on every tab reselect.

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

How do I add a resources folder to my Java project in Eclipse

If aim is to create a resources folder parallel to src/main/java, then do the following:

Right Click on your project > New > Source Folder
Provide Folder Name as src/main/resources
Finish

How do I center content in a div using CSS?

with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center

QString to char* conversion

It is a viable way to use std::vector as an intermediate container:

QString dataSrc("FooBar");
QString databa = dataSrc.toUtf8();
std::vector<char> data(databa.begin(), databa.end());
char* pDataChar = data.data();

How to hide element using Twitter Bootstrap and show it using jQuery?

Simply:

$(function(){
  $("#my-div").removeClass('hide');
});

Or if you somehow want the class to still be there:

$(function(){
  $("#my-div").css('display', 'block !important');
});

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

What fixed this symptom for me (VS2013) is uninstalling then reinstalling the EF package with Nuget. The difference in the csproj file changed this...

<Reference Include="EntityFramework">
  <HintPath>..\packages\EntityFramework.6.1.1\lib\net45\EntityFramework.dll</HintPath>
</Reference>

...into this...

<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\EntityFramework.6.1.1\lib\net45\EntityFramework.dll</HintPath>
</Reference>

I don't fully understand why yet, but it worked at least.

Creating an instance using the class name and calling constructor

Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing:

Case 1:- Here, is a small code in this Main class:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {

    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        // Get class name as string.
        String myClassName = Base.class.getName();
        // Create class of type Base.
        Class<?> myClass = Class.forName(myClassName);
        // Create constructor call with argument types.
        Constructor<?> ctr = myClass.getConstructor(String.class);
        // Finally create object of type Base and pass data to constructor.
        String arg1 = "My User Data";
        Object object = ctr.newInstance(new Object[] { arg1 });
        // Type-cast and access the data from class Base.
        Base base = (Base)object;
        System.out.println(base.data);
    }

}

And, here is the Base class structure:

public class Base {

    public String data = null;

    public Base() 
    {
        data = "default";
        System.out.println("Base()");
    }

    public Base(String arg1) {
        data = arg1;
        System.out.println("Base("+arg1+")");
    }

}

Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. For example, passing 3 arguments as parameter to the Base constructor will need the constructor to be created in class and a code change in above as:

Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" }); 

And here the Base class should somehow look like:

public class Base {

    public Base(String a, String b, String c){
        // This constructor need to be created in this case.
    }   
}

Note:- Don't forget to handle the various exceptions which need to be handled in the code.

Angular 2 Dropdown Options Default Value

You can do as above:

<select class="form-control" 
        [(ngModel)]="selectedWorkout" 
        (ngModelChange)="updateWorkout($event)">
    <option *ngFor="#workout of workouts;
                    let itemIndex = index"
            [attr.selected]="itemIndex == 0">
    {{workout.name}}
    </option>
</select>

In above code as you can see, selected attribute of the repeating option is set on checking index of the repeating loop of list. [attr.< html attribute name >] is used for setting html attribute in angular2.

Another approach will be setting model value in typescript file as :

this.selectedWorkout = this.workouts.length > 0
                       ? this.workouts[0].name
                       : 'No data found';//'arm'

How to check for Is not Null And Is not Empty string in SQL server?

in basic way

SELECT *
FROM [TableName]
WHERE column_name!='' AND column_name IS NOT NULL

How can I get table names from an MS Access Database?

SELECT 
Name 
FROM 
MSysObjects 
WHERE 
(Left([Name],1)<>"~") 
AND (Left([Name],4) <> "MSys") 
AND ([Type] In (1, 4, 6)) 
ORDER BY 
Name

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

For anyone struggling with similar cases

No index signature with a parameter of type 'string' was found on type X

trying to use it with simple objects (used as dicts) like:

DNATranscriber = {
   G:"C",
   C: "G",
   T: "A",
   A: "U"
}

and trying to dynamically access the value from a calculated key like:

const key = getFirstType(dnaChain);
const result = DNATranscriber[key];

and you faced the error as shown above, you can use the keyof operator and try something like

const key = getFirstType(dnaChain) as keyof typeof DNATranscriber;

certainly you will need a guard at the result but if it seems more intuitive than some custom types magic, it is ok.

XPath using starts-with function

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

How to convert "0" and "1" to false and true

You can use that form:

return returnValue.Equals("1") ? true : false;

Or more simply (thanks to Jurijs Kastanovs):

return returnValue.Equals("1");

MongoDB vs Firebase

Firebase is designed for real-time updates. It easily integrates with angular. Both are NoSQL databases. MongoDB can also do this with Angular through Socket.io integration. Meteor.js also makes use of MongoDB with an open socket connection for real-time updates.

MongoDB can be run locally, or hosted on many different cloud based providers. Firebase, in my opinion is great for smaller apps, very quick to get up and running. MongoDB is ideal for more robust larger apps, real-time integration is possible but it takes a bit more work.

Compile error: package javax.servlet does not exist

Even after trying suggested solution, it was not solving my problem because there where many instance of java path were entered by me.

  1. I removed all java related path (different version java) from "Path, JAVA_HOME, JRE_HOME" and created from fresh.

  2. i have set (path may changes as per different installation)
    a. JAVA_HOME as C:\Program Files\Java\jdk1.8.0_191
    b. JRE_HOME as C:\Program Files\Java\jdk1.8.0_191\jre\lib
    c. add binary file path in path: C:\Program Files\Java\jdk1.8.0_191\bin
    d. CLASSPATH as C:\apache-tomcat-7.0.93\lib

  3. never try in the same command prompt if its already open while doing changes/creting system/user variables. close it and open new one.

Reference Image: enter image description here

WPF ListView - detect when selected item is clicked

I would also suggest deselecting an item after it has been clicked and use the MouseDoubleClick event

private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    try {
        //Do your stuff here
        listBox.SelectedItem = null;
        listBox.SelectedIndex = -1;
    } catch (Exception ex) {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
}

How do I find out if a column exists in a VB.Net DataRow

Another way to find out if a column exists is to check for Nothing the value returned from the Columns collection indexer when passing the column name to it:

If dataRow.Table.Columns("ColumnName") IsNot Nothing Then
    MsgBox("YAY")
End If

This approach might be preferred over the one that uses the Contains("ColumnName") method when the following code will subsequently need to get that DataColumn for further usage. For example, you may want to know which type has a value stored in the column:

Dim column = DataRow.Table.Columns("ColumnName")
If column IsNot Nothing Then
    Dim type = column.DataType
End If

In this case this approach saves you a call to the Contains("ColumnName") at the same time making your code a bit cleaner.

Easiest way to read/write a file's content in Python

Slow, ugly, platform-specific... but one-liner ;-)

import subprocess

contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]

Is there a difference between PhoneGap and Cordova commands?

I found this difference which forced me to use a mixed bag of phonegap and cordova cli commands when building my app:

'phonegap plugin add' couldn't handle command line parameters correctly, whereas 'cordova platform add' works flawlessly

The command I use is:

'cordova plugin add https://github.com/crittercism/PhoneGap.git --variable IOS_APP_ID="[my_license_key]"

Note I am using phonegap 3.5

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

How to get all the AD groups for a particular user?

This is how I list all the groups (direct and indirect) for a specific Distinguished Name:

The string 1.2.840.113556.1.4.1941 specifies LDAP_MATCHING_RULE_IN_CHAIN.

This rule is limited to filters that apply to the DN. This is a special "extended" match operator that walks the chain of ancestry in objects all the way to the root until it finds a match.

This method is 25 times faster than the UserPrincipal.GetGroups() method in my testing.

Note: The primary group (typically Domain Users) is not returned by this or GetGroups() method. To get the primary group name too, I've confirmed this method works.

Additionally, I found this list of LDAP filters extremely useful.

private IEnumerable<string> GetGroupsForDistinguishedName(DirectoryEntry domainDirectoryEntry, string distinguishedName)
{
    var groups = new List<string>();
    if (!string.IsNullOrEmpty(distinguishedName))
    {
        var getGroupsFilterForDn = $"(&(objectCategory=group)(member:1.2.840.113556.1.4.1941:={distinguishedName}))";
        using (DirectorySearcher dirSearch = new DirectorySearcher(domainDirectoryEntry))
        {
            dirSearch.Filter = getGroupsFilterForDn;
            dirSearch.PropertiesToLoad.Add("name");

            using (var results = dirSearch.FindAll())
            {
                foreach (SearchResult result in results)
                {
                    if (result.Properties.Contains("name"))
                        groups.Add((string)result.Properties["name"][0]);
                }
            }
        }
    }

    return groups;
}

Where do I find the definition of size_t?

This way you always know what the size is, because a specific type is dedicated to sizes. The very own question shows that it can be an issue: is it an int or an unsigned int? Also, what is the magnitude (short, int, long, etc.)?

Because there is a specific type assigned, you don't have to worry about the length or the signed-ness.

The actual definition can be found in the C++ Reference Library, which says:

Type: size_t (Unsigned integral type)

Header: <cstring>

size_t corresponds to the integral data type returned by the language operator sizeof and is defined in the <cstring> header file (among others) as an unsigned integral type.

In <cstring>, it is used as the type of the parameter num in the functions memchr, memcmp, memcpy, memmove, memset, strncat, strncmp, strncpy and strxfrm, which in all cases it is used to specify the maximum number of bytes or characters the function has to affect.

It is also used as the return type for strcspn, strlen, strspn and strxfrm to return sizes and lengths.

missing FROM-clause entry for table

SELECT 
   AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, 
   BillLimit, Mode, PNotes, gtab82.memno 
FROM
   VCustomer AS v1
INNER JOIN   
   gtab82 ON gtab82.memacid = v1.AcId 
WHERE (AcGrCode = '204' OR CreDebt = 'True') 
AND Masked = 'false'
ORDER BY AcName

You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer but only use it in the ON clause for uncertain reasons. You may want to review that aspect of your code.

Select mySQL based only on month and year

$q="SELECT * FROM projects WHERE YEAR(date) = 2012 AND MONTH(date) = 1;

intellij idea - Error: java: invalid source release 1.9

Gradle I had the same issue and changing all the settings given in the earlier solutions made no difference. Than I went to the build.gradle and found this line and deleted it.

sourceCompatibility = '11'

and it worked! :)

Getting "Cannot call a class as a function" in my React Project

In my case, using JSX a parent component was calling other components without the "<>"

 <ComponentA someProp={someCheck ? ComponentX : ComponentY} />

fix

<ComponentA someProp={someCheck ? <ComponentX /> : <ComponentY />} />

How to reverse an std::string?

I'm not sure what you mean by a string that contains binary numbers. But for reversing a string (or any STL-compatible container), you can use std::reverse(). std::reverse() operates in place, so you may want to make a copy of the string first:

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string foo("foo");
    std::string copy(foo);
    std::cout << foo << '\n' << copy << '\n';

    std::reverse(copy.begin(), copy.end());
    std::cout << foo << '\n' << copy << '\n';
}

Mailto: Body formatting

From the first result on Google:

mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second

Capturing image from webcam in java?

I used Webcam Capture API...u can download from this http://webcam-capture.sarxos.pl/

        webcam = Webcam.getDefault();
        webcam.open();

        if (webcam.isOpen()) { //if web cam open 
            BufferedImage image = webcam.getImage();
            JLabel imageLbl = new JLabel();
            imageLbl.setSize(640, 480);             //show captured image
            imageLbl.setIcon(new ImageIcon(image));

            int showConfirmDialog = JOptionPane.showConfirmDialog(null, imageLbl, "Image Viewer", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(""));

            if (showConfirmDialog == JOptionPane.YES_OPTION) {
                JFileChooser chooser = new JFileChooser();
                chooser.setDialogTitle("Save Image");
                chooser.setFileFilter(new FileNameExtensionFilter("IMAGES ONLY", "png", "jpeg", "jpg")); //this file extentions are shown
                int showSaveDialog = chooser.showSaveDialog(this);
                if (showSaveDialog == 0) {                  //if pressed 'Save' button
                    String filePath = chooser.getCurrentDirectory().toString().replace("\\", "/");
                    String fileName = chooser.getSelectedFile().getName(); //get user entered file name to save
                    ImageIO.write(image, "PNG", new File(filePath + "/" + fileName + ".png"));

                }
            }
        }

Using dig to search for SPF records

The dig utility is pretty convenient to use. The order of the arguments don't really matter.I'll show you some easy examples.
To get all root name servers use

# dig

To get a TXT record of a specific host use

# dig example.com txt
# dig host.example.com txt

To query a specific name server just add @nameserver.tld

# dig host.example.com txt @a.iana-servers.net

The SPF RFC4408 says that SPF records can be stored as SPF or TXT. However nearly all use only TXT records at the moment. So you are pretty safe if you only fetch TXT records.

I made a SPF checker for visualising the SPF records of a domain. It might help you to understand SPF records better. You can find it here: http://spf.myisp.ch

Reference an Element in a List of Tuples

The code

my_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
    print t

prints

(1, 2)
(3, 4)
(5, 6)

The loop iterates over my_list, and assigns the elements of my_list to t one after the other. The elements of my_list happen to be tuples, so t will always be a tuple. To access the first element of the tuple t, use t[0]:

for t in my_list:
    print t[0]

To access the first element of the tuple at the given index i in the list, you can use

print my_list[i][0]

PHP Undefined Index

I don't see php file, but that could be that -
replace in your php file:

$query_age = $_GET['query_age'];

with:

$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.

How to create custom exceptions in Java?

public class MyException extends Exception {
        // special exception code goes here
}

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
   // something
}

Default Activity not found in Android Studio

I have tried all solutions, but not working at all. than I have tried to disable Instant run in my android studio.

Go to Android Studio Settings or Preferences (for MAC) -> Build,Execution,Deployment -> Instant Run.

uncheck the Instant run functionality and than after click sync project with gradle files from file menu

now run your build...

CSS to stop text wrapping under image

setting display:flexfor the text worked for me.

React Router Pass Param to Component

if you are using class component, you are most likely to use GSerjo suggestion. Pass in the params via <Route> props to your target component:

exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />}

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Adding a stylesheet to asp.net (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:

        @Styles.Render("~/Content/Main.css")

The entire head will look somethink like that:

    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>
         @Styles.Render("~/Content/main.css")
    </head>

Hope it helps!!

RichTextBox (WPF) does not have string property "Text"

"Extended WPF Toolkit" now provides a richtextbox with the Text property.

You can get or set the text in different formats (XAML, RTF and plaintext).

Here is the link: Extended WPF Toolkit RichTextBox

What is the difference between the kernel space and the user space?

The Random Access Memory (RAM) can be logically divided into two distinct regions namely - the kernel space and the user space.(The Physical Addresses of the RAM are not actually divided only the Virtual Addresses, all this implemented by the MMU)

The kernel runs in the part of memory entitled to it. This part of memory cannot be accessed directly by the processes of the normal users, while as the kernel can access all parts of the memory. To access some part of the kernel, the user processes have to use the predefined system calls i.e. open, read, write etc. Also, the C library functions like printf call the system call write in turn.

The system calls act as an interface between the user processes and the kernel processes. The access rights are placed on the kernel space in order to stop the users from messing up with the kernel, unknowingly.

So, when a system call occurs, a software interrupt is sent to the kernel. The CPU may hand over the control temporarily to the associated interrupt handler routine. The kernel process which was halted by the interrupt resumes after the interrupt handler routine finishes its job.

Python float to int conversion

Languages that use binary floating point representations (Python is one) cannot represent all fractional values exactly. If the result of your calculation is 250.99999999999 (and it might be), then taking the integer part will result in 250.

A canonical article on this topic is What Every Computer Scientist Should Know About Floating-Point Arithmetic.

How to check whether particular port is open or closed on UNIX?

netstat -ano|grep 443|grep LISTEN

will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

configuring project ':app' failed to find Build Tools revision

For me, dataBinding { enabled true } was enabled in gradle, removing this helped me

How to display my application's errors in JSF?

Found this while Googling. The second post makes a point about the different phases of JSF, which might be causing your error message to become lost. Also, try null in place of "newPassword" because you do not have any object with the id newPassword.

How do I iterate and modify Java Sets?

I don't like very much iterator's semantic, please consider this as an option. It's also safer as you publish less of your internal state

private Map<String, String> JSONtoMAP(String jsonString) {

    JSONObject json = new JSONObject(jsonString);
    Map<String, String> outMap = new HashMap<String, String>();

    for (String curKey : (Set<String>) json.keySet()) {
        outMap.put(curKey, json.getString(curKey));
    }

    return outMap;

}

Convert a string representation of a hex dump to a byte array using Java?

For what it's worth, here's another version which supports odd length strings, without resorting to string concatenation.

public static byte[] hexStringToByteArray(String input) {
    int len = input.length();

    if (len == 0) {
        return new byte[] {};
    }

    byte[] data;
    int startIdx;
    if (len % 2 != 0) {
        data = new byte[(len / 2) + 1];
        data[0] = (byte) Character.digit(input.charAt(0), 16);
        startIdx = 1;
    } else {
        data = new byte[len / 2];
        startIdx = 0;
    }

    for (int i = startIdx; i < len; i += 2) {
        data[(i + 1) / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4)
                + Character.digit(input.charAt(i+1), 16));
    }
    return data;
}

How do I delete all messages from a single queue using the CLI?

IMPORTANT NOTE: This will delete all users and config.

ALERT !!

ALERT !!

I don't suggest this answer until unless you want to delete data from all of the queues, including users and configs. Just Reset it !!!

rabbitmqctl stop_app
rabbitmqctl reset
rabbitmqctl start_app

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

I use from selenium-java-3.141.59 in windows 10 and solved my problem with this code:

System.setProperty("webdriver.gecko.driver", "C:\\gecko\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();

Custom toast on Android: a simple example

Heads Up, Updates to toasts in Android 11

Custom toasts from the background are blocked, Android 11 protects users by deprecating custom toast views. For security reasons and to maintain a good user experience, the system blocks toasts that contain custom views if those toasts are sent from the background by an app that targets Android 11.

addCallback() method added in Android R If you want to be notified when a toast (text or custom) appears or disappears.

The most important text in toast API changes that for apps that target Android 11 the getView() method returns null when you access it, So, ensure to protect your apps from FATAL EXCEPTION, you know what I mean :)

Use snackbars instead if applicable.

It's recommended that you use snackbars instead where possible. If your app's use case prevents you from using snackbars, such as when you need to send the user a message while your app is in the background, you can still use text toasts because they aren't restricted by the new behavior change.

See the official docs for more details on the topic.

ASP.NET 4.5 has not been registered on the Web server

Resolved it with VS update.

Follow this link (https://blogs.msdn.microsoft.com/webdev/2014/11/11/dialog-box-may-be-displayed-to-users-when-opening-projects-in-microsoft-visual-studio-after-installation-of-microsoft-net-framework-4-6/)

Resolution: Microsoft has published a fix for all impacted versions of Microsoft Visual Studio.

Visual Studio 2013 –

Download Visual Studio 2013 Update 4 For more information on the Visual Studio 2013 Update 4, please refer to: Visual Studio 2013 Update 4 KB Article Visual Studio 2012

An update to address this issue for Microsoft Visual Studio 2012 has been published: KB3002339 To install this update directly from the Microsoft Download Center, here Visual Studio 2010 SP1

An update to address this issue for Microsoft Visual Studio 2010 SP1 has been published: KB3002340 This update is available from Windows Update To install this update directly from the Microsoft Download Center, here

CURL alternative in Python

You can use HTTP Requests that are described in the Requests: HTTP for Humans user guide.

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.

sudo apt-get install openjfx

NoClassDefFoundError in Java: com/google/common/base/Function

Please include all the jar files of selenium stand-alone and lib folder, then this error will resolved

enable cors in .htaccess

Will be work 100%, Apply in .htaccess:

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(1xyz\.com|2xyz\.com)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

Certificate has either expired or has been revoked

A new problem with Xcode 8, what worked for me was to turn off the new "automatically manage signing" checkbox on the General tab for the target, then turn it back on.

This initiates an on-boarding wizard that sets things up correctly for Xcode 8.

Purpose of installing Twitter Bootstrap through npm?

Answer 1:

  • Downloading bootstrap through npm (or bower) permits you to gain some latency time. Instead of getting a remote resource, you get a local one, it's quicker, except if you use a cdn (check below answer)

  • "npm" was originally to get Node Module, but with the essort of the Javascript language (and the advent of browserify), it has a bit grown up. In fact, you can even download AngularJS on npm, that is not a server side framework. Browserify permits you to use AMD/RequireJS/CommonJS on client side so node modules can be used on client side.

Answer 2:

If you npm install bootstrap (if you dont use a particular grunt or gulp file to move to a dist folder), your bootstrap will be located in "./node_modules/bootstrap/bootstrap.min.css" if I m not wrong.

console.writeline and System.out.println

Here are the primary differences between using System.out/.err/.in and System.console():

  • System.console() returns null if your application is not run in a terminal (though you can handle this in your application)
  • System.console() provides methods for reading password without echoing characters
  • System.out and System.err use the default platform encoding, while the Console class output methods use the console encoding

This latter behaviour may not be immediately obvious, but code like this can demonstrate the difference:

public class ConsoleDemo {
  public static void main(String[] args) {
    String[] data = { "\u250C\u2500\u2500\u2500\u2500\u2500\u2510", 
        "\u2502Hello\u2502",
        "\u2514\u2500\u2500\u2500\u2500\u2500\u2518" };
    for (String s : data) {
      System.out.println(s);
    }
    for (String s : data) {
      System.console().writer().println(s);
    }
  }
}

On my Windows XP which has a system encoding of windows-1252 and a default console encoding of IBM850, this code will write:

???????
?Hello?
???????
+-----+
¦Hello¦
+-----+

Note that this behaviour depends on the console encoding being set to a different encoding to the system encoding. This is the default behaviour on Windows for a bunch of historical reasons.

How to select all instances of a variable and edit variable name in Sublime

Just in case anyone else stumbled on this question while looking for a way to replace a string across multiple files, it is Command+Shift+F

How to choose multiple files using File Upload Control?

step 1: add

<asp:FileUpload runat="server" id="fileUpload1" Multiple="Multiple">
    </asp:FileUpload>

step 2: add

Protected Sub uploadBtn_Click(sender As Object, e As System.EventArgs) Handles uploadBtn.Click
    Dim ImageFiles As HttpFileCollection = Request.Files
    For i As Integer = 0 To ImageFiles.Count - 1
        Dim file As HttpPostedFile = ImageFiles(i)
        file.SaveAs(Server.MapPath("Uploads/") & ImageFiles(i).FileName)
    Next

End Sub

Why do access tokens expire?

A couple of scenarios might help illustrate the purpose of access and refresh tokens and the engineering trade-offs in designing an oauth2 (or any other auth) system:

Web app scenario

In the web app scenario you have a couple of options:

  1. if you have your own session management, store both the access_token and refresh_token against your session id in session state on your session state service. When a page is requested by the user that requires you to access the resource use the access_token and if the access_token has expired use the refresh_token to get the new one.

Let's imagine that someone manages to hijack your session. The only thing that is possible is to request your pages.

  1. if you don't have session management, put the access_token in a cookie and use that as a session. Then, whenever the user requests pages from your web server send up the access_token. Your app server could refresh the access_token if need be.

Comparing 1 and 2:

In 1, access_token and refresh_token only travel over the wire on the way between the authorzation server (google in your case) and your app server. This would be done on a secure channel. A hacker could hijack the session but they would only be able to interact with your web app. In 2, the hacker could take the access_token away and form their own requests to the resources that the user has granted access to. Even if the hacker gets a hold of the access_token they will only have a short window in which they can access the resources.

Either way the refresh_token and clientid/secret are only known to the server making it impossible from the web browser to obtain long term access.

Let's imagine you are implementing oauth2 and set a long timeout on the access token:

In 1) There's not much difference here between a short and long access token since it's hidden in the app server. In 2) someone could get the access_token in the browser and then use it to directly access the user's resources for a long time.

Mobile scenario

On the mobile, there are a couple of scenarios that I know of:

  1. Store clientid/secret on the device and have the device orchestrate obtaining access to the user's resources.

  2. Use a backend app server to hold the clientid/secret and have it do the orchestration. Use the access_token as a kind of session key and pass it between the client and the app server.

Comparing 1 and 2

In 1) Once you have clientid/secret on the device they aren't secret any more. Anyone can decompile and then start acting as though they are you, with the permission of the user of course. The access_token and refresh_token are also in memory and could be accessed on a compromised device which means someone could act as your app without the user giving their credentials. In this scenario the length of the access_token makes no difference to the hackability since refresh_token is in the same place as access_token. In 2) the clientid/secret nor the refresh token are compromised. Here the length of the access_token expiry determines how long a hacker could access the users resources, should they get hold of it.

Expiry lengths

Here it depends upon what you're securing with your auth system as to how long your access_token expiry should be. If it's something particularly valuable to the user it should be short. Something less valuable, it can be longer.

Some people like google don't expire the refresh_token. Some like stackflow do. The decision on the expiry is a trade-off between user ease and security. The length of the refresh token is related to the user return length, i.e. set the refresh to how often the user returns to your app. If the refresh token doesn't expire the only way they are revoked is with an explicit revoke. Normally, a log on wouldn't revoke.

Hope that rather length post is useful.

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Frequently we deal with other fellow java programmers work which create these Stored Procedure. and we do not want to mess around with it. but there is possibility you get the result set where these exec sample return 0 (almost Stored procedure call returning zero).

check this sample :

public void generateINOUT(String USER, int DPTID){

    try {


        conUrl = JdbcUrls + dbServers +";databaseName="+ dbSrcNames+";instance=MSSQLSERVER";

        con = DriverManager.getConnection(conUrl,dbUserNames,dbPasswords);
        //stat = con.createStatement();
        con.setAutoCommit(false); 
        Statement st = con.createStatement(); 

        st.executeUpdate("DECLARE @RC int\n" +
                "DECLARE @pUserID nvarchar(50)\n" +
                "DECLARE @pDepartmentID int\n" +
                "DECLARE @pStartDateTime datetime\n" +
                "DECLARE @pEndDateTime datetime\n" +
                "EXECUTE [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] \n" +
                ""+USER +
                "," +DPTID+
                ",'"+STARTDATE +
                "','"+ENDDATE+"'");

        ResultSet rs = st.getGeneratedKeys();

        while (rs.next()){
              String userID = rs.getString("UserID");
              Timestamp timeIN = rs.getTimestamp("timeIN");
              Timestamp timeOUT = rs.getTimestamp ("timeOUT");
              int totTime = rs.getInt ("totalTime");
              int pivot = rs.getInt ("pivotvalue");

              timeINS = sdz.format(timeIN);
              userIN.add(timeINS);

              timeOUTS = sdz.format(timeOUT);
              userOUT.add(timeOUTS);

              System.out.println("User : "+userID+" |IN : "+timeIN+" |OUT : "+timeOUT+"| Total Time : "+totTime+" | PivotValue : "+pivot);
        }

        con.commit();

    }catch (Exception e) {
        e.printStackTrace();
        System.out.println(e);
        if (e.getCause() != null) {
        e.getCause().printStackTrace();}
    }  
}

I came to this solutions after few days trial and error, googling and get confused ;) it execute below Stored Procedure :

USE [AccessManager]
GO
/****** Object:  StoredProcedure [dbo].[SP_GenerateInOutDetailReportSimple]    
Script Date: 04/05/2013 15:54:11 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER PROCEDURE [dbo].[SP_GenerateInOutDetailReportSimple]
(
@pUserID nvarchar(50),
@pDepartmentID int,
@pStartDateTime datetime,
@pEndDateTime datetime
)
AS


Declare @ErrorCode int
Select @ErrorCode = @@Error

Declare @TransactionCountOnEntry int
If @ErrorCode = 0
Begin
    Select @TransactionCountOnEntry = @@TranCount
    BEGIN TRANSACTION
End


If @ErrorCode = 0
Begin       

    -- Create table variable instead of SQL temp table because report wont pick up the temp table
    DECLARE @tempInOutDetailReport TABLE
    (
        UserID nvarchar(50),
        LogDate datetime,   
        LogDay varchar(20), 
        TimeIN datetime,
        TimeOUT datetime,
        TotalTime int,
        RemarkTimeIn nvarchar(100),
        RemarkTimeOut nvarchar(100),
        TerminalIPTimeIn varchar(50),
        TerminalIPTimeOut varchar(50),
        TerminalSNTimeIn nvarchar(50),
        TerminalSNTimeOut nvarchar(50),
        PivotValue int
    )           

    -- Declare variables for the while loop
    Declare @LogUserID nvarchar(50)
    Declare @LogEventID nvarchar(50)
    Declare @LogTerminalSN nvarchar(50)
    Declare @LogTerminalIP nvarchar(50)
    Declare @LogRemark nvarchar(50)
    Declare @LogTimestamp datetime  
    Declare @LogDay nvarchar(20)

    -- Filter off userID, departmentID, StartDate and EndDate if specified, only process the remaining logs
    -- Note: order by user then timestamp
    Declare LogCursor Cursor For 
    Select distinct access_event_logs.USERID, access_event_logs.EVENTID, 
        access_event_logs.TERMINALSN, access_event_logs.TERMINALIP,
        access_event_logs.REMARKS, access_event_logs.LOCALTIMESTAMP, Datename(dw,access_event_logs.LOCALTIMESTAMP) AS WkDay
    From access_event_logs
        Left Join access_user on access_user.User_ID = access_event_logs.USERID
        Left Join access_user_dept on access_user.User_ID = access_user_dept.User_ID
    Where ((Dept_ID = @pDepartmentID) OR (@pDepartmentID IS NULL))
        And ((access_event_logs.USERID LIKE '%' + @pUserID + '%') OR (@pUserID IS NULL)) 
        And ((access_event_logs.LOCALTIMESTAMP >= @pStartDateTime ) OR (@pStartDateTime IS NULL)) 
        And ((access_event_logs.LOCALTIMESTAMP < DATEADD(day, 1, @pEndDateTime) ) OR (@pEndDateTime IS NULL)) 
        And (access_event_logs.USERID != 'UNKNOWN USER') -- Ignore UNKNOWN USER
    Order by access_event_logs.USERID, access_event_logs.LOCALTIMESTAMP

    Open LogCursor

    Fetch Next 
    From LogCursor
    Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay

    -- Temp storage for IN event details
    Declare @InEventUserID nvarchar(50)
    Declare @InEventDay nvarchar(20)
    Declare @InEventTimestamp datetime
    Declare @InEventRemark nvarchar(100)
    Declare @InEventTerminalIP nvarchar(50)
    Declare @InEventTerminalSN nvarchar(50)

    -- Temp storage for OUT event details
    Declare @OutEventUserID nvarchar(50)        
    Declare @OutEventTimestamp datetime
    Declare @OutEventRemark nvarchar(100)
    Declare @OutEventTerminalIP nvarchar(50)
    Declare @OutEventTerminalSN nvarchar(50)

    Declare @CurrentUser varchar(50) -- used to indicate when we change user group
    Declare @CurrentDay varchar(50) -- used to indicate when we change day
    Declare @FirstEvent int -- indicate the first event we received     
    Declare @ReceiveInEvent int -- indicate we have received an IN event
    Declare @PivotValue int -- everytime we change user or day - we reset it (reporting purpose), if same user..keep increment its value
    Declare @CurrTrigger varchar(50) -- used to keep track of the event of the current event log trigger it is handling 
    Declare @CurrTotalHours int -- used to keep track of total hours of the day of the user

    Declare @FirstInEvent datetime
    Declare @FirstInRemark nvarchar(100)
    Declare @FirstInTerminalIP nvarchar(50)
    Declare @FirstInTerminalSN nvarchar(50)
    Declare @FirstRecord int -- indicate another day of same user

    Set @PivotValue = 0 -- initialised
    Set @CurrentUser = '' -- initialised
    Set @FirstEvent = 1 -- initialised
    Set @ReceiveInEvent = 0 -- initialised  
    Set @CurrTrigger = '' -- Initialised    
    Set @CurrTotalHours = 0 -- initialised
    Set @FirstRecord = 1 -- initialised
    Set @CurrentDay = '' -- initialised

    While @@FETCH_STATUS = 0
    Begin
        -- use to track current log trigger
        Set @CurrTrigger =LOWER(@LogEventID)

        If (@CurrentUser != '' And @CurrentUser != @LogUserID) -- new batch of user
        Begin
            If @ReceiveInEvent = 1  -- previous IN event is not cleared (no OUT is found)
            Begin
                -- Check day
                If (@CurrentDay != @InEventDay) -- change to another day                    
                    Set @PivotValue = 0 -- Reset                        

                Else -- same day
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @InEventDay -- update the day

                -- invalid row (only has IN event)
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                    TerminalSNTimeIn, PivotValue, LogDate )
                values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                                                         
            End                 

            Set @FirstEvent = 1 -- Reset flag (we are having a new user group)
            Set @ReceiveInEvent = 0 -- Reset
            Set @PivotValue = 0 -- Reset
            --Set @CurrentDay = '' -- Reset
        End

        If LOWER(@LogEventID) = 'in' -- IN event
        Begin           
            If @ReceiveInEvent = 1  -- previous IN event is not cleared (no OUT is found)
            Begin
                -- Check day
                If (@CurrentDay != @InEventDay) -- change to another day
                Begin
                    Set @PivotValue = 0 -- Reset

                    --Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                    --  RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    --  LogDate)
                    --values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp,  @CurrTotalHours,
                    --  @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
                    --  DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))  
                End
                Else
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @InEventDay -- update the day


                -- invalid row (only has IN event)
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                    TerminalSNTimeIn, PivotValue, LogDate )
                values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                     
            End         

            If((@CurrentDay != @LogDay And @CurrentDay != '') Or (@CurrentUser != @LogUserID And @CurrentUser != '') )
            Begin

                    Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                        RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                        LogDate)
                    values( @CurrentUser, @CurrentDay, @FirstInEvent, @OutEventTimestamp, @CurrTotalHours,
                        @FirstInRemark, @OutEventRemark, @FirstInTerminalIP, @OutEventTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
                        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))      

                Set @FirstRecord = 1
            End
            -- Save it
            Set @InEventUserID = @LogUserID                         
            Set @InEventDay = @LogDay
            Set @InEventTimestamp = @LogTimeStamp
            Set @InEventRemark = @LogRemark
            Set @InEventTerminalIP = @LogTerminalIP
            Set @InEventTerminalSN = @LogTerminalSN

            If (@FirstRecord = 1) -- save for first in event record of the day
            Begin
                Set @FirstInEvent = @LogTimestamp
                Set @FirstInRemark = @LogRemark
                Set @FirstInTerminalIP = @LogTerminalIP
                Set @FirstInTerminalSN = @LogTerminalSN
                Set @CurrTotalHours = 0 --initialise total hours for another day
            End

            Set @FirstRecord = 0 -- no more first record of the day
            Set @ReceiveInEvent = 1 -- indicate we have received an "IN" event
            Set @FirstEvent = 0  -- no more "first" event
        End
        Else If LOWER(@LogEventID) = 'out' -- OUT event
        Begin
            If @FirstEvent = 1 -- the first OUT record when change users 
            Begin
                -- Check day
                If (@CurrentDay != @LogDay) -- change to another day
                    Set @PivotValue = 0 -- Reset
                Else
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @LogDay -- update the day

                -- Only an OUT event (no IN event) - invalid record but we show it anyway
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
                    PivotValue, LogDate )
                values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
                    DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)))                                              

                Set @FirstEvent = 0 -- not "first" anymore
            End
            Else -- Not first event
            Begin       

                If @ReceiveInEvent = 1 -- if there are IN event previously
                Begin           
                    -- Check day
                    If (@CurrentDay != @InEventDay) -- change to another day                        
                        Set @PivotValue = 0 -- Reset                        
                    Else
                        Set @PivotValue = @PivotValue + 1 -- increment
                    Set @CurrentDay = @InEventDay -- update the day     
                    Set @CurrTotalHours = @CurrTotalHours +  DATEDIFF(second,@InEventTimestamp, @LogTimeStamp) -- update total time             

                    Set @OutEventRemark = @LogRemark
                    Set @OutEventTerminalIP = @LogTerminalIP
                    Set @OutEventTerminalSN = @LogTerminalSN
                    Set @OutEventTimestamp = @LogTimestamp          
                    -- valid row
                    --Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                    --  RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    --  LogDate)
                    --values( @LogUserID, @InEventDay, @InEventTimestamp, @LogTimestamp,  Datediff(second, @InEventTimestamp, @LogTimeStamp),
                    --  @InEventRemark, @LogRemark, @InEventTerminalIP, @LogTerminalIP, @InEventTerminalSN, @LogTerminalSN, @PivotValue,
                    --  DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                      

                    Set @ReceiveInEvent = 0 -- Reset
                End
                Else -- no IN event previously
                Begin
                    -- Check day
                    If (@CurrentDay != @LogDay) -- change to another day
                        Set @PivotValue = 0 -- Reset
                    Else
                        Set @PivotValue = @PivotValue + 1 -- increment
                    Set @CurrentDay = @LogDay -- update the day                         

                    -- invalid row (only has OUT event)
                    Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
                        PivotValue, LogDate )
                    values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
                        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)) )             
                End             
            End         
        End

        Set @CurrentUser = @LogUserID -- update user        

        Fetch Next 
        From LogCursor
        Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
    End 

    -- Need to handle the last log if its IN log as it will not be processed by the while loop
    if @CurrTrigger='in'
    Begin 
    -- Check day
            If (@CurrentDay != @InEventDay) -- change to another day
                Set @PivotValue = 0 -- Reset
            Else -- same day
                Set @PivotValue = @PivotValue + 1 -- increment
            Set @CurrentDay = @InEventDay -- update the day

            -- invalid row (only has IN event)
            Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                TerminalSNTimeIn, PivotValue, LogDate )
            values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))     
    End
    else if @CurrTrigger = 'out'
    Begin
        Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
        RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
        LogDate)
        values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp,  @CurrTotalHours,
        @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))  
    End

    Close LogCursor
    Deallocate LogCursor

    Select * 
    From @tempInOutDetailReport tempTable
        Left Join access_user on access_user.User_ID = tempTable.UserID
    Order By tempTable.UserID, LogDate


End



If @@TranCount > @TransactionCountOnEntry
Begin
     If @ErrorCode = 0
            COMMIT TRANSACTION
     Else
            ROLLBACK TRANSACTION
End

return @ErrorCode

you will get the "java SQL Code" by right click on stored procedure in your database. something like this :

DECLARE @RC int
DECLARE @pUserID nvarchar(50)
DECLARE @pDepartmentID int
DECLARE @pStartDateTime datetime
DECLARE @pEndDateTime datetime

-- TODO: Set parameter values here.

EXECUTE @RC = [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] 
@pUserID,@pDepartmentID,@pStartDateTime,@pEndDateTime
GO

check the query String I've done, that is your homework ;) so sorry answering this long, this is my first answer since I register few weeks ago to get answer.

How can I get my webapp's base URL in ASP.NET MVC?

You can use the following script in view:

<script type="text/javascript">
    var BASE_URL = '<%= ResolveUrl("~/") %>';
</script>

Remove an entire column from a data.frame in R

To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset() syntax. E.g. for the data-frame

df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)

to remove just the a column you could do

Data <- subset( Data, select = -a )

and to remove the b and d columns you could do

Data <- subset( Data, select = -c(d, b ) )

You can remove all columns between d and b with:

Data <- subset( Data, select = -c( d : b )

As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset documentation:

Warning:

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like '[', and in particular the non-standard evaluation of argument 'subset' can have unanticipated consequences.

How to undo "git commit --amend" done instead of "git commit"

Possibly worth noting that if you're still in your editor with the commit message, you can delete the commit message and it will abort the git commit --amend command.

Clear android application user data

This command worked for me:

adb shell pm clear packageName

How can I inspect element in chrome when right click is disabled?

So use the short cut keys , Press ctrl + shift + I and then Click on Magnifying Option on Left side and Then Hover the mouse cursor and you will be navigate to proper way

How to properly export an ES6 class in Node 4?

Use

// aspect-type.js
class AspectType {

}

export default AspectType;

Then to import it

// some-other-file.js
import AspectType from './aspect-type';

Read http://babeljs.io/docs/learn-es2015/#modules for more details

How do I escape a percentage sign in T-SQL?

In MySQL,

WHERE column_name LIKE '%|%%' ESCAPE '|'

How can I safely create a nested directory?

I saw Heikki Toivonen and A-B-B's answers and thought of this variation.

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST or not os.path.isdir(path):
            raise

How do I test a website using XAMPP?

Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80> and </VirtualHost>

After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs/www"
    ServerName example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Be sure to create the www folder under htdocs. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html or index.php file and place in the www folder, then go to your browser and test it out localhost/ ... Note: if your server is serving php files over html then remember to add localhost/index.html if the html file is the one you choose to use for this test.

Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs"
    ServerName htdocs.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.

What is the MySQL VARCHAR max size?

you can also use MEDIUMBLOB/LONGBLOB or MEDIUMTEXT/LONGTEXT

A BLOB type in MySQL can store up to 65,534 bytes, if you try to store more than this much data MySQL will truncate the data. MEDIUMBLOB can store up to 16,777,213 bytes, and LONGBLOB can store up to 4,294,967,292 bytes.

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

GitHub Error Message - Permission denied (publickey)

you can use Https url to login

i guess you are trying to login with ssh url when you say git push if it as asking only password consider you are connecting through ssh.better you use http url.

how can select from drop down menu and call javascript function

Greetings if i get you right you need a JavaScript function that doing it

function report(v) {
//To Do
  switch(v) {
    case "daily":
      //Do something
      break;
    case "monthly":
      //Do somthing
      break;
    }
  }

Regards

How to render a DateTime in a specific format in ASP.NET MVC 3?

In MVC5 I'd use, if your model is the datetime

string dt = Model.ToString("dd/MM/yyy"); 

Or if your model contains the property of the datetime

string dt = Model.dateinModel.ToString("dd/MM/yyy"); 

Here's the official meaning of the Formats:

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

How do I start my app on startup?

The Sean's solution didn't work for me initially (Android 4.2.2). I had to add a dummy activity to the same Android project and run the activity manually on the device at least once. Then the Sean's solution started to work and the BroadcastReceiver was notified after subsequent reboots.

Change button background color using swift language

button.backgroundColor = UIColor.blue

Or any other color: red, green, yellow ,etc.

Another option is RGBA color:

button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)

Why is the jquery script not working?

This works fine. just insert your jquery code in document.ready function.

 $(document).ready(function(e) {   
    // your code here
 });

example:

jquery

    $(document).ready(function(e) {   

      $('[id^=\"btnRight\"]').click(function (e) {    
        $(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');    
      });

      $('[id^=\"btnLeft\"]').click(function (e) {
        $(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
      });

    });

html

    <div>
        <select id='canselect_code' name='canselect_code' multiple class='fl'>
            <option value='1'>toto</option>
            <option value='2'>titi</option>
        </select>
        <input type='button' id='btnRight_code' value='  >  ' />
        <br>
        <input type='button' id='btnLeft_code' value='  <  ' />
        <select id='isselect_code' name='isselect_code' multiple class='fr'>
            <option value='3'>tata</option>
            <option value='4'>tutu</option>
        </select>
    </div>

Powershell script to locate specific file/file name?

To search the whole computer:

gdr -PSProvider 'FileSystem' | %{ ls -r $_.root} 2>$null | where { $_.name -eq "httpd.exe" }

How to force Chrome's script debugger to reload javascript?

Deactivating Breakpoints caused the new script to load for me.

How to test abstract class in Java with JUnit?

You could do something like this

public abstract MyAbstractClass {

    @Autowire
    private MyMock myMock;        

    protected String sayHello() {
            return myMock.getHello() + ", " + getName();
    }

    public abstract String getName();
}

// this is your JUnit test
public class MyAbstractClassTest extends MyAbstractClass {

    @Mock
    private MyMock myMock;

    @InjectMocks
    private MyAbstractClass thiz = this;

    private String myName = null;

    @Override
    public String getName() {
        return myName;
    }

    @Test
    public void testSayHello() {
        myName = "Johnny"
        when(myMock.getHello()).thenReturn("Hello");
        String result = sayHello();
        assertEquals("Hello, Johnny", result);
    }
}

C++ Best way to get integer division and remainder

std::div returns a structure with both result and remainder.

Reloading submodules in IPython

Module named importlib allow to access to import internals. Especially, it provide function importlib.reload():

import importlib
importlib.reload(my_module)

In contrary of %autoreload, importlib.reload() also reset global variables set in module. In most cases, it is what you want.

importlib is only available since Python 3.1. For older version, you have to use module imp.

How to call Makefile from another Makefile?

It seems clear that $(TESTS) is empty so your 1.4.0 makefile is effectively

all: 

clean:
  rm -f  gtest.a gtest_main.a *.o

Indeed, all has nothing to do. and clean does exactly what it says rm -f gtest.a ...

SelectedValue vs SelectedItem.Value of DropDownList

One important distinction between the two (which is visible in the Reflected code) is that SelectedValue will return an empty string if a nothing is selected, whereas SelectedItem.Value will throw a NullReference exception.

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

Easiest way is use this way

my_var=`echo 2` echo $my_var output : 2

note that is not simple single quote is back quote ( ` ).

The differences between initialize, define, declare a variable

"So does it mean definition equals declaration plus initialization."

Not necessarily, your declaration might be without any variable being initialized like:

 void helloWorld(); //declaration or Prototype.

 void helloWorld()
 {
    std::cout << "Hello World\n";
 } 

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

I changed the header and footer of the PEM file to

-----BEGIN RSA PRIVATE KEY-----

and

-----END RSA PRIVATE KEY-----

Finally, it works!

How to make Twitter bootstrap modal full screen

I achieved this in Bootstrap 3 with the following code:

.modal-dialog {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.modal-content {
  height: auto;
  min-height: 100%;
  border-radius: 0;
}

In general, when you have questions about spacing / padding issues, try right+clicking (or cmd+clicking on mac) the element and select "inspect element" on Chrome or "inspect element with firebug" on Firefox. Try selecting different HTML elements in the "elements" panel and editing the CSS on the right in real-time until you get the padding / spacing you want.

Here is a live demo

Here is a link to the fiddle

AngularJS passing data to $http.get request

You can even simply add the parameters to the end of the url:

$http.get('path/to/script.php?param=hello').success(function(data) {
    alert(data);
});

Paired with script.php:

<? var_dump($_GET); ?>

Resulting in the following javascript alert:

array(1) {  
    ["param"]=>  
    string(4) "hello"
}

What's the proper value for a checked attribute of an HTML checkbox?

It's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:

  <input type="radio" ng-checked="false">

which is a lot more sane, if you need to make it unchecked.

Storing Images in DB - Yea or Nay?

Another benefit of storing the images in the file system is that you don't have to do anything special to have the client cache them...

...unless of course the image isn't accessible via the document root (e.g. authentication barrier), in which case you'll need to check the cache-control headers your code is sending.

How to print the values of slices

If you want to view the information in a slice in the same format that you'd use to type it in (something like ["one", "two", "three"]), here's a code example showing how to do that:

package main

import (
    "fmt"
    "strings"
)

func main() {
    test := []string{"one", "two", "three"}     // The slice of data
    semiformat := fmt.Sprintf("%q\n", test)     // Turn the slice into a string that looks like ["one" "two" "three"]
    tokens := strings.Split(semiformat, " ")    // Split this string by spaces
    fmt.Printf(strings.Join(tokens, ", "))      // Join the Slice together (that was split by spaces) with commas
}

Go Playground

Ship an application with a database

From what I've seen you should be be shipping a database that already has the tables setup and data. However if you want (and depending on the type of application you have) you can allow "upgrade database option". Then what you do is download the latest sqlite version, get the latest Insert/Create statements of a textfile hosted online, execute the statements and do a data transfer from the old db to the new one.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution

  1. Right click on installer(.exe)
  2. Select properties option.
  3. Click on checkbox to check Unblock at the bottom of Properties.

This solution work for Heroku CLI (heroku-x64) installer(.exe)

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I had a similar problem, not exactly the same conditions and then i saw this post. Hope it helps someone. Apparently i was using one of my EF entity models a base class for a type that was not specified as a db set in my dbcontext. To fix this issue i had to create a base class that had all the properties common to the two types and inherit from the new base class among the two types.

Example:

//Bad Flow
    //class defined in dbcontext as a dbset
    public class Customer{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //class not defined in dbcontext as a dbset
    public class DuplicateCustomer:Customer{ 
       public object DuplicateId {get; set;}
    }


    //Good/Correct flow*
    //Common base class
    public class CustomerBase{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //entity model referenced in dbcontext as a dbset
    public class Customer: CustomerBase{

    }

    //entity model not referenced in dbcontext as a dbset
    public class DuplicateCustomer:CustomerBase{

       public object DuplicateId {get; set;}

    }

How do I implement interfaces in python?

My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.

E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify action. This is checked at compile time.

In Python, there is no such thing as compile time and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify attribute.

This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used

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

and awk as well

awk 'NR!~/^(5|10|25)$/' file

Why use Optional.of over Optional.ofNullable?

In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .orElseThrow(NullPointerException::new);
                   // .orElseThrow(CustomException::new);

Amazon S3 upload file and get URL

a bit old but still for anyone stumbling upon this in the future:

you can do it with one line assuming you already wrote the CredentialProvider and the AmazonS3Client.

it will look like this:

 String ImageURL = String.valueOf(s3.getUrl(
                                  ConstantsAWS3.BUCKET_NAME, //The S3 Bucket To Upload To
                                  file.getName())); //The key for the uploaded object

and if you didn't wrote the CredentialProvider and the AmazonS3Client then just add them before getting the URL like this:

  CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
        getApplicationContext(),
        "POOL_ID", // Identity pool ID
        Regions.US_EAST_1 // Region
);

Can someone explain how to append an element to an array in C programming?

Short answer is: You don't have any choice other than:

arr[4] = 5;

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How can I rename a project folder from within Visual Studio?

Go to the .sln file, right click, open with Notepad++ (or any editor; Notepad++ is the fastest), find the path, change it.

Remove scroll bar track from ScrollView in Android

try this is your activity onCreate:

ScrollView sView = (ScrollView)findViewById(R.id.deal_web_view_holder);
// Hide the Scollbar
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);

http://developer.android.com/reference/android/view/View.html#setVerticalScrollBarEnabled%28boolean%29

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

Inserting values to SQLite table in Android

Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html

PHP AES encrypt / decrypt

Few important things to note with AES encryption:

  1. Never use plain text as encryption key. Always hash the plain text key and then use for encryption.
  2. Always use Random IV (initialization vector) for encryption and decryption. True randomization is important.
  3. As mentioned above, don't use mode, use CBC instead.

Better naming in Tuple classes than "Item1", "Item2"

In C# 7.0 (Visual Studio 2017) there is a new construction to do that:

(string first, string middle, string last) LookupName(long id)

FirstOrDefault: Default value other than null

You can use DefaultIfEmpty followed by First:

T customDefault = ...;
IEnumerable<T> mySequence = ...;
mySequence.DefaultIfEmpty(customDefault).First();

Force “landscape” orientation mode

screen.orientation.lock('landscape');

Will force it to change to and stay in landscape mode. Tested on Nexus 5.

http://www.w3.org/TR/screen-orientation/#examples

Oracle PL/SQL string compare issue

Let's fill in the gaps in your code, by adding the other branches in the logic, and see what happens:

SQL> DECLARE
  2   str1  varchar2(4000);
  3   str2  varchar2(4000);
  4  BEGIN
  5     str1:='';
  6     str2:='sdd';
  7     IF(str1<>str2) THEN
  8      dbms_output.put_line('The two strings is not equal');
  9     ELSIF (str1=str2) THEN
 10      dbms_output.put_line('The two strings are the same');
 11     ELSE
 12      dbms_output.put_line('Who knows?');
 13     END IF;
 14   END;
 15  /
Who knows?

PL/SQL procedure successfully completed.

SQL>

So the two strings are neither the same nor are they not the same? Huh?

It comes down to this. Oracle treats an empty string as a NULL. If we attempt to compare a NULL and another string the outcome is not TRUE nor FALSE, it is NULL. This remains the case even if the other string is also a NULL.

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Jenkins: Is there any way to cleanup Jenkins workspace?

You will need to install this plugin before the options mentioned above will appear

Workspace Cleanup Plugin

This plugin add the check box to all job configs to allow you to delete the whole workspace before any steps (inc source control) are run

This is useful to make sure you always start from a known point to guarantee how you build will run

How do I undo the most recent local commits in Git?

Use this command

git checkout -b old-state 0d1d7fc32

How to load GIF image in Swift?

You can try this new library. JellyGif respects Gif frame duration while being highly CPU & Memory performant. It works great with UITableViewCell & UICollectionViewCell too. To get started you just need to

import JellyGif

let imageView = JellyGifImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

//Animates Gif from the main bundle
imageView.startGif(with: .name("Gif name"))

//Animates Gif with a local path
let url = URL(string: "Gif path")!
imageView.startGif(with: .localPath(url))

//Animates Gif with data
imageView.startGif(with: .data(Data))

For more information you can look at its README

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

This is my error code:

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Access database engine could not find the object 'ByStore$'. Make sure the object exists and that you spell its name and the path name correctly. If 'ByStore$' is not a local object, check your network connection or contact the server administrator.".

Msg 7350, Level 16, State 2, Procedure PeopleCounter_daily, Line 26

Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

My problem was the excel file was missing at the path. Just put the file with the correct sheet will do.

How do you set autocommit in an SQL Server session?

With SQLServer 2005 Express, what I found was that even with autocommit off, insertions into a Db table were committed without my actually issuing a commit command from the Management Studio session. The only difference was, when autocommit was off, I could roll back all the insertions; with *autocommit on, I could not.* Actually, I was wrong. With autocommit mode off, I see the changes only in the QA (Query Analyzer) window from which the commands were issued. If I popped a new QA (Query Analyzer) window, I do not see the changes made by the first window (session), i.e. they are NOT committed! I had to issue explicit commit or rollback commands to make changes visible to other sessions(QA windows) -- my bad! Things are working correctly.

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

Link to reload current page

<a href="/">Clicking me refreshes the page</a>

<a href="?">Click Me To Reload the page</a>

How to express a One-To-Many relationship in Django

In Django, a one-to-many relationship is called ForeignKey. It only works in one direction, however, so rather than having a number attribute of class Dude you will need

class Dude(models.Model):
    ...

class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)

Many models can have a ForeignKey to one other model, so it would be valid to have a second attribute of PhoneNumber such that

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

You can access the PhoneNumbers for a Dude object d with d.phonenumber_set.objects.all(), and then do similarly for a Business object.

How to use local docker images with Minikube?

one thing to remember regarding 'minikube' is that minikube's host is not the same as your local host, therefore, what i realized, that in order to use local images for testing with minikube you must build your docker image first locally or pull it locally and then add it using the command bellow into the minikube context which is, nothing else as another linux instance.

 minikube cache add <image>:<tag>

yet, don't forget to set the imagePullPolicy: Never in your kubernetes deployment yamls, as it will ensure using locally added images instead of trying pull it remotely from the registry.

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

MD5 hashing in Android

MD5 is a bit old, SHA-1 is a better algorithm, there is a example here.

(Also as they note in that post, Java handles this on it's own, no Android specific code.)

Sort matrix according to first column in R

Creating a data.table with key=V1 automatically does this for you. Using Stephan's data foo

> require(data.table)
> foo.dt <- data.table(foo, key="V1")
> foo.dt
   V1  V2
1:  1 349
2:  1 393
3:  1 392
4:  2  94
5:  3  49
6:  3  32
7:  4 459

How to detect lowercase letters in Python?

There are many methods to this, here are some of them:

  1. Using the predefined str method islower():

    >>> c = 'a'
    >>> c.islower()
    True
    
  2. Using the ord() function to check whether the ASCII code of the letter is in the range of the ASCII codes of the lowercase characters:

    >>> c = 'a'
    >>> ord(c) in range(97, 123)
    True
    
  3. Checking if the letter is equal to it's lowercase form:

    >>> c = 'a'
    >>> c.lower() == c
    True
    
  4. Checking if the letter is in the list ascii_lowercase of the string module:

    >>> from string import ascii_lowercase
    >>> c = 'a'
    >>> c in ascii_lowercase
    True
    

But that may not be all, you can find your own ways if you don't like these ones: D.

Finally, let's start detecting:

d = str(input('enter a string : '))
lowers = [c for c in d if c.islower()]

# here i used islower() because it's the shortest and most-reliable
# one (being a predefined function), using this list comprehension
# is (probably) the most efficient way of doing this

How to generate class diagram from project in Visual Studio 2013?

Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"

How can I use a JavaScript variable as a PHP variable?

You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.

NodeJS / Express: what is "app.use"?

app.use() is a method that allows us to register a middleware.

The middleware method is like an interceptor in java, this method always executes for all requests.

Purpose and use of middleware:-

  1. To check if the session expired or not
  2. for user authentication and authorization
  3. check for cookie (expiry date)
  4. parse data before the response

This certificate has an invalid issuer Apple Push Services

You need to search the World from the top right search bar and delete the expired certificate. Make sure you selected Login and All items.

Enter image description here

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

If you'd like to use C# 6.0:

  1. Make sure your project's .NET version is higher than 4.5.2.
  2. And then check your .config file to perform the following modifications.

Look for the system.codedom and modify it so that it will look as shown below:

<system.codedom>
 <compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
 </compilers>
</system.codedom>

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

You can change the send line to this:

c.send(b'Thank you for connecting')

The b makes it bytes instead.

How do I use the JAVA_OPTS environment variable?

Just figured it out in Oracle Java the environmental variable is called: JAVA_TOOL_OPTIONS rather than JAVA_OPTS

What is the difference between linear regression and logistic regression?

The basic difference between Linear Regression and Logistic Regression is : Linear Regression is used to predict a continuous or numerical value but when we are looking for predicting a value that is categorical Logistic Regression come into picture.

Logistic Regression is used for binary classification.

PL/SQL, how to escape single quote in a string?

You can use literal quoting:

stmt := q'[insert into MY_TBL (Col) values('ER0002')]';

Documentation for literals can be found here.

Alternatively, you can use two quotes to denote a single quote:

stmt := 'insert into MY_TBL (Col) values(''ER0002'')';

The literal quoting mechanism with the Q syntax is more flexible and readable, IMO.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Java Equivalent of C# async/await?

There isn't anything native to java that lets you do this like async/await keywords, but what you can do if you really want to is use a CountDownLatch. You could then imitate async/await by passing this around (at least in Java7). This is a common practice in Android unit testing where we have to make an async call (usually a runnable posted by a handler), and then await for the result (count down).

Using this however inside your application as opposed to your test is NOT what I am recommending. That would be extremely shoddy as CountDownLatch depends on you effectively counting down the right number of times and in the right places.

What does "javax.naming.NoInitialContextException" mean?

Just read the docs:

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

This exception can be thrown during any interaction with the InitialContext, not only when the InitialContext is constructed. For example, the implementation of the initial context might lazily retrieve the context only when actual methods are invoked on it. The application should not have any dependency on when the existence of an initial context is determined.

But this is explained much better in the docs for InitialContext

Mark error in form using Bootstrap

Generally showing the error near where the error occurs is best. i.e. if someone has an error with entering their email, you highlight the email input box.

This article has a couple good examples. http://uxdesign.smashingmagazine.com/2011/05/27/getting-started-with-defensive-web-design/

Also twitter bootstrap has some nice styling that helps with that (scroll down to the Validation states section) http://twitter.github.com/bootstrap/base-css.html#forms

Highlighting each input box is a bit more complicated, so the easy way would be to just put an bootstrap alert at the top with details of what the user did wrong. http://twitter.github.com/bootstrap/components.html#alerts

How can I convert a date into an integer?

var dates = dates_as_int.map(function(dateStr) {
    return new Date(dateStr).getTime();
});

=>

[1468959781804, 1469029434776, 1469199218634, 1469457574527]

Update: ES6 version:

const dates = dates_as_int.map(date => new Date(date).getTime())

How to call a Web Service Method?

James' answer is correct, of course, but I should remind you that the whole ASMX thing is, if not obsolete, at least not the current method. I strongly suggest that you look into WCF, if only to avoid learning things you will need to forget.

Do we have router.reload in vue-router?

The simplest solution is to add a :key attribute to :

<router-view :key="$route.fullPath"></router-view>

This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.

Get all parameters from JSP page

Even though this is an old question, I had to do something similar today but I prefer JSTL:

<c:forEach var="par" items="${paramValues}">
    <c:if test="${fn:startsWith(par.key, 'question')}"> 
${par.key} = ${par.value[0]}; //whatever
    </c:if>
</c:forEach>

How do I determine if a port is open on a Windows server?

Do you want a tool for doing it? There is a website at http://www.canyouseeme.org/. Otherwise, you need some other server to call you back to see if a port is open...

error: invalid type argument of ‘unary *’ (have ‘int’)

I have reformatted your code.

The error was situated in this line :

printf("%d", (**c));

To fix it, change to :

printf("%d", (*c));

The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.

In addition, the () was optional.

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int *c = NULL;

    a = &b;
    c = &a;

    printf("%d", *c);

    return 0;
} 

EDIT :

The line :

c = &a;

must be replaced by :

c = a;

It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :

10

EDIT 2:

If you want to use a double * :

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int **c = NULL;

    a = &b;
    c = &a;

    printf("%d", **c);

    return 0;
} 

Output:

10

Why am I getting error for apple-touch-icon-precomposed.png

There’s a gem like quiet_assets that will silence these errors in your logs if, like me, you didn’t want to have to add these files to your Rails app:

https://github.com/davidcelis/quiet_safari

Way to get all alphabetic chars in an array in PHP?

range for A-Z but if you want to go for example from A to DU then:

 function generateAlphabet($na) {
        $sa = "";
        while ($na >= 0) {
            $sa = chr($na % 26 + 65) . $sa;
            $na = floor($na / 26) - 1;
        }
        return $sa;
    }

    $alphabet = Array();
    for ($na = 0; $na < 125; $na++) {
        $alphabet[]=generateAlphabet($na);
    }

    print_r($alphabet);

your answer will look like:

Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G [7] => H [8] => I [9] => J [10] => K [11] => L [12] => M [13] => N [14] => O [15] => P [16] => Q [17] => R [18] => S [19] => T [20] => U [21] => V [22] => W [23] => X [24] => Y [25] => Z [26] => AA [27] => AB [28] => AC [29] => AD [30] => AE [31] => AF [32] => AG [33] => AH [34] => AI [35] => AJ [36] => AK [37] => AL [38] => AM [39] => AN [40] => AO [41] => AP [42] => AQ [43] => AR [44] => AS [45] => AT [46] => AU [47] => AV [48] => AW [49] => AX [50] => AY [51] => AZ [52] => BA [53] => BB [54] => BC [55] => BD [56] => BE [57] => BF [58] => BG [59] => BH [60] => BI [61] => BJ [62] => BK [63] => BL [64] => BM [65] => BN [66] => BO [67] => BP [68] => BQ [69] => BR [70] => BS [71] => BT [72] => BU [73] => BV [74] => BW [75] => BX [76] => BY [77] => BZ [78] => CA [79] => CB [80] => CC [81] => CD [82] => CE [83] => CF [84] => CG [85] => CH [86] => CI [87] => CJ [88] => CK [89] => CL [90] => CM [91] => CN [92] => CO [93] => CP [94] => CQ [95] => CR [96] => CS [97] => CT [98] => CU [99] => CV [100] => CW [101] => CX [102] => CY [103] => CZ [104] => DA [105] => DB [106] => DC [107] => DD [108] => DE [109] => DF [110] => DG [111] => DH [112] => DI [113] => DJ [114] => DK [115] => DL [116] => DM [117] => DN [118] => DO [119] => DP [120] => DQ [121] => DR [122] => DS [123] => DT [124] => DU ) 

Android EditText Max Length

If you want to see a counter label you can use app:counterEnabled and android:maxLength, like:

<android.support.design.widget.TextInputLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  app:counterEnabled="true">

  <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLength="420" />

</android.support.design.widget.TextInputLayout>

DO NOT set app:counterMaxLength on TextInputLayout because it will conflict with android:maxLength resulting into the issue of invisible chars after the text hits the size limit.

Javascript - Append HTML to container element without innerHTML

alnafie has a great answer for this question. I wanted to give an example of his code for reference:

_x000D_
_x000D_
var childNumber = 3;_x000D_
_x000D_
function addChild() {_x000D_
  var parent = document.getElementById('i-want-more-children');_x000D_
  var newChild = '<p>Child ' + childNumber + '</p>';_x000D_
  parent.insertAdjacentHTML('beforeend', newChild);_x000D_
  childNumber++;_x000D_
}
_x000D_
body {_x000D_
  text-align: center;_x000D_
}_x000D_
button {_x000D_
  background: rgba(7, 99, 53, .1);_x000D_
  border: 3px solid rgba(7, 99, 53, 1);_x000D_
  border-radius: 5px;_x000D_
  color: rgba(7, 99, 53, 1);_x000D_
  cursor: pointer;_x000D_
  line-height: 40px;_x000D_
  font-size: 30px;_x000D_
  outline: none;_x000D_
  padding: 0 20px;_x000D_
  transition: all .3s;_x000D_
}_x000D_
button:hover {_x000D_
  background: rgba(7, 99, 53, 1);_x000D_
  color: rgba(255,255,255,1);_x000D_
}_x000D_
p {_x000D_
  font-size: 20px;_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<button type="button" onclick="addChild()">Append Child</button>_x000D_
<div id="i-want-more-children">_x000D_
  <p>Child 1</p>_x000D_
  <p>Child 2</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hopefully this is helpful to others.

How do I convert a float to an int in Objective C?

In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.

Anything you can do in regular old ANSI C can be done in Objective-C.

Cannot find "Package Explorer" view in Eclipse

Try Window > Open Perspective > Java Browsing or some other Java perspectives

error 1265. Data truncated for column when trying to load data from txt file

I had this issue when trying to convert an existing varchar column to enum. For me the issue was that there were existing values for that column that were not part of the enum's list of accepted values. So if your enum will only allow values, say ('dog', 'cat') but there is a row with bird in your table, the MODIFY COLUMN will fail with this error.

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

It looks like a bug http://code.google.com/p/android/issues/detail?id=939.

Finally I have to write something like this:

 <stroke android:width="3dp"
         android:color="#555555"
         />

 <padding android:left="1dp"
          android:top="1dp"
          android:right="1dp"
          android:bottom="1dp"
          /> 

 <corners android:radius="1dp"
  android:bottomRightRadius="2dp" android:bottomLeftRadius="0dp" 
  android:topLeftRadius="2dp" android:topRightRadius="0dp"/> 

I have to specify android:bottomRightRadius="2dp" for left-bottom rounded corner (another bug here).

Select rows of a matrix that meet a condition

m <- matrix(1:20, ncol = 4) 
colnames(m) <- letters[1:4]

The following command will select the first row of the matrix above.

subset(m, m[,4] == 16)

And this will select the last three.

subset(m, m[,4] > 17)

The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with

mf <- data.frame(m)

Then you can select with

mf[ mf$a == 16, ]

Or, you could use the subset command.

scrollIntoView Scrolls just too far

Found a workaround solution. Say that you want to scroll to an div, Element here for example, and you want to have a spacing of 20px above it. Set the ref to a created div above it:

<div ref={yourRef} style={{position: 'relative', bottom: 20}}/> <Element />

Doing so will create this spacing that you want.

If you have a header, create an empty div as well behind the header and assign to it a height equal to the height of the header and reference it.

What are the differences between a program and an application?

Without more information about the question, the terms 'program' and 'application' are nearly synonymous.

As Saif has indicated, 'application' tends to be used more for non-system related programs. That being said, I don't think it's wrong to describe the operating system as an special application that provides an environment in which to run other applications.

Changing button color programmatically

Probably best to change the className:

document.getElementById("button").className = 'button_color';

Then you add a buton style to the CSS where you can set the background color and anything else.

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

Callback to a Fragment from a DialogFragment

I was facing a similar problem. The solution that I found out was :

  1. Declare an interface in your DialogFragment just like James McCracken has explained above.

  2. Implement the interface in your activity (not fragment! That is not a good practice).

  3. From the callback method in your activity, call a required public function in your fragment which does the job that you want to do.

Thus, it becomes a two-step process : DialogFragment -> Activity and then Activity -> Fragment

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

Float elements will be rendered at the line they are normally in the layout. To fix this, you have two choices:

Move the header and the p after the login box:

<div class='container'>
    <div class='hero-unit'>

        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>

        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

Or enclose the left block in a pull-left div, and add a clearfix at the bottom

<div class='container'>
    <div class='hero-unit'>

        <div class="pull-left">

          <h2>Welcome</h2>

          <p>Please log in</p>

        </div>

        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>

        <div class="clearfix"></div>

    </div>
</div>

Check if file exists and whether it contains a specific string

You should use the grep -q flag for quiet output. See the man pages below:

man grep output :

 General Output Control

  -q, --quiet, --silent
              Quiet;  do  not write anything to standard output.  Exit immediately with zero status
              if any match is  found,  even  if  an  error  was  detected.   Also  see  the  -s  or
              --no-messages option.  (-q is specified by POSIX.)

This KornShell (ksh) script demos the grep quiet output and is a solution to your question.

grepUtil.ksh :

#!/bin/ksh

#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"

#Function to initialize variables
initialize(){
    echo "Entering initialize"
    echo "Exiting initialize"
}

#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
    echo "Entering createFileWithInput"
    orgDirectory=${PWD}
    cd ${1}
    > ${2}
    print ${3} >> ${2}
    cd ${orgDirectory}
    echo "Exiting createFileWithInput"
}

#Function to create File with Input
#Params: 1}directoryName
createDir(){
    echo "Entering createDir"
    mkdir -p ${1}
    echo "Exiting createDir"
}

#Params: 1}FileName
readLine(){
    echo "Entering readLine"
    file=${1}
    while read line
    do
        #assign last line to var
        var="$line"
    done <"$file"
    echo "Exiting readLine"
}
#Check if file exists 
#Params: 1}File
doesFileExit(){
    echo "Entering doesFileExit"
    orgDirectory=${PWD}
    cd ${PWD}${dirPath}
    #echo ${PWD}
    if [[ -e "${1}" ]]; then
        echo "${1} exists"
    else
        echo "${1} does not exist"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileExit"
}
#Check if file contains a string quietly
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainStringQuiet(){
    echo "Entering doesFileContainStringQuiet"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep -q ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainStringQuiet"
}
#Check if file contains a string with output
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainString(){
    echo "Entering doesFileContainString"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainString"
}

#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
#initialize #function call#
createDir ${dir} #function call#
createFileWithInput ${dir} ${file} ${searchString} #function call#
doesFileExit ${file} #function call#
if [ ${?} -eq 0 ];then
    doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#
    doesFileContainString ${dirPath} ${file} ${searchString} #function call#
fi
echo "Exiting: ${PWD}/${0}"

grepUtil.ksh Output :

user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1:  {2:  {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh

Regex to check if valid URL that ends in .jpg, .png, or .gif

(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png) worked really well for me.

This will match URLs in the following forms:

https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.jpg
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.jpg
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.gif
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.gif
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.png
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.png

Check this regular expression against the URLs here: http://regexr.com/3g1v7

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I added these configuration in web.xml and it works well for me!

<filter>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
    <init-param>
        <param-name>sessionFactoryBeanName</param-name>
        <param-value>sessionFactory</param-value>
    </init-param>
    <init-param>
        <param-name>flushMode</param-name>
        <param-value>AUTO</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Additionally, the most ranked answer give me clues to prevent application from panic at the first run.

What is Android's file system?

When analysing a Galaxy Ace 2.2 in a hex editor. The hex seemed to point to the device using FAT16 as its file system. I thought this unusual. However Fat 16 is compatible with the Linux kernel.

How do I access named capturing groups in a .NET Regex?

This answers improves on Rashmi Pandit's answer, which is in a way better than the rest because that it seems to completely resolve the exact problem detailed in the question.

The bad part is that is inefficient and not uses the IgnoreCase option consistently.

Inefficient part is because regex can be expensive to construct and execute, and in that answer it could have been constructed just once (calling Regex.IsMatch was just constructing the regex again behind the scene). And Match method could have been called only once and stored in a variable and then linkand name should call Result from that variable.

And the IgnoreCase option was only used in the Match part but not in the Regex.IsMatch part.

I also moved the Regex definition outside the method in order to construct it just once (I think is the sensible approach if we are storing that the assembly with the RegexOptions.Compiled option).

private static Regex hrefRegex = new Regex("<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>",  RegexOptions.IgnoreCase | RegexOptions.Compiled);

public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
    var matches = hrefRegex.Match(htmlTd);
    if (matches.Success)
    {
        link = matches.Result("${link}");
        name = matches.Result("${name}");
        return true;
    }
    else
    {
        link = null;
        name = null;
        return false;
    }
}

Reading Datetime value From Excel sheet

You may want to try out simple function I posted on another thread related to reading date value from excel sheet.

It simply takes text from the cell as input and gives DateTime as output.

I would be happy to see improvement in my sample code provided for benefit of the .Net development community.

Here is the link for the thread C# not reading excel date from spreadsheet

Proxies with Python 'Requests' module

It’s a bit late but here is a wrapper class that simplifies scraping proxies and then making an http POST or GET:

ProxyRequests

https://github.com/rootVIII/proxy_requests

Where do I configure log4j in a JUnit test class?

The LogManager class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:

  1. If you specify log4j.defaultInitOverride to false, it will not configure log4j at all.
  2. Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java:

    -Dlog4j.configuration=<path to properties file>

    in your test runner configuration.

  3. Allow log4j to scan the classpath for a log4j config file during your test. (the default)

See also the online documentation.

Check if a variable is between two numbers with Java

<<= is like +=, but for a left shift. x <<= 1 means x = x << 1. That's why 90 >>= angle doesn't parse. And, like others have said, Java doesn't have an elegant syntax for checking if a number is an an interval, so you have to do it the long way. It also can't do if (x == 0 || 1), and you're stuck writing it out the long way.

Postgres user does not exist?

By psql --help, when you didn't set options for database name (without -d option) it would be your username, if you didn't do -U, the database username would be your username too, etc.

But by initdb (to create the first database) command it doesn't have your username as any database name. It has a database named postgres. The first database is always created by the initdb command when the data storage area is initialized. This database is called postgres.

So if you don't have another database named your username, you need to do psql -d postgres for psql command to work. And it seems it gives -d option by default, psql postgres also works.

If you have created another database names the same to your username, (it should be done with createdb) then you may command psql only. And it seems the first database user name sets as your machine username by brew.

psql -d <first database name> -U <first database user name>

or,

psql -d postgres -U <your machine username>
psql -d postgres

would work by default.

How to get file name when user select a file via <input type="file" />?

You can use the next code:

JS

    function showname () {
      var name = document.getElementById('fileInput'); 
      alert('Selected file: ' + name.files.item(0).name);
      alert('Selected file: ' + name.files.item(0).size);
      alert('Selected file: ' + name.files.item(0).type);
    };

HTML

<body>
    <p>
        <input type="file" id="fileInput" multiple onchange="showname()"/>
    </p>    
</body>

How to get the PYTHONPATH in shell?

Just write:

just write which python in your terminal and you will see the python path you are using.

Linking a UNC / Network drive on an html page

Setup IIS on the network server and change the path to http://server/path/to/file.txt

EDIT: Make sure you enable directory browsing in IIS

Iterator invalidation rules

Here is a nice summary table from cppreference.com:

enter image description here

Here, insertion refers to any method which adds one or more elements to the container and erasure refers to any method which removes one or more elements from the container.

babel-loader jsx SyntaxError: Unexpected token

This works perfect for me

{
    test: /\.(js|jsx)$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
        presets: ['es2015','react']
    }
},

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

How do I auto-submit an upload form when a file is selected?

You can put this code to make your code work with just single line of code

<input type="file" onchange="javascript:this.form.submit()">

This will upload the file on server without clicking on submit button

tell pip to install the dependencies of packages listed in a requirement file

Extending Piotr's answer, if you also need a way to figure what to put in requirements.in, you can first use pip-chill to find the minimal set of required packages you have. By combining these tools, you can show the dependency reason why each package is installed. The full cycle looks like this:

  1. Create virtual environment:
    $ python3 -m venv venv
  2. Activate it:
    $ . venv/bin/activate
  3. Install newest version of pip, pip-tools and pip-chill:
    (venv)$ pip install --upgrade pip
    (venv)$ pip install pip-tools pip-chill
  4. Build your project, install more pip packages, etc, until you want to save...
  5. Extract minimal set of packages (ie, top-level without dependencies):
    (venv)$ pip-chill --no-version > requirements.in
  6. Compile list of all required packages (showing dependency reasons):
    (venv)$ pip-compile requirements.in
  7. Make sure the current installation is synchronized with the list:
    (venv)$ pip-sync

Using a string variable as a variable name

You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

How do I add a simple onClick event handler to a canvas element?

When you draw to a canvas element, you are simply drawing a bitmap in immediate mode.

The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.

Therefore, to get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset.

To add a click event to your canvas element, use...

canvas.addEventListener('click', function() { }, false);

To determine which element was clicked...

var elem = document.getElementById('myCanvas'),
    elemLeft = elem.offsetLeft + elem.clientLeft,
    elemTop = elem.offsetTop + elem.clientTop,
    context = elem.getContext('2d'),
    elements = [];

// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
    var x = event.pageX - elemLeft,
        y = event.pageY - elemTop;

    // Collision detection between clicked offset and element.
    elements.forEach(function(element) {
        if (y > element.top && y < element.top + element.height 
            && x > element.left && x < element.left + element.width) {
            alert('clicked an element');
        }
    });

}, false);

// Add element.
elements.push({
    colour: '#05EFFF',
    width: 150,
    height: 100,
    top: 20,
    left: 15
});

// Render elements.
elements.forEach(function(element) {
    context.fillStyle = element.colour;
    context.fillRect(element.left, element.top, element.width, element.height);
});?

jsFiddle.

This code attaches a click event to the canvas element, and then pushes one shape (called an element in my code) to an elements array. You could add as many as you wish here.

The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties.

When the click event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements array. If so, it fires an alert(), which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas.


For completeness, why your attempts didn't work...

elem.onClick = alert("hello world"); // displays alert without clicking

This is assigning the return value of alert() to the onClick property of elem. It is immediately invoking the alert().

elem.onClick = alert('hello world');  // displays alert without clicking

In JavaScript, the ' and " are semantically identical, the lexer probably uses ['"] for quotes.

elem.onClick = "alert('hello world!')"; // does nothing, even with clicking

You are assigning a string to the onClick property of elem.

elem.onClick = function() { alert('hello world!'); }; // does nothing

JavaScript is case sensitive. The onclick property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML.

elem.onClick = function() { alert("hello world!"); }; // does nothing

Again, ' === ".

Select distinct values from a table field

By example:

# select distinct code from Platform where id in ( select platform__id from Build where product=p)
pl_ids = Build.objects.values('platform__id').filter(product=p)
platforms = Platform.objects.values_list('code', flat=True).filter(id__in=pl_ids).distinct('code')
platforms = list(platforms) if platforms else []

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

How to check if string input is a number?

Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.

numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]

for item in numList:

    try:
        print (item / 2) #You can divide by any number really, except zero
    except:
        print "Not A Number: " + item

Result:

249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number: 

Custom date format with jQuery validation plugin

nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.

How can I do an asc and desc sort using underscore.js?

Descending order using underscore can be done by multiplying the return value by -1.

//Ascending Order:
_.sortBy([2, 3, 1], function(num){
    return num;
}); // [1, 2, 3]


//Descending Order:
_.sortBy([2, 3, 1], function(num){
    return num * -1;
}); // [3, 2, 1]

If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

After return forward method you can simply do this:

return null;

It will break the current scope.

How to check if my string is equal to null?

WORKING !!!!

 if (myString != null && !myString.isEmpty()) {
        return true;
    }
    else {
        return false;
    }

Updated

For Kotlin we check if the string is null or not by following

return myString.isNullOrEmpty() // Returns `true` if this nullable String is either `null` or empty, false otherwise

return myString.isEmpty() // Returns `true` if this char sequence is empty (contains no characters), false otherwise

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, java.sql.Timestamp extends java.util.Date and adds a nanoseconds field. The equals implementation for Timestamp does violate symmetry and can cause erratic behavior if Timestamp and Date objects are used in the same collection or are otherwise intermixed. The Timestamp class has a disclaimer cautioning programmers against mixing dates and timestamps. While you won’t get into trouble as long as you keep them separate, there’s nothing to prevent you from mixing them, and the resulting errors can be hard to debug. This behavior of the Timestamp class was a mistake and should not be emulated.

check out this link

http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/

Filter Linq EXCEPT on properties

Construct a List<AppMeta> from the excluded List and use the Except Linq operator.

var ex = excludedAppIds.Select(x => new AppMeta{Id = x}).ToList();                           
var result = ex.Except(unfilteredApps).ToList();

Set font-weight using Bootstrap classes

Create in your Site.css (or in another place) a new class named for example .font-bold and set it to your element

.font-bold {
  font-weight: bold;
}

Leaflet changing Marker color

Ahh an event listener and change the icon through setIcon() method:

createdMarker.on("dblclick", function(evt) {

        var myIcon = L.icon({
            iconUrl: 'res/marker-icon-red.png',
            shadowUrl: 'res/marker-shadow.png'
        });
        this.setIcon(myIcon);
});

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

This error caused because of output buffering modules extension(ob_gzhandler) added. While output buffering use at starting ob_start() and ending ob_flush()

<?php   
    ob_start( 'ob_gzhandler' ); 
    echo json_encode($array);
    ob_end_flush();
?>

Use this:

<?php   
    ob_start(); 
    echo json_encode($array);
    ob_flush();
?>

Deleting a file in VBA

An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be

With New FileSystemObject
    If .FileExists(yourFilePath) Then
        .DeleteFile yourFilepath
    End If
End With

Same effect but fewer (well, none at all) variable declarations.

The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).