Programs & Examples On #Drupal themes

This tag is for questions about themes hosted on Drupal.org. Don't use it to generally mean "this question is about a theme," when the question is about a theme's code, or when the question is already using a specific tag, such as "theming," "theme-template," or a tag specific for the used theme, such as "zen."

How can I make an entire HTML form "readonly"?

I'd rather use jQuery:

$('#'+formID).find(':input').attr('disabled', 'disabled');

find() would go much deeper till nth nested child than children(), which looks for immediate children only.

How to insert an object in an ArrayList at a specific position

Actually the way to do it on your specific question is arrayList.add(1,"INSERTED ELEMENT"); where 1 is the position

Binding a WPF ComboBox to a custom list

You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.

Have you set the DataContext to your ConnectionViewModel object?

I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.

Here is my XAML content:

<Window x:Class="WpfApplication6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
<Grid>
    <StackPanel>
        <Button Click="Button_Click">asdf</Button>
        <ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Name"
                  SelectedValue="{Binding Path=PhonebookEntry}" />
    </StackPanel>
</Grid>
</Window>

And here is my code-behind:

namespace WpfApplication6
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ConnectionViewModel vm = new ConnectionViewModel();
            DataContext = vm;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((ConnectionViewModel)DataContext).PhonebookEntry = "test";
        }
    }

    public class PhoneBookEntry
    {
        public string Name { get; set; }

        public PhoneBookEntry(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public class ConnectionViewModel : INotifyPropertyChanged
    {
        public ConnectionViewModel()
        {
            IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
            list.Add(new PhoneBookEntry("test"));
            list.Add(new PhoneBookEntry("test2"));
            _phonebookEntries = new CollectionView(list);
        }

        private readonly CollectionView _phonebookEntries;
        private string _phonebookEntry;

        public CollectionView PhonebookEntries
        {
            get { return _phonebookEntries; }
        }

        public string PhonebookEntry
        {
            get { return _phonebookEntry; }
            set
            {
                if (_phonebookEntry == value) return;
                _phonebookEntry = value;
                OnPropertyChanged("PhonebookEntry");
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.

Maybe there is an issue with the CollectionView? I noticed a warning in the output console:

System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.

Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.

Set a button group's width to 100% and make buttons equal width?

Bootstrap 4 Solution

<div class="btn-group w-100">
    <button type="button" class="btn">One</button>
    <button type="button" class="btn">Two</button>
    <button type="button" class="btn">Three</button>
</div>

You basically tell the btn-group container to have width 100% by adding w-100 class to it. The buttons inside will fill in the whole space automatically.

Validation to check if password and confirm password are same is not working

if((pswd.length<6 || pswd.length>12) || pswd == ""){
        document.getElementById("passwordloc").innerHTML="character should be between 6-12 characters"; status=false;

} 

else {  
    if(pswd != pswdcnf) {
        document.getElementById("passwordconfirm").innerHTML="password doesnt matched"; status=true;
    } else {
        document.getElementById("passwordconfirm").innerHTML="password  matche";
        document.getElementById("passwordloc").innerHTML = '';
    }

}

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

DateTime to javascript date

JavaScript Date constructor accepts number of milliseconds since Unix epoch (1 January 1970 00:00:00 UTC). Here’s C# extension method that converts .Net DateTime object to JavaScript date:

public static class DateTimeJavaScript
{
   private static readonly long DatetimeMinTimeTicks =
      (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;

   public static long ToJavaScriptMilliseconds(this DateTime dt)
   {
      return (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
   }
}

JavaScript Usage:

var dt = new Date(<%= DateTime.Today.ToJavaScriptMilliseconds() %>);
alert(dt);

MySQL Error: #1142 - SELECT command denied to user

You should have to just clear sessions data thats it everything will work

Javascript - validation, numbers only

Using the form you already have:

var input = document.querySelector('form[name=myForm] #username');

input.onkeyup = function() {
    var patterns = /[^0-9]/g;
    var caretPos = this.selectionStart;

    this.value = input.value.replace(patterns, '');
    this.setSelectionRange(caretPos, caretPos);
}

This will delete all non-digits after the key is released.

Android: adbd cannot run as root in production builds

For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root can run smoothly.

How to enable multidexing with the new Android Multidex support library

Multi_Dex.java

public class Multi_Dex extends Application {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

ORA-00054: resource busy and acquire with NOWAIT specified

Step 1:

select object_name, s.sid, s.serial#, p.spid 
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;

Step 2:

alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1

More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php

What is the best free SQL GUI for Linux for various DBMS systems

I'm sticking with DbVisualizer Free until something better comes along.

EDIT/UPDATE: been using https://dbeaver.io/ lately, really enjoying this

Plain Old CLR Object vs Data Transfer Object

Don't even call them DTOs. They're called Models....Period. Models never have behavior. I don't know who came up with this dumb term DTO but it must be a .NET thing is all I can figure. Think of view models in MVC, same dam** thing, models are used to transfer state between layers server side or over the wire period, they are all models. Properties with data. These are models you pass ove the wire. Models, Models Models. That's it.

I wish the stupid term DTO would go away from our vocabulary.

'tuple' object does not support item assignment

You probably want the next transformation for you pixels:

pixels = map(list, image.getdata())

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

Set up git to pull and push all branches

The simplest way is to do:

git push --all origin

This will push tags and branches.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

Usually the msb file not found problems are the result of an environment setting problem, but in your case I'm a little suspicious of the installation (I've never used the apt-get + configure method).

To check the sanity of the installation:

  • ORACLE_HOME should be set to a directory path one level above the bin directory where sqlplus executable is found.
  • There should some .msb files under $ORACLE_HOME/sqlplus/mesg
  • There should be hundreds (not sure of the number with XE) of .msb files under $ORACLE_HOME (try find $ORACLE_HOME -name "*.msb" -print to show them)
  • Your PATH should include $ORACLE_HOME/bin.
  • All files under ORACLE_HOME should be owned by user:oracle group:dba.

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

EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'; worked for me. closing the varchar/string with two pairs of single quotes did the trick. Other option could be to use using keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'; Remember using keyword will not work, if you are using EXECUTE IMMEDIATE to execute DDL's with parameters, however, using quotes will work for DDL's.

Regular expression which matches a pattern, or is an empty string

\b matches a word boundary. I think you can use ^$ for empty string.

Nested classes' scope?

You might be better off if you just don't use nested classes. If you must nest, try this:

x = 1
class OuterClass:
    outer_var = x
    class InnerClass:
        inner_var = x

Or declare both classes before nesting them:

class OuterClass:
    outer_var = 1

class InnerClass:
    inner_var = OuterClass.outer_var

OuterClass.InnerClass = InnerClass

(After this you can del InnerClass if you need to.)

Apply CSS styles to an element depending on its child elements

On top of @kp's answer:

I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).

But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the decisions in the logic and not based on a CSS state.

tl;dr; apply the a and b styles to the parent <div>, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).

<style>
  .parent            { height: 50px; }
  .parent div        { display: none; }
  .with-children     { height: 100px; }
  .with-children div { display: block; }
</style>

<div class="parent">
  <div>child</div>
</div>

<script>
  // to show the children
  $('.parent').addClass('with-children');
</script>

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

How to set Highcharts chart maximum yAxis value

Try this:

yAxis: {min: 0, max: 100}

See this jsfiddle example

Python: Passing variables between functions

You're just missing one critical step. You have to explicitly pass the return value in to the second function.

def main():
    l = defineAList()
    useTheList(l)

Alternatively:

def main():
    useTheList(defineAList())

Or (though you shouldn't do this! It might seem nice at first, but globals just cause you grief in the long run.):

l = []

def defineAList():
    global l
    l.extend(['1','2','3'])

def main():
    global l
    defineAList()
    useTheList(l)

The function returns a value, but it doesn't create the symbol in any sort of global namespace as your code assumes. You have to actually capture the return value in the calling scope and then use it for subsequent operations.

GitHub Error Message - Permission denied (publickey)

I know about this problem. After add ssh key, add you ssh key to ssh agent too (from official docs)

ssh-agent -s
ssh-add ~/.ssh/id_rsa

After it all work fine, git can view proper key, before couldn't.

What's the UIScrollView contentInset property for?

While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:

  _|?_cW_?_|_?_
   |       | 
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
   |content|    
-------------?-

That's what you get when you do it, but the usefulness of it only shows when you scroll:

  _|?_cW_?_|_?_
   |content| ? content is still visible
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
  _|_______|___ 
             ?

That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top"

To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.

Fastest way to check a string is alphanumeric in Java

Use String.matches(), like:

String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));

That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.

Replace last occurrence of character in string

You can use this code

_x000D_
_x000D_
var str="test_String_ABC";_x000D_
var strReplacedWith=" and ";_x000D_
var currentIndex = str.lastIndexOf("_");_x000D_
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);_x000D_
_x000D_
alert(str);
_x000D_
_x000D_
_x000D_

Redirect to external URL with return in laravel

return Redirect::away($url); should work to redirect

Also, return Redirect::to($url); to redirect inside the view.

ASP.Net MVC Redirect To A Different View

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is:

return RedirectToAction("Index", model);

Then in your Index method, return the view you want.

git: fatal: I don't handle protocol '??http'

I used double quotes for the URL and it worked. So something like

git clone "??http://git.fedorahosted.org/git/ibus-typing-booster.git"

works.. single quotes dont help. It has to be double quotes.

How to skip to next iteration in jQuery.each() util?

By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return true, 1, 'non-false', or whatever else you can think up.

Multiple commands on a single line in a Windows batch file

Use:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.


That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):

onClick=""

OR

The element css needs to have the following declaration:

cursor:pointer

Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working

How can I disable ReSharper in Visual Studio and enable it again?

You can disable ReSharper 5 and newer versions by using the Suspend button in menu Tools -> Options -> ReSharper.

enter image description here

How do I declare an array variable in VBA?

Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

sub Demo_array()
    Dim MyArray as Variant, MyArray2 as Variant, i as Long

    MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
    MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too

    For i = 0 to UBound(MyArray)
        Debug.Print i, MyArray(i)
    Next i
    For i = 0 to UBound(MyArray2)
        Debug.Print i, MyArray2(i)
    Next i
End Sub

I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

, "Egg"

in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

How to use google maps without api key

this simple code work 100% all you need is changing 'lat','long' for address to show

<iframe src="http://maps.google.com/maps?q=25.3076008,51.4803216&z=16&output=embed" height="450" width="600"></iframe>

setting multiple column using one update

Just add parameters, split by comma:

UPDATE tablename SET column1 = "value1", column2 = "value2" ....

See also: mySQL manual on UPDATE

What is the C# equivalent of NaN or IsNumeric?

I prefer something like this, it lets you decide what NumberStyle to test for.

public static Boolean IsNumeric(String input, NumberStyles numberStyle) {
    Double temp;
    Boolean result = Double.TryParse(input, numberStyle, CultureInfo.CurrentCulture, out temp);
    return result;
}

How to find keys of a hash?

You could use Underscore.js, which is a Javascript utility library.

_.keys({one : 1, two : 2, three : 3}); 
// => ["one", "two", "three"]

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

First install your targeted version

npm i [email protected] --save-dev --save-exact

Then before compiling do

   npm i

How to check if a number is a power of 2

A number is a power of 2 if it contains only 1 set bit. We can use this property and the generic function countSetBits to find if a number is power of 2 or not.

This is a C++ program:

int countSetBits(int n)
{
        int c = 0;
        while(n)
        {
                c += 1;
                n  = n & (n-1);
        }
        return c;
}

bool isPowerOfTwo(int n)
{        
        return (countSetBits(n)==1);
}
int main()
{
    int i, val[] = {0,1,2,3,4,5,15,16,22,32,38,64,70};
    for(i=0; i<sizeof(val)/sizeof(val[0]); i++)
        printf("Num:%d\tSet Bits:%d\t is power of two: %d\n",val[i], countSetBits(val[i]), isPowerOfTwo(val[i]));
    return 0;
}

We dont need to check explicitly for 0 being a Power of 2, as it returns False for 0 as well.

OUTPUT

Num:0   Set Bits:0   is power of two: 0
Num:1   Set Bits:1   is power of two: 1
Num:2   Set Bits:1   is power of two: 1
Num:3   Set Bits:2   is power of two: 0
Num:4   Set Bits:1   is power of two: 1
Num:5   Set Bits:2   is power of two: 0
Num:15  Set Bits:4   is power of two: 0
Num:16  Set Bits:1   is power of two: 1
Num:22  Set Bits:3   is power of two: 0
Num:32  Set Bits:1   is power of two: 1
Num:38  Set Bits:3   is power of two: 0
Num:64  Set Bits:1   is power of two: 1
Num:70  Set Bits:3   is power of two: 0

Split string by single spaces

You can even develop your own split function (I know, little old-fashioned):

size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
    size_t pos = txt.find( ch );
    size_t initialPos = 0;
    strs.clear();

    // Decompose statement
    while( pos != std::string::npos ) {
        strs.push_back( txt.substr( initialPos, pos - initialPos ) );
        initialPos = pos + 1;

        pos = txt.find( ch, initialPos );
    }

    // Add the last one
    strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );

    return strs.size();
}

Then you just need to invoke it with a vector<string> as argument:

int main()
{
    std::vector<std::string> v;

    split( "This  is a  test", v, ' ' );
    dump( cout, v );

    return 0;
}

Find the code for splitting a string in IDEone.

Hope this helps.

Create an array of strings

one of the simplest ways to create a string matrix is as follow :

x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]

How to pass a JSON array as a parameter in URL

I know this could be a later post, but, for new visitors I will share my solution, as the OP was asking for a way to pass a JSON object via GET (not POST as suggested in other answers).

  1. Take the JSON object and convert it to string (JSON.stringify)
  2. Take the string and encode it in Base64 (you can find some useful info on this here
  3. Append it to the URL and make the GET call
  4. Reverse the process. decode and parse it into an object

I have used this in some cases where I only can do GET calls and it works. Also, this solution is practically cross language.

How to remove new line characters from a string?

If speed and low memory usage are important, do something like this:

var sb = new StringBuilder(s.Length);

foreach (char i in s)
    if (i != '\n' && i != '\r' && i != '\t')
        sb.Append(i);

s = sb.ToString();

Directory Chooser in HTML page

Can't be done in pure HTML/JavaScript for security reasons.

Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.

You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.

Another thought would be opening an iframe showing the user's C: drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).

What do you need this for?

What's the best way to add a drop shadow to my UIView

On viewWillLayoutSubviews:

override func viewWillLayoutSubviews() {
    sampleView.layer.masksToBounds =  false
    sampleView.layer.shadowColor = UIColor.darkGrayColor().CGColor;
    sampleView.layer.shadowOffset = CGSizeMake(2.0, 2.0)
    sampleView.layer.shadowOpacity = 1.0
}

Using Extension of UIView:

extension UIView {

    func addDropShadowToView(targetView:UIView? ){
        targetView!.layer.masksToBounds =  false
        targetView!.layer.shadowColor = UIColor.darkGrayColor().CGColor;
        targetView!.layer.shadowOffset = CGSizeMake(2.0, 2.0)
        targetView!.layer.shadowOpacity = 1.0
    }
}

Usage:

sampleView.addDropShadowToView(sampleView)

How do I debug jquery AJAX calls?

2020 answer with Chrome dev tools

To debug any XHR request:

  1. Open Chrome DEV tools (F12)
  2. Right-click your Ajax url in the console

Chrome console Ajax request

for a GET request:

  • click Open in new tab

for a POST request:

  1. click Reveal in Network panel

  2. In the Network panel:

    1. click on your request

    2. click on the response tab to see the details Chrome Network panel's response tab

How to define several include path in Makefile

You have to prepend every directory with -I:

INC=-I/usr/informix/incl/c++ -I/opt/informix/incl/public

A html space is showing as %2520 instead of %20

Try this?

encodeURIComponent('space word').replace(/%20/g,'+')

How do I remove a single file from the staging area (undo git add)?

After version 2.23, Git has introduced the git restore command which you can use to do that. Quoting the official documentation:

Restore specified paths in the working tree with some contents from a restore source. If a path is tracked but does not exist in the restore source, it will be removed to match the source.

The command can also be used to restore the content in the index with --staged, or restore both the working tree and the index with --staged --worktree.

So you can invoke git restore --staged <path> and unstage the file but also keep the changes you made. Remember that if the file was not staged you lose all the changes you made to it.

Removing padding gutter from grid columns in Bootstrap 4

Need an edge-to-edge design? Drop the parent .container or .container-fluid.

Still if you need to remove padding from .row and immediate child columns you have to add the class .no-gutters with the code from @Brian above to your own CSS file, actually it's Not 'right out of the box', check here for official details on the final Bootstrap 4 release: https://getbootstrap.com/docs/4.0/layout/grid/#no-gutters

What's the difference between setWebViewClient vs. setWebChromeClient?

WebViewClient provides the following callback methods, with which you can interfere in how WebView makes a transition to the next content.

void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)

WebChromeClient provides the following callback methods, with which your Activity or Fragment can update the surroundings of WebView.

Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

No pressing enter required

Here's a longer, but reusable and modular approach:

  • Returns 0=yes and 1=no
  • No pressing enter required - just a single character
  • Can press enter to accept the default choice
  • Can disable default choice to force a selection
  • Works for both zsh and bash.

Defaulting to "no" when pressing enter

Note that the N is capitalsed. Here enter is pressed, accepting the default:

$ confirm "Show dangerous command" && echo "rm *"
Show dangerous command [y/N]?

Also note, that [y/N]? was automatically appended. The default "no" is accepted, so nothing is echoed.

Re-prompt until a valid response is given:

$ confirm "Show dangerous command" && echo "rm *"
Show dangerous command [y/N]? X
Show dangerous command [y/N]? y
rm *

Defaulting to "yes" when pressing enter

Note that the Y is capitalised:

$ confirm_yes "Show dangerous command" && echo "rm *"
Show dangerous command [Y/n]?
rm *

Above, I just pressed enter, so the command ran.

No default on enter - require y or n

$ get_yes_keypress "Here you cannot press enter. Do you like this"
Here you cannot press enter. Do you like this [y/n]? k
Here you cannot press enter. Do you like this [y/n]?
Here you cannot press enter. Do you like this [y/n]? n
$ echo $?
1

Here, 1 or false was returned. Note no capitalisation in [y/n]?

Code

# Read a single char from /dev/tty, prompting with "$*"
# Note: pressing enter will return a null string. Perhaps a version terminated with X and then remove it in caller?
# See https://unix.stackexchange.com/a/367880/143394 for dealing with multi-byte, etc.
function get_keypress {
  local REPLY IFS=
  >/dev/tty printf '%s' "$*"
  [[ $ZSH_VERSION ]] && read -rk1  # Use -u0 to read from STDIN
  # See https://unix.stackexchange.com/q/383197/143394 regarding '\n' -> ''
  [[ $BASH_VERSION ]] && </dev/tty read -rn1
  printf '%s' "$REPLY"
}

# Get a y/n from the user, return yes=0, no=1 enter=$2
# Prompt using $1.
# If set, return $2 on pressing enter, useful for cancel or defualting
function get_yes_keypress {
  local prompt="${1:-Are you sure} [y/n]? "
  local enter_return=$2
  local REPLY
  # [[ ! $prompt ]] && prompt="[y/n]? "
  while REPLY=$(get_keypress "$prompt"); do
    [[ $REPLY ]] && printf '\n' # $REPLY blank if user presses enter
    case "$REPLY" in
      Y|y)  return 0;;
      N|n)  return 1;;
      '')   [[ $enter_return ]] && return "$enter_return"
    esac
  done
}
    
# Credit: http://unix.stackexchange.com/a/14444/143394
# Prompt to confirm, defaulting to NO on <enter>
# Usage: confirm "Dangerous. Are you sure?" && rm *
function confirm {
  local prompt="${*:-Are you sure} [y/N]? "
  get_yes_keypress "$prompt" 1
}    

# Prompt to confirm, defaulting to YES on <enter>
function confirm_yes {
  local prompt="${*:-Are you sure} [Y/n]? "
  get_yes_keypress "$prompt" 0
}

React proptype array with shape

There's a ES6 shorthand import, you can reference. More readable and easy to type.

import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';

class ExampleComponent extends Component {
  static propTypes = {
    annotationRanges: arrayOf(shape({
      start: number,
      end: number,
    })).isRequired,
  }

  static defaultProps = {
     annotationRanges: [],
  }
}

Insert NULL value into INT column

Does the column allow null?

Seems to work. Just tested with phpMyAdmin, the column is of type int that allows nulls:

INSERT INTO `database`.`table` (`column`) VALUES (NULL);

How do I create delegates in Objective-C?

//1.
//Custom delegate 
@protocol TB_RemovedUserCellTag <NSObject>

-(void)didRemoveCellWithTag:(NSInteger)tag;

@end

//2.
//Create a weak reference in a class where you declared the delegate
@property(weak,nonatomic)id <TB_RemovedUserCellTag> removedCellTagDelegate;

//3. 
// use it in the class
  [self.removedCellTagDelegate didRemoveCellWithTag:self.tag];

//4. import the header file in the class where you want to conform to the protocol
@interface MyClassUsesDelegate ()<TB_RemovedUserCellTag>

@end

//5. Implement the method in the class .m -(void)didRemoveCellWithTag:(NSInteger)tag { NSLog@("Tag %d",tag);

}

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

Thanks to Vinod for the well presented answer.

I got the same error as Mick Byrne when I followed the steps above. Turning it back to All Unassigned sorted it but I had to tweak a few other things as well:

  • Add the user my site was running under to the users on the Security Tab in SMTP Virtual Server.
  • Changed the value in the mailSettings > network > host attribute in my web.config to the specific server IP (for example 192.168.100.120) as opposed to localhost (which was pointing at 127.0.0.1 in the hosts file).

Hope this saves someone a few mins of messing about.

CMake: How to build external projects and include their targets

I think you're mixing up two different paradigms here.

As you noted, the highly flexible ExternalProject module runs its commands at build time, so you can't make direct use of Project A's import file since it's only created once Project A has been installed.

If you want to include Project A's import file, you'll have to install Project A manually before invoking Project B's CMakeLists.txt - just like any other third-party dependency added this way or via find_file / find_library / find_package.

If you want to make use of ExternalProject_Add, you'll need to add something like the following to your CMakeLists.txt:

ExternalProject_Add(project_a
  URL ...project_a.tar.gz
  PREFIX ${CMAKE_CURRENT_BINARY_DIR}/project_a
  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
)

include(${CMAKE_CURRENT_BINARY_DIR}/lib/project_a/project_a-targets.cmake)

ExternalProject_Get_Property(project_a install_dir)
include_directories(${install_dir}/include)

add_dependencies(project_b_exe project_a)
target_link_libraries(project_b_exe ${install_dir}/lib/alib.lib)

htaccess redirect if URL contains a certain string

RewriteCond %{REQUEST_URI} foobar
RewriteRule .* index.php

or some variant thereof.

Read CSV file column by column

I am sorry, but none of these answers provide an optimal solution. If you use a library such as OpenCSV you will have to write a lot of code to handle special cases to extract information from specific columns.

For example, if you have rows with less columns than what you're after, you'll have to write a lot of code to handle it. Using the OpenCSV example:

  CSVReader reader = new CSVReader(new FileReader(strFile));
  String [] nextLine;
  while ((nextLine = reader.readNext()) != null) {
       //let's say you are interested in getting columns 20, 30, and 40
       String[] outputRow = new String[3];
       if(parsedRow.length < 40){
            outputRow[2] = null;
       } else {
            outputRow[2] = parsedRow[40]
       }
       if(parsedRow.length < 30){
            outputRow[1] = null;
       } else {
            outputRow[1] = parsedRow[30]
       }
       if(parsedRow.length < 20){
            outputRow[0] = null;
       } else {
            outputRow[0] = parsedRow[20]
       }

  }

This is a lot of code for a simple requirement. It gets worse if you are trying to get values of columns by name. You should use a more modern parser such as the one provided by uniVocity-parsers.

To reliably and easily get the columns you want, simply write:

CsvParserSettings settings = new CsvParserSettings();
parserSettings.selectIndexes(20, 30, 40);
CsvParser parser = new CsvParser(settings);
List<String[]> allRows = parser.parseAll(new FileReader(yourFile));

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

How to capture and save an image using custom camera in Android?

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

                // create intent with ACTION_IMAGE_CAPTURE action
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                /**
 Here REQUEST_IMAGE is the unique integer value you can pass it any integer
 **/
                // start camera activity
                startActivityForResult(intent, TAKE_PICTURE);
            }

            }

        );

then u can now give the image a file name as follows and then convert it into bitmap and later on to file

 private void createImageFile(Bitmap bitmap) throws IOException {
        // Create an image file name
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        FileOutputStream stream = new FileOutputStream(image);
        stream.write(bytes.toByteArray());
        stream.close();
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        fileUri = image.getAbsolutePath();
        Picasso.with(getActivity()).load(image).into(showbookimage);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (requestCode == TAKE_PICTURE && resultCode== Activity.RESULT_OK && intent != null){
            // get bundle
            Bundle extras = intent.getExtras();
            // get
            bitMap = (Bitmap) extras.get("data");
//            showbookimage.setImageBitmap(bitMap);
            try {
                createImageFile(bitMap);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

use picasso for images to display rather fast

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

For those who want to use simpleUML in Android Studio and having issues in running SimpleUML.

First download simpleUML jar from here https://plugins.jetbrains.com/plugin/4946-simpleumlce

Now follow the below steps.

Step 1:

Click on File and go to Settings (File ? Settings)

Step 2

Select Plugins from Left Panel and click Install plugin from disk


1]

Step 3:

Locate the SimpleUML jar file and select it.

2]

Step 4:

Now Restart Android Studio (File ? Invalidate Caches/Restart ? Just Restart)

Step 5:

After you restart Right Click the Package name and Select New Diagram or Add to simpleUML Diagram ? New Diagram.

3

Step 6:

Set a file name and create UML file. I created with name NewDiagram

enter image description here Step 7:

Now Right Click the Package name and Select the file you created. In my case it was NewDiagram

enter image description here

Step 8:

All files are stacked on top of one another. You can just drag and drop them and set a hierarchy.

enter image description here

Like this below, you can drag these classes

enter image description here

sending mail from Batch file

There are multiple methods for handling this problem.

My advice is to use the powerful Windows freeware console application SendEmail.

sendEmail.exe -f [email protected] -o message-file=body.txt -u subject message -t [email protected] -a attachment.zip -s smtp.gmail.com:446 -xu gmail.login -xp gmail.password

How to create a md5 hash of a string in C?

It would appear that you should

  • Create a struct MD5context and pass it to MD5Init to get it into a proper starting condition
  • Call MD5Update with the context and your data
  • Call MD5Final to get the resulting hash

These three functions and the structure definition make a nice abstract interface to the hash algorithm. I'm not sure why you were shown the core transform function in that header as you probably shouldn't interact with it directly.

The author could have done a little more implementation hiding by making the structure an abstract type, but then you would have been forced to allocate the structure on the heap every time (as opposed to now where you can put it on the stack if you so desire).

Error: Jump to case label

JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn't use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

Converting java date to Sql timestamp

The problem is with the way you are printing the Time data

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
System.out.println(sa); //this will print the milliseconds as the toString() has been written in that format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(timestamp)); //this will print without ms

How can I scroll a div to be visible in ReactJS?

I assume that you have some sort of List component and some sort of Item component. The way I did it in one project was to let the item know if it was active or not; the item would ask the list to scroll it into view if necessary. Consider the following pseudocode:

class List extends React.Component {
  render() {
    return <div>{this.props.items.map(this.renderItem)}</div>;
  }

  renderItem(item) {
    return <Item key={item.id} item={item}
                 active={item.id === this.props.activeId}
                 scrollIntoView={this.scrollElementIntoViewIfNeeded} />
  }

  scrollElementIntoViewIfNeeded(domNode) {
    var containerDomNode = React.findDOMNode(this);
    // Determine if `domNode` fully fits inside `containerDomNode`.
    // If not, set the container's scrollTop appropriately.
  }
}

class Item extends React.Component {
  render() {
    return <div>something...</div>;
  }

  componentDidMount() {
    this.ensureVisible();
  }

  componentDidUpdate() {
    this.ensureVisible();
  }

  ensureVisible() {
    if (this.props.active) {
      this.props.scrollIntoView(React.findDOMNode(this));
    }
  }
}

A better solution is probably to make the list responsible for scrolling the item into view (without the item being aware that it's even in a list). To do so, you could add a ref attribute to a certain item and find it with that:

class List extends React.Component {
  render() {
    return <div>{this.props.items.map(this.renderItem)}</div>;
  }

  renderItem(item) {
    var active = item.id === this.props.activeId;
    var props = {
      key: item.id,
      item: item,
      active: active
    };
    if (active) {
      props.ref = "activeItem";
    }
    return <Item {...props} />
  }

  componentDidUpdate(prevProps) {
    // only scroll into view if the active item changed last render
    if (this.props.activeId !== prevProps.activeId) {
      this.ensureActiveItemVisible();
    }
  }

  ensureActiveItemVisible() {
    var itemComponent = this.refs.activeItem;
    if (itemComponent) {
      var domNode = React.findDOMNode(itemComponent);
      this.scrollElementIntoViewIfNeeded(domNode);
    }
  }

  scrollElementIntoViewIfNeeded(domNode) {
    var containerDomNode = React.findDOMNode(this);
    // Determine if `domNode` fully fits inside `containerDomNode`.
    // If not, set the container's scrollTop appropriately.
  }
}

If you don't want to do the math to determine if the item is visible inside the list node, you could use the DOM method scrollIntoView() or the Webkit-specific scrollIntoViewIfNeeded, which has a polyfill available so you can use it in non-Webkit browsers.

HTML set image on browser tab

<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />

Excellent tool for cross-browser favicon - http://www.convertico.com/

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

Submit form on pressing Enter with AngularJS

I wanted something a little more extensible/semantic than the given answers so I wrote a directive that takes a javascript object in a similar way to the built-in ngClass:

HTML

<input key-bind="{ enter: 'go()', esc: 'clear()' }" type="text"></input>

The values of the object are evaluated in the context of the directive's scope - ensure they are encased in single quotes otherwise all of the functions will be executed when the directive is loaded(!)

So for example: esc : 'clear()' instead of esc : clear()

Javascript

myModule
    .constant('keyCodes', {
        esc: 27,
        space: 32,
        enter: 13,
        tab: 9,
        backspace: 8,
        shift: 16,
        ctrl: 17,
        alt: 18,
        capslock: 20,
        numlock: 144
    })
    .directive('keyBind', ['keyCodes', function (keyCodes) {
        function map(obj) {
            var mapped = {};
            for (var key in obj) {
                var action = obj[key];
                if (keyCodes.hasOwnProperty(key)) {
                    mapped[keyCodes[key]] = action;
                }
            }
            return mapped;
        }
        
        return function (scope, element, attrs) {
            var bindings = map(scope.$eval(attrs.keyBind));
            element.bind("keydown keypress", function (event) {
                if (bindings.hasOwnProperty(event.which)) {
                    scope.$apply(function() {
                         scope.$eval(bindings[event.which]);
                    });
                }
            });
        };
    }]);

Java ArrayList Index

You have ArrayList all wrong,

  • You can't have an integer array and assign a string value.
  • You cannot do a add() method in an array

Rather do this:

List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");

String value = alist.get(1); //returns the 2nd item from list, in this case "banana"

Indexing is counted from 0 to N-1 where N is size() of list.

Extract every nth element of a vector

a <- 1:120
b <- a[seq(1, length(a), 6)]

Disable and later enable all table indexes in Oracle

combining 3 answers together: (because a select statement does not execute the DDL)

set pagesize 0

alter session set skip_unusable_indexes = true;
spool c:\temp\disable_indexes.sql
select 'alter index ' || u.index_name || ' unusable;' from user_indexes u;
spool off
@c:\temp\disable_indexes.sql

Do import...

select 'alter index ' || u.index_name || 
' rebuild online;' from user_indexes u;

Note this assumes that the import is going to happen in the same (sqlplus) session.
If you are calling "imp" it will run in a separate session so you would need to use "ALTER SYSTEM" instead of "ALTER SESSION" (and remember to put the parameter back the way you found it.

Five equal columns in twitter bootstrap

Is someone uses bootstrap-sass (v3), here is simple code for 5 columns using bootstrap mixings:

  .col-xs-5ths {
     @include make-xs-column(2.4);
  }

  @media (min-width: $screen-sm-min) {
     .col-sm-5ths {
        @include make-sm-column(2.4);
     }
  }

  @media (min-width: $screen-md-min) {
     .col-md-5ths {
        @include make-md-column(2.4);
     }
  }

  @media (min-width: $screen-lg-min) {
     .col-lg-5ths {
        @include make-lg-column(2.4);
     }
  }

Make sure you have included:

@import "bootstrap/variables";
@import "bootstrap/mixins";

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

It may happen, e.g. after an interrupted download, that Maven cached a broken version of the referenced package in your local repository.

Solution: Manually delete the folder of this plugin from cache (i.e. your local repository), and repeat maven install.

How to find the right folder? Folders in Maven repository follow the structure:

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-source-plugin</artifactId>
    <version>2.4</version>
</dependency>

is cached in ${USER_HOME}\.m2\repository\org\apache\maven\plugins\maven-source-plugin\2.4

How to calculate percentage with a SQL statement

I simply use this when ever I need to work out a percentage..

ROUND(CAST((Numerator * 100.0 / Denominator) AS FLOAT), 2) AS Percentage

Note that 100.0 returns decimals, whereas 100 on it's own will round up the result to the nearest whole number, even with the ROUND() function!

Remove all special characters, punctuation and spaces from string

This will remove all non-alphanumeric characters except spaces.

string = "Special $#! characters   spaces 888323"
''.join(e for e in string if (e.isalnum() or e.isspace()))

Special characters spaces 888323

Sending HTTP POST Request In Java

The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the HttpResponse with Java libraries.

Here is the more complete code :

/*
 * Create the POST request
 */
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
/*
 * Execute the HTTP Request
 */
try {
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity respEntity = response.getEntity();

    if (respEntity != null) {
        // EntityUtils to get the response content
        String content =  EntityUtils.toString(respEntity);
    }
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}

How to select all rows which have same value in some column

How about

SELECT *
FROM Employees
WHERE PhoneNumber IN (
    SELECT PhoneNumber
    FROM Employees
    GROUP BY PhoneNumber
    HAVING COUNT(Employee_ID) > 1
    )

SQL Fiddle DEMO

Multiple aggregate functions in HAVING clause

For your example query, the only possible value greater than 2 and less than 4 is 3, so we simplify:

GROUP BY meetingID
HAVING COUNT(caseID) = 3

In your general case:

GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7

Or (possibly easier to read?),

GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6

How to check a string against null in java?

Use TextUtils Method if u working in Android.

TextUtils.isEmpty(str) : Returns true if the string is null or 0-length. Parameters: str the string to be examined Returns: true if str is null or zero length

  if(TextUtils.isEmpty(str)) {
        // str is null or lenght is 0
    }

Below is source code of this method.You can use direclty.

 /**
     * Returns true if the string is null or 0-length.
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
    public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;
    }

How should I remove all the leading spaces from a string? - swift

Swift 3

You can simply use this method to remove all normal spaces in a string (doesn't consider all types of whitespace):

let myString = " Hello World ! "
let formattedString = myString.replacingOccurrences(of: " ", with: "")

The result will be:

HelloWorld!

Call js-function using JQuery timer

Might want to check out jQuery Timer to manage one or multiple timers.

http://code.google.com/p/jquery-timer/

var timer = $.timer(yourfunction, 10000);

function yourfunction() { alert('test'); }

Then you can control it with:

timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

When to use HashMap over LinkedList or ArrayList and vice-versa

Lists represent a sequential ordering of elements. Maps are used to represent a collection of key / value pairs.

While you could use a map as a list, there are some definite downsides of doing so.

Maintaining order: - A list by definition is ordered. You add items and then you are able to iterate back through the list in the order that you inserted the items. When you add items to a HashMap, you are not guaranteed to retrieve the items in the same order you put them in. There are subclasses of HashMap like LinkedHashMap that will maintain the order, but in general order is not guaranteed with a Map.

Key/Value semantics: - The purpose of a map is to store items based on a key that can be used to retrieve the item at a later point. Similar functionality can only be achieved with a list in the limited case where the key happens to be the position in the list.

Code readability Consider the following examples.

    // Adding to a List
    list.add(myObject);         // adds to the end of the list
    map.put(myKey, myObject);   // sure, you can do this, but what is myKey?
    map.put("1", myObject);     // you could use the position as a key but why?

    // Iterating through the items
    for (Object o : myList)           // nice and easy
    for (Object o : myMap.values())   // more code and the order is not guaranteed

Collection functionality Some great utility functions are available for lists via the Collections class. For example ...

    // Randomize the list
    Collections.shuffle(myList);

    // Sort the list
    Collections.sort(myList, myComparator);  

Hope this helps,

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

Verify if file exists or not in C#

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

How to convert Java String to JSON Object

Your json -

{
    "title":"Free Music Archive - Genres",
    "message":"",
    "errors":[
    ],
    "total":"163",
    "total_pages":82,
    "page":1,
    "limit":"2",
    "dataset":[
    {
    "genre_id":"1",
    "genre_parent_id":"38",
    "genre_title":"Avant-Garde",
    "genre_handle":"Avant-Garde",
    "genre_color":"#006666"
    },
    {
    "genre_id":"2",
    "genre_parent_id":null,
    "genre_title":"International",
    "genre_handle":"International",
    "genre_color":"#CC3300"
    }
    ]
    }

Using the JSON library from json.org -

JSONObject o = new JSONObject(jsonString);

NOTE:

The following information will be helpful to you - json.org.

UPDATE:

import org.json.JSONObject;
 //Other lines of code
URL seatURL = new URL("http://freemusicarchive.org/
 api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
 //Return the JSON Response from the API
 BufferedReader br = new BufferedReader(new         
 InputStreamReader(seatURL.openStream(),
 Charset.forName("UTF-8")));
 String readAPIResponse = " ";
 StringBuilder jsonString = new StringBuilder();
 while((readAPIResponse = br.readLine()) != null){
   jsonString.append(readAPIResponse);
 }
 JSONObject jsonObj = new JSONObject(jsonString.toString());
 System.out.println(jsonString);
 System.out.println("---------------------------");
 System.out.println(jsonObj);

What's the best way to use R scripts on the command line (terminal)?

Try smallR for writing quick R scripts in the command line:

http://code.google.com/p/simple-r/

(r command in the directory)

Plotting from the command line using smallR would look like this:

r -p file.txt

Process with an ID #### is not running in visual studio professional 2013 update 3

Found the solution!

I had something similar:

It took a while to figure this out. Have tried:

1. Reinstalling the whole VS2019 web development environment
2. Deleting `%userprofile%\Documents\IISExpress`
3. Deleting projects' `.vs` folders
4. Removing `IIExpress 10` from `Programms` in Win10
5. Changing projects' settings/properties

The main problem was a registry entry Start located at

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP

So, changing value of a key Start from 4 to 3 and rebooting fixed the issue.

One of possible reason I would recall is running the Laragon which required changing this value to 4 to start an Nginx web server.

Benefits of inline functions in C++?

Our computer science professor urged us to never use inline in a c++ program. When asked why, he kindly explained to us that modern compilers should detect when to use inline automatically.

So yes, the inline can be an optimization technique to be used wherever possible, but apparently this is something that is already done for you whenever it's possible to inline a function anyways.

How can I get an HTTP response body as a string?

Here are two examples from my working project.

  1. Using EntityUtils and HttpEntity

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    
  2. Using BasicResponseHandler

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler().handleResponse(response);
    System.out.println(responseString);
    

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

How to export a MySQL database to JSON?

I know this is old, but for the sake of somebody looking for an answer...

There's a JSON library for MYSQL that can be found here You need to have root access to your server and be comfortable installing plugins (it's simple).

1) upload the lib_mysqludf_json.so into the plugins directory of your mysql installation

2) run the lib_mysqludf_json.sql file (it pretty much does all of the work for you. If you run into trouble just delete anything that starts with 'DROP FUNCTION...')

3) encode your query in something like this:

SELECT json_array(
         group_concat(json_object( name, email))
FROM ....
WHERE ...

and it will return something like

[ 
   { 
     "name": "something",
     "email": "[email protected]"
    }, 
   { 
     "name": "someone",
     "email": "[email protected]"
    }

]

Working with time DURATION, not time of day

The custom format hh:mm only shows the number of hours correctly up to 23:59, after that, you get the remainder, less full days. For example, 48 hours would be displayed as 00:00, even though the underlaying value is correct.

To correctly display duration in hours and seconds (below or beyond a full day), you should use the custom format [h]:mm;@ In this case, 48 hours would be displayed as 48:00.

Cheers.

Laravel migration table field's type change

Not really an answer, but just a note about ->change():

Only the following column types can be "changed": bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

https://laravel.com/docs/5.8/migrations#modifying-columns

If your column isn't one of these you will need to either drop the column or use the alter statement as mentioned in other answers.

PDO mysql: How to know if insert was successful

If an update query executes with values that match the current database record then $stmt->rowCount() will return 0 for no rows were affected. If you have an if( rowCount() == 1 ) to test for success you will think the updated failed when it did not fail but the values were already in the database so nothing change.

$stmt->execute();
if( $stmt ) return "success";

This did not work for me when I tried to update a record with a unique key field that was violated. The query returned success but another query returns the old field value.

How to format JSON in notepad++

The answer was to install the plugin individually. I installed all the three plugins shown in the screenshot together. And it created the issue. I had to install each plugin individually and then it worked fine. I am able to format the JSON string.

java.util.NoSuchElementException: No line found

You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html

What is the difference between Python and IPython?

Even after viewing this thread, I had thought that ipython was a synonym for the python shell, in other words that typing python at the command line put one into ipython mode.

It is in fact, as referenced above, a very cool interactive shell (command line program) that can be installed from iPython.org or simply by running

pip install ipython

or the more extensive:

pip install ipython[notebook]

from the command line.

JQuery - File attributes

If #uploadedfile is an input with type "file" :

var file = $("#uploadedfile")[0].files[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");

Normally this would fire on the change event, like so:

$("#uploadedfile").on("change", function(){
   var file = this.files[0],
       fileName = file.name,
       fileSize = file.size;
   alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
   CustomFileHandlingFunction(file);
});

FIDDLE

Fill formula down till last row in column

Alternatively, you may use FillDown

Range("M3") = "=G3&"",""&L3": Range("M3:M" & LastRow).FillDown

Select statement to find duplicates on certain fields

try this query to have sepratley count of each SELECT statements :

select field1,count(field1) as field1Count,field2,count(field2) as field2Counts,field3, count(field3) as field3Counts
from table_name
group by field1,field2,field3
having count(*) > 1

How to compare timestamp dates with date-only parameter in MySQL?

When I read your question, I thought your were on Oracle DB until I saw the tag 'MySQL'. Anyway, for people working with Oracle here is the way:

SELECT *
FROM table
where timestamp = to_timestamp('21.08.2017 09:31:57', 'dd-mm-yyyy hh24:mi:ss');

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

Make Bootstrap's Carousel both center AND responsive?

I assume you have different sized images. I tested this myself, and it works as you describe (always centered, images widths appropriately)

/*CSS*/
div.c-wrapper{
    width: 80%; /* for example */
    margin: auto;
}

.carousel-inner > .item > img, 
.carousel-inner > .item > a > img{
width: 100%; /* use this, or not */
margin: auto;
}

<!--html-->
<div class="c-wrapper">
<div id="carousel-example-generic" class="carousel slide">
  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol>

  <!-- Wrapper for slides -->
  <div class="carousel-inner">
    <div class="item active">
      <img src="http://placehold.it/600x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
        <div class="item">
      <img src="http://placehold.it/500x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
    <div class="item">
      <img src="http://placehold.it/700x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
  </div>

  <!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
    <span class="icon-prev"></span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
    <span class="icon-next"></span>
  </a>
</div>
</div>

This creates a "jump" due to variable heights... to solve that, try something like this: Select the tallest image of a list

Or use media-query to set your own fixed height.

How to implement a read only property

The second method is preferred because of the encapsulation. You can certainly have the readonly field be public, but that goes against C# idioms in which you have data access occur through properties and not fields.

The reasoning behind this is that the property defines a public interface and if the backing implementation to that property changes, you don't end up breaking the rest of the code because the implementation is hidden behind an interface.

Reading from memory stream to string

If you'd checked the results of stream.Read, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;.) However, it's easier to just call ToArray:

settingsString = LocalEncoding.GetString(stream.ToArray());

(You'll need to change the type of stream from Stream to MemoryStream, but that's okay as it's in the same method where you create it.)

Alternatively - and even more simply - just use StringWriter instead of StreamWriter. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.

I'm concerned by the way you're just catching Exception and assuming that it means something harmless, by the way - without even logging anything. Note that using statements are generally cleaner than writing explicit finally blocks.

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

Off the top of my head, if the element is not a block element - make it so.

and then give it a width.

Determine file creation date in Java

This is a basic example of how to get the creation date of a file in Java, using BasicFileAttributes class:

   Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt");
    BasicFileAttributes attr;
    try {
    attr = Files.readAttributes(path, BasicFileAttributes.class);
    System.out.println("Creation date: " + attr.creationTime());
    //System.out.println("Last access date: " + attr.lastAccessTime());
    //System.out.println("Last modified date: " + attr.lastModifiedTime());
    } catch (IOException e) {
    System.out.println("oops error! " + e.getMessage());
}

Pandas aggregate count distinct

Just adding to the answers already given, the solution using the string "nunique" seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M

%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s

%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s

%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s

javascript: get a function's variable's value within another function

the OOP way to do this in ES5 is to make that variable into a property using the this keyword.

function first(){
    this.nameContent=document.getElementById('full_name').value;
}

function second() {
    y=new first();
    alert(y.nameContent);
}

Java - how do I write a file to a specified directory

The best practice is using File.separator in the paths.

jQuery's .on() method combined with the submit event

You need to delegate event to the document level

$(document).on('submit','form.remember',function(){
   // code
});

$('form.remember').on('submit' work same as $('form.remember').submit( but when you use $(document).on('submit','form.remember' then it will also work for the DOM added later.

Java Swing revalidate() vs repaint()

revalidate is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel are considered dirty by the RepaintManager.

repaint is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.

How to make a simple rounded button in Storyboard?

You can do something like this:

@IBDesignable class MyButton: UIButton
{
    override func layoutSubviews() {
        super.layoutSubviews()

        updateCornerRadius()
    }

    @IBInspectable var rounded: Bool = false {
        didSet {
            updateCornerRadius()
        }
    }

    func updateCornerRadius() {
        layer.cornerRadius = rounded ? frame.size.height / 2 : 0
    }
}

Set class to MyButton in Identity Inspector and in IB you will have rounded property:

enter image description here

how to count the spaces in a java string?

s.length() - s.replaceAll(" ", "").length() returns you number of spaces.

There are more ways. For example"

int spaceCount = 0;
for (char c : str.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}

etc., etc.

In your case you tried to split string using \t - TAB. You will get right result if you use " " instead. Using \s may be confusing since it matches all whitepsaces - regular spaces and TABs.

Scrolling a div with jQuery

I don't know if this is exactly what you want, but did you know you can use the CSS overflow property to create scrollbars?

CSS:

div.box{
  width: 200px;
  height: 200px;
  overflow: scroll;
}

HTML:

<div class="box">
  All your text content...
</div>

How to position a Bootstrap popover?

If you take a look at bootstrap source codes, you will notice that position can be modified using margin.

So, first you should change popover template to add own css class to not get in conflict with other popovers:

$(".trigger").popover({
  html: true,
  placement: 'bottom',
  trigger: 'click',
  template: '<div class="popover popover--topright" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
});

Then using css you can easily shift popover position:

.popover.popover--topright {
  /* margin-top: 0px; // Use to change vertical position */
  margin-right: 40px; /* Use to change horizontal position */
}
.popover.popover--topright .arrow {
  left: 88% !important; /* fix arrow position */
}

This solution would not influence other popovers you have. Same solution can be used on tooltips as well because popover class inherit from tooltip class.

Here's a simple jsFiddle

How to insert a line break <br> in markdown

Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so

let markdown = `
    1. Apple
    2. Mango
     this is juicy
    3. Orange
`

Excel data validation with suggestions/autocomplete

None of the above mentioned solution worked. The one that seemed to work only provide the functionality for just one cell

Recently I had to enter a lot of names and without suggestions, it was a huge pain. I was fortunate enough to have this excel autocomplete add-in to enable the autocompletion. The down side is that you need to enable macro (but you can always turn it off later)

Replace all elements of Python NumPy Array that are greater than some value

Another way is to use np.place which does in-place replacement and works with multidimentional arrays:

import numpy as np

# create 2x3 array with numbers 0..5
arr = np.arange(6).reshape(2, 3)

# replace 0 with -10
np.place(arr, arr == 0, -10)

test attribute in JSTL <c:if> tag

Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.

If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

How to make an "alias" for a long path?

Put the following line in your myscript

set myFold = '~/Files/Scripts/Main'

In the terminal use

source myscript
cd $myFold

String delimiter in string.split method

Double quotes are interpreted as literals in regex; they are not special characters. You are trying to match a literal "||".

Just use Pattern.quote(delimiter):

As requested, here's a line of code (same as Sanjay's)

final String[] tokens = line.split(Pattern.quote(delimiter));

If that doesn't work, you're not passing in the correct delimiter.

Select from multiple tables without a join?

If your question was this -- Select ename, dname FROM emp, dept without using joins..

Then, I would do this...

SELECT ename, (SELECT dname 
FROM dept
WHERE dept.deptno=emp.deptno)dname
FROM EMP

Output:

ENAME      DNAME
---------- --------------
SMITH      RESEARCH
ALLEN      SALES
WARD       SALES
JONES      RESEARCH
MARTIN     SALES
BLAKE      SALES
CLARK      ACCOUNTING
SCOTT      RESEARCH
KING       ACCOUNTING
TURNER     SALES
ADAMS      RESEARCH

ENAME      DNAME
---------- --------------
JAMES      SALES
FORD       RESEARCH
MILLER     ACCOUNTING

14 rows selected.

What is a web service endpoint?

A web service endpoint is the URL that another program would use to communicate with your program. To see the WSDL you add ?wsdl to the web service endpoint URL.

Web services are for program-to-program interaction, while web pages are for program-to-human interaction.

So: Endpoint is: http://www.blah.com/myproject/webservice/webmethod

Therefore, WSDL is: http://www.blah.com/myproject/webservice/webmethod?wsdl


To expand further on the elements of a WSDL, I always find it helpful to compare them to code:

A WSDL has 2 portions (physical & abstract).

Physical Portion:

Definitions - variables - ex: myVar, x, y, etc.

Types - data types - ex: int, double, String, myObjectType

Operations - methods/functions - ex: myMethod(), myFunction(), etc.

Messages - method/function input parameters & return types

  • ex: public myObjectType myMethod(String myVar)

Porttypes - classes (i.e. they are a container for operations) - ex: MyClass{}, etc.

Abstract Portion:

Binding - these connect to the porttypes and define the chosen protocol for communicating with this web service. - a protocol is a form of communication (so text/SMS, vs. phone vs. email, etc.).

Service - this lists the address where another program can find your web service (i.e. your endpoint).

Content-Disposition:What are the differences between "inline" and "attachment"?

Because when I use one or another I get a window prompt asking me to download the file for both of them.

This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.

If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.

UITableView, Separator color where to set?

If you just want to set the same color to every separator and it is opaque you can use:

 self.tableView.separatorColor = UIColor.redColor()

If you want to use different colors for the separators or clear the separator color or use a color with alpha.

BE CAREFUL: You have to know that there is a backgroundView in the separator that has a default color.

To change it you can use this functions:

    func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if(view.isKindOfClass(UITableViewHeaderFooterView)){
            var headerView = view as! UITableViewHeaderFooterView;
            headerView.backgroundView?.backgroundColor = myColor

           //Other colors you can change here
           // headerView.backgroundColor = myColor
           // headerView.contentView.backgroundColor = myColor
        }
    }

    func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        if(view.isKindOfClass(UITableViewHeaderFooterView)){
            var footerView = view as! UITableViewHeaderFooterView;
            footerView.backgroundView?.backgroundColor = myColor
           //Other colors you can change here
           //footerView.backgroundColor = myColor
           //footerView.contentView.backgroundColor = myColor
        }
    }

Hope it helps!

Best way to check function arguments?

This is not the solution to you, but if you want to restrict the function calls to some specific parameter types then you must use the PROATOR { The Python Function prototype validator }. you can refer the following link. https://github.com/mohit-thakur-721/proator

How to split elements of a list?

Something like:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']

Who is listening on a given TCP port on Mac OS X?

For macOS I use two commands together to show information about the processes listening on the machine and process connecting to remote servers. In other words, to check the listening ports and the current (TCP) connections on a host you could use the two following commands together

1. netstat -p tcp -p udp 

2. lsof -n -i4TCP -i4UDP 

Thought I would add my input, hopefully it can end up helping someone.

In .NET, which loop runs faster, 'for' or 'foreach'?

I did test it a while ago, with the result that a for loop is much faster than a foreach loop. The cause is simple, the foreach loop first needs to instantiate an IEnumerator for the collection.

Can you 'exit' a loop in PHP?

You are looking for the break statement.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

How do I save JSON to local text file

It's my solution to save local data to txt file.

_x000D_
_x000D_
function export2txt() {_x000D_
  const originalData = {_x000D_
    members: [{_x000D_
        name: "cliff",_x000D_
        age: "34"_x000D_
      },_x000D_
      {_x000D_
        name: "ted",_x000D_
        age: "42"_x000D_
      },_x000D_
      {_x000D_
        name: "bob",_x000D_
        age: "12"_x000D_
      }_x000D_
    ]_x000D_
  };_x000D_
_x000D_
  const a = document.createElement("a");_x000D_
  a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {_x000D_
    type: "text/plain"_x000D_
  }));_x000D_
  a.setAttribute("download", "data.txt");_x000D_
  document.body.appendChild(a);_x000D_
  a.click();_x000D_
  document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2txt()">Export data to local txt file</button>
_x000D_
_x000D_
_x000D_

Disable native datepicker in Google Chrome

I know this is an old question now, but I just landed here looking for information about this so somebody else might too.

You can use Modernizr to detect whether the browser supports HTML5 input types, like 'date'. If it does, those controls will use the native behaviour to display things like datepickers. If it doesn't, you can specify what script should be used to display your own datepicker. Works well for me!

I added jquery-ui and Modernizr to my page, then added this code:

<script type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initDateControls);
    initDateControls();

    function initDateControls() {
        //Adds a datepicker to inputs with a type of 'date' when the browser doesn't support that HTML5 tag (type=date)'
        Modernizr.load({
            test: Modernizr.inputtypes.datetime,
            nope: "scripts/jquery-ui.min.js",
            callback: function () {
                $("input[type=date]").datepicker({ dateFormat: "dd-mm-yy" });
            }
        });
    }

</script>

This means that the native datepicker is displayed in Chrome, and the jquery-ui one is displayed in IE.

Drawing a simple line graph in Java

There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV) file with the XChart library. Disclaimer: I'm the lead developer of the project.

In this example, two text files exist in ./CSV/CSVChartRows/. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1 contains x, y, and error bar data, whereas series2 contains just x and y, data.

series1.csv

1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5

series2.csv

1,56
2,34
3,12
4,26

Source Code

public class CSVChartRows {

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

    // import chart from a folder containing CSV files
    XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);

    // Show it
    new SwingWrapper(chart).displayChart();
  }
}

Resulting Plot

enter image description here

Session TimeOut in web.xml

You can see many options as answer for your question, however you can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete. E.g.:

   <session-config>
        <session-timeout>-1</session-timeout>
    </session-config>

Or if you don't want a timeout happening for some purpose:

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

Another option could be increase the number to 1000, etc, etc, bla, bla, bla.

But if you really want to stop and you consider that is unnecessary for your application to force the user to logout, just add a logout button and the user will decide when to leave.

Here is what you can do to solve the problem if you do not need to force to logout, and in you are loading files that could take time base on server and your computer speed and the size of the file.

<!-- sets the default session timeout to 60 minutes. -->
   <!-- <session-config>
     <session-timeout>60</session-timeout>
   </session-config> -->

Just comment it or deleted that's it! Tan tararantan, tan tan!

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

What is the default lifetime of a session?

Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds.

I believe the default is 1440 seconds (24 mins)

http://www.php.net/manual/en/session.configuration.php

Edit: As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to implement session lifetimes is available here:

How do I expire a PHP session after 30 minutes?

twitter bootstrap 3.0 typeahead ajax example

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
var data = ["Aamir", "Amol", "Ayesh", "Sameera", "Sumera", "Kajol", "Kamal",
  "Akash", "Robin", "Roshan", "Aryan"];
$(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
               process(data);
            });
        }
    });
});
</script>

How do I prompt for Yes/No/Cancel input in a Linux shell script?

more generic would be:

function menu(){
    title="Question time"
    prompt="Select:"
    options=("Yes" "No" "Maybe")
    echo "$title"
    PS3="$prompt"
    select opt in "${options[@]}" "Quit/Cancel"; do
        case "$REPLY" in
            1 ) echo "You picked $opt which is option $REPLY";;
            2 ) echo "You picked $opt which is option $REPLY";;
            3 ) echo "You picked $opt which is option $REPLY";;
            $(( ${#options[@]}+1 )) ) clear; echo "Goodbye!"; exit;;
            *) echo "Invalid option. Try another one.";continue;;
         esac
     done
     return
}

pandas get rows which are NOT in other dataframe

You can also concat df1, df2:

x = pd.concat([df1, df2])

and then remove all duplicates:

y = x.drop_duplicates(keep=False, inplace=False)

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

Calculate a MD5 hash from a string

You can use Convert.ToBase64String to convert 16 byte output of MD5 to a ~24 char string. A little bit better without reducing security. (j9JIbSY8HuT89/pwdC8jlw== for your example)

How to JOIN three tables in Codeigniter

Use this code in model

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    if($query->num_rows() != 0)
    {
        return $query->result_array();
    }
    else
    {
        return false;
    }
}

Get git branch name in Jenkins Pipeline/Jenkinsfile

For pipeline:

pipeline {
  environment {
     BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
  }
}

How to reference Microsoft.Office.Interop.Excel dll?

You have to check which version of Excel you are targeting?

If you are targeting Excel 2010 use version 14 (as per Grant's screenshot answer), Excel 2007 use version 12 . You can not support Excel 2003 using vS2012 as they do not have the correct Interop dll installed.

How do I get Month and Date of JavaScript in 2 digit format?

Why not use padStart ?

_x000D_
_x000D_
var dt = new Date();

year  = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day   = dt.getDate().toString().padStart(2, "0");

console.log(year + '/' + month + '/' + day);
_x000D_
_x000D_
_x000D_

This will always return 2 digit numbers even if the month or day is less than 10.

Notes:

  • This will only work with Internet Explorer if the js code is transpiled using babel.
  • getFullYear() returns the 4 digit year and doesn't require padStart.
  • getMonth() returns the month from 0 to 11.
    • 1 is added to the month before padding to keep it 1 to 12
  • getDate() returns the day from 1 to 31.
    • the 7th day will return 07 and so we do not need to add 1 before padding the string.

How do I view Android application specific cache?

Question: Where is application-specific cache located on Android?

Answer: /data/data

Passing multiple argument through CommandArgument of Button in Asp.net

After poking around it looks like Kelsey is correct.

Just use a comma or something and split it when you want to consume it.

What is the Windows equivalent of the diff command?

I've found a lightweight graphical software for windows that seems to be useful in lack of diff command. It could solve all of my problems.

WinDiff http://www.grigsoft.com/download-windiff.htm

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

Submit two forms with one button

In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)

If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.

I recommend you use/generate a single request which you can transact server-side.

IntelliJ does not show 'Class' when we right click and select 'New'

The directory or one of the parent directories must be marked as Source Root (In this case, it appears in blue).

If this is not the case, right click your root source directory -> Mark As -> Source Root.

SQL Server function to return minimum date (January 1, 1753)

Here is a fast and highly readable way to get the min date value

Note: This is a Deterministic Function, so to improve performance further we might as well apply WITH SCHEMABINDING to the return value.

Create a function

CREATE FUNCTION MinDate()
RETURNS DATETIME WITH SCHEMABINDING
AS
BEGIN
    RETURN CONVERT(DATETIME, -53690)

END

Call the function

dbo.MinDate()

Example 1

PRINT dbo.MinDate()

Example 2

PRINT 'The minimimum date allowed in an SQL database is ' + CONVERT(VARCHAR(MAX), dbo.MinDate())

Example 3

SELECT * FROM Table WHERE DateValue > dbo.MinDate()

Example 4

SELECT dbo.MinDate() AS MinDate

Example 5

DECLARE @MinDate AS DATETIME = dbo.MinDate()

SELECT @MinDate AS MinDate

What is the difference between print and puts?

puts call the to_s of each argument and adds a new line to each string, if it does not end with new line. print just output each argument by calling their to_s.

for example: puts "one two": one two

{new line}

puts "one two\n": one two

{new line} #puts will not add a new line to the result, since the string ends with a new line

print "one two": one two

print "one two\n": one two

{new line}

And there is another way to output: p

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

It is helpful to output debugging message. p "aa\n\t": aa\n\t

Select max value of each group

SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN
       (SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2
    ON t1.ProdId = t2.ProdId
   AND t1.Quantity = t2.MaxQuantity
 ORDER BY t1.ProdId

this will give you the idea.

HTML form do some "action" when hit submit button

Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems

Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:

For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:

<html>   
<head>
 <title>Test Page</title>
</head>   
<body>   
    <h2>Data Collection</h2><p>
    <form action="process.php" method="post">  
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="Name"/></td>
            </tr>   
            <tr>
                <td>Age:</td>
                <td><input type="text" name="Age"/></td>
            </tr>   
            <tr>
                <td colspan="2" align="center">
                <input type="submit"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:

<?php   
    print "Your name is ". $Name;   
    print "<br />";   
    print "You are ". $Age . " years old";   
    print "<br />";   $old = 25 + $Age;
    print "In 25 years you will be " . $old . " years old";   
?>

As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.

Additional JavaScript Example

This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.

Note: document.getElementById("fname").value gets the object with the ID tag that equals fname and then pulls it's value - which in this case is the text in the First Name textbox.

 <html>
    <head>
     <script type="text/javascript">
     function ExampleJS(){
        var jFirst = document.getElementById("fname").value;
        var jLast = document.getElementById("lname").value;
        alert("Your name is: " + jFirst + " " + jLast);
     }
     </script>

    </head>
    <body>
        <FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">

             First name: <input type="text" id="fname" name="firstname" /><br />
             Last name:  <input type="text" id="lname" name="lastname" /><br />
            <input name="Submit"  type="submit" value="Update" />
        </FORM>
    </body>
</html>

Multiple rows to one comma-separated value in Sql Server

Test Data

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

Query

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

Result Set

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

SQL Server 2017 and Later Versions

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

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


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

Result Set

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

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

How to remove duplicate values from a multi-dimensional array in PHP

I had a similar problem but I found a 100% working solution for it.

<?php
    function super_unique($array,$key)
    {
       $temp_array = [];
       foreach ($array as &$v) {
           if (!isset($temp_array[$v[$key]]))
           $temp_array[$v[$key]] =& $v;
       }
       $array = array_values($temp_array);
       return $array;

    }


$arr="";
$arr[0]['id']=0;
$arr[0]['titel']="ABC";
$arr[1]['id']=1;
$arr[1]['titel']="DEF";
$arr[2]['id']=2;
$arr[2]['titel']="ABC";
$arr[3]['id']=3;
$arr[3]['titel']="XYZ";

echo "<pre>";
print_r($arr);
echo "unique*********************<br/>";
print_r(super_unique($arr,'titel'));

?>

How to find integer array size in java

we can find length of array by using array_name.length attribute

int [] i = i.length;

Change selected value of kendo ui dropdownlist

The Simplest way to do this is:

$("#Instrument").data('kendoDropDownList').value("A value");

Here is the JSFiddle example.

Encrypt and decrypt a password in Java

EDIT : this answer is old. Usage of MD5 is now discouraged as it can easily be broken.


MD5 must be good enough for you I imagine? You can achieve it with MessageDigest.

MessageDigest.getInstance("MD5");

There are also other algorithms listed here.

And here's an third party version of it, if you really want: Fast MD5

How to keep console window open

If you want to keep it open when you are debugging, but still let it close normally when not debugging, you can do something like this:

if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();

Like other answers have stated, the call to Console.ReadLine() will keep the window open until enter is pressed, but Console.ReadLine() will only be called if the debugger is attached.

Changing every value in a hash in Ruby

The best way to modify a Hash's values in place is

hash.update(hash){ |_,v| "%#{v}%" }

Less code and clear intent. Also faster because no new objects are allocated beyond the values that must be changed.

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

I ran into this while testing on a new Xoom. I had previously installed my app from the Marketplace. Later while trying to test a new version of the app I ran into this error.

I fixed it by removing the app that was installed via Marketplace (just hold and drag to the trash). Thereafter I was able to deploy my development version without any issue.

How to restart Jenkins manually?

If you have no permissions or access to the command line directly, you can do e.g. one of the following:

  1. Create a job with shell/batch step that will trigger a restart from the Jenkins installation folder
  2. Install/update some plugin while checking "restart after installation" (at least this works in old versions)

Both above are hacks, but I actively used them in a very restricted environment where no one wanted me to restart Jenkins, huh.

Dynamically adding properties to an ExpandoObject

i think this add new property in desired type without having to set a primitive value, like when property defined in class definition

var x = new ExpandoObject();
x.NewProp = default(string)

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

I faced the same issue:

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

I resolved by using the following commands:

apt-get update
apt-get install gnupg

1052: Column 'id' in field list is ambiguous

Already there are lots of answers to your question, You can do it like this also. You can give your table an alias name and use that in the select query like this:

SELECT a.id, b.id, name, section
FROM tbl_names as a 
LEFT JOIN tbl_section as b ON a.id = b.id;

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

How to replace local branch with remote branch entirely in Git?

Replace everything with the remote branch; but, only from the same commit your local branch is on:

git reset --hard origin/some-branch

OR, get the latest from the remote branch and replace everything:

git fetch origin some-branch
git reset --hard FETCH_HEAD

As an aside, if needed, you can wipe out untracked files & directories that you haven't committed yet:

git clean -fd

Add a dependency in Maven

Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven. And I say our because I'm just getting introduced to maven.

In Eclipse, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:

  • Go to mvnrepository
  • Search for the library you want to add
  • Copy the dependency statement into your pom.xml
  • rebuild via mvn

Now, maven will connect and download the jar along with the list of dependencies, and automatically resolve any additional dependencies that jar may have had. So if the jar also needed commons-logging, that will be downloaded as well.

How can I set the initial value of Select2 when using AJAX?

For a simple and semantic solution i prefer to define the initial value in HTML, example:

<select name="myfield" data-placeholder="Select an option">
    <option value="initial-value" selected>Initial text</option>
</select>

So when i call $('select').select2({ ajax: {...}}); the initial value is initial-value and its option text is Initial text.

My current Select2 version is 4.0.3, but i think it has a great compatibility with other versions.

alert a variable value

Note, while the above answers are correct, if you want, you can do something like:

alert("The variable named x1 has value:  " + x1);

Javascript: Unicode string to hex

Here you go. :D

"??".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")
"6f225b57"

for non unicode

"hi".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")
"6869"

ASCII (utf-8) binary HEX string to string

"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")

String to ASCII (utf-8) binary HEX string

"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")

--- unicode ---

String to UNICODE (utf-16) binary HEX string

"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")

UNICODE (utf-16) binary HEX string to string

"00680065006c006c006f00200077006f0072006c00640021".match(/.{1,4}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

What is the difference between SQL and MySQL?

SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.

MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.

Classpath including JAR within a JAR

I was about to advise to extract all the files at the same level, then to make a jar out of the result, since the package system should keep them neatly separated. That would be the manual way, I suppose the tools indicated by Steve will do that nicely.

How to get a value from the last inserted row?

For MyBatis 3.0.4 with Annotations and Postgresql driver 9.0-801.jdbc4 you define an interface method in your Mapper like

public interface ObjectiveMapper {

@Select("insert into objectives" +
        " (code,title,description) values" +
        " (#{code}, #{title}, #{description}) returning id")
int insert(Objective anObjective);

Note that @Select is used instead of @Insert.

Change the Value of h1 Element within a Form with JavaScript

You may try the following:

document.getElementById("your_h1_id").innerHTML = "your new text here"

Android: How to add R.raw to project?

enter image description hereRight click on package or Res folder click on new on popup then click on android resource directory

a new window will be appear change the resource type to raw and hit OK copy and past song to raw folder remember don't drag and drop song file to raw folder and song spell should be in lower case! This method is for Android Studio Also Check MY Link

Import Google Play Services library in Android Studio

//gradle.properties

systemProp.http.proxyHost=www.somehost.org

systemProp.http.proxyPort=8080

systemProp.http.proxyUser=userid

systemProp.http.proxyPassword=password

systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

Combining two sorted lists in Python

Well, the naive approach (combine 2 lists into large one and sort) will be O(N*log(N)) complexity. On the other hand, if you implement the merge manually (i do not know about any ready code in python libs for this, but i'm no expert) the complexity will be O(N), which is clearly faster. The idea is described wery well in post by Barry Kelly.

Is it safe to expose Firebase apiKey to the public?

I am not convinced to expose security/config keys to client. I would not call it secure, not because some one can steal all private information from first day, because someone can make excessive request, and drain your quota and make you owe to Google a lot of money.

You need to think about many concepts from restricting people not to access where they are not supposed to be, DOS attacks etc.

I would more prefer the client first will hit to your web server, there you put what ever first hand firewall, captcha , cloudflare, custom security in between the client and server, or between server and firebase and you are good to go. At least you can first stop suspect activity before it reaches to firebase. You will have much more flexibility.

I only see one good usage scenario for using client based config for internal usages. For example, you have internal domain, and you are pretty sure outsiders cannot access there, so you can setup environment like browser -> firebase type.

How to convert entire dataframe to numeric while preserving decimals?

df2 <- data.frame(apply(df1, 2, function(x) as.numeric(as.character(x))))

How to remove padding around buttons in Android?

It's not a padding but or the shadow of the background drawable or a problem with the minHeight and minWidth.

If you still want the nice ripple affect, you can make your own button style using the ?attr/selectableItemBackground:

<style name="Widget.AppTheme.MyCustomButton" parent="Widget.AppCompat.Button.Borderless">
    <item name="android:minHeight">0dp</item>
    <item name="android:minWidth">0dp</item>
    <item name="android:layout_height">48dp</item>
    <item name="android:background">?attr/selectableItemBackground</item>
</style>

And apply it to the button:

<Button 
    style="@style/Widget.AppTheme.MyCustomButton"
    ... />