Programs & Examples On #Alasset

jQuery remove special characters from string and more

replace(/[^a-z0-9\s]/gi, '') will filter the string down to just alphanumeric values and replace(/[_\s]/g, '-') will replace underscores and spaces with hyphens:

str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-')

Source for Regex: RegEx for Javascript to allow only alphanumeric

Here is a demo: http://jsfiddle.net/vNfrk/

How do you create optional arguments in php?

Much like the manual, use an equals (=) sign in your definition of the parameters:

function dosomething($var1, $var2, $var3 = 'somevalue'){
    // Rest of function here...
}

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

Thanks for Ben's solution, my use case to display only particular fields in order

with object

Code:

    handlebars.registerHelper('eachToDisplayProperty', function(context, toDisplays, options) {
    var ret = "";
    var toDisplayKeyList = toDisplays.split(",");
    for(var i = 0; i < toDisplayKeyList.length; i++) {
        toDisplayKey = toDisplayKeyList[i];
        if(context[toDisplayKey]) {
            ret = ret + options.fn({
                property : toDisplayKey,
                value : context[toDisplayKey]
            });
        }

    }
    return ret;
});

Source object:

   { locationDesc:"abc", name:"ghi", description:"def", four:"you wont see this"}

Template:

{{#eachToDisplayProperty this "locationDesc,description,name"}}
    <div>
        {{property}} --- {{value}}
    </div>
    {{/eachToDisplayProperty}}

Output:

locationDesc --- abc
description --- def
name --- ghi

Why is there no xrange function in Python3?

comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2

>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.656799077987671

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.579368829727173

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

21.54827117919922

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

22.014557123184204

With timeit number=1 param:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.2245171070098877

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)

0.10750913619995117

comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.113872020003328

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.07014398300089

With timeit number=1,2,3,4 param works quick and in linear way:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.09329321900440846

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)

0.18501482300052885

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)

0.2703447980020428

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)

0.36209142999723554

So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.

How to use Oracle's LISTAGG function with a unique filter?

create table demotable(group_id number, name varchar2(100));
insert into demotable values(1,'David');
insert into demotable values(1,'John');
insert into demotable values(1,'Alan');
insert into demotable values(1,'David');
insert into demotable values(2,'Julie');
insert into demotable values(2,'Charles');
commit;

select group_id, 
       (select listagg(column_value, ',') within group (order by column_value) from table(coll_names)) as names
from (
  select group_id, collect(distinct name) as coll_names 
    from demotable
    group by group_id 
)

GROUP_ID    NAMES
1   Alan,David,John
2   Charles,Julie

Number of visitors on a specific page

If you want to know the number of visitors (as is titled in the question) and not the number of pageviews, then you'll need to create a custom report.

 

Terminology


Google Analytics has changed the terminology they use within the reports. Now, visits is named "sessions" and unique visitors is named "users."

User - A unique person who has visited your website. Users may visit your website multiple times, and they will only be counted once.

Session - The number of different times that a visitor came to your site.

Pageviews - The total number of pages that a user has accessed.

 

Creating a Custom Report


  1. To create a custom report, click on the "Customization" item in the left navigation menu, and then click on "Custom Reports".

customization item expanded in navigation menu

  1. The "Create Custom Report" page will open.
  2. Enter a name for your report.
  3. In the "Metric Groups" section, enter either "Users" or "Sessions" depending on what information you want to collect (see Terminology, above).
  4. In the "Dimension Drilldowns" section, enter "Page".
  5. Under "Filters" enter the individual page (exact) or group of pages (using regex) that you would like to see the data for. enter image description here
  6. Save the report and run it.

Clearing coverage highlighting in Eclipse

Click the "Remove all Sessions" button in the toolbar of the "Coverage" view.

enter image description here

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Disable Drag and Drop on HTML elements?

I will just leave it here. Helped me after I tried everything.

   $(document.body).bind("dragover", function(e) {
        e.preventDefault();
        return false;
   });

   $(document.body).bind("drop", function(e){
        e.preventDefault();
        return false;
   });

How do I prevent an Android device from going to sleep programmatically?

If you just want to prevent the sleep mode on a specific View, just call setKeepScreenOn(true) on that View or set the keepScreenOn property to true. This will prevent the screen from going off while the View is on the screen. No special permission required for this.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

How to set a Timer in Java?

Use this

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.

while (elapsedTime < 2*60*1000) {
    //perform db poll/check
    elapsedTime = (new Date()).getTime() - startTime;
}

//Throw your exception

How to get jQuery dropdown value onchange event

$('#drop').change(
    function() {
        var val1 = $('#pick option:selected').val();
        var val2 = $('#drop option:selected').val();

        // Do something with val1 and val2 ...
    }
);

How to change the pop-up position of the jQuery DatePicker control

This puts the functionality into a method named function, allowing for your code to encapsulate it or for the method to be made a jquery extension. Just used on my code, works perfectly

var nOffsetTop  = /* whatever value, set from wherever */;
var nOffsetLeft = /* whatever value, set from wherever */;

$(input).datepicker
(
   beforeShow : function(oInput, oInst) 
   { 
      AlterPostion(oInput, oInst, nOffsetTop, nOffsetLeft); 
   }
);

/* can be converted to extension, or whatever*/
var AlterPosition = function(oInput, oItst, nOffsetTop, nOffsetLeft)
{
   var divContainer = oInst.dpDiv;
   var oElem        = $(this);
       oInput       = $(oInput);

   setTimeout(function() 
   { 
      divContainer.css
      ({ 
         top  : (nOffsetTop >= 0 ? "+=" + nOffsetTop : "-=" + (nOffsetTop * -1)), 
         left : (nOffsetTop >= 0 ? "+=" + nOffsetLeft : "-=" + (nOffsetLeft * -1))
      }); 
   }, 10);
}

Check if multiple strings exist in another string

You need to iterate on the elements of a.

a = ['a', 'b', 'c']
str = "a123"
found_a_string = False
for item in a:    
    if item in str:
        found_a_string = True

if found_a_string:
    print "found a match"
else:
    print "no match found"

Create an Array of Arraylists

This works:

ArrayList<String>[] group = new ArrayList[4];

How to install a specific version of package using Composer?

Add double quotes to use caret operator in version number.

composer require middlewares/whoops "^0.4"

How to fix Git error: object file is empty?

Had the same problem after checking out master from a clean branch. After a while I recognized a lot of modified files in master. I don't know why they have been there, after switching from a clean branch. Anyways, because the modified files made no sense to me, I just stashed them and the error was gone.

git:(master) git stash

Using css transform property in jQuery

I started using the 'prefix-free' Script available at http://leaverou.github.io/prefixfree so I don't have to take care about the vendor prefixes. It neatly takes care of setting the correct vendor prefix behind the scenes for you. Plus a jQuery Plugin is available as well so one can still use jQuery's .css() method without code changes, so the suggested line in combination with prefix-free would be all you need:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

Printing object properties in Powershell

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.

Vue js error: Component template should contain exactly one root element

Just make sure that you have one root div and put everything inside this root

  <div class="root">
    <!--and put all child here --!>
   <div class='child1'></div>
   <div class='child2'></div>
  </div>

and so on

Swift Beta performance: sorting arrays

As of Xcode 7 you can turn on Fast, Whole Module Optimization. This should increase your performance immediately.

enter image description here

How to Update/Drop a Hive Partition?

You can either copy files into the folder where external partition is located or use

INSERT OVERWRITE TABLE tablename1 PARTITION (partcol1=val1, partcol2=val2...)...

statement.

Broadcast Receiver within a Service

The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.

Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.

Eg:

<receiver android:name=".FooReceiver" >
    <intent-filter >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().

Eg:

public class FooReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do your work quickly!
        // then call context.startService();
    }   
}

How do I declare a model class in my Angular 2 component using TypeScript?

In your case you are having model on same page, but you have it declared after your Component class, so that's you need to use forwardRef to refer to Class. Don't prefer to do this, always have model object in separate file.

export class testWidget {
    constructor(@Inject(forwardRef(() => Model)) private service: Model) {}
}

Additionally you have to change you view interpolation to refer to correct object

{{model?.param1}}

Better thing you should do is, you can have your Model Class define in different file & then import it as an when you require it by doing. Also have export before you class name, so that you can import it.

import { Model } from './model';

How do I set an absolute include path in PHP?

The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.

So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.

ini_set("include_path", "/your_include_path:".ini_get("include_path"));

This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Find and copy files

If your intent is to copy the found files into /home/shantanu/tosend, you have the order of the arguments to cp reversed:

find /home/shantanu/processed/ -name '*2011*.xml' -exec cp "{}" /home/shantanu/tosend  \;

Please, note: the find command use {} as placeholder for matched file.

Javascript : Send JSON Object with Ajax?

With jQuery:

$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });

Without jQuery:

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));

How do I count the number of occurrences of a char in a String?

public static void getCharacter(String str){

        int count[]= new int[256];

        for(int i=0;i<str.length(); i++){


            count[str.charAt(i)]++;

        }
        System.out.println("The ascii values are:"+ Arrays.toString(count));

        //Now display wht character is repeated how many times

        for (int i = 0; i < count.length; i++) {
            if (count[i] > 0)
               System.out.println("Number of " + (char) i + ": " + count[i]);
        }


    }
}

SSH Key - Still asking for password and passphrase

Problem seems to be because you're cloning from HTTPS and not SSH. I tried all the other solutions here but was still experiencing problems. This did it for me.

Using the osxkeychain helper like so:

  1. Find out if you have it installed.

    git credential-osxkeychain

  2. If it's not installed, you'll be prompted to download it as part of Xcode Command Line Tools.

  3. If it is installed, tell Git to use osxkeychain helper using the global credential.helper config:

    git config --global credential.helper osxkeychain

The next time you clone an HTTPS url, you'll be prompted for the username/password, and to grant access to the OSX keychain. After you do this the first time, it should be saved in your keychain and you won't have to type it in again.

How do I print the full value of a long string in gdb?

As long as your program's in a sane state, you can also call (void)puts(your_string) to print it to stdout. Same principle applies to all functions available to the debugger, actually.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

Set the "long" type of id instead of java.lang.Integer. And add getters and setters to your fields.

How to handle Pop-up in Selenium WebDriver using Java

public void Test(){

     WebElement sign = fc.findElement(By.xpath(".//*[@id='login-scroll']/a"));
        sign.click();
        WebElement LoginAsGuest=fc.findElement(By.xpath(".//*[@id='guest-login-option']"));
        LoginAsGuest.click();
        WebElement email_id= fc.findElement(By.xpath(".//*[@id='guestemail']"));
        email_id.sendKeys("[email protected]");
        WebElement ContinueButton=fc.findElement(By.xpath(".//*[@id='contibutton']"));
        ContinueButton.click();

}

Convert string in base64 to image and save on filesystem in Python

You can use Pillow.

pip install Pillow



image = base64.b64decode(str(base64String))       
fileName = 'test.jpeg'

imagePath = FILE_UPLOAD_DIR + fileName

img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
return fileName

reference for complete source code: https://abhisheksharma.online/convert-base64-blob-to-image-file-in-python/

Finding local IP addresses using Python's stdlib

To get the ip address you can use a shell command directly in python:

import socket, subprocess

def get_ip_and_hostname():
    hostname =  socket.gethostname()

    shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'"
    proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()

    ip_list = out.split('\n')
    ip = ip_list[0]

    for _ip in ip_list:
        try:
            if _ip != "127.0.0.1" and _ip.split(".")[3] != "1":
                ip = _ip
        except:
            pass
    return ip, hostname

ip_addr, hostname = get_ip_and_hostname()

Bootstrap - floating navbar button right

In bootstrap 4 use:

<ul class="nav navbar-nav ml-auto">

This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.

Fit background image to div

You can use this attributes:

background-size: contain;
background-repeat: no-repeat;

and you code is then like this:

 <div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
background-repeat: no-repeat;" id="mainpage">

How to specify a multi-line shell variable?

I would like to give one additional answer, while the other ones will suffice in most cases.

I wanted to write a string over multiple lines, but its contents needed to be single-line.

sql="                       \
SELECT c1, c2               \
from Table1, ${TABLE2}      \
where ...                   \
"

I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.

Split string on whitespace in Python

The str.split() method without an argument splits on whitespace:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']

How do I get the "id" after INSERT into MySQL database with Python?

SELECT @@IDENTITY AS 'Identity';

or

SELECT last_insert_id();

How can I detect when an Android application is running in the emulator?

I found the new emulator Build.HARDWARE = "ranchu".

Reference:https://groups.google.com/forum/#!topic/android-emulator-dev/dltBnUW_HzU

And also I found the Android official way to check whether emulator or not.I think it's good reference for us.

Since Android API Level 23 [Android 6.0]

package com.android.internal.util;

/**
 * @hide
 */
public class ScreenShapeHelper {
    private static final boolean IS_EMULATOR = Build.HARDWARE.contains("goldfish");
}

We have ScreenShapeHelper.IS_EMULATOR to check whether emulator.

Since Android API Level 24 [Android 7.0]

package android.os;

/**
 * Information about the current build, extracted from system properties.
 */
public class Build {


    /**
     * Whether this build was for an emulator device.
     * @hide
     */
    public static final boolean IS_EMULATOR = getString("ro.kernel.qemu").equals("1");

}

We have Build.IS_EMULATOR to check whether emulator.

The way the official to check whether emulator is not new,and also maybe not enough,the answers above also mentioned.

But this maybe show us that the official will provide the way of official to check whether emulator or not.

As using the above all ways mentioned,right now we can also use the two ways about to check whether emulator.

How to access the com.android.internal package and @hide

and wait for the official open SDK.

Using external images for CSS custom cursors

I found out that you need to add the pointer eg:

div{
    cursor: url('cursorurl.png'), pointer;
}

"Sub or Function not defined" when trying to run a VBA script in Outlook

I think you need to update your libraries so that your VBA code works, your using ms outlook

Where's my invalid character (ORA-00911)

One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .

Sublime Text 2 multiple line edit

I was facing the same problem on Linux, what I did was to select all the content (ctrl-A) and then press ctrl+shift+L, It gives you a cursor on each line and then you can add similar content to each column.

Also you can perform other operations like cut, copy and paste column wise.

PS :- If you want to select a rectangular set of data from text, you can also press shift and hold Right Mouse button and then select data in a rectangular fashion. Then press CTRL+SHIFT+L to get the cursor on each line.

How can you detect the version of a browser?

function BrowserCheck()
{
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) {M[2]=tem[1];}
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;
}

This will return an array, first element is the browser name, second element is the complete version number in string format.

How do I loop through or enumerate a JavaScript object?

Multiple way to iterate object in javascript

Using for...in loop

_x000D_
_x000D_
 var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
for (let key in p){_x000D_
   if(p.hasOwnProperty(key)){_x000D_
     console.log(`${key} : ${p[key]}`)_x000D_
   }_x000D_
}
_x000D_
_x000D_
_x000D_

Using for...of loop

_x000D_
_x000D_
 var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
for (let key of Object.keys(p)){_x000D_
     console.log(`key: ${key} & value: ${p[key]}`)_x000D_
}
_x000D_
_x000D_
_x000D_

Using forEach() with Object.keys, Object.values, Object.entries

_x000D_
_x000D_
var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
Object.keys(p).forEach(key=>{_x000D_
   console.log(`${key} : ${p[key]}`);_x000D_
});_x000D_
Object.values(p).forEach(value=>{_x000D_
   console.log(value);_x000D_
});_x000D_
Object.entries(p).forEach(([key,value])=>{_x000D_
    console.log(`${key}:${value}`)_x000D_
})
_x000D_
_x000D_
_x000D_

How to get city name from latitude and longitude coordinates in Google Maps?

Just Use this method and pass your lat, long.

public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {

//Set Address
try {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
    if (addresses != null && addresses.size() > 0) {



        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();
        String postalCode = addresses.get(0).getPostalCode();
        String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

        Log.d(TAG, "getAddress:  address" + address);
        Log.d(TAG, "getAddress:  city" + city);
        Log.d(TAG, "getAddress:  state" + state);
        Log.d(TAG, "getAddress:  postalCode" + postalCode);
        Log.d(TAG, "getAddress:  knownName" + knownName);

    }
} catch (IOException e) {
    e.printStackTrace();
}
    return;
}

Width of input type=text element

I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.

Check if PHP-page is accessed from an iOS device

function user_agent(){
    $iPod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
    $iPhone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $iPad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    file_put_contents('./public/upload/install_log/agent',$_SERVER['HTTP_USER_AGENT']);
    if($iPad||$iPhone||$iPod){
        return 'ios';
    }else if($android){
        return 'android';
    }else{
        return 'pc';
    }
}

Iterate through a HashMap

for (Map.Entry<String, String> item : hashMap.entrySet()) {
    String key = item.getKey();
    String value = item.getValue();
}

How to get a list of column names

Yes, you can achieve this by using the following commands:

sqlite> .headers on
sqlite> .mode column

The result of a select on your table will then look like:

id          foo         bar         age         street      address
----------  ----------  ----------  ----------  ----------  ----------
1           val1        val2        val3        val4        val5
2           val6        val7        val8        val9        val10

Bootstrap: add margin/padding space between columns

I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:

<div class="row">
  <div class="col-md-6">
    <div class="col-md-12">
     Set room heater temperature
   </div>
 </div>
 <div class="col-md-6">
   <div class="col-md-12">
     Set room heater temperature
   </div>
 </div>
</div>

enter image description here

This will automatically render some space between the 2 divs.

SQL Server using wildcard within IN

The IN operator is nothing but a fancy OR of '=' comparisons. In fact it is so 'nothing but' that in SQL 2000 there was a stack overflow bug due to expansion of the IN into ORs when the list contained about 10k entries (yes, there are people writing 10k IN entries...). So you can't use any wildcard matching in it.

Easy login script without database

It's not an ideal solution but here's a quick and dirty example that shows how you could store login info in the PHP code:

<?php
session_start();

$userinfo = array(
                'user1'=>'password1',
                'user2'=>'password2'
                );

if(isset($_GET['logout'])) {
    $_SESSION['username'] = '';
    header('Location:  ' . $_SERVER['PHP_SELF']);
}

if(isset($_POST['username'])) {
    if($userinfo[$_POST['username']] == $_POST['password']) {
        $_SESSION['username'] = $_POST['username'];
    }else {
        //Invalid Login
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Login</title>
    </head>
    <body>
        <?php if($_SESSION['username']): ?>
            <p>You are logged in as <?=$_SESSION['username']?></p>
            <p><a href="?logout=1">Logout</a></p>
        <?php endif; ?>
        <form name="login" action="" method="post">
            Username:  <input type="text" name="username" value="" /><br />
            Password:  <input type="password" name="password" value="" /><br />
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

How to compile c# in Microsoft's new Visual Studio Code?

SHIFT+CTRL+B should work

However sometimes an issue can happen in a locked down non-adminstrator evironment:

If you open an existing C# application from the folder you should have a .sln (solution file) etc..

Commonly you can get these message in VS Code

Downloading package 'OmniSharp (.NET 4.6 / x64)' (19343 KB) .................... Done!
Downloading package '.NET Core Debugger (Windows / x64)' (39827 KB) .................... Done!

Installing package 'OmniSharp (.NET 4.6 / x64)'
Installing package '.NET Core Debugger (Windows / x64)'

Finished
Failed to spawn 'dotnet --info'  //this is a possible issue

To which then you will be asked to install .NET CLI tools

If impossible to get SDK installed with no admin privilege - then use other solution.

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

What is the correct way to free memory in C#

Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.

For managed resources, the garbage collector will know when this is, and you don't need to do anything.

For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)

If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)

plotting different colors in matplotlib

Joe Kington's excellent answer is already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cycler module) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

The color of individual lines

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the color keyword argument,

plt.plot(x, y, color=my_color)

my_color is either

The color cycle

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

The color cycle is a property of the axes object, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in

my_ax.set_color_cycle(['kbkykrkg'])

(as noted in a comment this API has been deprecated, more on this later).

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

enter image description here

(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)

The cycler module: composable cycles

The following code shows that the color cycle notion has been deprecated

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
Out[2]: 
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cycle was a generic sequence of valid color denominations, now by default it is a cycler object containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cycler objects are composable and when you iterate on a composed cycler what you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

You can use the new defaults on a per axes object ratio,

my_ax.set_prop_cycle(new_prop_cycle)

or you can install temporarily the new default

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrc file.

Last possibility, use a context manager

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
    ...

to have the new cycler used in a group of different plots, reverting to defaults at the end of the context.

The doc string of the cycler() function is useful, but the (not so much) gory details about the cycler module and the cycler() function, as well as examples, can be found in the fine docs.

Adjust width and height of iframe to fit with content in it

If the content is just a very simple html, the simplest way is to remove the iframe with javascript

HTML code:

<div class="iframe">
    <iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe>
</div>

Javascript code:

function removeIframe(obj) {
    var iframeDocument = obj.contentDocument || obj.contentWindow.document;
    var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML;
    obj.remove();
    document.getElementsByClassName("iframe")[0].innerHTML = mycontent;
}

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

You want:

  • Affect to a single file

  • Remove file from staging area

  • Not remove single file from index

  • Don't undo the change itself

and the solution is

git reset HEAD file_name.ext

or

git reset HEAD path/to/file/file_name.ext

Renaming Columns in an SQL SELECT Statement

you have to rename each column

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

How to use SQL Order By statement to sort results case insensitive?

You can just convert everything to lowercase for the purposes of sorting:

SELECT * FROM NOTES ORDER BY LOWER(title);

If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:

SELECT * FROM NOTES ORDER BY LOWER(title), title;

SQL count rows in a table

Use This Query :

Select
    S.name + '.' + T.name As TableName ,
    SUM( P.rows ) As RowCont 

From sys.tables As T
    Inner Join sys.partitions As P On ( P.OBJECT_ID = T.OBJECT_ID )
    Inner Join sys.schemas As S On ( T.schema_id = S.schema_id )
Where
    ( T.is_ms_shipped = 0 )
    AND 
    ( P.index_id IN (1,0) )
    And
    ( T.type = 'U' )

Group By S.name , T.name 

Order By SUM( P.rows ) Desc

PHP/regex: How to get the string value of HTML tag?

Since attribute values may contain a plain > character, try this regular expression:

$pattern = '/<'.preg_quote($tagname, '/').'(?:[^"'>]*|"[^"]*"|\'[^\']*\')*>(.*?)<\/'.preg_quote($tagname, '/').'>/s';

But regular expressions are not suitable for parsing non-regular languages like HTML. You should better use a parser like SimpleXML or DOMDocument.

How Do I Upload Eclipse Projects to GitHub?

Many of these answers mention how to share the project on Git, which is easy, you just share the code on git, but one thing to take note of is that there is no apparent "project file" that the end user can double click on. Instead you have to use Import->General->Existing project and select the whole folder

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

On Mac OS X Lion with the latest macport:

sudo port install curl-ca-bundle  
export SSL_CERT_FILE=/opt/local/share/curl/curl-ca-bundle.crt  

Then, rerun the failed job.

Note, the cert file location seems to have changed since Eric G answered on May 12.

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

What does this GCC error "... relocation truncated to fit..." mean?

I ran into this problem while building a program that requires a huge amount of stack space (over 2 GiB). The solution was to add the flag -mcmodel=medium, which is supported by both GCC and Intel compilers.

Check if an element is present in a Bash array

As bash does not have a built-in value in array operator and the =~ operator or the [[ "${array[@]" == *"${item}"* ]] notation keep confusing me, I usually combine grep with a here-string:

colors=('black' 'blue' 'light green')
if grep -q 'black' <<< "${colors[@]}"
then
    echo 'match'
fi

Beware however that this suffers from the same false positives issue as many of the other answers that occurs when the item to search for is fully contained, but is not equal to another item:

if grep -q 'green' <<< "${colors[@]}"
then
    echo 'should not match, but does'
fi

If that is an issue for your use case, you probably won't get around looping over the array:

for color in "${colors[@]}"
do
    if [ "${color}" = 'green' ]
    then
        echo "should not match and won't"
        break
    fi
done

for color in "${colors[@]}"
do
    if [ "${color}" = 'light green' ]
    then
        echo 'match'
        break
    fi
done

How to POST using HTTPclient content type = application/x-www-form-urlencoded

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);

Or

var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);

Check if item is in an array / list

I'm also going to assume that you mean "list" when you say "array." Sven Marnach's solution is good. If you are going to be doing repeated checks on the list, then it might be worth converting it to a set or frozenset, which can be faster for each check. Assuming your list of strs is called subjects:

subject_set = frozenset(subjects)
if query in subject_set:
    # whatever

Angular 2.0 and Modal Dialog

Here is my full implementation of modal bootstrap angular2 component:

I assume that in your main index.html file (with <html> and <body> tags) at the bottom of <body> tag you have:

  <script src="assets/js/jquery-2.1.1.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>

modal.component.ts:

import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';

declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

@Component({
  selector: 'modal',
  templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {

    @Input() title:string;
    @Input() showClose:boolean = true;
    @Output() onClose: EventEmitter<any> = new EventEmitter();

    modalEl = null;
    id: string = uniqueId('modal_');

    constructor(private _rootNode: ElementRef) {}

    open() {
        this.modalEl.modal('show');
    }

    close() {
        this.modalEl.modal('hide');
    }

    closeInternal() { // close modal when click on times button in up-right corner
        this.onClose.next(null); // emit event
        this.close();
    }

    ngAfterViewInit() {
        this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
    }

    has(selector) {
        return $(this._rootNode.nativeElement).find(selector).length;
    }
}

let modal_id: number = 0;
export function uniqueId(prefix: string): string {
    return prefix + ++modal_id;
}

modal.html:

<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog"  aria-hidden="true" #thisModal>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
                <button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <ng-content select="mhead"></ng-content>
                <h4 *ngIf='title' class="modal-title">{{ title }}</h4>
            </div>
            <div class="modal-body">
                <ng-content></ng-content>
            </div>

            <div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
                <ng-content select="mfoot"></ng-content>
            </div>
        </div>
    </div>
</div>

And example of usage in client Editor component: client-edit-component.ts:

import { Component } from '@angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';

@Component({
  selector: 'client-edit',
  directives: [ Modal ],
  templateUrl: './client-edit.html',
  providers: [ ClientService ]
})
export class ClientEdit {

    _modal = null;

    constructor(private _ClientService: ClientService) {}

    bindModal(modal) {this._modal=modal;}

    open(client) {
        this._modal.open();
        console.log({client});
    }

    close() {
        this._modal.close();
    }

}

client-edit.html:

<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
    <mhead>Som non-standart title</mhead>
    Some contents
    <mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>

Ofcourse title, showClose, <mhead> and <mfoot> ar optional parameters/tags.

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

Using a .php file to generate a MySQL dump

To dump database using shell_exec(), below is the method :

shell_exec('mysqldump -h localhost -u username -ppassword databasename  | gzip > dbname.sql.gz');

Get current working directory in a Qt application

Thank you RedX and Kaz for your answers. I don't get why by me it gives the path of the exe. I found an other way to do it :

QString pwd("");
char * PWD;
PWD = getenv ("PWD");
pwd.append(PWD);
cout << "Working directory : " << pwd << flush;

It is less elegant than a single line... but it works for me.

Apache is downloading php files instead of displaying them

I had similar symptoms, yet another solution: in /etc/apache2/mods-enabled/php5.conf there was a helpful advice in the comment, which I followed:

# To re-enable php in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.

Python: Ignore 'Incorrect padding' error when base64 decoding

In case this error came from a web server: Try url encoding your post value. I was POSTing via "curl" and discovered I wasn't url-encoding my base64 value so characters like "+" were not escaped so the web server url-decode logic automatically ran url-decode and converted + to spaces.

"+" is a valid base64 character and perhaps the only character which gets mangled by an unexpected url-decode.

extracting days from a numpy.timedelta64 value

Use dt.days to obtain the days attribute as integers.

For eg:

In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))

In [15]: s
Out[15]: 
0    1 days 00:00:00
1    3 days 02:00:00
2    5 days 04:00:00
3    7 days 06:00:00
4    9 days 08:00:00
5   11 days 10:00:00
dtype: timedelta64[ns]

In [16]: s.dt.days
Out[16]: 
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

More generally - You can use the .components property to access a reduced form of timedelta.

In [17]: s.dt.components
Out[17]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     1      0        0        0             0             0            0
1     3      2        0        0             0             0            0
2     5      4        0        0             0             0            0
3     7      6        0        0             0             0            0
4     9      8        0        0             0             0            0
5    11     10        0        0             0             0            0

Now, to get the hours attribute:

In [23]: s.dt.components.hours
Out[23]: 
0     0
1     2
2     4
3     6
4     8
5    10
Name: hours, dtype: int64

How do I make background-size work in IE?

A bit late, but this could also be useful. There is an IE filter, for IE 5.5+, which you can apply:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

However, this scales the entire image to fit in the allocated area, so if you're using a sprite, this may cause issues.

Specification: AlphaImageLoader Filter @microsoft

Get controller and action name from within controller?

Why not having something simpler?

Just call Request.Path, it will return a String Separated by the "/"

and then you can use .Split('/')[1] to get the Controller Name.

enter image description here

Zabbix server is not running: the information displayed may not be current

Install nmap (( # yum/apt-get install nmap ))tool and check to find out which port the zabbix is listenning to?(( # nmap -sT -p1-65535 localhost )) 10050 or 10051? The result should be somthing like this:

Starting Nmap 6.40 ( http://nmap.org ) at 2016-11-01 22:54 IRST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00032s latency).
Other addresses for localhost (not scanned): 127.0.0.1
Not shown: 65530 closed ports
PORT      STATE SERVICE
22/tcp    open  ssh
25/tcp    open  smtp
80/tcp    open  http
3306/tcp  open  mysql
10050/tcp open  unknown    <--- In my case this is it

Then open /etc/zabbix/web/zabbix.conf.php and check the line starting with: $ZBX_SERVER_PORT , it's value should be the same number you saw in the nmap scan result. Change it and restart zabbix-server and httpd and you are good to go!

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The string you're trying to parse as a JSON is not encoded in UTF-8. Most likely it is encoded in ISO-8859-1. Try the following:

json.loads(unicode(opener.open(...), "ISO-8859-1"))

That will handle any umlauts that might get in the JSON message.

You should read Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). I hope that it will clarify some issues you're having around Unicode.

Oracle SQL Developer: Unable to find a JVM

I just installed SQL Developer 4.0.0.13 and the SetJavaHome can now be overridden by a user-specific configuration file (not sure if this is new to 4.0.0.13 or not).

The location of this user-specific configuration file can be seen in the user.conf property under 'Help -> About' on the 'Properties' tab. For example, mine was set to:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0\product.conf

On Windows 7.

The first section of this file is used to set the JDK that SQLDeveloper should use:

#
# By default, the product launcher will search for a JDK to use, and if none
# can be found, it will ask for the location of a JDK and store its location
# in this file. If a particular JDK should be used instead, uncomment the
# line below and set the path to your preferred JDK.
#
SetJavaHome C:\Program Files (x86)\Java\jdk1.7.0_03

This setting overrides the setting in sqldeveloper.conf

Get width/height of SVG element

From Firefox 33 onwards you can call getBoundingClientRect() and it will work normally, i.e. in the question above it will return 300 x 100.

Firefox 33 will be released on 14th October 2014 but the fix is already in Firefox nightlies if you want to try it out.

Set android shape color programmatically

this is the solution that works for me...wrote it in another question as well: How to change shape color dynamically?

//get the image button by id
ImageButton myImg = (ImageButton) findViewById(R.id.some_id);

//get drawable from image button
GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();

//set color as integer
//can use Color.parseColor(color) if color is a string
drawable.setColor(color)

How do I add more members to my ENUM-type column in MySQL?

Your code works for me. Here is my test case:

mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                            |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
  `country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                       |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
  `country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

What error are you seeing?

FWIW this would also work:

ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');

I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.

EDIT: Now that I can see your error message:

ERROR 1265 (01000): Data truncated for column 'country' at row 1.

I suspect you have some values in your country column that do not appear in your ENUM. What is the output of the following command?

SELECT DISTINCT country FROM carmake;

ANOTHER EDIT: What is the output of the following command?

SHOW VARIABLES LIKE 'sql_mode';

Is it STRICT_TRANS_TABLES or STRICT_ALL_TABLES? That could lead to an error, rather than the usual warning MySQL would give you in this situation.

YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM. The new ENUM definition only allows 'Sweden' and 'Malaysia'. The table has 'USA', 'India' and several others.

LAST EDIT (MAYBE): I think you're trying to do this:

ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

Merge two HTML table cells

Add an attribute colspan (abbriviation for 'column span') in your top cell (<td>) and set its value to 2. Your table should resembles the following;

<table>
    <tr>
        <td colspan = "2">
            <!-- Merged Columns -->
        </td>
    </tr>

    <tr>
        <td>
            <!-- Column 1 -->
        </td>

        <td>
            <!-- Column 2 -->
        </td>
    </tr>
</table>

See also
     W3 official docs on HTML Tables

jQuery removing '-' character from string

$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');

if you have done it that way variable string now holds "123456"

you can also (i guess the better way) do this...

$mylabel.text("-123456");
$mylabel.text(function(i,v){
   return v.replace('-','');
});

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

Many of the examples here will not work for 11, 12, 13. This is more generic and will work for all case.

switch (date) {
                case 1:
                case 21:
                case 31:
                    return "" + date + "st";

                case 2:
                case 22:
                    return "" + date + "nd";

                case 3:
                case 23:
                    return "" + date + "rd";

                default:
                    return "" + date + "th";
}

How to replace NaNs by preceding values in pandas DataFrame?

Only one column version

  • Fill NAN with last valid value
df[column_name].fillna(method='ffill', inplace=True)
  • Fill NAN with next valid value
df[column_name].fillna(method='backfill', inplace=True)

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

Need to perform Wildcard (*,?, etc) search on a string using Regex

The correct regular expression formulation of the glob expression d* is ^d, which means match anything that starts with d.

    string input = "Message";
    string pattern = @"^d";
    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

(The @ quoting is not necessary in this case, but good practice since many regexes use backslash escapes that need to be left alone, and it also indicates to the reader that this string is special).

What is WEB-INF used for in a Java EE web application?

The Servlet 2.4 specification says this about WEB-INF (page 70):

A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.

This means that WEB-INF resources are accessible to the resource loader of your Web-Application and not directly visible for the public.

This is why a lot of projects put their resources like JSP files, JARs/libraries and their own class files or property files or any other sensitive information in the WEB-INF folder. Otherwise they would be accessible by using a simple static URL (usefull to load CSS or Javascript for instance).

Your JSP files can be anywhere though from a technical perspective. For instance in Spring you can configure them to be in WEB-INF explicitly:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/jsp/" 
    p:suffix=".jsp" >
</bean>

The WEB-INF/classes and WEB-INF/lib folders mentioned in Wikipedia's WAR files article are examples of folders required by the Servlet specification at runtime.

It is important to make the difference between the structure of a project and the structure of the resulting WAR file.

The structure of the project will in some cases partially reflect the structure of the WAR file (for static resources such as JSP files or HTML and JavaScript files, but this is not always the case.

The transition from the project structure into the resulting WAR file is done by a build process.

While you are usually free to design your own build process, nowadays most people will use a standardized approach such as Apache Maven. Among other things Maven defines defaults for which resources in the project structure map to what resources in the resulting artifact (the resulting artifact is the WAR file in this case). In some cases the mapping consists of a plain copy process in other cases the mapping process includes a transformation, such as filtering or compiling and others.

One example: The WEB-INF/classes folder will later contain all compiled java classes and resources (src/main/java and src/main/resources) that need to be loaded by the Classloader to start the application.

Another example: The WEB-INF/lib folder will later contain all jar files needed by the application. In a maven project the dependencies are managed for you and maven automatically copies the needed jar files to the WEB-INF/lib folder for you. That explains why you don't have a lib folder in a maven project.

How do I get the file name from a String containing the Absolute file path?

just use File.getName()

File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());

using String methods:

  File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");  
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));

Passing data to components in vue.js

I've found a way to pass parent data to component scope in Vue, i think it's a little a bit of a hack but maybe this will help you.

1) Reference data in Vue Instance as an external object (data : dataObj)

2) Then in the data return function in the child component just return parentScope = dataObj and voila. Now you cann do things like {{ parentScope.prop }} and will work like a charm.

Good Luck!

Sending JSON to PHP using ajax

That's because $_POST is pre-populated with form data.

To get JSON data (or any raw input), use php://input.

$json = json_decode(file_get_contents("php://input"));

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Why split the <script> tag when writing it with document.write()?

</script> has to be broken up because otherwise it would end the enclosing <script></script> block too early. Really it should be split between the < and the /, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </):

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.

However in practice browsers only end parsing a CDATA script block on an actual </script> close-tag.

In XHTML there is no such special handling for script blocks, so any < (or &) character inside them must be &escaped; like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:

<script type="text/javascript">
    document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>

copy all files and folders from one drive to another drive using DOS (command prompt)

This worked for me On Windows 10,

xcopy /s {source drive..i.e. C:} {destination drive..i.e. D:} This will copy all the files and folders plus the folder contents.

Node.js global variables

I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:

// Some global/configuration file that gets called in initialisation

global.MyError = [Function of MyError];

Yes, it is taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or at least somewhere to:

  1. Define the Error class in the first place
  2. In the script where you're throwing it
  3. In the script where you're catching it

Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.

When to use pthread_exit() and when to use pthread_join() in Linux?

  #include<stdio.h>
  #include<pthread.h>
  #include<semaphore.h>
 
   sem_t st;
   void *fun_t(void *arg);
   void *fun_t(void *arg)
   {
       printf("Linux\n");
       sem_post(&st);
       //pthread_exit("Bye"); 
       while(1);
       pthread_exit("Bye");
   }
   int main()
   {
       pthread_t pt;
       void *res_t;
       if(pthread_create(&pt,NULL,fun_t,NULL) == -1)
           perror("pthread_create");
       if(sem_init(&st,0,0) != 0)
           perror("sem_init");
       if(sem_wait(&st) != 0)
           perror("sem_wait");
       printf("Sanoundry\n");
       //Try commenting out join here.
       if(pthread_join(pt,&res_t) == -1)
           perror("pthread_join");
       if(sem_destroy(&st) != 0)
           perror("sem_destroy");
       return 0;
   }

Copy and paste this code on a gdb. Onlinegdb would work and see for yourself.

Make sure you understand once you have created a thread, the process run along with main together at the same time.

  1. Without the join, main thread continue to run and return 0
  2. With the join, main thread would be stuck in the while loop because it waits for the thread to be done executing.
  3. With the join and delete the commented out pthread_exit, the thread will terminate before running the while loop and main would continue
  4. Practical usage of pthread_exit can be used as an if conditions or case statements to ensure 1 version of some code runs before exiting.
void *fun_t(void *arg)
   {
       printf("Linux\n");
       sem_post(&st); 
       if(2-1 == 1)  
           pthread_exit("Bye");
       else
       { 
           printf("We have a problem. Computer is bugged");
           pthread_exit("Bye"); //This is redundant since the thread will exit at the end
                                //of scope. But there are instances where you have a bunch
                                //of else if here.
       }
   }

I would want to demonstrate how sometimes you would need to have a segment of code running first using semaphore in this example.

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>

sem_t st;

void* fun_t (void* arg)
{
    printf("I'm thread\n");
    sem_post(&st);
}

int main()
{
    pthread_t pt;
    pthread_create(&pt,NULL,fun_t,NULL);
    sem_init(&st,0,0);
    sem_wait(&st);
    printf("before_thread\n");
    pthread_join(pt,NULL);
    printf("After_thread\n");
    
}

Noticed how fun_t is being ran after "before thread" The expected output if it is linear from top to bottom would be before thread, I'm thread, after thread. But under this circumstance, we block the main from running any further until the semaphore is released by func_t. The result can be verified with https://www.onlinegdb.com/

What does the PHP error message "Notice: Use of undefined constant" mean?

You should quote your array keys:

$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);

As is, it was looking for constants called department, name, email, message, etc. When it doesn't find such a constant, PHP (bizarrely) interprets it as a string ('department', etc). Obviously, this can easily break if you do defined such a constant later (though it's bad style to have lower-case constants).

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

What's the best way to convert a number to a string in JavaScript?

You can call Number object and then call toString().

Number.call(null, n).toString()

You may use this trick for another javascript native objects.

Clicking URLs opens default browser

Add this 2 lines in your code -

mWebView.setWebChromeClient(new WebChromeClient()); 
mWebView.setWebViewClient(new WebViewClient());?

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How schedule build in Jenkins?

In the job configuration one can define various build triggers. With periodically build you can schedule the build by defining the date or day of the week and the time to execute the build.

The format is as follows:

MINUTE (0-59), HOUR (0-23), DAY (1-31), MONTH (1-12), DAY OF THE WEEK (0-6)

The letter H, representing the word Hash can be inserted instead of any of the values, it will calculate the parameter based on the hash code of your project name, this is so that if you are building several projects on your build machine at the same time, lets say midnight each day, they do not all start there build execution at the same time, each project starts its execution at a different minute depending on its hash code. You can also specify the value to be between numbers, i.e. H(0,30) will return the hash code of the project where the possible hashes are 0-30

Examples:

start build daily at 08:30 in the morning, Monday - Friday:

  • 30 08 * * 1-5

weekday daily build twice a day, at lunchtime 12:00 and midnight 00:00, Sunday to Thursday:

  • 00 0,12 * * 0-4

start build daily in the late afternoon between 4:00 p.m. - 4:59 p.m. or 16:00 -16:59 depending on the projects hash:

  • H 16 * * 1-5

start build at midnight:

  • @midnight

or start build at midnight, every Saturday:

  • 59 23 * * 6

every first of every month between 2:00 a.m. - 02:30 a.m. :

  • H(0-30) 02 01 * *

more on CRON expressions

Get domain name from given url

In my case i only needed the main domain and not the subdomain (no "www" or whatever the subdomain is) :

public static String getUrlDomain(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String domain = uri.getHost();
    String[] domainArray = domain.split("\\.");
    if (domainArray.length == 1) {
        return domainArray[0];
    }
    return domainArray[domainArray.length - 2] + "." + domainArray[domainArray.length - 1];
}

With this method the url "https://rest.webtoapp.io/llSlider?lg=en&t=8" will have for domain "webtoapp.io".

Set initial value in datepicker with jquery?

Use it after initialization code to get current date (in datepicker format):

$(".ui-datepicker-today").trigger("click");

How to find nth occurrence of character in a string?

Another approach:

public static void main(String[] args) {
    String str = "/folder1/folder2/folder3/"; 
    int index = nthOccurrence(str, '/', 3);
    System.out.println(index);
}

public static int nthOccurrence(String s, char c, int occurrence) {
    return nthOccurrence(s, 0, c, 0, occurrence);
}

public static int nthOccurrence(String s, int from, char c, int curr, int expected) {
    final int index = s.indexOf(c, from);
    if(index == -1) return -1;
    return (curr + 1 == expected) ? index : 
        nthOccurrence(s, index + 1, c, curr + 1, expected);
}

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

Python: maximum recursion depth exceeded while calling a Python object

You can increase the capacity of the stack by the following :

import sys
sys.setrecursionlimit(10000)

How to create a .NET DateTime from ISO 8601 format

It seems important to exactly match the format of the ISO string for TryParseExact to work. I guess Exact is Exact and this answer is obvious to most but anyway...

In my case, Reb.Cabin's answer doesn't work as I have a slightly different input as per my "value" below.

Value: 2012-08-10T14:00:00.000Z

There are some extra 000's in there for milliseconds and there may be more.

However if I add some .fff to the format as shown below, all is fine.

Format String: @"yyyy-MM-dd\THH:mm:ss.fff\Z"

In VS2010 Immediate Window:

DateTime.TryParseExact(value,@"yyyy-MM-dd\THH:mm:ss.fff\Z", CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal, out d);

true

You may have to use DateTimeStyles.AssumeLocal as well depending upon what zone your time is for...

how to bold words within a paragraph in HTML/CSS?

<p><b> BOLD TEXT </b> not in bold </p>;

Include the text you want to be in bold between <b>...</b>

Saving excel worksheet to CSV files with filename+worksheet name using VB

Is this what you are trying?

Option Explicit

Public Sub SaveWorksheetsAsCsv()
    Dim WS As Worksheet
    Dim SaveToDirectory As String, newName As String

    SaveToDirectory = "H:\test\"

    For Each WS In ThisWorkbook.Worksheets
        newName = GetBookName(ThisWorkbook.Name) & "_" & WS.Name
        WS.Copy
        ActiveWorkbook.SaveAs SaveToDirectory & newName, xlCSV
        ActiveWorkbook.Close Savechanges:=False
    Next
End Sub

Function GetBookName(strwb As String) As String
    GetBookName = Left(strwb, (InStrRev(strwb, ".", -1, vbTextCompare) - 1))
End Function

Removing u in list

That 'u' is part of the external representation of the string, meaning it's a Unicode string as opposed to a byte string. It's not in the string, it's part of the type.

As an example, you can create a new Unicode string literal by using the same synax. For instance:

>>> sandwich = u"smörgås"
>>> sandwich
u'sm\xf6rg\xe5s'

This creates a new Unicode string whose value is the Swedish word for sandwich. You can see that the non-English characters are represented by their Unicode code points, ö is \xf6 and å is \xe5. The 'u' prefix appears just like in your example to signify that this string holds Unicode text.

To get rid of those, you need to encode the Unicode string into some byte-oriented representation, such as UTF-8. You can do that with e.g.:

>>> sandwich.encode("utf-8")
'sm\xc3\xb6rg\xc3\xa5s'

Here, we get a new string without the prefix 'u', since this is a byte string. It contains the bytes representing the characters of the Unicode string, with the Swedish characters resulting in multiple bytes due to the wonders of the UTF-8 encoding.

How to find the type of an object in Go?

Use the reflect package:

Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}

    fmt.Println(reflect.TypeOf(b))
    fmt.Println(reflect.TypeOf(s))
    fmt.Println(reflect.TypeOf(n))
    fmt.Println(reflect.TypeOf(f))
    fmt.Println(reflect.TypeOf(a))
}

Produces:

bool
string
int
float64
[]string

Playground

Example using ValueOf(i interface{}).Kind():

package main

import (
    "fmt"
    "reflect"
)

func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}

    fmt.Println(reflect.ValueOf(b).Kind())
    fmt.Println(reflect.ValueOf(s).Kind())
    fmt.Println(reflect.ValueOf(n).Kind())
    fmt.Println(reflect.ValueOf(f).Kind())
    fmt.Println(reflect.ValueOf(a).Index(0).Kind()) // For slices and strings
}

Produces:

bool
string
int
float64
string

Playground

jQuery change event on dropdown

The html

<select id="drop"  name="company" class="company btn btn-outline   dropdown-toggle" >
   <option value="demo1">Group Medical</option>
   <option value="demo">Motor Insurance</option>
</select>

Script.js

$("#drop").change(function () {                            
   var category= $('select[name=company]').val() // Here we can get the value of selected item
   alert(category); 
});

How can I check for "undefined" in JavaScript?

I use it as a function parameter and exclude it on function execution that way I get the "real" undefined. Although it does require you to put your code inside a function. I found this while reading the jQuery source.

undefined = 2;

(function (undefined) {
   console.log(undefined); // prints out undefined
   // and for comparison:
   if (undeclaredvar === undefined) console.log("it works!")
})()

Of course you could just use typeof though. But all my code is usually inside a containing function anyways, so using this method probably saves me a few bytes here and there.

Filtering a spark dataframe based on date

Don't use this as suggested in other answers

.filter(f.col("dateColumn") < f.lit('2017-11-01'))

But use this instead

.filter(f.col("dateColumn") < f.unix_timestamp(f.lit('2017-11-01 00:00:00')).cast('timestamp'))

This will use the TimestampType instead of the StringType, which will be more performant in some cases. For example Parquet predicate pushdown will only work with the latter.

How to select an option from drop down using Selenium WebDriver C#?

IWebElement element = _browserInstance.Driver.FindElement(By.XPath("//Select"));
IList<IWebElement> AllDropDownList = element.FindElements(By.XPath("//option"));
int DpListCount = AllDropDownList.Count;
for (int i = 0; i < DpListCount; i++)
{
    if (AllDropDownList[i].Text == "nnnnnnnnnnn")
    {
        AllDropDownList[i].Click();
        _browserInstance.ScreenCapture("nnnnnnnnnnnnnnnnnnnnnn");
    }
}

String.Format alternative in C++

As already mentioned the C++ way is using stringstreams.

#include <sstream>

string a = "test";
string b = "text.txt";
string c = "text1.txt";

std::stringstream ostr;
ostr << a << " " << b << " > " << c;

Note that you can get the C string from the string stream object like so.

std::string formatted_string = ostr.str();
const char* c_str = formatted_string.c_str();

Programmatically relaunch/recreate an activity?

Call the recreate() method from where you want to recreate your activity . This method will destroy current instance of Activity with onDestroy() and then recreate activity with onCreate().

Defining lists as global variables in Python

Yes, you need to use global foo if you are going to write to it.

foo = []

def bar():
    global foo
    ...
    foo = [1]

How to convert object array to string array in Java

The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:

Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
        String apply(Object from){
             return from.toString();
        }
 });

This take you away from using arrays,but I think this would be my prefered way.

How to query DATETIME field using only date in Microsoft SQL Server?

I am using MySQL 5.6 and there is a DATE function to extract only the date part from date time. So the simple solution to the question is -

 select * from test where DATE(date) = '2014-03-19';

http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html

Converting bool to text in C++

How about the simple:

constexpr char const* toString(bool b)
{
   return b ? "true" : "false";
}

Is Laravel really this slow?

I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync. I tried both cygwin and minGW. It seems like rsync is incompatible with git for windows's version of ssh.

Here is what worked for me: NFS.

Vagrant docs says:

NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.

This isn't true anymore. We can use vagrant-winnfsd plugin nowadays. It's really simple to install:

  1. Execute vagrant plugin install vagrant-winnfsd
  2. Change in your Vagrantfile: config.vm.synced_folder ".", "/vagrant", type: "nfs"
  3. Add to Vagrantfile: config.vm.network "private_network", type: "dhcp"

That's all I needed to make NFS work. Laravel response time decreased from 500ms to 100ms for me.

Oracle Sql get only month and year in date datatype

Easiest solution is to create the column using the correct data type: DATE

For example:

  1. Create table:

    create table test_date (mydate date);

  2. Insert row:

    insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));

To get the month and year, do as follows:

select to_char(mydate, 'MM-YYYY') from test_date;

Your result will be as follows: 01-2011

Another cool function to use is "EXTRACT"

select extract(year from mydate) from test_date;

This will return: 2011

How to display the string html contents into webbrowser control?

Try this:

webBrowser1.DocumentText =
    "<html><body>Please enter your name:<br/>" +
    "<input type='text' name='userName'/><br/>" +
    "<a href='http://www.microsoft.com'>continue</a>" +
    "</body></html>";

Where can I download english dictionary database in a text format?

I dont know if its too late, but i thought it would help someone else.

I wanted the same badly...found it eventually.

Maybe its not perfect,but to me its adequate(for my little dictionary app).

http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip

Its not a dump file, but a MYSQL .sql script file

The words are in WN_SYNSET table and the glossary/meaning in the WN_GLOSS table

How to adjust text font size to fit textview

I had the same problem and wrote a class that seems to work for me. Basically, I used a static layout to draw the text in a separate canvas and remeasure until I find a font size that fits. You can see the class posted in the topic below. I hope it helps.

Auto Scale TextView Text to Fit within Bounds

How do I install Maven with Yum?

Not just mvn, for any util, you can find out yourself by giving yum whatprovides {command_name}

How to represent empty char in Java Character class

If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.

String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character

Reading a file line by line in Go

Example from this gist

func readLine(path string) {
  inFile, err := os.Open(path)
  if err != nil {
     fmt.Println(err.Error() + `: ` + path)
     return
  }
  defer inFile.Close()

  scanner := bufio.NewScanner(inFile)
  for scanner.Scan() {
    fmt.Println(scanner.Text()) // the line
  }
}

but this gives an error when there is a line that larger than Scanner's buffer.

When that happened, what I do is use reader := bufio.NewReader(inFile) create and concat my own buffer either using ch, err := reader.ReadByte() or len, err := reader.Read(myBuffer)

Another way that I use (replace os.Stdin with file like above), this one concats when lines are long (isPrefix) and ignores empty lines:


func readLines() []string {
  r := bufio.NewReader(os.Stdin)
  bytes := []byte{}
  lines := []string{}
  for {
    line, isPrefix, err := r.ReadLine()
    if err != nil {
      break
    }
    bytes = append(bytes, line...)
    if !isPrefix {
      str := strings.TrimSpace(string(bytes))
      if len(str) > 0 {
        lines = append(lines, str)
        bytes = []byte{}
      }
    }
  }
  if len(bytes) > 0 {
    lines = append(lines, string(bytes))
  }
  return lines
}

adding multiple event listeners to one element

//catch volume update
var volEvents = "change,input";
var volEventsArr = volEvents.split(",");
for(var i = 0;i<volknob.length;i++) {
    for(var k=0;k<volEventsArr.length;k++) {
    volknob[i].addEventListener(volEventsArr[k], function() {
        var cfa = document.getElementsByClassName('watch_televised');
        for (var j = 0; j<cfa.length; j++) {
            cfa[j].volume = this.value / 100;
        }
    });
}
}

How to convert std::string to lower case?

std::ctype::tolower() from the standard C++ Localization library will correctly do this for you. Here is an example extracted from the tolower reference page

#include <locale>
#include <iostream>

int main () {
  std::locale::global(std::locale("en_US.utf8"));
  std::wcout.imbue(std::locale());
  std::wcout << "In US English UTF-8 locale:\n";
  auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
  std::wstring str = L"HELLo, wORLD!";
  std::wcout << "Lowercase form of the string '" << str << "' is ";
  f.tolower(&str[0], &str[0] + str.size());
  std::wcout << "'" << str << "'\n";
}

Values of disabled inputs will not be submitted

There are two attributes, namely readonly and disabled, that can make a semi-read-only input. But there is a tiny difference between them.

<input type="text" readonly />
<input type="text" disabled />
  • The readonly attribute makes your input text disabled, and users are not able to change it anymore.
  • Not only will the disabled attribute make your input-text disabled(unchangeable) but also cannot it be submitted.

jQuery approach (1):

$("#inputID").prop("readonly", true);
$("#inputID").prop("disabled", true);

jQuery approach (2):

$("#inputID").attr("readonly","readonly");
$("#inputID").attr("disabled", "disabled");

JavaScript approach:

document.getElementById("inputID").readOnly = true;
document.getElementById("inputID").disabled = true;

PS disabled and readonly are standard html attributes. prop introduced with jQuery 1.6.

ALTER TABLE add constraint

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

Update select2 data without rebuilding the control

I think it suffices to hand the data over directly:

$("#inputhidden").select2("data", data, true);

Note that the second parameter seems to indicate that a refresh is desired.

Thanks to @Bergi for help with this.


If that doesn't automatically update you could either try calling it's updateResults method directly.

$("#inputhidden").select2("updateResults");

Or trigger it indirectly by sending a trigger to the "input.select2-input" like so:

var search = $("#inputhidden input.select2-input");
search.trigger("input");

Extract first item of each sublist

Had the same issue and got curious about the performance of each solution.

Here's is the %timeit:

import numpy as np
lst = [['a','b','c'], [1,2,3], ['x','y','z']]

The first numpy-way, transforming the array:

%timeit list(np.array(lst).T[0])
4.9 µs ± 163 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Fully native using list comprehension (as explained by @alecxe):

%timeit [item[0] for item in lst]
379 ns ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Another native way using zip (as explained by @dawg):

%timeit list(zip(*lst))[0]
585 ns ± 7.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Second numpy-way. Also explained by @dawg:

%timeit list(np.array(lst)[:,0])
4.95 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Surprisingly (well, at least for me) the native way using list comprehension is the fastest and about 10x faster than the numpy-way. Running the two numpy-ways without the final list saves about one µs which is still in the 10x difference.

Note that, when I surrounded each code snippet with a call to len, to ensure that Generators run till the end, the timing stayed the same.

What represents a double in sql server?

float

Or if you want to go old-school:

real

You can also use float(53), but it means the same thing as float.

("real" is equivalent to float(24), not float/float(53).)

The decimal(x,y) SQL Server type is for when you want exact decimal numbers rather than floating point (which can be approximations). This is in contrast to the C# "decimal" data type, which is more like a 128-bit floating point number.

MSSQL's float type is equivalent to the 64-bit double type in .NET. (My original answer from 2011 said there could be a slight difference in mantissa, but I've tested this in 2020 and they appear to be 100% compatible in their binary representation of both very small and very large numbers -- see https://dotnetfiddle.net/wLX5Ox for my test).

To make things more confusing, a "float" in C# is only 32-bit, so it would be more equivalent in SQL to the real/float(24) type in MSSQL than float/float(53).

In your specific use case... All you need is 5 places after the decimal point to represent latitude and longitude within about one-meter precision, and you only need up to three digits before the decimal point for the degrees. Float(24) or decimal(8,5) will best fit your needs in MSSQL, and using float in C# is good enough, you don't need double. In fact, your users will probably thank you for rounding to 5 decimal places rather than having a bunch of insignificant digits coming along for the ride.

Invalid URI: The format of the URI could not be determined

It may help to use a different constructor for Uri.

If you have the server name

string server = "http://www.myserver.com";

and have a relative Uri path to append to it, e.g.

string relativePath = "sites/files/images/picture.png"

When creating a Uri from these two I get the "format could not be determined" exception unless I use the constructor with the UriKind argument, i.e.

// this works, because the protocol is included in the string
Uri serverUri = new Uri(server);

// needs UriKind arg, or UriFormatException is thrown
Uri relativeUri = new Uri(relativePath, UriKind.Relative); 

// Uri(Uri, Uri) is the preferred constructor in this case
Uri fullUri = new Uri(serverUri, relativeUri);

FormsAuthentication.SignOut() does not log the user out

The key here is that you say "If I type in a URL directly...".

By default under forms authentication the browser caches pages for the user. So, selecting a URL directly from the browsers address box dropdown, or typing it in, MAY get the page from the browser's cache, and never go back to the server to check authentication/authorization. The solution to this is to prevent client-side caching in the Page_Load event of each page, or in the OnLoad() of your base page:

Response.Cache.SetCacheability(HttpCacheability.NoCache);

You might also like to call:

Response.Cache.SetNoStore();

Generating all permutations of a given string

Simple python solution using recursion.

def get_permutations(string):

    # base case
    if len(string) <= 1:
        return set([string])

    all_chars_except_last = string[:-1]
    last_char = string[-1]

    # recursive call: get all possible permutations for all chars except last
    permutations_of_all_chars_except_last = get_permutations(all_chars_except_last)

    # put the last char in all possible positions for each of the above permutations
    permutations = set()
    for permutation_of_all_chars_except_last in permutations_of_all_chars_except_last:
        for position in range(len(all_chars_except_last) + 1):
            permutation = permutation_of_all_chars_except_last[:position] + last_char + permutation_of_all_chars_except_last[position:]
            permutations.add(permutation)

    return permutations

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

Alternatively,

select id from call
minus
select id from phone_number

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

I've encountered the same problem for years now, working in Visual Studio 2008. And I've tried every "solution" on StackOverflow and dozens of blogs, just like I'm sure all of you have. And sometimes they work, and sometimes they don't, just like I'm sure all of you have encountered. And apparently it's still an issue in VS2010 and VS2012.

So finally, a couple of months ago, I decided enough was enough, and over a few weeks I built a tool called "Redesigner" that generates .designer files. It's open-source under the BSD license, with the source code available on SourceForge — free to use, free to steal, free to do anything you please with. And it does what Visual Studio fails to do so often, which is generate .designer files quickly and reliably.

It's a stand-alone command-line tool that parses .aspx and .ascx files, performs all the necessary reflection magic, and spits out correct .designer files. It does all the parsing and reflection itself to avoid relying on existing code, which we all know too well is broken. It's written in C# against .NET 3.5, but it makes pains to avoid using even System.Web for anything other than type declarations, and it doesn't use or rely on Visual Studio at all.

Redesigner can generate new .designer files; and it offers a --verbose option so that when things go wrong, you get far better error messages than "Exception of type System.Exception was thrown." And there's a --verify option that can be used to tell you when your existing .designer files are broken — missing controls, bad property declarations, unreadable by Visual Studio, or otherwise just plain borked.

We've been using it at my workplace to get us out of jams for the better part of the last month now, and while Redesigner is still a beta, it's getting far enough along that it's worth sharing its existence with the public. I soon intend to create a Visual Studio plugin for it so you can simply right-click to verify or regenerate designer files the way you always wished you could. But in the interim, the command-line usage is pretty easy and will save you a lot of headaches.

Anyway, go download a copy of Redesigner now and stop pulling out your hair. You won't always need it, but when you do, you'll be glad you have it!

https://sourceforge.net/projects/redesigner/

Can we have multiple <tbody> in same <table>?

Yes you can use them, for example I use them to more easily style groups of data, like this:

_x000D_
_x000D_
thead th { width: 100px; border-bottom: solid 1px #ddd; font-weight: bold; }_x000D_
tbody:nth-child(odd) { background: #f5f5f5;  border: solid 1px #ddd; }_x000D_
tbody:nth-child(even) { background: #e5e5e5;  border: solid 1px #ddd; }
_x000D_
<table>_x000D_
    <thead>_x000D_
        <tr><th>Customer</th><th>Order</th><th>Month</th></tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 1</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 1</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 1</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 2</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 2</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 2</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 3</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 3</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 3</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

You can view an example here. It'll only work in newer browsers, but that's what I'm supporting in my current application, you can use the grouping for JavaScript etc. The main thing is it's a convenient way to visually group the rows to make the data much more readable. There are other uses of course, but as far as applicable examples, this one is the most common one for me.

What are the differences between if, else, and else if?

The else if can be used in conjunction with 'if', and 'else' to further break down the logic

//if less than zero
if( myInt < 0){
      //do something
}else if( myInt > 0 && myInt < 10){
//else if between 0 and 10      
      //do something
}else{
//else all others  
      //do something
}

Add a properties file to IntelliJ's classpath

I spent quite a lot of time figuring out how to do this in Intellij 13x. I apparently never added the properties files to the artifacts that required them, which is a separate step in Intellij. The setup below also works when you have a properties file that is shared by multiple modules.

  • Go to your project setup (CTRL + ALT + SHIFT + S)
  • In the list, select the module that you want to add one or more properties files to.
  • On the right, select the Dependencies tab.
  • Click the green plus and select "Jars or directories".
  • Now select the folder that contains the property file(s). (I haven't tried including an individual file)
  • Intellij will now ask you what the "category" of the selected file is. Choose "classes" (even though they are not).
  • Now you must add the properties files to the artifact. Intellij will give you the shortcut shown below. It will show errors in the red part at the bottom and a 'red lightbulb' that when clicked shows you an option to add the files to the artifact. You can also go to the 'artifacts' section and add the files to the artifacts manually.

enter image description here

Recyclerview and handling different type of row inflation

You can just return ItemViewType and use it. See below code:

@Override
public int getItemViewType(int position) {

    Message item = messageList.get(position);
    // return my message layout
    if(item.getUsername() == Message.userEnum.I)
        return R.layout.item_message_me;
    else
        return R.layout.item_message; // return other message layout
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(viewType, viewGroup, false);
    return new ViewHolder(view);
}

In a bootstrap responsive page how to center a div

Good answer ppollono. I was just playing around and I got a slightly better solution. The CSS would remain the same, i.e. :

html, body, .container {
    height: 100%;
}
.container {
    display: table;
    vertical-align: middle;
}
.vertical-center-row {
    display: table-cell;
    vertical-align: middle;
}

But for HTML:

<div class="container">
    <div class="vertical-center-row">
        <div align="center">TEXT</div>
    </div>
</div>

This would be enough.

Simple mediaplayer play mp3 from file path?

String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();   
mediaPlayer.start()

and this play from raw folder.

int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());

            MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
            mediaPlayer.prepare();
            mediaPlayer.start();

mycontext=application.this. use.

ADB.exe is obsolete and has serious performance problems

Try update your SDK Tools items, and then delete all currently created emulator and recreate again. it works for me

how to use math.pi in java

You're missing the multiplication operator. Also, you want to do 4/3 in floating point, not integer math.

volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
           ^^      ^

close fxml window by code, javafx

If you have a window which extends javafx.application.Application; you can use the following method. (This will close the whole application, not just the window. I misinterpreted the OP, thanks to the commenters for pointing it out).

Platform.exit();

Example:

public class MainGUI extends Application {
.........

Button exitButton = new Button("Exit");
exitButton.setOnAction(new ExitButtonListener());
.........

public class ExitButtonListener implements EventHandler<ActionEvent> {

  @Override
  public void handle(ActionEvent arg0) {
    Platform.exit();
  }
}

Edit for the beauty of Java 8:

 public class MainGUI extends Application {
    .........

    Button exitButton = new Button("Exit");
    exitButton.setOnAction(actionEvent -> Platform.exit());
 }

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Unzip files (7-zip) via cmd command

make sure that your path is pointing to .exe file in C:\Program Files\7-Zip (may in bin directory)

regular expression to match exactly 5 digits

I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.

Try this...

var str = 'f 34 545 323 12345 54321 123456',
    matches = str.match(/\b\d{5}\b/g);

console.log(matches); // ["12345", "54321"]

jsFiddle.

The word boundary \b is your friend here.

Update

My regex will get a number like this 12345, but not like a12345. The other answers provide great regexes if you require the latter.

Is there a way to make npm install (the command) to work behind proxy?

Have you tried command-line options instead of the .npmrc file?

I think something like npm --proxy http://proxy-server:8080/ install {package-name} worked for me.

I've also seen the following: npm config set proxy http://proxy-server:8080/

What is the correct way to read from NetworkStream in .NET

Networking code is notoriously difficult to write, test and debug.

You often have lots of things to consider such as:

  • what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.

  • are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive

  • how does congestion in the real world which causes delays in the stream affect your reading/writing logic

If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).

Here are several different ways to handle the exchange:

  • have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"

  • use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"

  • use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.

  • have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)

Each approach has its pros and cons for "correctness".

The code below uses the "timeout" method, as that seems to be the one you want.

See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  // Set a 250 millisecond timeout for reading (instead of Infinite the default)
  stm.ReadTimeout = 250;
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  int bytesread = stm.Read(resp, 0, resp.Length);
  while (bytesread > 0)
  {
      memStream.Write(resp, 0, bytesread);
      bytesread = stm.Read(resp, 0, resp.Length);
  }
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);

Can someone explain mappedBy in JPA and Hibernate?

mappedby speaks for itself, it tells hibernate not to map this field. it's already mapped by this field [name="field"].
field is in the other entity (name of the variable in the class not the table in the database)..

If you don't do that, hibernate will map this two relation as it's not the same relation

so we need to tell hibernate to do the mapping in one side only and co-ordinate between them.

How do the major C# DI/IoC frameworks compare?

Just read this great .Net DI container comparison blog by Philip Mat.

He does some thorough performance comparison tests on;

He recommends Autofac as it is small, fast, and easy to use ... I agree. It appears that Unity and Ninject are the slowest in his tests.

Java Code for calculating Leap Year

boolean leapYear = ( ( year % 4 ) == 0 );

Windows ignores JAVA_HOME: how to set JDK as default?

Set Path environment variable to your desired jdk/bin directory

No plot window in matplotlib

The code snippet below works on both Eclipse and the Python shell:

import numpy as np
import matplotlib.pyplot as plt

# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)

# Just print x and y for fun
print x
print y

# Plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)

# Without the line below, the figure won't show
plt.show()

Not an enclosing class error Android Studio

It should be

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.

not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.

Katra_home.this is invalid construct

flutter run: No connected devices

If there is a problem with ADB Interface driver:

enter image description here

Try to find an appropriate driver on manufacturer's web-site. For Intel read this Installing the Android Debug Bridge (ADB) USB Driver on a Windows Computer.

Use custom build output folder when using create-react-app

You can update the configuration with a little hack, under your root directory:

  1. npm run eject
  2. config/webpack.config.prod.js - line 61 - change path to: __dirname + './../--your directory of choice--'
  3. config/paths.js - line 68 - update to resolveApp('./--your directory of choice--')

replace --your directory of choice-- with the folder directory you want it to build on

note the path I provided can be a bit dirty, but this is all you need to do to modify the configuration.

MySql Error: 1364 Field 'display_name' doesn't have default value

I also had this issue using Lumen, but fixed by setting DB_STRICT_MODE=false in .env file.

how to add button click event in android studio

When you define an OnClickListener (or any listener) this way

btnClick.setOnClickListener(this);

you need to implement the OnClickListener in your Activity.

public class MainActivity extends ActionBarActivity implements OnClickListener{

How do I convert an interval into a number of hours with postgres?

Probably the easiest way is:

SELECT EXTRACT(epoch FROM my_interval)/3600

OpenJDK availability for Windows OS

You can find the thoroughly tested OpenJDK releases provided by Oracle at http://jdk.java.net .

For example, ready to use builds of OpenJDK 10.0.2 from Oracle for 64-bit Linux, MacOS and Windows can be found at http://jdk.java.net/10/ .

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

Definition of "downstream" and "upstream"

Upstream (as related to) Tracking

The term upstream also has some unambiguous meaning as comes to the suite of GIT tools, especially relative to tracking

For example :

   $git rev-list --count --left-right "@{upstream}"...HEAD
   >4   12

will print (the last cached value of) the number of commits behind (left) and ahead (right) of your current working branch, relative to the (if any) currently tracking remote branch for this local branch. It will print an error message otherwise:

    >error: No upstream branch found for ''
  • As has already been said, you may have any number of remotes for one local repository, for example, if you fork a repository from github, then issue a 'pull request', you most certainly have at least two: origin (your forked repo on github) and upstream (the repo on github you forked from). Those are just interchangeable names, only the 'git@...' url identifies them.

Your .git/configreads :

   [remote "origin"]
       fetch = +refs/heads/*:refs/remotes/origin/*
       url = [email protected]:myusername/reponame.git
   [remote "upstream"]
       fetch = +refs/heads/*:refs/remotes/upstream/*
       url = [email protected]:authorname/reponame.git
  • On the other hand, @{upstream}'s meaning for GIT is unique :

it is 'the branch' (if any) on 'said remote', which is tracking the 'current branch' on your 'local repository'.

It's the branch you fetch/pull from whenever you issue a plain git fetch/git pull, without arguments.

Let's say want to set the remote branch origin/master to be the tracking branch for the local master branch you've checked out. Just issue :

   $ git branch --set-upstream  master origin/master
   > Branch master set up to track remote branch master from origin.

This adds 2 parameters in .git/config :

   [branch "master"]
       remote = origin
       merge = refs/heads/master

now try (provided 'upstream' remote has a 'dev' branch)

   $ git branch --set-upstream  master upstream/dev
   > Branch master set up to track remote branch dev from upstream.

.git/config now reads:

   [branch "master"]
       remote = upstream
       merge = refs/heads/dev

git-push(1) Manual Page :

   -u
   --set-upstream

For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see branch.<name>.merge in git-config(1).

git-config(1) Manual Page :

   branch.<name>.merge

Defines, together with branch.<name>.remote, the upstream branch for the given branch. It tells git fetch/git pull/git rebase which branch to merge and can also affect git push (see push.default). \ (...)

   branch.<name>.remote

When in branch < name >, it tells git fetch and git push which remote to fetch from/push to. It defaults to origin if no remote is configured. origin is also used if you are not on any branch.

Upstream and Push (Gotcha)

take a look at git-config(1) Manual Page

   git config --global push.default upstream
   git config --global push.default tracking  (deprecated)

This is to prevent accidental pushes to branches which you’re not ready to push yet.

PHP - Getting the index of a element from a array

I recently had to figure this out for myself and ended up on a solution inspired by @Zahymaka 's answer, but solving the 2x looping of the array.

What you can do is create an array with all your keys, in the order they exist, and then loop through that.

        $keys=array_keys($items);
        foreach($keys as $index=>$key){
                    echo "position: $index".PHP_EOL."item: ".PHP_EOL;
                    var_dump($items[$key]);
                    ...
        }

PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else

Emulate Samsung Galaxy Tab

You can't.

"The Samsung Emulator has the same functionality as the Generic Android Emulator, but varies with the size and appearance of the device."

The problem with Samsung is that they don't use a generic android image, they have custom apps and they react in custom ways and do weird things you wouldn't expect and when you're trying to fix bugs that's what you want. You cannot get that. You need access to a physical device to get the right ecosystem to hunt down the bugs and map out which intents work and how they work on that device. And sometimes there are errors that only occur on Samsung devices because some of the core rendering code is different as well. I've had errors where all Android devices except Samsung would work flawlessly but the scheme itself could not work on Samsung and had to be scrapped. The only thing Samsung allows is skinning and that won't properly note the changes in the rendering pipeline or how the samsung ecosystem deals with intents.

You can make the device look similar, that's worthless. I don't care what it looks like, I care whether this bug still affects that particular model or whether the tweak to the intents I made rectified the issue and I can't learn that from a pretty picture as the border to the same device.

How to use onResume()?

Most of the previous answers do a good job explaining how, why, and when to use onResume() but I would like to add something about re-creating your Activity.

I want to know if I want to restart the activity at the end of exectuion of an other what method is executed onCreate() or onResume()

The answer is onCreate() However, when deciding to actually re-create it, you should ask yourself how much of the Activity needs to be re-created. If it is data in an adapter, say for a list, then you can call notifyDataChanged() on the adapter to repopulate the adapter and not have to redraw everything.

Also, if you just need to update certain views but not all then it may be more efficient to call invalidate() on the view(s) that need updated. This will only redraw those views and possibly allow your application to run more smoothly. I hope this can help you.

HTML5 Audio Looping

You could try a setInterval, if you know the exact length of the sound. You could have the setInterval play the sound every x seconds. X would be the length of your sound.

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

Get the library from http://commons.apache.org/net/download_net.cgi

//NTP server list: http://tf.nist.gov/tf-cgi/servers.cgi
public static final String TIME_SERVER = "time-a.nist.gov";

public static long getCurrentNetworkTime() {
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    //long returnTime = timeInfo.getReturnTime();   //local device time
    long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();   //server time

    Date time = new Date(returnTime);
    Log.d(TAG, "Time from " + TIME_SERVER + ": " + time);

    return returnTime;
}

getReturnTime() is same as System.currentTimeMillis().

getReceiveTimeStamp() or getTransmitTimeStamp() method should be used.

You can see the difference after setting system time to 1 hour ago.

local time :
System.currentTimeMillis()
timeInfo.getReturnTime()
timeInfo.getMessage().getOriginateTimeStamp().getTime()

NTP server time :
timeInfo.getMessage().getReceiveTimeStamp().getTime()
timeInfo.getMessage().getTransmitTimeStamp().getTime()

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

How many threads is too many?

I've written a number of heavily multi-threaded apps. I generally allow the number of potential threads to be specified by a configuration file. When I've tuned for specific customers, I've set the number high enough that my utilization of the all the CPU cores was pretty high, but not so high that I ran into memory problems (these were 32-bit operating systems at the time).

Put differently, once you reach some bottleneck be it CPU, database throughput, disk throughput, etc, adding more threads won't increase the overall performance. But until you hit that point, add more threads!

Note that this assumes the system(s) in question are dedicated to your app, and you don't have to play nicely (avoid starving) other apps.

Get string character by index - Java

Here's the correct code. If you're using zybooks this will answer all the problems.

for (int i = 0; i<passCode.length(); i++)
{
    char letter = passCode.charAt(i);
    if (letter == ' ' )
    {
        System.out.println("Space at " + i);
    }
}

How can I reset or revert a file to a specific revision?

Many answers here claims to use git reset ... <file> or git checkout ... <file> but by doing so, you will loose every modifications on <file> committed after the commit you want to revert.

If you want to revert changes from one commit on a single file only, just as git revert would do but only for one file (or say a subset of the commit files), I suggest to use both git diff and git apply like that (with <sha> = the hash of the commit you want to revert) :

git diff <sha>^ <sha> path/to/file.ext | git apply -R

Basically, it will first generate a patch corresponding to the changes you want to revert, and then reverse-apply the patch to drop those changes.

Of course, it shall not work if reverted lines had been modified by any commit between <sha1> and HEAD (conflict).

Error: JAVA_HOME is not defined correctly executing maven

Use these two commands (for Java 8):

sudo update-java-alternatives --set java-8-oracle
java -XshowSettings 2>&1 | grep -e 'java.home' | awk '{print "JAVA_HOME="$3}' | sed "s/\/jre//g" >> /etc/environment

How to use DISTINCT and ORDER BY in same SELECT statement?

2) Order by CreationDate is very important

The original results indicated that "test3" had multiple results...

It's very easy to start using MAX all the time to remove duplicates in Group By's... and forget or ignore what the underlying question is...

The OP presumably realised that using MAX was giving him the last "created" and using MIN would give the first "created"...

Reloading a ViewController

If you know your database has been updated and you want to just refresh your ViewController (which was my case). I didn't find another solution but what I did was when my database updated, I called:

[self viewDidLoad];

again, and it worked. Remember if you override other viewWillAppear or loadView then call them too in same order. like.

[self viewDidLoad]; [self viewWillAppear:YES];

I think there should be a more specific solution like refresh button in browser.

Fetch first element which matches criteria

I think this is the best way:

this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);

How to add subject alernative name to ssl certs?

Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS entries for a host name and IP entries for IP addresses).

To quote myself:

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1

Note that you only need Java 7's keytool to use this command. Once you've prepared your keystore, it should work with previous versions of Java.

(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)

jQuery iframe load() event?

Along the lines of Tim Down's answer but leveraging jQuery (mentioned by the OP) and loosely coupling the containing page and the iframe, you could do the following:

In the iframe:

<script>
    $(function() {
        var w = window;
        if (w.frameElement != null
                && w.frameElement.nodeName === "IFRAME"
                && w.parent.jQuery) {
            w.parent.jQuery(w.parent.document).trigger('iframeready');
        }
    });
</script>

In the containing page:

<script>
    function myHandler() {
        alert('iframe (almost) loaded');
    }
    $(document).on('iframeready', myHandler);
</script>

The iframe fires an event on the (potentially existing) parent window's document - please beware that the parent document needs a jQuery instance of itself for this to work. Then, in the parent window you attach a handler to react to that event.

This solution has the advantage of not breaking when the containing page does not contain the expected load handler. More generally speaking, it shouldn't be the concern of the iframe to know its surrounding environment.

Please note, that we're leveraging the DOM ready event to fire the event - which should be suitable for most use cases. If it's not, simply attach the event trigger line to the window's load event like so:

$(window).on('load', function() { ... });

How to bind a List<string> to a DataGridView control?

The following should work as long as you're bound to anything that implements IEnumerable<string>. It will bind the column directly to the string itself, rather than to a Property Path of that string object.

<sdk:DataGridTextColumn Binding="{Binding}" />

Cannot use special principal dbo: Error 15405

This answer doesn't help for SQL databases where SharePoint is connected. db_securityadmin is required for the configuration databases. In order to add db_securityadmin, you will need to change the owner of the database to an administrative account. You can use that account just for dbo roles.