Programs & Examples On #Ddd debugger

Data Display Debugger (DDD). A GUI based front-end for command line debuggers. Distributed under the GNU GPL license.

Very Simple, Very Smooth, JavaScript Marquee

I just created a simple jQuery plugin for that. Try it ;)

https://github.com/aamirafridi/jQuery.Marquee

Can I change the checkbox size using CSS?

You can make checkboxes larger in Safari — which is generally resistant to the usual approaches — with this attribute: -webkit-transform: scale(1.3, 1.3);

Source

Sort array by value alphabetically php

asort() - Maintains key association: yes.

sort() - Maintains key association: no.

Source: http://php.net/manual/en/array.sorting.php

Can you get a Windows (AD) username in PHP?

This is a simple NTLM AD integration example, allows single sign on with Internet Explorer, requires login/configuration in other browsers.

PHP Example

<?php 
$user = $_SERVER['REMOTE_USER'];
$domain = getenv('USERDOMAIN');

?>

In your apache httpd.conf file

LoadModule authnz_sspi_module modules/mod_authnz_sspi.so

<Directory "/path/to/folder">
    AllowOverride     All
    Options           ExecCGI
    AuthName          "SSPI Authentication"
    AuthType          SSPI
    SSPIAuth          On
    SSPIAuthoritative On
    SSPIOmitDomain    On
    Require           valid-user
    Require           user "NT AUTHORITY\ANONYMOUS LOGON" denied
</Directory>

And if you need the module, this link is useful:

https://www.apachehaus.net/modules/mod_authnz_sspi/

Removing a non empty directory programmatically in C or C++

If you are using a POSIX compliant OS, you could use nftw() for file tree traversal and remove (removes files or directories). If you are in C++ and your project uses boost, it is not a bad idea to use the Boost.Filesystem as suggested by Manuel.

In the code example below I decided not to traverse symbolic links and mount points (just to avoid a grand removal:) ):

#include <stdio.h>
#include <stdlib.h>
#include <ftw.h>

static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb)
{
    if(remove(pathname) < 0)
    {
        perror("ERROR: remove");
        return -1;
    }
    return 0;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr,"usage: %s path\n",argv[0]);
        exit(1);
    }

    // Delete the directory and its contents by traversing the tree in reverse order, without crossing mount boundaries and symbolic links

    if (nftw(argv[1], rmFiles,10, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) < 0)
    {
        perror("ERROR: ntfw");
        exit(1);
    }

    return 0;
}

Converting a string to an integer on Android

You can use the following to parse a string to an integer:

int value=Integer.parseInt(textView.getText().toString());

(1) input: 12 then it will work.. because textview has taken this 12 number as "12" string.

(2) input: "abdul" then it will throw an exception that is NumberFormatException. So to solve this we need to use try catch as I have mention below:

  int tax_amount=20;
  EditText edit=(EditText)findViewById(R.id.editText1);
     try
       {

        int value=Integer.parseInt(edit.getText().toString());
        value=value+tax_amount;
        edit.setText(String.valueOf(value));// to convert integer to string 

       }catch(NumberFormatException ee){
       Log.e(ee.toString());
       }

You may also want to refer to the following link for more information: http://developer.android.com/reference/java/lang/Integer.html

How can I add additional PHP versions to MAMP

MAMP takes only two highest versions of the PHP in the following folder /Application/MAMP/bin/php

As you can see here highest versions are 7.0.10 and 5.6.25 MAMP php Versions 7.0.10 and 5.6.25

Now 7.0.10 version is removed and as you can see highest two versions are 5.6.25 and 5.5.38 as shown in preferencesphp versions 5.6.25 and 5.5.38

What exactly is Apache Camel?

BASED ON ANALOGY

Camel based routing can be understood much easily by putting yourself in the shoes of a Airline owner (eg.: American Airlines, Jet Airways) .

Purpose of 'your airline' is to 'carry' 'passengers' from one 'city' to another one in the world. You use aircrafts from different 'aircraft companies' like Boeing, Airbus, HAL for carrying passengers.

Your airline's boards passengers using 'airports' of the from city and deboards them using the airport of the to city. A passenger may 'travel' to multiple cities, but everywhere they have to go through the airport to travel between your airline's aircraft and the city.

Note that a passenger 'departing' from the city is essentially 'arriving' into your airlines' aircraft. And a passeger 'arriving' into the city, is essentially departing from the aircraft. Since we are in the shoes of airline owner, the term 'arrival passenger' and 'departing passenger' are reversed from our conventional notions which are based on cities perspective.

Same 'airport' infrastructure of each city is used by 'departing' passengers and 'arrival' passengers. An airport provides 'departing infrastructure' for departing passengers, which is different from the 'arrival infrastructure' provided for arriving passengers.

Passengers can continue doing their day to their activities due to various 'amenities' provided inside the aircraft by your airlines, while travelling.

On top of that, your airline also provides lounge facilities for special treatments like 'understanding local language' and or preparing you for the 'travel'.

Lets replace few words/phrases used above with following:

your airline: Apache Camel

aircraft companies: Transport mechanisms

your airline's aircraft: Apache Camel's underlying transport mechanism

carry: route

passengers: message;

city: system;

airport: Camel Component;

understanding local languages: Type Conversions;

departing: producing, produced

arriving: consuming, consumed

travel: routed

amenities: provided

After replacing the words, here is what you get:

Purpose of 'Apache Camel' is to route 'messages' from one 'system' to another one in the world. Apache camel uses different transport mechanisms for message routing.

Apache Camel picks up messages using 'Camel based Component' of the 'from' system and drops them using the 'Camel based Component' of the 'to' system. A message may route to multiple systems, but everywhere they have to go through 'Camel based Components' to travel between 'Apache Camel's underlying transport mechanism' and the system.

Note that a message 'produced' from the system is essentially 'consumed' into Apache Camel's underlying transport mechanism'. And a message consumed by a system, is essentially produced by the 'Apache Camel's underlying transport mechanism'.

Since we are attempting to understand Camel, we must think from Camel's perspective here onwards. The meaning of the terms 'consumer message' and 'producer message' are ,thus, reversed from our conventional notions which are based on a system's perspective.

Same 'Camel based Component's ' coding infrastructure is used by 'producer message' and 'consumer message'. A 'Camel based Component' provides a 'producer endpoint' for 'producer message' and a 'consumer endpoint' for 'consumer message'.

Messages can be processed by Camel when they are being routed.

On top of this routing, Camel provides special features like 'Type Conversion' and many more...

Using Powershell to stop a service remotely without WMI or remoting

Based on the built-in Powershell examples, this is what Microsoft suggests. Tested and verified:

To stop:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StopService()

To start:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StartService()

Post form data using HttpWebRequest

Both the field name and the value should be url encoded. format of the post data and query string are the same

The .net way of doing is something like this

NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("field1","value1");
outgoingQueryString.Add("field2", "value2");
string postdata = outgoingQueryString.ToString();

This will take care of encoding the fields and the value names

How to setup Tomcat server in Netbeans?

I had same issue. No need to re install.

In Netbeans 6.0 , Find RunTime -> Servers - > Add server -> select Tomcat install 'root' directory

In Netbeans 7.x -> Tools -> Servers-> Add server -> select Tomcat install 'root' directory

Here is in Netbeans Wiki.

http://wiki.netbeans.org/AddExternalTomcat

Using {% url ??? %} in django templates

Instead of importing the logout_view function, you should provide a string in your urls.py file:

So not (r'^login/', login_view),

but (r'^login/', 'login.views.login_view'),

That is the standard way of doing things. Then you can access the URL in your templates using:

{% url login.views.login_view %}

Convert HashBytes to VarChar

With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:

@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)

Select DataFrame rows between two dates

With my testing of pandas version 0.22.0 you can now answer this question easier with more readable code by simply using between.

# create a single column DataFrame with dates going from Jan 1st 2018 to Jan 1st 2019
df = pd.DataFrame({'dates':pd.date_range('2018-01-01','2019-01-01')})

Let's say you want to grab the dates between Nov 27th 2018 and Jan 15th 2019:

# use the between statement to get a boolean mask
df['dates'].between('2018-11-27','2019-01-15', inclusive=False)

0    False
1    False
2    False
3    False
4    False

# you can pass this boolean mask straight to loc
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=False)]

    dates
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
335 2018-12-02

Notice the inclusive argument. very helpful when you want to be explicit about your range. notice when set to True we return Nov 27th of 2018 as well:

df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]

    dates
330 2018-11-27
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01

This method is also faster than the previously mentioned isin method:

%%timeit -n 5
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
868 µs ± 164 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)


%%timeit -n 5

df.loc[df['dates'].isin(pd.date_range('2018-01-01','2019-01-01'))]
1.53 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

However, it is not faster than the currently accepted answer, provided by unutbu, only if the mask is already created. but if the mask is dynamic and needs to be reassigned over and over, my method may be more efficient:

# already create the mask THEN time the function

start_date = dt.datetime(2018,11,27)
end_date = dt.datetime(2019,1,15)
mask = (df['dates'] > start_date) & (df['dates'] <= end_date)

%%timeit -n 5
df.loc[mask]
191 µs ± 28.5 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

How to parse XML using jQuery?

$xml = $( $.parseXML( xml ) );

$xml.find("<<your_xml_tag_name>>").each(function(index,elem){
    // elem = found XML element
});

Django Rest Framework File Upload

I'm using the same stack and was also looking for an example of file upload, but my case is simpler since I use the ModelViewSet instead of APIView. The key turned out to be the pre_save hook. I ended up using it together with the angular-file-upload module like so:

# Django
class ExperimentViewSet(ModelViewSet):
    queryset = Experiment.objects.all()
    serializer_class = ExperimentSerializer

    def pre_save(self, obj):
        obj.samplesheet = self.request.FILES.get('file')

class Experiment(Model):
    notes = TextField(blank=True)
    samplesheet = FileField(blank=True, default='')
    user = ForeignKey(User, related_name='experiments')

class ExperimentSerializer(ModelSerializer):
    class Meta:
        model = Experiment
        fields = ('id', 'notes', 'samplesheet', 'user')

// AngularJS
controller('UploadExperimentCtrl', function($scope, $upload) {
    $scope.submit = function(files, exp) {
        $upload.upload({
            url: '/api/experiments/' + exp.id + '/',
            method: 'PUT',
            data: {user: exp.user.id},
            file: files[0]
        });
    };
});

Typescript: difference between String and string

Here is an example that shows the differences, which will help with the explanation.

var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;

String is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2 in the example above creates a new string without the use of the new keyword and without explicitly using the String object.

string is the TypeScript string type, which you can use to type variables, parameters and return values.

Additional notes...

Currently (Feb 2013) Both s1 and s2 are valid JavaScript. s3 is valid TypeScript.

Use of String. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:

var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();

If you really had a penchant for the string, you could use it in TypeScript in one of two ways...

var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type

Set default format of datetimepicker as dd-MM-yyyy

Try this,

string Date = datePicker1.SelectedDate.Value.ToString("dd-MMM-yyyy");

It worked for me the output format will be '02-May-2016'

Create a list with initial capacity in Python

As others have mentioned, the simplest way to preseed a list is with NoneType objects.

That being said, you should understand the way Python lists actually work before deciding this is necessary.

In the CPython implementation of a list, the underlying array is always created with overhead room, in progressively larger sizes ( 4, 8, 16, 25, 35, 46, 58, 72, 88, 106, 126, 148, 173, 201, 233, 269, 309, 354, 405, 462, 526, 598, 679, 771, 874, 990, 1120, etc), so that resizing the list does not happen nearly so often.

Because of this behavior, most list.append() functions are O(1) complexity for appends, only having increased complexity when crossing one of these boundaries, at which point the complexity will be O(n). This behavior is what leads to the minimal increase in execution time in S.Lott's answer.

Source: Python list implementation

How to get store information in Magento?

Great answers here. If you're looking for the default view "Store Name" set in the Magento configuration:

Mage::app()->getStore()->getFrontendName()

Backup a single table with its data from a database in sql server 2008

Backup a single table with its data from a database in sql server 2008

SELECT * INTO  [dbo].[tbl_NewTable] 
FROM [dbo].[tbl_OldTable]

How to check if an object implements an interface?

If you want a method like public void doSomething([Object implements Serializable]) you can just type it like this public void doSomething(Serializable serializableObject). You can now pass it any object that implements Serializable but using the serializableObject you only have access to the methods implemented in the object from the Serializable interface.

Installing a specific version of angular with angular cli

npx @angular/cli@10 new my-poject

you can replace 10 with your version of choice... no need to uninstall your existing CLI! Just learnt that now...

How do I install command line MySQL client on mac?

Mysql has a client-only set of utilities:

Mysql client shell https://dev.mysql.com/downloads/shell/

Other command line utilities https://dev.mysql.com/downloads/utilities/

Mac OSX version available.

Editing hosts file to redirect url?

hosts file:

1.2.3.4 google.com

1.2.3.4 - ip of your server.

Run script on the server for redirecting users to url that you want.

How to set JAVA_HOME in Mac permanently?

1) The first step is to if you have Java installed and running your system.

which java

Usually, it should be /usr/bin/java.

2) JAVA_HOME is essentially the full path of the directory that contains a sub-directory named bin which in turn contains the java.

cd /Library/Java/
  • You should have bin folder inside /Java folder and in turn it must contain the [java] executable package.

Folder structure for Mac OS

3.1) If you want to set the path only for the current session then execute this command in your terminal export JAVA_HOME=/Library/Java

3.2) If you want it to persist, you will have to add the command to your ~/.bash_profile file

  • Open up Terminal vi ~/.bash_profile
  • Add these lines to terminal export JAVA_HOME=/Library/Java/Home and save it
  • Execute below command source ~/.bash_profile

4) Verify you have correctly added JAVA_HOME path. Below command should give you the proper Java version.

That's it and your ready to use!!

How can I explicitly free memory in Python?

As other answers already say, Python can keep from releasing memory to the OS even if it's no longer in use by Python code (so gc.collect() doesn't free anything) especially in a long-running program. Anyway if you're on Linux you can try to release memory by invoking directly the libc function malloc_trim (man page). Something like:

import ctypes
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)

How can I find WPF controls by name or type?

Try this

<TextBlock x:Name="txtblock" FontSize="24" >Hai Welcom to this page
</TextBlock>

Code Behind

var txtblock = sender as Textblock;
txtblock.Foreground = "Red"

Why does Maven have such a bad rep?

It's common for Maven defenders to say "well, you just don't understand it". This, they think, is a real snappy rejoinder.

It goes like this:

Super Programmer: "hey, I need to keep this door open, does anyone have a doorstop" Maven Programmer: "why yes, here's one" (shows him a complex collection of popsicle sticks) Super Programmer: "these sticks aren't holding the door open!" Maven Programmer (smug, chuckling): "You just don't understand it. I suggest you read the manual, and really study the thing for about 1 year!!!"

Multi-Line Comments in Ruby?

=begin
My 
multiline
comment
here
=end

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

How can I sort an ArrayList of Strings in Java?

You might sort the helper[] array directly:

java.util.Arrays.sort(helper, 1, helper.length);

Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.

See Arrays.sort(Object[] a, int fromIndex, int toIndex)

Using R to download zipped data file, extract, and import data

Zip archives are actually more a 'filesystem' with content metadata etc. See help(unzip) for details. So to do what you sketch out above you need to

  1. Create a temp. file name (eg tempfile())
  2. Use download.file() to fetch the file into the temp. file
  3. Use unz() to extract the target file from temp. file
  4. Remove the temp file via unlink()

which in code (thanks for basic example, but this is simpler) looks like

temp <- tempfile()
download.file("http://www.newcl.org/data/zipfiles/a1.zip",temp)
data <- read.table(unz(temp, "a1.dat"))
unlink(temp)

Compressed (.z) or gzipped (.gz) or bzip2ed (.bz2) files are just the file and those you can read directly from a connection. So get the data provider to use that instead :)

How to return more than one value from a function in Python?

Return as a tuple, e.g.

def foo (a):
    x=a
    y=a*2
    return (x,y)

How can I reload .emacs after changing it?

Although M-x eval-buffer will work you may run into problems with toggles and other similar things. A better approach might be to "mark" or highlight whats new in your .emacs (or even scratch buffer if your just messing around) and then M-x eval-region. Hope this helps.

sql delete statement where date is greater than 30 days

To delete records from a table that have a datetime value in Date_column older than 30 days use this query:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < GETDATE() - 30

...or this:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(dd,-30,GETDATE())

To delete records from a table that have a datetime value in Date_column older than 12 hours:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(hh,-12,GETDATE())

To delete records from a table that have a datetime value in Date_column older than 15 minutes:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(mi,-15,GETDATE())

From: http://zarez.net/?p=542

Padding or margin value in pixels as integer using jQuery

You could also extend the jquery framework yourself with something like:

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.

fx.

$("#myObject").margin().top

java how to use classes in other package?

It should be like import package_name.Class_Name --> If you want to import a specific class (or)

import package_name.* --> To import all classes in a package

Verify host key with pysftp

FWIR, if authentication is only username & pw, add remote server ip address to known_hosts like ssh-keyscan -H 192.168.1.162 >> ~/.ssh/known_hosts for ref https://www.techrepublic.com/article/how-to-easily-add-an-ssh-fingerprint-to-your-knownhosts-file-in-linux/

What is the best way to find the users home directory in Java?

Others have answered the question before me but a useful program to print out all available properties is:

for (Map.Entry<?,?> e : System.getProperties().entrySet()) {
    System.out.println(String.format("%s = %s", e.getKey(), e.getValue())); 
}

PHP: Split string

explode('.', $string)

If you know your string has a fixed number of components you could use something like

list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;

Prints:

object
attribute

Why does adb return offline after the device string?

I post here my question just in case is helpful for somebody else. My problem was that my colleague was connected to the same device and I was not able to connect to the same device.

Note: I had this problem with Amazon Fire TV connecting over Wifi.

There are 2 solutions:

Easy to "drop" his connection (sorry buddy :)

Restart the device
adb kill-server
adb start-server
adb connect device-ip

A bit more difficult but two clients can use the same device (use different TCP ports)

Please look at this answer

Node.js heap out of memory

Just in case it may help people having this issue while using nodejs apps that produce heavy logging, a colleague solved this issue by piping the standard output(s) to a file.

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Finding the number of days between two dates

I read all previous solutions, none of them use PHP 5.3 tools: DateTime::Diff and DateInterval::Days

DateInterval::Days contains exactly the right numbers of days between to date. It is not necessary to create something special and bizarre.

/**
 * We suppose that PHP is configured in UTC
 * php.ini configuration:
 * [Date]
 * ; Defines the default timezone used by the date functions
 * ; http://php.net/date.timezone
 * date.timezone = UTC
 * @link http://php.net/date.timezone
 */

/**
 * getDaysBetween2Dates
 *
 * Return the difference of days between $date1 and $date2 ($date1 - $date2)
 * if $absolute parameter is false, the return value is negative if $date2 is after than $date1
 *
 * @param DateTime $date1
 * @param DateTime $date2
 * @param Boolean $absolute
 *            = true
 * @return integer
 */
function getDaysBetween2Dates(DateTime $date1, DateTime $date2, $absolute = true)
{
    $interval = $date2->diff($date1);
    // if we have to take in account the relative position (!$absolute) and the relative position is negative,
    // we return negatif value otherwise, we return the absolute value
    return (!$absolute and $interval->invert) ? - $interval->days : $interval->days;
}

echo '<h3>2020-03-01 - 2020-02-01: 29 days as it\'s a standard leap year</h3>';
echo getDaysBetween2Dates(new DateTime("2020-03-01"), new DateTime("2020-02-01"), false);

echo '<h3>1900-03-01 - 1900-02-01: 28 days as it\'s a "standard" century</h3>';
echo getDaysBetween2Dates(new DateTime("1900-03-01"), new DateTime("1900-02-01"), false);

echo '<h3>2000-03-01 - 2000-02-01: 29 days as it\'s a century multiple of 400: 2000=400x5</h3>';
echo getDaysBetween2Dates(new DateTime("2000-03-01"), new DateTime("2000-02-01"), false);

echo '<h3>2020-03-01 - 2020-04-01: -28 days as 2020-03-01 is before 2020-04-01</h3>';
echo getDaysBetween2Dates(new DateTime("2020-02-01"), new DateTime("2020-03-01"), false);

What are my options for storing data when using React Native? (iOS and Android)

you can use Realm or Sqlite if you want to manage complex data type.

Otherwise go with inbuilt react native asynstorage

GCC -fPIC option

Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.

E.g. jumps would be generated as relative rather than absolute.

Pseudo-assembly:

PIC: This would work whether the code was at address 100 or 1000

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP

Non-PIC: This will only work if the code is at address 100

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP

EDIT: In response to comment.

If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.

Contains method for a slice

No, such method does not exist, but is trivial to write:

func contains(s []int, e int) bool {
    for _, a := range s {
        if a == e {
            return true
        }
    }
    return false
}

You can use a map if that lookup is an important part of your code, but maps have cost too.

The property 'value' does not exist on value of type 'HTMLElement'

The problem is here:

document.getElementById(elementId).value

You know that HTMLElement returned from getElementById() is actually an instance of HTMLInputElement inheriting from it because you are passing an ID of input element. Similarly in statically typed Java this won't compile:

public Object foo() {
  return 42;
}

foo().signum();

signum() is a method of Integer, but the compiler only knows the static type of foo(), which is Object. And Object doesn't have a signum() method.

But the compiler can't know that, it can only base on static types, not dynamic behaviour of your code. And as far as the compiler knows, the type of document.getElementById(elementId) expression does not have value property. Only input elements have value.

For a reference check HTMLElement and HTMLInputElement in MDN. I guess Typescript is more or less consistent with these.

Run jQuery function onclick

There's several things you can improve upon here. To start, there's no reason to use an <a> (anchor) tag since you don't have a link.

Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.

I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?

== EDIT ==

The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.

http://jsfiddle.net/THEtheChad/j9Ump/

Return outside function error in Python

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

Bootstrap dropdown sub menu missing

Comment to Skelly's really helpful workaround: in Bootstrap-sass 3.3.6, utilities.scss, line 19: .pull-left has float:left !important. Since that, I recommend to use !important in his CSS as well:

.dropdown-submenu.pull-left {
    float:none !important;
}

What does it mean to write to stdout in C?

It depends.

When you commit to sending output to stdout, you're basically leaving it up to the user to decide where that output should go.

If you use printf(...) (or the equivalent fprintf(stdout, ...)), you're sending the output to stdout, but where that actually ends up can depend on how I invoke your program.

If I launch your program from my console like this, I'll see output on my console:

$ prog
Hello, World! # <-- output is here on my console

However, I might launch the program like this, producing no output on the console:

$ prog > hello.txt

but I would now have a file "hello.txt" with the text "Hello, World!" inside, thanks to the shell's redirection feature.

Who knows – I might even hook up some other device and the output could go there. The point is that when you decide to print to stdout (e.g. by using printf()), then you won't exactly know where it will go until you see how the process is launched or used.

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

is there a post render callback for Angular JS directive?

You can use the 'link' function, also known as postLink, which runs after the template is put in.

app.directive('myDirective', function() {
  return {
    link: function(scope, elm, attrs) { /*I run after template is put in */ },
    template: '<b>Hello</b>'
  }
});

Give this a read if you plan on making directives, it's a big help: http://docs.angularjs.org/guide/directive

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

How to send json data in the Http request using NSURLRequest

Most of you already know this by now, but I am posting this, just incase, some of you are still struggling with JSON in iOS6+.

In iOS6 and later, we have the NSJSONSerialization Class that is fast and has no dependency on including "outside" libraries.

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 

This is the way iOS6 and later can now parse JSON efficiently.The use of SBJson is also pre-ARC implementation and brings with it those issues too if you are working in an ARC environment.

I hope this helps!

"installation of package 'FILE_PATH' had non-zero exit status" in R

The .zip file provided by the authors is not a valid R package, and they do state that the source is for "direct use" in R (by which I assume they mean it's necessary to load the included functions manually). The non-zero exit status simply indicates that there was an error during the installation of the "package".

You can extract the archive manually and then load the functions therein with, e.g., source('bivpois.table.R'), or you can download the .RData file they provide and load that into the workspace with load('.RData'). This does not install the functions as part of a package; rather, it loads the functions into your global environment, making them temporarily available.

You can download, extract, and load the .RData from R as follows:

download.file('http://stat-athens.aueb.gr/~jbn/papers/files/14/14_bivpois_RDATA.zip', 
              f <- tempfile())
unzip(f, exdir=tempdir())
load(file.path(tempdir(), '.RData'))

If you want the .RData file to be available in the current working directory, to be loaded in the future, you could use the following instead:

download.file('http://stat-athens.aueb.gr/~jbn/papers/files/14/14_bivpois_RDATA.zip', 
              f <- tempfile())
unzip(f, exdir=tempdir())
file.copy(file.path(tempdir(), '.RData'), 'bivpois.RData')
# the above copies the .RData file to a file called bivpois.RData in your current 
# working directory.
load('bivpois.RData')

In future R sessions, you can just call load('bivpois.RData').

JSON string to JS object

the string in your question is not a valid json string. From json.org website:

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is 
  realized as an object, record, struct, dictionary, hash table, keyed list, or
  associative array.
* An ordered list of values. In most languages, this is realized as an
  array, vector, list, or sequence.

Basically a json string will always start with either { or [.

Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.

IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.

Format y axis as percent

I propose an alternative method using seaborn

Working code:

import pandas as pd
import seaborn as sns
data=np.random.rand(10,2)*100
df = pd.DataFrame(data, columns=['A', 'B'])
ax= sns.lineplot(data=df, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='title')
#changing ylables ticks
y_value=['{:,.2f}'.format(x) + '%' for x in ax.get_yticks()]
ax.set_yticklabels(y_value)

enter image description here

Need to navigate to a folder in command prompt

When I open a "DOS" command prompt, I use a batch file which sets all of the options I need and adds my old-time dos utilities to the path too.

@set path=%path%;c:\utils
@doskey cd=cd/d $*
@cd \wip
@cmd.exe

The doskey line sets the CD command so that it will do both drive and folder simultaneously. If this doesn't work, it is possibly because of the version of windows that you're running.

using stored procedure in entity framework

You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.

public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

then register the GetFunctionByID model class in your DbContext.

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

When you call your stored procedure, just see below:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

Hiding table data using <div style="display:none">

You are not allowed to have div tags between tr tags. You have to look for some other strategies like creating a CSS class with display: none and adding it to concerning rows or adding inline style display: none to concerning rows.

.hidden
{
  display:none;
}

<table>
  <tr><td>I am visible</td><tr>
  <tr class="hidden"><td>I am hidden using CSS class</td><tr>
  <tr class="hidden"><td>I am hidden using CSS class</td><tr>
  <tr class="hidden"><td>I am hidden using CSS class</td><tr>
  <tr class="hidden"><td>I am hidden using CSS class</td><tr>
</table>

or

<table>
  <tr><td>I am visible</td><tr>
  <tr style="display:none"><td>I am hidden using inline style</td><tr>
  <tr style="display:none"><td>I am hidden using inline style</td><tr>
  <tr style="display:none"><td>I am hidden using inline style</td><tr>
</table>

How to get jQuery to wait until an effect is finished?

With jQuery 1.6 version you can use the .promise() method.

$(selector).fadeOut('slow');
$(selector).promise().done(function(){
    // will be called when all the animations on the queue finish
});

How to exit in Node.js

The exit in node js is done in two ways:

  • Calling process.exit() explicitly.
  • Or, if nodejs event loop is done with all tasks, and there is nothing left to do. Then, the node application will automatically exit.

How it works?

If you want to force the execution loop to stop the process, yo can use the global variable process which is an instance of EventEmitter. So when you call process.exit() you actually emit the exit event that ends all tasks immediately even if there still are asynchronous operations not been done.

process.exit() takes an exit code (Integer) as a parameter. The code 0 is the default and this means it exit with a 'success'. While the code 1 means it exit with a 'failure'.

Download single files from GitHub

I recently found a service called gitzip and its also open source:

site - http://kinolien.github.io/gitzip/

repo - https://github.com/KinoLien/gitzip

Vist the above site, enter the repo or directory URL, you can download individual files or whole directory as a zip file.

Best way to do a split pane in HTML

Improving on Reza's answer:

  • prevent the browser from interfering with a drag
  • prevent setting an element to a negative size
  • prevent drag getting out of sync with the mouse due to incremental delta interaction with element width saturation

_x000D_
_x000D_
<html><head><style>

.splitter {
    width: 100%;
    height: 100px;
    display: flex;
}

#separator {
    cursor: col-resize;
    background-color: #aaa;
    background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='30'><path d='M2 0 v30 M5 0 v30 M8 0 v30' fill='none' stroke='black'/></svg>");
    background-repeat: no-repeat;
    background-position: center;
    width: 10px;
    height: 100%;

    /* Prevent the browser's built-in drag from interfering */
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

#first {
    background-color: #dde;
    width: 20%;
    height: 100%;
    min-width: 10px;
}

#second {
    background-color: #eee;
    width: 80%;
    height: 100%;
    min-width: 10px;
}

</style></head><body>

<div class="splitter">
    <div id="first"></div>
    <div id="separator" ></div>
    <div id="second" ></div>
</div>

<script>

// A function is used for dragging and moving
function dragElement(element, direction)
{
    var   md; // remember mouse down info
    const first  = document.getElementById("first");
    const second = document.getElementById("second");

    element.onmousedown = onMouseDown;

    function onMouseDown(e)
    {
        //console.log("mouse down: " + e.clientX);
        md = {e,
              offsetLeft:  element.offsetLeft,
              offsetTop:   element.offsetTop,
              firstWidth:  first.offsetWidth,
              secondWidth: second.offsetWidth
             };

        document.onmousemove = onMouseMove;
        document.onmouseup = () => {
            //console.log("mouse up");
            document.onmousemove = document.onmouseup = null;
        }
    }

    function onMouseMove(e)
    {
        //console.log("mouse move: " + e.clientX);
        var delta = {x: e.clientX - md.e.clientX,
                     y: e.clientY - md.e.clientY};

        if (direction === "H" ) // Horizontal
        {
            // Prevent negative-sized elements
            delta.x = Math.min(Math.max(delta.x, -md.firstWidth),
                       md.secondWidth);

            element.style.left = md.offsetLeft + delta.x + "px";
            first.style.width = (md.firstWidth + delta.x) + "px";
            second.style.width = (md.secondWidth - delta.x) + "px";
        }
    }
}


dragElement( document.getElementById("separator"), "H" );

</script></body></html>
_x000D_
_x000D_
_x000D_

RegEx for Javascript to allow only alphanumeric

Save this constant

const letters = /^[a-zA-Z0-9]+$/

now, for checking part use .match()

const string = 'Hey there...' // get string from a keyup listner
let id = ''
// iterate through each letters
for (var i = 0; i < string.length; i++) {
  if (string[i].match(letters) ) {
    id += string[i]
  } else {
    // In case you want to replace with something else
    id += '-'  
  }
}
return id

HTML5 video - show/hide controls programmatically

Here's how to do it:

var myVideo = document.getElementById("my-video")    
myVideo.controls = false;

Working example: https://jsfiddle.net/otnfccgu/2/

See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp

What does "|=" mean? (pipe equal operator)

|= reads the same way as +=.

notification.defaults |= Notification.DEFAULT_SOUND;

is the same as

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

where | is the bit-wise OR operator.

All operators are referenced here.

A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.

If you look at those constants, you'll see that they're in powers of two :

public static final int DEFAULT_SOUND = 1;
public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary
public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary

So you can use bit-wise OR to add flags

int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011

so

myFlags |= DEFAULT_LIGHTS;

simply means we add a flag.

And symmetrically, we test a flag is set using & :

boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

You can also just copy the file to GAC using a command prompt. I use the following batch script to copy the DLL and restart IIS.

copy /b/v/y "PathToAssembly\MyAssembly.dll" "C:\Windows\assembly\" 
iisreset /noforce
pause

Saves the need to use or install gacutil

ASP.NET MVC Razor render without encoding

You can also use the WriteLiteral method

Writing a dictionary to a text file?

I do it like this in python 3:

with open('myfile.txt', 'w') as f:
    print(mydictionary, file=f)

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

PYTHONPATH only affects import statements, not the top-level Python interpreter's lookup of python files given as arguments.

Needing PYTHONPATH to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.

Have a read of https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/ - 'The Hitchhiker's Guide to Packaging', and also http://docs.python.org/3/tutorial/modules.html - which explains PYTHONPATH and packages at a lower level.

LINQ equivalent of foreach for IEnumerable<T>

MoreLinq has IEnumerable<T>.ForEach and a ton of other useful extensions. It's probably not worth taking the dependency just for ForEach, but there's a lot of useful stuff in there.

https://www.nuget.org/packages/morelinq/

https://github.com/morelinq/MoreLINQ

How do you explicitly set a new property on `window` in TypeScript?

Make a custom interface extends the Window and add your custom property as optional.

Then, let the customWindow that use the custom interface, but valued with the original window.

It's worked with the [email protected].

interface ICustomWindow extends Window {
  MyNamespace?: any
}

const customWindow:ICustomWindow = window;

customWindow.MyNamespace = customWindow.MyNamespace {} 

Embed image in a <button> element

Add new folder with name of Images in your project. Put some images into Images folder. Then it will work fine.

<input type="image" src="~/Images/Desert.jpg" alt="Submit" width="48" height="48">

How to append strings using sprintf?

Use the return value of sprintf()

Buffer += sprintf(Buffer,"Hello World");
Buffer += sprintf(Buffer,"Good Morning");
Buffer += sprintf(Buffer,"Good Afternoon");

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

How to make an inline element appear on new line, or block element not occupy the whole line?

You can give it a property display block; so it will behave like a div and have its own line

CSS:

.feature_desc {
   display: block;
   ....
}

Which JRE am I using?

The following command will tell you a lot of information about your java version, including the vendor:

java -XshowSettings:properties -version

It works on Windows, Mac, and Linux.

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

How do you split a list into evenly sized chunks?

I've created these two fancy one-liners which are efficient and lazy, both input and output are iterables, also they doen't depend on any module:

First one-liner is totally lazy meaning that it returns iterator producing iterators (i.e. each chunk produced is iterator iterating over chunk's elements), this version is good for the case if chunks are very large or elements are produced slowly one by one and should become available immediately as they are produced:

Try it online!

chunk_iters = lambda it, n: ((e for i, g in enumerate(((f,), cit)) for j, e in zip(range((1, n - 1)[i]), g)) for cit in (iter(it),) for f in cit)

Second one-liner returns iterator that produces lists. Each list is produced as soon as elements of whole chunk become available through input iterator or if very last element of last chunk is reached. This version should be used if input elements are produced fast or all available immediately. Other wise first more-lazy one-liner version should be used.

Try it online!

chunk_lists = lambda it, n: (l for l in ([],) for i, g in enumerate((it, ((),))) for e in g for l in (l[:len(l) % n] + [e][:1 - i],) if (len(l) % n == 0) != i)

Also I provide multi-line version of first chunk_iters one-liner, which returns iterator producing another iterators (going through each chunk's elements):

Try it online!

def chunk_iters(it, n):
    cit = iter(it)
    def one_chunk(f):
        yield f
        for i, e in zip(range(n - 1), cit):
            yield e
    for f in cit:
        yield one_chunk(f)

(How) can I count the items in an enum?

For C++, there are various type-safe enum techniques available, and some of those (such as the proposed-but-never-submitted Boost.Enum) include support for getting the size of a enum.

The simplest approach, which works in C as well as C++, is to adopt a convention of declaring a ...MAX value for each of your enum types:

enum Folders { FA, FB, FC, Folders_MAX = FC };
ContainerClass *m_containers[Folders_MAX + 1];
....
m_containers[FA] = ...; // etc.

Edit: Regarding { FA, FB, FC, Folders_MAX = FC} versus {FA, FB, FC, Folders_MAX]: I prefer setting the ...MAX value to the last legal value of the enum for a few reasons:

  1. The constant's name is technically more accurate (since Folders_MAX gives the maximum possible enum value).
  2. Personally, I feel like Folders_MAX = FC stands out from other entries out a bit more (making it a bit harder to accidentally add enum values without updating the max value, a problem Martin York referenced).
  3. GCC includes helpful warnings like "enumeration value not included in switch" for code such as the following. Letting Folders_MAX == FC + 1 breaks those warnings, since you end up with a bunch of ...MAX enumeration values that should never be included in switch.
switch (folder) 
{
  case FA: ...;
  case FB: ...;
  // Oops, forgot FC!
}

http://localhost/phpMyAdmin/ unable to connect

XAMPP by default uses http://localhost/phpmyadmin

It also requires you start both Apache and MySQL from the control panel (or as a service).

In the XAMPP Control Panel, clicking [ Admin ] on the MySQL line will open your default browser at the configured URL for the phpMyAdmin application.

If you get a phpMyAdmin error stating "Cannot connect: invalid settings." You will need to make sure your MySQL config file has a matching port for server and client. If it is not the standard 3306 port, you will also need to change your phpMyAdmin config file under apache (config.inc.php) to meet the new port settings. (127.0.0.1 becomes 127.0.0.1:<port>)

Printing Exception Message in java

The output looks correct to me:

Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1

I think Invalid Javascript code: .. is the start of the exception message.

Normally the stacktrace isn't returned with the message:

try {
    throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
    System.out.println(e.getMessage()); // prints "hu?"
}

So maybe the code you are calling catches an exception and rethrows a ScriptException. In this case maybe e.getCause().getMessage() can help you.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

If you want to use that on localhost, then use WAMP.

Then click on tray icon>PHP Services> and there enable the followings:

  • SOAP
  • php_openssl
  • openssl
  • curl

p.s. some free web-hosting may not have those options

How do I load an HTML page in a <div> using JavaScript?

showhide.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript">
        function showHide(switchTextDiv, showHideDiv)
        {
          var std = document.getElementById(switchTextDiv);
          var shd = document.getElementById(showHideDiv);
          if (shd.style.display == "block")
          {
            shd.style.display = "none";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>"; 
          }
          else
          {
            if (shd.innerHTML.length <= 0)
            {
              shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
            }
            shd.style.display = "block";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
          }
        }
      </script>
    </head>
    <body>
      <a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
        <span style="display: block; background-color: yellow">Show</span>
      </a>
      <div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
    </body>
</html>

showhide_embedded.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript"> 
        function load()
        {
          var ts = document.getElementById("theString");
          ts.scrollIntoView(true);
        }
      </script>
    </head>
    <body onload="load()">
      <pre>
        some text 1
        some text 2
        some text 3
        some text 4
        some text 5
        <span id="theString" style="background-color: yellow">some text 6 highlight</span>
        some text 7
        some text 8
        some text 9
      </pre>
    </body>
</html>

How to subtract 30 days from the current datetime in mysql?

If you only need the date and not the time use:

select*from table where exec_datetime
between subdate(curdate(), 30)and curdate();

Since curdate() omits the time component, it's potentially faster than now() and more "semantically correct" in cases where you're only interested in the date.

Also, subdate()'s 2-arity overload is potentially faster than using interval. interval is meant to be for cases when you need a non-day component.

How can I scroll a web page using selenium webdriver in python?

None of these answers worked for me, at least not for scrolling down a facebook search result page, but I found after a lot of testing this solution:

while driver.find_element_by_tag_name('div'):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    Divs=driver.find_element_by_tag_name('div').text
    if 'End of Results' in Divs:
        print 'end'
        break
    else:
        continue

Eclipse - debugger doesn't stop at breakpoint

Happened to me once, when I had unchecked "Run > Build automatically" and forgot to re-check it.

How to avoid 'undefined index' errors?

Figure out what keys are in the $output array, and fill the missing ones in with empty strings.

$keys = array_keys($output);
$desired_keys = array('author', 'new_icon', 'admin_link', 'etc.');

foreach($desired_keys as $desired_key){
   if(in_array($desired_key, $keys)) continue;  // already set
   $output[$desired_key] = '';
}

How to sort with lambda in Python

lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)

It will print as following:

[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]

How to implement __iter__(self) for a container object (Python)

I normally would use a generator function. Each time you use a yield statement, it will add an item to the sequence.

The following will create an iterator that yields five, and then every item in some_list.

def __iter__(self):
   yield 5
   yield from some_list

Pre-3.3, yield from didn't exist, so you would have to do:

def __iter__(self):
   yield 5
   for x in some_list:
      yield x

how to print an exception using logger?

You should probably clarify which logger are you using.

org.apache.commons.logging.Log interface has method void error(Object message, Throwable t) (and method void info(Object message, Throwable t)), which logs the stack trace together with your custom message. Log4J implementation has this method too.

So, probably you need to write:

logger.error("BOOM!", e);

If you need to log it with INFO level (though, it might be a strange use case), then:

logger.info("Just a stack trace, nothing to worry about", e);

Hope it helps.

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

Use Device Login on Smart TV / Console

Implement Login for Devices

Facebook Login for Devices is for devices that directly make HTTP calls over the internet. The following are the API calls and responses your device can make.

1. Enable Login for Devices

Change Settings > Advanced > OAuth Settings > Login from Devices to 'Yes'.

2. Generate a Code which is required for facebook device identification

When the person clicks Log in with Facebook, you device should make an HTTP POST to:

POST https://graph.facebook.com/oauth/device?
       type=device_code
       &amp;client_id=<YOUR_APP_ID>
       &amp;scope=<COMMA_SEPARATED_PERMISSION_NAMES> // e.g.public_profile,user_likes

The response comes in this form:

{
  "code": "92a2b2e351f2b0b3503b2de251132f47",
  "user_code": "A1NWZ9",
  "verification_uri": "https://www.facebook.com/device",
  "expires_in": 420,
  "interval": 5
}

This response means:

  • Display the string “A1NWZ9” on your device
  • Tell the person to go to “facebook.com/device” and enter this code
  • The code expires in 420 seconds. You should cancel the login flow after that time if you do not receive an access token
  • Your device should poll the Device Login API every 5 seconds to see if the authorization has been successful

3. Display the Code

Your device should display the user_code and tell people to visit the verification_uri such as facebook.com/device on their PC or smartphone. See the Design Guidelines.

4. Poll for Authorization

Your device should poll the Device Login API to see if the person successfully authorized your application. You should do this at the interval in the response to your call in Step 1, which is every 5 seconds. Your device should poll to:

POST https://graph.facebook.com/oauth/device?
       type=device_token
       &amp;client_id=<YOUR_APP_ID> 
       &amp;code=<LONG_CODE_FROM_STEP_1> //e.g."92a2b2e351f2b0b3503b2de251132f47"

You will get 200 HTTP code i.e User has successfully authorized the device. The device can now use the access_token value to make authenticated API calls.

5. Confirm Successful Login

Your device should display their name and if available, a profile picture until they click Continue. To get the person's name and profile picture, your device should make a standard Graph API call:

GET https://graph.facebook.com/v2.3/me?
      fields=name,picture&amp;
      access_token=<USER_ACCESS_TOKEN>

Response:

{
  "name": "John Doe", 
  "picture": {
    "data": {
      "is_silhouette": false, 
      "url": "https://fbcdn.akamaihd.net/hmac...ile.jpg"
    }
  }, 
  "id": "2023462875238472"
}

6. Store Access Tokens

Your device should persist the access token to make other requests to the Graph API.

Device Login access tokens may be valid for up to 60 days but may be invalided in a number of scenarios. For example when a person changes their Facebook password their access token is invalidated.

If the token is invalid, your device should delete the token from its memory. The person using your device needs to perform the Device Login flow again from Step 1 to retrieve a new, valid token.

How to send string from one activity to another?

TWO CASES

There are two situations possible when we talk about passing data between activities.

Let's say there are two activities A and B and there is a String X. and you are in Activity A.

Now let's see the two cases

  1. A-------->B
  2. A<--------B

CASE 1:
String X is in A and you want to get it in Activity B.

It is very straightforward.

In Activity A.

1) Create Intent
2) Put Extra value
3) startActivity

Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)

In Activity B

Inside onCreate() method retrieve string X using the key which you used while storing X (Your_KEY).

Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");

Case 2:
This case is little tricky if u are new to Android development Because you are in Activity A, you move to Activity B, collect the string, move back to Activity A and retrieve the collected String or data. Let's see how to deal with this situation.

In Activity A
1) Create Intent
2) start an activity with a request code.

Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);

In Activity B
1) Put string X in intent
2) Set result
3) Finish activity

Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent);   // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();

Again in Activity A
1) Override onActivityResult method

onActivityResult(int req_code, int res_code, Intent data)
{
       if(req_code==your_req_code)
       {
          String X = data.getStringExtra("KEY")
       }
}

Further understanding of Case 2

You might wonder what is the reqCode, resCode in the onActivityResult(int reqCode, resCode, Intent data)

reqCode is useful when you have to identify from which activity you are getting the result from.

Let's say you have two buttons, one button starts Camera (you click a photo and get the bitmap of that image in your Activity as a result), another button starts GoogleMap( you get back the current coordinates of your location as a result). So to distinguish between the results of both activities you start CameraActivty and MapActivity with different request codes.

resCode: is useful when you have to distinguish between how results are coming back to requesting activity.

For eg: You start Camera Activity. When the camera activity starts, you could either take a photo or just move back to requesting activity without taking a photo with the back button press. So in these two situations, your camera activity sends result with different resCode ACTIVITY.RESULT_OK and ACTIVITY.RESULT_CANCEL respectively.

Relevant Links

Read more on Getting result

Bootstrap 3 Glyphicons CDN

With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

In css:

 @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");

Here is a working demo.

Note that you have to use .glyphicon classes instead of .icon:

Example:

<span class="glyphicon glyphicon-heart"></span>

Also note that you would still need to include bootstrap.min.js for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.


If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

In css:

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");

Since the css file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css file is all there is to do to start using Glyphicons.

Here is a working demo of the Glyphicons without Bootstrap.

Ruby: Calling class method from instance

Using self.class.blah is NOT the same as using ClassName.blah when it comes to inheritance.

class Truck
  def self.default_make
    "mac"
  end

  def make1
    self.class.default_make
  end

  def make2
    Truck.default_make
  end
end


class BigTruck < Truck
  def self.default_make
    "bigmac"
  end
end

ruby-1.9.3-p0 :021 > b=BigTruck.new
 => #<BigTruck:0x0000000307f348> 
ruby-1.9.3-p0 :022 > b.make1
 => "bigmac" 
ruby-1.9.3-p0 :023 > b.make2
 => "mac" 

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

Specifying maxlength for multiline textbox

try this javascript:

function checkTextAreaMaxLength(textBox,e, length)
{

        var mLen = textBox["MaxLength"];
        if(null==mLen)
            mLen=length;

        var maxLength = parseInt(mLen);
        if(!checkSpecialKeys(e))
        {
         if(textBox.value.length > maxLength-1)
         {
            if(window.event)//IE
              e.returnValue = false;
            else//Firefox
                e.preventDefault();
         }
    }   
}
function checkSpecialKeys(e)
{
    if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
        return false;
    else
        return true;
}

On the control invoke it like this:

<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');"  TextMode="multiLine" runat="server"> </asp:TextBox>

You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.

Get Country of IP Address with PHP

You can try the services of https://www.geoip-db.com They provide a JSON or JSONP-callback solution.

<?php

    $json = file_get_contents("https://www.geoip-db.com/json");
    $data = json_decode($json);

    print $data->country_code . "<br>";
    print $data->country_name . "<br>";
    print $data->state . "<br>";
    print $data->city . "<br>";
    print $data->postal . "<br>";
    print $data->latitude . "<br>";
    print $data->longitude . "<br>";
    print $data->IPv4 . "<br>";

?>

MongoDB not equal to

If there is a null in an array and you want to avoid it:

db.test.find({"contain" : {$ne :[] }}).pretty()

How to get the selected value from drop down list in jsp?

I know that this is an old question, but as I was googling it was the first link in a results. So here is the jsp solution:

<form action="some.jsp">
  <select name="item">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <input type="submit" value="Submit">
</form>

in some.jsp

request.getParameter("item");

this line will return the selected option (from the example it is: 1, 2 or 3)

Does Ruby have a string.startswith("abc") built in method?

If this is for a non-Rails project, I'd use String#index:

"foobar".index("foo") == 0  # => true

How can I export a GridView.DataSource to a datatable or dataset?

You should convert first DataSource in BindingSource, look example

BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource 
DataTable tCxC = (DataTable) bs.DataSource;

With the data of tCxC you can do anything.

Create Elasticsearch curl query for not null and not empty("")

A null value and an empty string both result in no value being indexed, in which case you can use the exists filter

curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1'  -d '
{
   "query" : {
      "constant_score" : {
         "filter" : {
            "exists" : {
               "field" : "myfield"
            }
         }
      }
   }
}
'

Or in combination with (eg) a full text search on the title field:

curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1'  -d '
{
   "query" : {
      "filtered" : {
         "filter" : {
            "exists" : {
               "field" : "myfield"
            }
         },
         "query" : {
            "match" : {
               "title" : "search keywords"
            }
         }
      }
   }
}
'

How to Display Selected Item in Bootstrap Button Dropdown Title

I have corrected script for multiple dropdowns on the page

$(function(){
    $(".dropdown-menu li a").click(function(){
        var item = $(this);
        var id = item.parent().parent().attr("aria-labelledby");

        $("#"+id+":first-child").text($(this).text());
        $("#"+id+":first-child").val($(this).text());
   });
});

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

In MacOS Catalina, run

sudo nano ~/.bash_profile

In bash_profile, add:

export JAVA_HOME=$(/usr/libexec/java_home)
source ~/.bash_profile

Verify by running java --version

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

It looks like you don't have the python mysql package installed, try:

pip install mysql-python

or if not using a virtual environment (on *nix hosts):

sudo pip install mysql-python

How to insert a newline in front of a pattern?

echo one,two,three | sed 's/,/\
/g'

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Thanks to this thread, and especially budidino because his code is what drove it home for me. Just wanted to contribute how to retrieve the JSON data from a request. Make changes to "//create request" request array part of the code to perform different requests. Ultimately, this will output the JSON onto the browser screen

<?php
    function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}

function returnTweet(){
    $oauth_access_token         = "2602299919-lP6mgkqAMVwvHM1L0Cplw8idxJzvuZoQRzyMkOx";
    $oauth_access_token_secret  = "wGWny2kz67hGdnLe3Uuy63YZs4nIGs8wQtCU7KnOT5brS";
    $consumer_key               = "zAzJRrPOj5BvOsK5QhscKogVQ";
    $consumer_secret            = "Uag0ujVJomqPbfdoR2UAWbRYhjzgoU9jeo7qfZHCxR6a6ozcu1";

    $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me

    //  create request
        $request = array(
            'screen_name'       => 'burownrice',
            'count'             => '3'
        );

    $oauth = array(
        'oauth_consumer_key'        => $consumer_key,
        'oauth_nonce'               => time(),
        'oauth_signature_method'    => 'HMAC-SHA1',
        'oauth_token'               => $oauth_access_token,
        'oauth_timestamp'           => time(),
        'oauth_version'             => '1.0'
    );

    //  merge request and oauth to one array
        $oauth = array_merge($oauth, $request);

    //  do some magic
        $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
        $composite_key          = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
        $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
        $oauth['oauth_signature']   = $oauth_signature;

    //  make request
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);

        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $json = curl_exec($feed);
        curl_close($feed);

    return $json;
}

$tweet = returnTweet();
echo $tweet;

?>

Access denied for user 'homestead'@'localhost' (using password: YES)

I had the same issue using SQLite. My problem was that DB_DATABASE was pointing to the wrong file location.

Create the sqlite file with the touch command and output the file path using php artisan tinker.

$ touch database/database.sqlite
$ php artisan tinker
Psy Shell v0.8.0 (PHP 5.6.27 — cli) by Justin Hileman
>>> database_path(‘database.sqlite’)
=> "/Users/connorleech/Projects/laravel-5-rest-api/database/database.sqlite"

Then output that exact path to the DB_DATABASE variable.

DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=/Users/connorleech/Projects/laravel-5-rest-api/database/database.sqlite
DB_USERNAME=homestead
DB_PASSWORD=secret

Without the correct path you will get the access denied error

JQuery get data from JSON array

I think you need something like:

var text= data.response.venue.tips.groups[0].items[1].text;

Default instance name of SQL Server Express

The default instance name after installing is,

Server name:

.\SQLExpress

Authentication:

Windows Authentication

Note: The period in the server Name field means your local machine. For remote machines, use the machine name instead of the period.

This video also helps you to Find your sql server name (instance) for Management Studio .

How can I make Visual Studio wrap lines at 80 characters?

Unless someone can recommend a free tool to do this, you can achieve this with ReSharper:

ReSharper >> Options... >> Languages/C# >> Line Breaks and Wrapping

  • Check "Wrap long lines"
  • Set "Right Margin (columns)" to the required value (default is 120)

Hope that helps.

Get value of a specific object property in C# without knowing the class behind

Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:

  object value = GetValue();
  string propertyName = "MyProperty";

  var parameter = Expression.Parameter(typeof(object));
  var cast = Expression.Convert(parameter, value.GetType());
  var propertyGetter = Expression.Property(cast, propertyName);
  var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing

  var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();

 var retrivedPropertyValue = propertyRetriver(value);

This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.

Java variable number or arguments for a method

That's correct. You can find more about it in the Oracle guide on varargs.

Here's an example:

void foo(String... args) {
    for (String arg : args) {
        System.out.println(arg);
    }
}

which can be called as

foo("foo"); // Single arg.
foo("foo", "bar"); // Multiple args.
foo("foo", "bar", "lol"); // Don't matter how many!
foo(new String[] { "foo", "bar" }); // Arrays are also accepted.
foo(); // And even no args.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

consider changing host entry 127.0.0.1 to localhost or even the IP address of the server.

$cfg['Servers'][$i]['host']

How to permanently set $PATH on Linux/Unix?

You can add that line to your console config file (e.g. .bashrc) , or to .profile

How to print multiple lines of text with Python

The triple quotes answer is great for ASCII art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:

print("\n".join(<*iterable*>))

For example:

print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))

Draw path between two points using Google Maps Android API v2

in below code midpointsList is an ArrayList of waypoints

private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList<LatLng> midpointsList) {
    String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;

    String midpoints = "";
    for (int mid = 0; mid < midpointsList.size(); mid++) {
        midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
    }

    String waypoints = "waypoints=optimize:true" + midpoints + "|";

    String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
    String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";

    String sensor = "sensor=false";
    String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;


    Log.e("url", url);
    parseDirectionApidata(url, googleMap);
    return url;
}

Then copy and paste this url in your browser to check And the below code is to parse the url

    private void parseDirectionApidata(String url, final GoogleMap googleMap) {

    final JSONObject jsonObject = new JSONObject();

    try {

        AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
            @Override
            public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {

                if (jsonResult != null) {

                    Log.e("jsonRes", jsonResult.toString());

                    String status = jsonResult.optString("status");

                    if (status.equalsIgnoreCase("ok")) {
                        drawPath(jsonResult, googleMap);
                    }

                } else {

                    Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
                }

            }
        }, url, jsonObject);

    } catch (Exception e) {
        e.printStackTrace();

    }
}

And then pass the result to the drawPath method

    public void drawPath(JSONObject jObject, GoogleMap googleMap) {

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;
    List<LatLng> list = null;
    try {

        Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
        jRoutes = jObject.getJSONArray("routes");

        /** Traversing all routes */
        for (int i = 0; i < jRoutes.length(); i++) {
            jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            /** Traversing all legs */
            for (int j = 0; j < jLegs.length(); j++) {
                jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                /** Traversing all steps */
                for (int k = 0; k < jSteps.length(); k++) {
                    String polyline = "";
                    polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                    list = decodePoly(polyline);
                }
                Log.e("list", list.toString());
                routes.add(path);
                Log.e("routes", routes.toString());
                if (list != null) {
                    Polyline line = googleMap.addPolyline(new PolylineOptions()
                            .addAll(list)
                            .width(12)
                            .color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
                            .geodesic(true)
                    );
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

  private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

decode poly function is to decode the points(lat and long) provided by Directions API in encoded form

How to set the From email address for mailx command?

On macOS Sierra, creating ~/.mailrc with smtp setup did the trick:

set smtp-use-starttls
set smtp=smtp://smtp.gmail.com:587
set smtp-auth=login
set [email protected]
set smtp-auth-password=yourpass

Then to send mail from CLI:

echo "your message" | mail -s "your subject" [email protected]

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

This happens sometimes when I'm trying to open my old projects, what helps me is to change projects target framework. Go to Project -> projectname Properties... and change the Target framework to the one that you have installed. Project properties

How can I get the root domain URI in ASP.NET?

string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"

How to get the first word of a sentence in PHP?

strtok is quicker than extract or preg_* functions.

Resize image proportionally with MaxHeight and MaxWidth constraints

Much longer solution, but accounts for the following scenarios:

  1. Is the image smaller than the bounding box?
  2. Is the Image and the Bounding Box square?
  3. Is the Image square and the bounding box isn't
  4. Is the image wider and taller than the bounding box
  5. Is the image wider than the bounding box
  6. Is the image taller than the bounding box

    private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
    {
        //throw error if bouning box is to small
        if (desiredWidth < 4 || desiredHeight < 4)
            throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");            
        var original = Bitmap.FromFile(sourceImage.FullName);
    
        //store image widths in variable for easier use
        var oW = (decimal)original.Width;
        var oH = (decimal)original.Height;
        var dW = (decimal)desiredWidth;
        var dH = (decimal)desiredHeight;
    
        //check if image already fits
        if (oW < dW && oH < dH)
            return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
    
        //check for double squares
        if (oW == oH && dW == dH)
        {
            //image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
            Bitmap square = new Bitmap(original, (int)dW, (int)dH);
            original.Dispose();
            return square;
        }
    
        //check original image is square
        if (oW == oH)
        {
            //image is square, bounding box isn't.  Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
            int smallSide = (int)Math.Min(dW, dH);
            Bitmap square = new Bitmap(original, smallSide, smallSide);
            original.Dispose();
            return square;
        }
    
        //not dealing with squares, figure out resizing within aspect ratios            
        if (oW > dW && oH > dH) //image is wider and taller than bounding box
        {
            var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
            var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
            var nW = oW * r;
            var resized = new Bitmap(original, (int)nW, (int)nH);
            original.Dispose();
            return resized;
        }
        else
        {
            if (oW > dW) //image is wider than bounding box
            {
                var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
                var nW = oW * r; //downscale image by r to fit in the bounding box...
                var nH = oH * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
            else
            {
                //original image is taller than bounding box
                var r = dH / oH;
                var nH = oH * r;
                var nW = oW * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
        }
    }
    

How do I subscribe to all topics of a MQTT broker

Subscribing to # gives you a subscription to everything except for topics that start with a $ (these are normally control topics anyway).

It is better to know what you are subscribing to first though, of course, and note that some broker configurations may disallow subscribing to # explicitly.

Method call if not null in C#

Cerating extention method like one suggested does not really solve issues with race conditions, but rather hide them.

public static void SafeInvoke(this EventHandler handler, object sender)
{
    if (handler != null) handler(sender, EventArgs.Empty);
}

As stated this code is the elegant equivalent to solution with temporary variable, but...

The problem with both that it's possible that subsciber of the event could be called AFTER it has unsubscribed from the event. This is possible because unsubscription can happen after delegate instance is copied to the temp variable (or passed as parameter in the method above), but before delegate is invoked.

In general the behaviour of the client code is unpredictable in such case: component state could not allow to handle event notification already. It's possible to write client code in the way to handle it, but it would put unnecesssary responsibility to the client.

The only known way to ensure thread safity is to use lock statement for the sender of the event. This ensures that all subscriptions\unsubscriptions\invocation are serialized.

To be more accurate lock should be applied to the same sync object used in add\remove event accessor methods which is be default 'this'.

date format yyyy-MM-ddTHH:mm:ssZ

"o" format is different for DateTime vs DateTimeOffset :(

DateTime.UtcNow.ToString("o") -> "2016-03-09T03:30:25.1263499Z"

DateTimeOffset.UtcNow.ToString("o") -> "2016-03-09T03:30:46.7775027+00:00"

My final answer is

DateTimeOffset.UtcDateTime.ToString("o")   //for DateTimeOffset type
DateTime.UtcNow.ToString("o")              //for DateTime type

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

How to reload/refresh an element(image) in jQuery

To bypass caching and avoid adding infinite timestamps to the image url, strip the previous timestamp before adding a new one, this is how I've done it.

//refresh the image every 60seconds
var xyro_refresh_timer = setInterval(xyro_refresh_function, 60000);

function xyro_refresh_function(){
//refreshes an image with a .xyro_refresh class regardless of caching
    //get the src attribute
    source = jQuery(".xyro_refresh").attr("src");
    //remove previously added timestamps
    source = source.split("?", 1);//turns "image.jpg?timestamp=1234" into "image.jpg" avoiding infinitely adding new timestamps
    //prep new src attribute by adding a timestamp
    new_source = source + "?timestamp="  + new Date().getTime();
    //alert(new_source); //you may want to alert that during developement to see if you're getting what you wanted
    //set the new src attribute
    jQuery(".xyro_refresh").attr("src", new_source);
}

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

White space showing up on right side of page when background image should extend full length of page

I added:

html,body
{
    width: 100%;
    height: 100%;
    margin: 0px;
    padding: 0px;
    overflow-x: hidden; 
}

into your CSS at the very top above the other classes and it seemed to fix your issue.

Your updated .css file is available here

How to open an elevated cmd using command line for Windows?

Similar to some of the other solutions above, I created an elevate batch file which runs an elevated PowerShell window, bypassing the execution policy to enable running everything from simple commands to batch files to complex PowerShell scripts. I recommend sticking it in your C:\Windows\System32 folder for ease of use.

The original elevate command executes its task, captures the output, closes the spawned PowerShell window and then returns, writing out the captured output to the original window.

I created two variants, elevatep and elevatex, which respectively pause and keep the PowerShell window open for more work.

https://github.com/jt-github/elevate

And in case my link ever dies, here's the code for the original elevate batch file:

@Echo Off
REM Executes a command in an elevated PowerShell window and captures/displays output
REM Note that any file paths must be fully qualified!

REM Example: elevate myAdminCommand -myArg1 -myArg2 someValue

if "%1"=="" (
    REM If no command is passed, simply open an elevated PowerShell window.
    PowerShell -Command "& {Start-Process PowerShell.exe -Wait -Verb RunAs}"
) ELSE (
    REM Copy command+arguments (passed as a parameter) into a ps1 file
    REM Start PowerShell with Elevated access (prompting UAC confirmation)
    REM     and run the ps1 file
    REM     then close elevated window when finished
    REM Output captured results

    IF EXIST %temp%\trans.txt del %temp%\trans.txt
    Echo %* ^> %temp%\trans.txt *^>^&1 > %temp%\tmp.ps1
    Echo $error[0] ^| Add-Content %temp%\trans.txt -Encoding Default >> %temp%\tmp.ps1
    PowerShell -Command "& {Start-Process PowerShell.exe -Wait -ArgumentList '-ExecutionPolicy Bypass -File ""%temp%\tmp.ps1""' -Verb RunAs}"
    Type %temp%\trans.txt
)

Linq to SQL how to do "where [column] in (list of values)"

Use

where list.Contains(item.Property)

Or in your case:

var foo = from codeData in channel.AsQueryable<CodeData>()
          where codeIDs.Contains(codeData.CodeId)
          select codeData;

But you might as well do that in dot notation:

var foo = channel.AsQueryable<CodeData>()
                 .Where(codeData => codeIDs.Contains(codeData.CodeId));

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

Call ASP.NET function from JavaScript?

I think blog post How to fetch & show SQL Server database data in ASP.NET page using Ajax (jQuery) will help you.

JavaScript Code

<script src="http://code.jquery.com/jquery-3.3.1.js" />
<script language="javascript" type="text/javascript">

    function GetCompanies() {
        $("#UpdatePanel").html("<div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCompanies",
            data: "{}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            error: OnError
        });
    }

    function OnSuccess(data) {
        var TableContent = "<table border='0'>" +
                                "<tr>" +
                                    "<td>Rank</td>" +
                                    "<td>Company Name</td>" +
                                    "<td>Revenue</td>" +
                                    "<td>Industry</td>" +
                                "</tr>";
        for (var i = 0; i < data.d.length; i++) {
            TableContent += "<tr>" +
                                    "<td>"+ data.d[i].Rank +"</td>" +
                                    "<td>"+data.d[i].CompanyName+"</td>" +
                                    "<td>"+data.d[i].Revenue+"</td>" +
                                    "<td>"+data.d[i].Industry+"</td>" +
                                "</tr>";
        }
        TableContent += "</table>";

        $("#UpdatePanel").html(TableContent);
    }

    function OnError(data) {

    }
</script>

ASP.NET Server Side Function

[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static List<TopCompany> GetCompanies()
{
    System.Threading.Thread.Sleep(5000);
    List<TopCompany> allCompany = new List<TopCompany>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        allCompany = dc.TopCompanies.ToList();
    }
    return allCompany;
}

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

Facebook key hash does not match any stored key hashes

What I found was that my SHA-1 that was used to sign the app to be uploaded to the Google Playstore was not correct. I realized that my app was being signed by the Google Play Store with a different token. I followed these steps:

  1. Go to Google Play Console
  2. Click Release Management
  3. Click App Signing
  4. Convert App-Signing Certificate SHA-1 to Base64 (this will be different than your current upload certificate)
  5. Enter Base64 converted SHA-1 into my Facebook Developer dashboard settings

    I am now able to log into my app when the Facebook is downloaded on and Android device.

MySQL FULL JOIN?

Hm, combining LEFT and RIGHT JOIN with UNION could do this:

SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p
LEFT JOIN
        orders AS o
ON      p.P_Id = Orders.P_Id
UNION ALL
SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p 
RIGHT JOIN
        orders AS o
ON      p.P_Id = Orders.P_Id
WHERE   p.P_Id IS NULL

How to chain scope queries with OR instead of AND?

Just posting the Array syntax for same column OR queries to help peeps out.

Person.where(name: ["John", "Steve"])

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

How to get terminal's Character Encoding

The terminal uses environment variables to determine which character set to use, therefore you can determine it by looking at those variables:

echo $LC_CTYPE

or

echo $LANG

Why am I getting this redefinition of class error?

the implementation in the cpp file should be in the form

gameObject::gameObject()
    {
    x = 0;
    y = 0;
    }
gameObject::gameObject(int inx, int iny)
    {
        x = inx;
        y = iny;
    }

gameObject::~gameObject()
    {
    //
    }
int gameObject::add()
    {
        return x+y;
    }

not within a class gameObject { } definition block

Can I invoke an instance method on a Ruby module without including it?

As I understand the question, you want to mix some of a module's instance methods into a class.

Let's begin by considering how Module#include works. Suppose we have a module UsefulThings that contains two instance methods:

module UsefulThings
  def add1
    self + 1
  end
  def add3
    self + 3
  end
end

UsefulThings.instance_methods
  #=> [:add1, :add3]

and Fixnum includes that module:

class Fixnum
  def add2
    puts "cat"
  end
  def add3
    puts "dog"
  end
  include UsefulThings
end

We see that:

Fixnum.instance_methods.select { |m| m.to_s.start_with? "add" }
  #=> [:add2, :add3, :add1] 
1.add1
2 
1.add2
cat
1.add3
dog

Were you expecting UsefulThings#add3 to override Fixnum#add3, so that 1.add3 would return 4? Consider this:

Fixnum.ancestors
  #=> [Fixnum, UsefulThings, Integer, Numeric, Comparable,
  #    Object, Kernel, BasicObject] 

When the class includes the module, the module becomes the class' superclass. So, because of how inheritance works, sending add3 to an instance of Fixnum will cause Fixnum#add3 to be invoked, returning dog.

Now let's add a method :add2 to UsefulThings:

module UsefulThings
  def add1
    self + 1
  end
  def add2
    self + 2
  end
  def add3
    self + 3
  end
end

We now wish Fixnum to include only the methods add1 and add3. Is so doing, we expect to get the same results as above.

Suppose, as above, we execute:

class Fixnum
  def add2
    puts "cat"
  end
  def add3
    puts "dog"
  end
  include UsefulThings
end

What is the result? The unwanted method :add2 is added to Fixnum, :add1 is added and, for reasons I explained above, :add3 is not added. So all we have to do is undef :add2. We can do that with a simple helper method:

module Helpers
  def self.include_some(mod, klass, *args)
    klass.send(:include, mod)
    (mod.instance_methods - args - klass.instance_methods).each do |m|
      klass.send(:undef_method, m)
    end
  end
end

which we invoke like this:

class Fixnum
  def add2
    puts "cat"
  end
  def add3
    puts "dog"
  end
  Helpers.include_some(UsefulThings, self, :add1, :add3)
end

Then:

Fixnum.instance_methods.select { |m| m.to_s.start_with? "add" }
  #=> [:add2, :add3, :add1] 
1.add1
2 
1.add2
cat
1.add3
dog

which is the result we want.

Daemon Threads Explanation

When your second thread is non-Daemon, your application's primary main thread cannot quit because its exit criteria is being tied to the exit also of non-Daemon thread(s). Threads cannot be forcibly killed in python, therefore your app will have to really wait for the non-Daemon thread(s) to exit. If this behavior is not what you want, then set your second thread as daemon so that it won't hold back your application from exiting.

Bootstrap table striped: How do I change the stripe background colour?

.table-striped>tbody>tr:nth-child(odd)>td,
.table-striped>tbody>tr:nth-child(odd)>th {
  background-color: #e08283;
  color: white;
}
.table-striped>tbody>tr:nth-child(even)>td,
.table-striped>tbody>tr:nth-child(even)>th {
  background-color: #ECEFF1;
  color: white;
}

Use 'even' for change colour of even rows and use 'odd' for change colour of odd rows.

Javascript objects: get parent

Many of the answers here involve looping through an object and "manually" (albeit programmatically) creating a parent property that stores the reference to the parent. The two ways of implementing this seem to be...

  1. Use an init function to loop through at the time the nested object is created, or...
  2. Supply the nested object to a function that fills out the parent property

Both approaches have the same issue...

How do you maintain parents as the nested object grows/changes??

If I add a new sub-sub-object, how does it get its parent property filled? If you're (1) using an init function, the initialization is already done and over, so you'd have to (2) pass the object through a function to search for new children and add the appropriate parent property.

Using ES6 Proxy to add parent whenever an object/sub-object is set

The approach below is to create a handler for a proxy always adds a parent property each time an object is set. I've called this handler the parenter handler. The parenter responsibilities are to recognize when an object is being set and then to...

  1. Create a dummy proxy with the appropriate parent and the parenter handler

    var p = new Proxy({parent: target}, parenter);
    
  2. Copy in the supplied objects properties-- Because you're setting the proxy properties in this loop the parenter handler is working recursively; nested objects are given parents at each level

    for(key in value){
        p[key] = value[key];
      }
    
  3. Set the proxy not the supplied object

    return target[prop] = p;
    

Full code

var parenter = {
  set: function(target, prop, value){
    if(typeof value === "object"){
      var p = new Proxy({parent: target}, parenter);
      for(key in value){
        p[key] = value[key];
      }
      return target[prop] = p;
    }else{
      target[prop] = value;
    }
  }
}

var root = new Proxy({}, parenter);

// some examples
root.child1 = {
    color: "red", 
    value: 10, 
    otherObj: { 
       otherColor: "blue", 
       otherValue: 20
    }
}

// parents exist/behave as expected
console.log(root.child1.color)                 // "red"
console.log(root.child1.otherObj.parent.color) // "red"

// new children automatically have correct parent
root.child2 = {color: "green", value3: 50};
console.log(root.child2.parent.child1.color)   // "red"

// changes are detected throughout
root.child1.color = "yellow"
console.log(root.child2.parent.child1.color)   // "yellow"

Notice that all root children always have parent properties, even children that are added later.

ORA-00907: missing right parenthesis

ORA-00907: missing right parenthesis

This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.

Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis and leaves it to us to spot the actual bloomer.

The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.

Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.

In-line declaration doesn't have a comma and doesn't include the referencing column name.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8) 
          CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
    order_id           VARCHAR2 (10) NOT NULL,
          CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)

Table level constraints are a separate component, and so do have a comma and do mention the referencing column.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8),    
    order_id           VARCHAR2 (10) NOT NULL,
    CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,   
   CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)

Here is a list of other syntax errors:

  1. The referenced table (and the referenced primary key or unique constraint) must already exist before we can create a foreign key against them. So you cannot create a foreign key for HISTORYS_T before you have created the referenced ORDERS table.
  2. You have misspelled the names of the referenced tables in some of the foreign key clauses (LIBRARY_T and FORMAT_T).
  3. You need to provide an expression in the DEFAULT clause. For DATE columns that is usually the current date, DATE DEFAULT sysdate.

Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).

As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.

  1. You have not named most of your constraints. Oracle will give them a default name but it will be a horrible one, and makes the data dictionary harder to understand. Explicitly naming every constraint helps us navigate the physical database. It also leads to more comprehensible error messages when our SQL trips a constraint violation.
  2. Name your constraints consistently. HISTORY_T has constraints called historys_T_FK and fk_order_id_orders, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk. So history_customer_fk and history_order_fk respectively.
  3. It can be useful to create the constraints with separate statements. Creating tables then primary keys then foreign keys will avoid the problems with dependency ordering identified above.
  4. You are trying to create cyclic foreign keys between LIBRARY_T and FORMATS. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.
  5. Avoid blank lines in your scripts. Some tools will handle them but some will not. We can configure SQL*Plus to handle them but it's better to avoid the need.
  6. The naming convention of LIBRARY_T is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.
  7. T_CUSTOMERS is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers is not a keyword.

Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS and LIBRARY_T my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_ or a _TAB.

gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

got it setup by simply :

brew uninstall gpg 

brew install gpg2

How to write a large buffer into a binary file in C++, fast?

Could you use FILE* instead, and the measure the performance you've gained? A couple of options is to use fwrite/write instead of fstream:

#include <stdio.h>

int main ()
{
  FILE * pFile;
  char buffer[] = { 'x' , 'y' , 'z' };
  pFile = fopen ( "myfile.bin" , "w+b" );
  fwrite (buffer , 1 , sizeof(buffer) , pFile );
  fclose (pFile);
  return 0;
}

If you decide to use write, try something similar:

#include <unistd.h>
#include <fcntl.h>

int main(void)
{
    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);

    if (filedesc < 0) {
        return -1;
    }

    if (write(filedesc, "This will be output to testfile.txt\n", 36) != 36) {
        write(2, "There was an error writing to testfile.txt\n", 43);
        return -1;
    }

    return 0;
}

I would also advice you to look into memory map. That may be your answer. Once I had to process a 20GB file in other to store it in the database, and the file as not even opening. So the solution as to utilize moemory map. I did that in Python though.

What does MVW stand for?

It stands indeed for whatever, as in whatever works for you

MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.

How does DISTINCT work when using JPA and Hibernate

Update: See the top-voted answer please.

My own is currently obsolete. Only kept here for historical reasons.


Distinct in HQL is usually needed in Joins and not in simple examples like your own.

See also How do you create a Distinct query in HQL

What is the difference between static func and class func in Swift?

Is it simply that static is for static functions of structs and enums, and class for classes and protocols?

That's the main difference. Some other differences are that class functions are dynamically dispatched and can be overridden by subclasses.

Protocols use the class keyword, but it doesn't exclude structs from implementing the protocol, they just use static instead. Class was chosen for protocols so there wouldn't have to be a third keyword to represent static or class.

From Chris Lattner on this topic:

We considered unifying the syntax (e.g. using "type" as the keyword), but that doesn't actually simply things. The keywords "class" and "static" are good for familiarity and are quite descriptive (once you understand how + methods work), and open the door for potentially adding truly static methods to classes. The primary weirdness of this model is that protocols have to pick a keyword (and we chose "class"), but on balance it is the right tradeoff.

And here's a snippet that shows some of the override behavior of class functions:

class MyClass {
    class func myFunc() {
        println("myClass")
    }
}

class MyOtherClass: MyClass {
    override class func myFunc() {
        println("myOtherClass")
    }
}

var x: MyClass = MyOtherClass()
x.dynamicType.myFunc() //myOtherClass
x = MyClass()
x.dynamicType.myFunc() //myClass

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

These commands worked for me

sudo npm cache clean --force

sudo npm cache verify

sudo npm i npm@latest -g

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can use it like this:

In Mvc:

@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});

In Html:

<input type="text" name="Id" data_val_number="10"/>

Finding modified date of a file/folder

If you run the Get-Item or Get-ChildItem commands these will output System.IO.FileInfo and System.IO.DirectoryInfo objects that contain this information e.g.:

Get-Item c:\folder | Format-List  

Or you can access the property directly like so:

Get-Item c:\folder | Foreach {$_.LastWriteTime}

To start to filter folders & files based on last write time you can do this:

Get-ChildItem c:\folder | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

PHP display current server path

here is a test script to run on your server to see what is reliabel.

<?php
$host = gethostname();
$ip = gethostbyname($host);
echo "gethostname and gethostbyname: $host at $ip<br>";
$server = $_SERVER['SERVER_ADDR'];
echo "_SERVER[SERVER_ADDR]: $server<br>";
$my_current_ip=exec("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'");
echo "exec ifconfig ... : $my_current_ip<br>";
$external_ip = file_get_contents("http://ipecho.net/plain");
echo "get contents ipecho.net: $external_ip<br>";
?>

The only different option in there is using fiel_get_contents rather than curl for the extrernal website lookup.

This is the result of hitting the web page on a shared hosting, free account. (actual server name and IP changed)

gethostname and gethostbyname: freesites.servercluster.com at 345.27.413.51
_SERVER[SERVER_ADDR]: 127.0.0.7
exec ifconfig ... :
get contents ipecho.net: 345.27.413.51

Why needed this? Decided to point A record at server to see if it opens the web page. Later ran script to save ip and update on ghost site on same server to lookup IP and alert if changed.

In this case, good results optained by:

gethostname() & 
gethostbyname($host)
or 
file_get_contents("http://ipecho.net/plain")

How to get system time in Java without creating a new Date

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

What does EntityManager.flush do and why do I need to use it?

So when you call EntityManager.persist(), it only makes the entity get managed by the EntityManager and adds it (entity instance) to the Persistence Context. An Explicit flush() will make the entity now residing in the Persistence Context to be moved to the database (using a SQL).

Without flush(), this (moving of entity from Persistence Context to the database) will happen when the Transaction to which this Persistence Context is associated is committed.

Font Awesome & Unicode

I got a simillary problem using unicode and fontawesome. when i wrote :

font-family: 'Font Awesome\ 5 Free';
content: "\f061"; /* FontAwesome Unicode */

On google chrome, a square appear instead of the icon. The new version of Font Awesome also requires

font-weight: 900;

That's work for me.

From : https://github.com/FortAwesome/Font-Awesome/issues/11946

Hope that's will help.

Replace whitespace with a comma in a text file in Linux

This command should work:

sed "s/\s/,/g" < infile.txt > outfile.txt

Note that you have to redirect the output to a new file. The input file is not changed in place.

how to set value of a input hidden field through javascript?

It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/

Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value. You have to wrap in the input in a <form> tag like with the proper name attribute, like shown below:

<form name="FormName">
    <input type="hidden" name="checkyear" id="checkyear" value="">
</form>

Have you considered using the jQuery Library? Here are the docs for .val() function.

How can I check if my Element ID has focus?

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

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

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

And then you can simply

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

Or use the

$(document.activeElement)

As been suggested previously.

How to use this boolean in an if statement?

= is for assignment

write

if(stop){
   //your code
}

or

if(stop == true){
   //your code
}

Run a .bat file using python code

If you are trying to call another exe file inside the bat-file. You must use SET Path inside the bat-file that you are calling. set Path should point into the directory there the exe-file is located:

set PATH=C:\;C:\DOS     {Sets C:\;C:\DOS as the current search path.} 

How can I stop the browser back button using JavaScript?

<html>
<head>
    <title>Disable Back Button in Browser - Online Demo</title>
    <style type="text/css">
        body, input {
            font-family: Calibri, Arial;
        }
    </style>
    <script type="text/javascript">
        window.history.forward();
        function noBack() {
            window.history.forward();
        }
    </script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <H2>Demo</H2>
    <p>This page contains the code to avoid Back button.</p>
    <p>Click here to Goto <a href="noback.html">NoBack Page</a></p>
</body>
</html>

Android splash screen image sizes to fit all devices

Using PNG is not such a good idea. Actually it's costly as far as performance is concerned. You can use drawable XML files, for example, Facebook's background.

This will help you to smooth and speed up your performance, and for the logo use .9 patch images.

SQL split values to multiple rows

Best Practice. Result:

SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX('ab,bc,cd',',',help_id+1),',',-1) AS oid
FROM
(
SELECT @xi:=@xi+1 as help_id from 
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc2,
(SELECT @xi:=-1) xc0
) a
WHERE 
help_id < LENGTH('ab,bc,cd')-LENGTH(REPLACE('ab,bc,cd',',',''))+1

First, create a numbers table:

SELECT @xi:=@xi+1 as help_id from 
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc2,
(SELECT @xi:=-1) xc0;
| help_id  |
| --- |
| 0   |
| 1   |
| 2   |
| 3   |
| ...   |
| 24   |

Second, just split the str:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('ab,bc,cd',',',help_id+1),',',-1) AS oid
FROM
numbers_table
WHERE
help_id < LENGTH('ab,bc,cd')-LENGTH(REPLACE('ab,bc,cd',',',''))+1
| oid  |
| --- |
| ab   |
| bc   |
| cd   |

How can I open multiple files using "with open" in Python?

Just replace and with , and you're done:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

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.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

I am using Spring Boot 5. I have this controller that I want an unauthenticated user to invoke.

  //Builds a form to send to devices   
@RequestMapping(value = "/{id}/ViewFormit", method = RequestMethod.GET)
@ResponseBody
String doFormIT(@PathVariable String id) {
    try
    {
        //Get a list of forms applicable to the current user
        FormService parent = new FormService();

Here is what i did in the configuuration.

  @Override
   protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers(
                    "/registration**",
                    "/{^[\\\\d]$}/ViewFormit",

Hope this helps....

Java: get greatest common divisor

Unless I have Guava, I define like this:

int gcd(int a, int b) {
  return a == 0 ? b : gcd(b % a, a);
}

Bootstrap 3 grid with no gap

The grid system in Bootstrap 3 requires a bit of a lateral shift in your thinking from Bootstrap 2. A column in BS2 (col-*) is NOT synonymous with a column in BS3 (col-sm-*, etc), but there is a way to achieve the same result.

Check out this update to your fiddle: http://jsfiddle.net/pjBzY/22/ (code copied below).

First of all, you don't need to specify a col for each screen size if you want 50/50 columns at all sizes. col-sm-6 applies not only to small screens, but also medium and large, meaning class="col-sm-6 col-md-6" is redundant (the benefit comes in if you want to change the column widths at different size screens, such as col-sm-6 col-md-8).

As for the margins issue, the negative margins provide a way to align blocks of text in a more flexible way than was possible in BS2. You'll notice in the jsfiddle, the text in the first column aligns visually with the text in the paragraph outside the row -- except at "xs" window sizes, where the columns aren't applied.

If you need behavior closer to what you had in BS2, where there is padding between each column and there are no visual negative margins, you will need to add an inner-div to each column. See the inner-content in my jsfiddle. Put something like this in each column, and they will behave the way old col-* elements did in BS2.


jsfiddle HTML

<div class="container">
    <p class="other-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquam sed sem nec viverra. Phasellus fringilla metus vitae libero posuere mattis. Integer sit amet tincidunt felis. Maecenas et pharetra leo. Etiam venenatis purus et nibh laoreet blandit.</p>
    <div class="row">
        <div class="col-sm-6 my-column">
            Col 1
            <p class="inner-content">Inner content - THIS element is more synonymous with a Bootstrap 2 col-*.</p>
        </div>
        <div class="col-sm-6 my-column">
            Col 2
        </div>
    </div>
</div>

and the CSS

.row {
    border: blue 1px solid;
}
.my-column {
    background-color: green;
    padding-top: 10px;
    padding-bottom: 10px;
}
.my-column:first-child {
    background-color: red;
}

.inner-content {
    background: #eee;
    border: #999;
    border-radius: 5px;
    padding: 15px;
}

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

File > Workspace Settings > Build System > Legacy Build System

This worked for me. Xcode 10.0

Checking if a textbox is empty in Javascript

your validation should be occur before your event suppose you are going to submit your form.

anyway if you want this on onchange, so here is code.

function valid(id)
{
    var textVal=document.getElementById(id).value;
    if (!textVal.match(/\S/)) 
    {
        alert("Field is blank");
        return false;
    } 
    else 
    {
        return true;
    }
 }

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

Setting a system environment variable from a Windows batch file?

For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

Android Device not recognized by adb

Generally, I think your USB connection should be set to use MTP (Media Transfer), however, I couldn't get my computer to recognize my device (Nexus 4). Oddly, setting the USB connection to Camera got it working for me.

Why can't I define my workbook as an object?

It's actually a sensible question. Here's the answer from Excel 2010 help:

"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."

So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:

Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")

Difference between <span> and <div> with text-align:center;?

Like other have said, span is an in-line element.

See here: http://www.w3.org/TR/CSS2/visuren.html

Additionally, you can make a span behave like a div by applying a

style="display: block; margin: 0px auto; text-align: center;"

All ASP.NET Web API controllers return 404

I have solved similar problem by attaching with debugger to application init. Just start webserver (for example, access localhost), attach to w3wp and see, if app initialization finished correctly. In my case there was exception, and controllers was not registered.

What is the difference between single and double quotes in SQL?

Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database.

Stick to using single quotes.

That's the primary use anyway. You can use single quotes for a column alias — where you want the column name you reference in your application code to be something other than what the column is actually called in the database. For example: PRODUCT.id would be more readable as product_id, so you use either of the following:

  • SELECT PRODUCT.id AS product_id
  • SELECT PRODUCT.id 'product_id'

Either works in Oracle, SQL Server, MySQL… but I know some have said that the TOAD IDE seems to give some grief when using the single quotes approach.

You do have to use single quotes when the column alias includes a space character, e.g., product id, but it's not recommended practice for a column alias to be more than one word.

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

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

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

I was also facing the same error. The reason for this is that there is no smtp server on your environment. For creating a fake smtp server I used this fake-smtp.jar file for creating a virtual server and listening to all the requests. If you are facing the same error, I recommend you to use this jar and run it after extracting and then try to run your application.

Download latest version of fake smtp

How to clear a chart from a canvas so that hover events cannot be triggered?

I have faced the same problem few hours ago.

The ".clear()" method actually clears the canvas, but (evidently) it leaves the object alive and reactive.

Reading carefully the official documentation, in the "Advanced usage" section, I have noticed the method ".destroy()", described as follows:

"Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js."

It actually does what it claims and it has worked fine for me, I suggest you to give it a try.

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

Use css gradient over background image

_x000D_
_x000D_
#multiple-background{_x000D_
 box-sizing: border-box;_x000D_
 width: 123px;_x000D_
 height: 30px;_x000D_
 font-size: 12pt;_x000D_
 border-radius: 7px;  _x000D_
 background: url("https://cdn0.iconfinder.com/data/icons/woocons1/Checkbox%20Full.png"), linear-gradient(to bottom, #4ac425, #4ac425);_x000D_
 background-repeat: no-repeat, repeat;_x000D_
 background-position: 5px center, 0px 0px;_x000D_
    background-size: 18px 18px, 100% 100%;_x000D_
 color: white; _x000D_
 border: 1px solid #e4f6df;_x000D_
 box-shadow: .25px .25px .5px .5px black;_x000D_
 padding: 3px 10px 0px 5px;_x000D_
 text-align: right;_x000D_
 }
_x000D_
<div id="multiple-background"> Completed </div>
_x000D_
_x000D_
_x000D_

How to get next/previous record in MySQL?

How to get next/previous record in MySQL & PHP?

My example is to get the id only

function btn_prev(){

  $id = $_POST['ids'];
  $re = mysql_query("SELECT * FROM table_name WHERE your_id < '$id'  ORDER BY your_id DESC LIMIT 1");

  if(mysql_num_rows($re) == 1)
  {
    $r = mysql_fetch_array($re);
    $ids = $r['your_id'];
    if($ids == "" || $ids == 0)
    {
        echo 0;
    }
    else
    {
        echo $ids;
    }
  }
  else
  {
    echo 0;
  }
}



function btn_next(){

  $id = $_POST['ids'];
  $re = mysql_query("SELECT * FROM table_name WHERE your_id > '$id'  ORDER BY your_id ASC LIMIT 1");

  if(mysql_num_rows($re) == 1)
  {
    $r = mysql_fetch_array($re);
    $ids = $r['your_id'];
    if($ids == "" || $ids == 0)
    {
        echo 0;
    }
    else
    {
        echo $ids;
    }
  }
  else
  {
    echo 0;
  }
}

How to have git log show filenames like svn log -v

Another useful command would be git diff-tree <hash> where hash can be also a hash range (denoted by <old>..<new>notation). An output example:

$ git diff-tree  HEAD
:040000 040000 8e09a be406 M myfile

The fields are:

source mode, dest mode, source hash, dest hash, status, filename

Statuses are the ones you would expect: D (deleted), A (added), M (modified) etc. See man page for full description.

Http Post With Body

You can use HttpClient and HttpPost to send a json string as body:

public void post(String completeUrl, String body) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(completeUrl);
    httpPost.setHeader("Content-type", "application/json");
    try {
        StringEntity stringEntity = new StringEntity(body);
        httpPost.getRequestLine();
        httpPost.setEntity(stringEntity);

        httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Json body example:

{
  "param1": "value 1",
  "param2": 123,
  "testStudentArray": [
    {
      "name": "Test Name 1",
      "gpa": 3.5
    },
    {
      "name": "Test Name 2",
      "gpa": 3.8
    }
  ]
}

How can I show/hide a specific alert with twitter bootstrap?

You can simply use id(#)selector like this.

 $('#passwordsNoMatchRegister').show();
 $('#passwordsNoMatchRegister').hide();