Programs & Examples On #Nowdoc

Reference — What does this symbol mean in PHP?

== is used for check equality without considering variable data-type

=== is used for check equality for both the variable value and data-type

Example

$a = 5

  1. if ($a == 5) - will evaluate to true

  2. if ($a == '5') - will evaluate to true, because while comparing this both value PHP internally convert that string value into integer and then compare both values

  3. if ($a === 5) - will evaluate to true

  4. if ($a === '5') - will evaluate to false, because value is 5, but this value 5 is not an integer.

Android - drawable with rounded corners at the top only

In my case below code

    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="10dp" android:bottom="-10dp"
        >

        <shape android:shape="rectangle">
            <solid android:color="@color/maincolor" />

            <corners
                android:topLeftRadius="10dp"
                android:topRightRadius="10dp"
                android:bottomLeftRadius="0dp"
                android:bottomRightRadius="0dp"
            />
        </shape>

    </item>
    </layer-list>

How to pause a vbscript execution?

You can use a WScript object and call the Sleep method on it:

Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds

Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000

adding a datatable in a dataset

I assume that you haven't set the TableName property of the DataTable, for example via constructor:

var tbl = new DataTable("dtImage");

If you don't provide a name, it will be automatically created with "Table1", the next table will get "Table2" and so on.

Then the solution would be to provide the TableName and then check with Contains(nameOfTable).

To clarify it: You'll get an ArgumentException if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException if there's already a DataTable in the DataSet with the same name(not case-sensitive).

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

View array in Visual Studio debugger?

I use the ArrayDebugView add-in for Visual Studio (http://arraydebugview.sourceforge.net/).

It seems to be a long dead project (but one I'm looking at continuing myself) but the add-in still works beautifully for me in VS2010 for both C++ and C#.

It has a few quirks (tab order, modal dialog, no close button) but the ability to plot the contents of an array in a graph more than make up for it.

Edit July 2014: I have finally built a new Visual Studio extension to replace ArrayebugView's functionality. It is available on the VIsual Studio Gallery, search for ArrayPlotter or go to http://visualstudiogallery.msdn.microsoft.com/2fde2c3c-5b83-4d2a-a71e-5fdd83ce6b96?SRC=Home

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

Your problem is that you have declare twice the exec-maven-plugin :

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-  
      integration\src\main\java\example\Main< /mainClass>
    </configuration>
</plugin>

...

< plugin>
    < groupId>org.codehaus.mojo</groupId>
    < artifactId>exec-maven-plugin</artifactId>
    < version>1.2</version>
< /plugin>

Convert PDF to clean SVG?

Inkscape is used by many people on Wikipedia to convert PDF to SVG.

http://inkscape.org/

They even have a handy guide on how to do so!

http://en.wikipedia.org/wiki/Wikipedia:Graphic_Lab/Resources/PDF_conversion_to_SVG#Conversion_with_Inkscape

Comprehensive methods of viewing memory usage on Solaris

The command free is nice. Takes a short while to understand the "+/- buffers/cache", but the idea is that cache and buffers doesn't really count when evaluating "free", as it can be dumped right away. Therefore, to see how much free (and used) memory you have, you need to remove the cache/buffer usage - which is conveniently done for you.

basic authorization command for curl

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" http://localhost:7990/rest/api/1.0/projects

--note

base46 encode =ZnJlZDpmcmVk

filters on ng-model in an input

Use a directive which adds to both the $formatters and $parsers collections to ensure that the transformation is performed in both directions.

See this other answer for more details including a link to jsfiddle.

How to convert Calendar to java.sql.Date in Java?

Converting is easy, setting date and time is a little tricky. Here's an example:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()));

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

For me, I had to remove the intellij internal sdk and started to use my local sdk. When I started to use the internal, the error was gone.

my sdks

React - changing an uncontrolled input

Simply create a fallback to '' if the this.state.name is null.

<input name="name" type="text" value={this.state.name || ''} onChange={this.onFieldChange('name').bind(this)}/>

This also works with the useState variables.

An App ID with Identifier '' is not available. Please enter a different string

Version 7.3 (7D175)

The Application ID Name should be same as application bundle identifier, if you application bundle identifier is com.abc.xyz than the application ID name for this bundle ID should be XC com abc xyz

enter image description here

A name in any other format won't be seen by Xcode.

How can I get client information such as OS and browser

Here's my code that works, as of today, with some of the latest browsers.

Naturally, it will break as User-Agent's evolve, but it's simple, and easy to fix.

    String userAgent = "Unknown";
    String osType = "Unknown";
    String osVersion = "Unknown";
    String browserType = "Unknown";
    String browserVersion = "Unknown";
    String deviceType = "Unknown";

    try {
        userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";
        //userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/15E148 Safari/604.1";
        boolean exceptionTest = false;
        if(exceptionTest) throw new Exception("EXCEPTION TEST");

        if (userAgent.indexOf("Windows NT") >= 0) {
            osType = "Windows";
            osVersion = userAgent.substring(userAgent.indexOf("Windows NT ")+11, userAgent.indexOf(";"));

        } else if (userAgent.indexOf("Mac OS") >= 0) {
            osType = "Mac";
            osVersion = userAgent.substring(userAgent.indexOf("Mac OS ")+7, userAgent.indexOf(")"));

            if(userAgent.indexOf("iPhone") >= 0) {
                deviceType = "iPhone";
            } else if(userAgent.indexOf("iPad") >= 0) {
                deviceType = "iPad";
            }

        } else if (userAgent.indexOf("X11") >= 0) {
            osType = "Unix";
            osVersion = "Unknown";

        } else if (userAgent.indexOf("android") >= 0) {
            osType = "Android";
            osVersion = "Unknown";
        }
        logger.trace("end of os section");

        if (userAgent.contains("Edge/")) {
            browserType = "Edge";
            browserVersion = userAgent.substring(userAgent.indexOf("Edge")).split("/")[1];

        } else if (userAgent.contains("Safari/") && userAgent.contains("Version/")) {
            browserType = "Safari";
            browserVersion = userAgent.substring(userAgent.indexOf("Version/")+8).split(" ")[0];

        } else if (userAgent.contains("OPR/") || userAgent.contains("Opera/")) {
            browserType = "Opera";
            browserVersion = userAgent.substring(userAgent.indexOf("OPR")).split("/")[1];

        } else if (userAgent.contains("Chrome/")) {
            browserType = "Chrome"; 
            browserVersion = userAgent.substring(userAgent.indexOf("Chrome")).split("/")[1];
            browserVersion = browserVersion.split(" ")[0];

        } else if (userAgent.contains("Firefox/")) {
            browserType = "Firefox"; 
            browserVersion = userAgent.substring(userAgent.indexOf("Firefox")).split("/")[1];
        }            
        logger.trace("end of browser section");

    } catch (Exception ex) {
        logger.error("ERROR: " +ex);            
    }

    logger.debug(
              "\n userAgent: " + userAgent
            + "\n osType: " + osType
            + "\n osVersion: " + osVersion
            + "\n browserType: " + browserType
            + "\n browserVersion: " + browserVersion
            + "\n deviceType: " + deviceType
            );

Logger Output:

 userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165
 osType: Windows
 osVersion: 10.0
 browserType: Opera
 browserVersion: 60.0.3255.165
 deviceType: Unknown

\n or \n in php echo not print

Better use PHP_EOL ("End Of Line") instead. It's cross-platform.

E.g.:

$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';

Populate XDocument from String

You can use XDocument.Parse(string) instead of Load(string).

iOS start Background Thread

Swift 2.x answer:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        self.getResultSetFromDB(docids)
    }

Remove an element from a Bash array

This is a quick-and-dirty solution that will work in simple cases but will break if (a) there are regex special characters in $delete, or (b) there are any spaces at all in any items. Starting with:

array+=(pluto)
array+=(pippo)
delete=(pluto)

Delete all entries exactly matching $delete:

array=(`echo $array | fmt -1 | grep -v "^${delete}$" | fmt -999999`)

resulting in echo $array -> pippo, and making sure it's an array: echo $array[1] -> pippo

fmt is a little obscure: fmt -1 wraps at the first column (to put each item on its own line. That's where the problem arises with items in spaces.) fmt -999999 unwraps it back to one line, putting back the spaces between items. There are other ways to do that, such as xargs.

Addendum: If you want to delete just the first match, use sed, as described here:

array=(`echo $array | fmt -1 | sed "0,/^${delete}$/{//d;}" | fmt -999999`)

How to deploy a Java Web Application (.war) on tomcat?

  • copy the .war file in the webapps folder
  • upload the file using the manager application - http://host:port/manager. You will have to setup some users beforehand.
  • (not recommended, but working) - manually extract the .war file as a .zip archive and place the extracted files in webapps/webappname

Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:

After you have it deployed (check the /logs dir for any problems), it should be accessible via: http://host:port/yourwebappname/. So in your case, one of those:

http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/

If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How to add anything in <head> through jquery/javascript?

jQuery

$('head').append( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

Strangest language feature

Feature: Bash, the Korn shell (ksh93) and the Z shell each allow subscripting arrays with variables with or without a dollar sign:

array[index]=$value
array[$index]=$value

This, with the dollar sign, will produce the expected value of 10000:

unset array
for i in {1..10000}
do
    ((array[$RANDOM%6+1]++))
done
unset total
for count in ${array[@]}
do
    ((total += count))
done
echo $total

Strangeness: If you remove the dollar sign from RANDOM, the total will vary randomly, even to be greater than 10000.

Similarly, this produces 3 instead of 2:

a=1; ((r[a++]++)); echo $a

And you can't use a dollar sign there because it's an assignment (a is on the lhs), although you could do it if you were using indirection, but the double evaluation still occurs.

The Reason: With the dollar sign, the variable expansion is performed before the arithmetic evaluation so only gets done once. Without the dollar sign, it's performed twice, once to calculate the index for the lookup and again to calculate the index for the assignment (so, in effect, an assignment at one step in the loop might look like array[4] = $array[6] + 1 which totally scrambles the array).

Getting CheckBoxList Item values

Instead of this:

CheckboxList1.Items[i].value;

Try This:

CheckboxList1.Items[i].ToString();

It worked for me :)

VBA: Conditional - Is Nothing

Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.

Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.

Sub test()

Dim dict As Object
Set dict = CreateObject("scripting.dictionary")

If Not dict Is Nothing Then
    MsgBox "Dict is something!"  '<--- This shows
Else
    MsgBox "Dict is nothing!"
End If

End Sub

However if you declare an object but never create it, it's nothing.

Sub test()

Dim temp As Object

If Not temp Is Nothing Then
    MsgBox "Temp is something!"
Else
    MsgBox "Temp is nothing!" '<---- This shows
End If

End Sub

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

How do I sort an NSMutableArray with custom objects in it?

See the NSMutableArray method sortUsingFunction:context:

You will need to set up a compare function which takes two objects (of type Person, since you are comparing two Person objects) and a context parameter.

The two objects are just instances of Person. The third object is a string, e.g. @"birthDate".

This function returns an NSComparisonResult: It returns NSOrderedAscending if PersonA.birthDate < PersonB.birthDate. It will return NSOrderedDescending if PersonA.birthDate > PersonB.birthDate. Finally, it will return NSOrderedSame if PersonA.birthDate == PersonB.birthDate.

This is rough pseudocode; you will need to flesh out what it means for one date to be "less", "more" or "equal" to another date (such as comparing seconds-since-epoch etc.):

NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
  if ([firstPerson birthDate] < [secondPerson birthDate])
    return NSOrderedAscending;
  else if ([firstPerson birthDate] > [secondPerson birthDate])
    return NSOrderedDescending;
  else 
    return NSOrderedSame;
}

If you want something more compact, you can use ternary operators:

NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
  return ([firstPerson birthDate] < [secondPerson birthDate]) ? NSOrderedAscending : ([firstPerson birthDate] > [secondPerson birthDate]) ? NSOrderedDescending : NSOrderedSame;
}

Inlining could perhaps speed this up a little, if you do this a lot.

Can I create a One-Time-Use Function in a Script or Stored Procedure?

The below is what I have used i the past to accomplish the need for a Scalar UDF in MS SQL:

IF OBJECT_ID('tempdb..##fn_Divide') IS NOT NULL DROP PROCEDURE ##fn_Divide
GO
CREATE PROCEDURE ##fn_Divide (@Numerator Real, @Denominator Real) AS
BEGIN
    SELECT Division =
        CASE WHEN @Denominator != 0 AND @Denominator is NOT NULL AND  @Numerator != 0 AND @Numerator is NOT NULL THEN
        @Numerator / @Denominator
        ELSE
            0
        END
    RETURN
END
GO

Exec ##fn_Divide 6,4

This approach which uses a global variable for the PROCEDURE allows you to make use of the function not only in your scripts, but also in your Dynamic SQL needs.

LINQ select one field from list of DTO objects to array

I think you're looking for;

  string[] skus = myLines.Select(x => x.Sku).ToArray();

However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray() bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;

  var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>

  foreach (string sku in skus) // forces execution of the query

Java Minimum and Maximum values in Array

You can try this too, If you don't want to do this by your method.

    Arrays.sort(arr);
    System.out.println("Min value "+arr[0]);
    System.out.println("Max value "+arr[arr.length-1]);

What does it mean to "call" a function in Python?

when you invoke a function , it is termed 'calling' a function . For eg , suppose you've defined a function that finds the average of two numbers like this-

def avgg(a,b) :
        return (a+b)/2;

now, to call the function , you do like this .

x=avgg(4,6)
print x

value of x will be 5 .

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

With Nodejs, if you are using routers, make sure to add cors before the routers. Otherwise, you'll still get the cors error. Like below:

const cors = require('cors');

const userRouter = require('./routers/user');

expressApp = express();
expressApp.use(cors());
expressApp.use(express.json());
expressApp.use(userRouter);

How to resolve the C:\fakepath?

seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path

How to preview selected image in input type="file" in popup using jQuery?

You can use URL.createObjectURL

_x000D_
_x000D_
    function img_pathUrl(input){
        $('#img_url')[0].src = (window.URL ? URL : webkitURL).createObjectURL(input.files[0]);
    }
_x000D_
#img_url {
  background: #ddd;
  width:100px;
  height: 90px;
  display: block;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="" id="img_url" alt="your image">
<br>
<input type="file" id="img_file" onChange="img_pathUrl(this);">
_x000D_
_x000D_
_x000D_

SQL Server Insert if not exists

As explained in below code: Execute below queries and verify yourself.

CREATE TABLE `table_name` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `tele` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

Insert a record:

INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_name WHERE name = 'Nazir'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0

SELECT * FROM `table_name`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Nazir  | Kolkata   | 033  |
+----+--------+-----------+------+

Now, try to insert the same record again:

INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_name WHERE name = 'Nazir'
) LIMIT 1;

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Nazir  | Kolkata   | 033  |
+----+--------+-----------+------+

Insert a different record:

INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Santosh', 'Kestopur', '044') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_name WHERE name = 'Santosh'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0

SELECT * FROM `table_name`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Nazir  | Kolkata   | 033  |
|  2 | Santosh| Kestopur  | 044  |
+----+--------+-----------+------+

Passing arguments to an interactive program non-interactively

You can also use printf to pipe the input to your script.

var=val
printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Chrome needs a user interaction for the video to be autoplayed or played via js (video.play()). But the interaction can be of any kind, in any moment. If you just click random on the page, the video will autoplay. I resolved then, adding a button (only on chrome browsers) that says "enable video autoplay". The button does nothing, but just clicking it, is the required user interaction for any further video.

convert htaccess to nginx

You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :

$content = $_POST['content'];

    $lines   = explode(PHP_EOL, $content);
    $results = '';

    foreach($lines as $line)
    {
        $items = explode(' ', $line);

        $q = str_replace("^", "^/", $items[1]);

        if (substr($q, strlen($q) - 1) !== '$') $q .= '$';

        $buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';

        $results .= $buffer.PHP_EOL;
    }

    die($results);

ASP.NET Web Api: The requested resource does not support http method 'GET'

Replace the following code in this path

Path :

App_Start => WebApiConfig.cs

Code:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}/{Param}",
            defaults: new { id = RouteParameter.Optional,
                            Param = RouteParameter.Optional }
                          );

Python error when trying to access list by index - "List indices must be integers, not str"

Were you expecting player to be a dict rather than a list?

>>> player=[1,2,3]
>>> player["score"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> player={'score':1, 'age': 2, "foo":3}
>>> player['score']
1

Replacing few values in a pandas dataframe column with another value

This solution will change the existing dataframe itself:

mydf = pd.DataFrame({"BrandName":["A", "B", "ABC", "D", "AB"], "Speciality":["H", "I", "J", "K", "L"]})
mydf["BrandName"].replace(["ABC", "AB"], "A", inplace=True)

MySQL load NULL values from CSV data

Converted the input file to include \N for the blank column data using the below sed command in UNix terminal:

sed -i 's/,,/,\\N,/g' $file_name

and then use LOAD DATA INFILE command to load to mysql

What is the purpose of flush() in Java streams?

From the docs of the flush method:

Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.

Manipulate a url string by adding GET parameters

another improved function version. Mix of existing answers with small improvements (port support) and bugfixes (checking keys properly).

/**
 * @param string $url original url to modify - can be relative, partial etc
 * @param array $paramsOverride associative array, can be empty
 * @return string modified url
 */
protected function overrideUrlQueryParams($url, $paramsOverride){
    if (!is_array($paramsOverride)){
        return $url;
    }

    $url_parts = parse_url($url);

    if (isset($url_parts['query'])) {
        parse_str($url_parts['query'], $params);
    } else {
        $params = [];
    }

    $params = array_merge($params, $paramsOverride);

    $res = '';

    if(isset($url_parts['scheme'])) {
        $res .= $url_parts['scheme'] . ':';
    }

    if(isset($url_parts['host'])) {
        $res .= '//' . $url_parts['host'];
    }

    if(isset($url_parts['port'])) {
        $res .= ':' . $url_parts['port'];
    }

    if (isset($url_parts['path'])) {
        $res .= $url_parts['path'];
    }

    if (count($params) > 0) {
        $res .= '?' . http_build_query($params);
    }

    return $res;
}

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Because an interface is just a contract. And a class is actually a container for data.

disable textbox using jquery?

HTML

<span id="radiobutt">
  <input type="radio" name="rad1" value="1" />
  <input type="radio" name="rad1" value="2" />
  <input type="radio" name="rad1" value="3" />
</span>
<div>
  <input type="text" id="textbox1" />
  <input type="checkbox" id="checkbox1" />
</div>

Javascript

  $("#radiobutt input[type=radio]").each(function(i){
    $(this).click(function () {
        if(i==2) { //3rd radiobutton
            $("#textbox1").attr("disabled", "disabled"); 
            $("#checkbox1").attr("disabled", "disabled"); 
        }
        else {
            $("#textbox1").removeAttr("disabled"); 
            $("#checkbox1").removeAttr("disabled"); 
        }
      });

  });

How can I do GUI programming in C?

The most famous library to create some GUI in C language is certainly GTK.

With this library you can easily create some buttons (for your example). When a user clicks on the button, a signal is emitted and you can write a handler to do some actions.

How to move the layout up when the soft keyboard is shown android

Put this in your activity declaration in manifest file <activity android:windowSoftInputMode="adjustPan|adjustResize"> </activity>

or if you want you can add in onCreate() method of your activity

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

Python ImportError: No module named wx

Generally, package names in the site-packages folder are intended to be imported using the exact name of the module or subfolder.

If my site-packages folder has a subfolder named "foobar", I would import that package by typing import foobar.

One solution might be to rename site-packages\wx-2.8-msw-unicode to site-packages\wx.

Or you could add C:\Python27\Lib\site-packages\wx-2.8-msw-unicode to your PYTHONPATH environment variable.

Generate a Hash from string in Javascript

Based on accepted answer in ES6. Smaller, maintainable and works in modern browsers.

_x000D_
_x000D_
function hashCode(str) {_x000D_
  return str.split('').reduce((prevHash, currVal) =>_x000D_
    (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);_x000D_
}_x000D_
_x000D_
// Test_x000D_
console.log("hashCode(\"Hello!\"): ", hashCode('Hello!'));
_x000D_
_x000D_
_x000D_

EDIT (2019-11-04):

one-liner arrow function version :

_x000D_
_x000D_
const hashCode = s => s.split('').reduce((a,b) => (((a << 5) - a) + b.charCodeAt(0))|0, 0)_x000D_
_x000D_
// test_x000D_
console.log(hashCode('Hello!'))
_x000D_
_x000D_
_x000D_

Ways to eliminate switch in code

Everybody loves HUGE if else blocks. So easy to read! I am curious as to why you would want to remove switch statements, though. If you need a switch statement, you probably need a switch statement. Seriously though, I'd say it depends on what the code's doing. If all the switch is doing is calling functions (say) you could pass function pointers. Whether it's a better solution is debatable.

Language is an important factor here also, I think.

Get resultset from oracle stored procedure

Hi I know this was asked a while ago but I've just figured this out and it might help someone else. Not sure if this is exactly what you're looking for but this is how I call a stored proc and view the output using SQL Developer.
In SQL Developer when viewing the proc, right click and choose 'Run' or select Ctrl+F11 to bring up the Run PL/SQL window. This creates a template with the input and output params which you need to modify. My proc returns a sys_refcursor. The tricky part for me was declaring a row type that is exactly equivalent to the select stmt / sys_refcursor being returned by the proc:

DECLARE
  P_CAE_SEC_ID_N NUMBER;
  P_FM_SEC_CODE_C VARCHAR2(200);
  P_PAGE_INDEX NUMBER;
  P_PAGE_SIZE NUMBER;
  v_Return sys_refcursor;
  type t_row is record (CAE_SEC_ID NUMBER,FM_SEC_CODE VARCHAR2(7),rownum number, v_total_count number);
  v_rec t_row;

BEGIN
  P_CAE_SEC_ID_N := NULL;
  P_FM_SEC_CODE_C := NULL;
  P_PAGE_INDEX := 0;
  P_PAGE_SIZE := 25;

  CAE_FOF_SECURITY_PKG.GET_LIST_FOF_SECURITY(
    P_CAE_SEC_ID_N => P_CAE_SEC_ID_N,
    P_FM_SEC_CODE_C => P_FM_SEC_CODE_C,
    P_PAGE_INDEX => P_PAGE_INDEX,
    P_PAGE_SIZE => P_PAGE_SIZE,
    P_FOF_SEC_REFCUR => v_Return
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('P_FOF_SEC_REFCUR = ');
  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('sec_id = ' || v_rec.CAE_SEC_ID || 'sec code = ' ||v_rec.FM_SEC_CODE);
  end loop;

END;

How can I use std::maps with user-defined types as key?

The right solution is to Specialize std::less for your class/Struct.

• Basically maps in cpp are implemented as Binary Search Trees.

  1. BSTs compare elements of nodes to determine the organization of the tree.
  2. Nodes who's element compares less than that of the parent node are placed on the left of the parent and nodes whose elements compare greater than the parent nodes element are placed on the right. i.e.

For each node, node.left.key < node.key < node.right.key

Every node in the BST contains Elements and in case of maps its KEY and a value, And keys are supposed to be ordered. More About Map implementation : The Map data Type.

In case of cpp maps , keys are the elements of the nodes and values does not take part in the organization of the tree its just a supplementary data .

So It means keys should be compatible with std::less or operator< so that they can be organized. Please check map parameters.

Else if you are using user defined data type as keys then need to give meaning full comparison semantics for that data type.

Solution : Specialize std::less:

The third parameter in map template is optional and it is std::less which will delegate to operator< ,

So create a new std::less for your user defined data type. Now this new std::less will be picked by std::map by default.

namespace std
{
    template<> struct  less<MyClass>
    {
        bool operator() (const MyClass& lhs, const MyClass& rhs) const
        {
            return lhs.anyMemen < rhs.age;
        }
    };

}

Note: You need to create specialized std::less for every user defined data type(if you want to use that data type as key for cpp maps).

Bad Solution: Overloading operator< for your user defined data type. This solution will also work but its very bad as operator < will be overloaded universally for your data type/class. which is undesirable in client scenarios.

Please check answer Pavel Minaev's answer

how to remove time from datetime

SELECT DATE('2012-11-12 00:00:00');

returns

2012-11-12

text flowing out of div

use overflow:auto it will give a scroller to your text within the div :).

How to retrieve form values from HTTPPOST, dictionary or?

If you want to get the form data directly from Http request, without any model bindings or FormCollection you can use this:

[HttpPost] 
public ActionResult SubmitAction() {

    // This will return an string array of all keys in the form.
    // NOTE: you specify the keys in form by the name attributes e.g:
    // <input name="this is the key" value="some value" type="test" />
    var keys = Request.Form.AllKeys;

    // This will return the value for the keys.
    var value1 = Request.Form.Get(keys[0]);
    var value2 = Request.Form.Get(keys[1]);
}

Algorithm to detect overlapping periods

I don't believe that the framework itself has this class. Maybe a third-party library...

But why not create a Period value-object class to handle this complexity? That way you can ensure other constraints, like validating start vs end datetimes. Something like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Whatever.Domain.Timing {
    public class Period {
        public DateTime StartDateTime {get; private set;}
        public DateTime EndDateTime {get; private set;}

        public Period(DateTime StartDateTime, DateTime EndDateTime) {
            if (StartDateTime > EndDateTime)
                throw new InvalidPeriodException("End DateTime Must Be Greater Than Start DateTime!");
            this.StartDateTime = StartDateTime;
            this.EndDateTime = EndDateTime;
        }


        public bool Overlaps(Period anotherPeriod){
            return (this.StartDateTime < anotherPeriod.EndDateTime && anotherPeriod.StartDateTime < this.EndDateTime)
        }

        public TimeSpan GetDuration(){
            return EndDateTime - StartDateTime;
        }

    }

    public class InvalidPeriodException : Exception {
        public InvalidPeriodException(string Message) : base(Message) { }    
    }
}

That way you will be able to individually compare each period...

How to verify CuDNN installation?

On Ubuntu 20.04LTS:

cat /usr/local/cuda/include/cudnn_version.h | grep CUDNN_MAJOR

returned the expected results

How to set Status Bar Style in Swift 3

Swift 4+

for white statusbar text:

navigationController.navigationBar.barStyle = .blackTranslucent

How to read the Stock CPU Usage data

This should be the Unix load average. Wikipedia has a nice article about this.

The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes

java.lang.IllegalArgumentException: No converter found for return value of type

The issue occurred in my case because spring framework couldn't fetch the properties of nested objects. Getters/Setters is one way of solving. Making the properties public is another quick and dirty solution to validate if this is indeed the problem.

How do I check two or more conditions in one <c:if>?

If you are using JSP 2.0 and above It will come with the EL support: so that you can write in plain english and use and with empty operators to write your test:

<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">

How to create a file on Android Internal Storage?

Hi try this it will create directory + file inside it

File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
    mediaDir.mkdir();
}

File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();

System.out.println("Your file has been written");  

Django - iterate number in for loop of a template

I think you could call the id, like this

{% for days in days_list %}
    <h2># Day {{ days.id }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

If you want to change the permissions of an existing file, use chmod (change mode):

$itWorked = chmod ("/yourdir/yourfile", 0777);

If you want all new files to have certain permissions, you need to look into setting your umode. This is a process setting that applies a default modification to standard modes.

It is a subtractive one. By that, I mean a umode of 022 will give you a default permission of 755 (777 - 022 = 755).

But you should think very carefully about both these options. Files created with that mode will be totally unprotected from changes.

How to change the default GCC compiler in Ubuntu?

Here's a complete example of jHackTheRipper's answer for the TL;DR crowd. :-) In this case, I wanted to run g++-4.5 on an Ubuntu system that defaults to 4.6. As root:

apt-get install g++-4.5
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 100
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.5 50
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 100
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.5 50
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.6 100
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.5 50
update-alternatives --set g++ /usr/bin/g++-4.5
update-alternatives --set gcc /usr/bin/gcc-4.5
update-alternatives --set cpp-bin /usr/bin/cpp-4.5

Here, 4.6 is still the default (aka "auto mode"), but I explicitly switch to 4.5 temporarily (manual mode). To go back to 4.6:

update-alternatives --auto g++
update-alternatives --auto gcc
update-alternatives --auto cpp-bin

(Note the use of cpp-bin instead of just cpp. Ubuntu already has a cpp alternative with a master link of /lib/cpp. Renaming that link would remove the /lib/cpp link, which could break scripts.)

How to sort the letters in a string alphabetically in Python

You can do:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'

How to query data out of the box using Spring data JPA by both Sort and Pageable?

There are two ways to achieve this:

final PageRequest page1 = new PageRequest(
  0, 20, Direction.ASC, "lastName", "salary"
);

final PageRequest page2 = new PageRequest(
  0, 20, new Sort(
    new Order(Direction.ASC, "lastName"), 
    new Order(Direction.DESC, "salary")
  )
);

dao.findAll(page1);

As you can see the second form is more flexible as it allows to define different direction for every property (lastName ASC, salary DESC).

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

How to check the version of scipy

In [95]: import scipy

In [96]: scipy.__version__
Out[96]: '0.12.0'

In [104]: scipy.version.*version?
scipy.version.full_version
scipy.version.short_version
scipy.version.version

In [105]: scipy.version.full_version
Out[105]: '0.12.0'

In [106]: scipy.version.git_revision
Out[106]: 'cdd6b32233bbecc3e8cbc82531905b74f3ea66eb'

In [107]: scipy.version.release
Out[107]: True

In [108]: scipy.version.short_version
Out[108]: '0.12.0'

In [109]: scipy.version.version
Out[109]: '0.12.0'

See SciPy doveloper documentation for reference.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I had the same problem (i.e. indexing with multi-conditions, here it's finding data in a certain date range). The (a-b).any() or (a-b).all() seem not working, at least for me.

Alternatively I found another solution which works perfectly for my desired functionality (The truth value of an array with more than one element is ambigous when trying to index an array).

Instead of using suggested code above, simply using a numpy.logical_and(a,b) would work. Here you may want to rewrite the code as

selected  = r[numpy.logical_and(r["dt"] >= startdate, r["dt"] <= enddate)]

JavaScript ES6 promise for loop

here's my 2 cents worth:

  • resuable function forpromise()
  • emulates a classic for loop
  • allows for early exit based on internal logic, returning a value
  • can collect an array of results passed into resolve/next/collect
  • defaults to start=0,increment=1
  • exceptions thrown inside loop are caught and passed to .catch()

_x000D_
_x000D_
    function forpromise(lo, hi, st, res, fn) {_x000D_
        if (typeof res === 'function') {_x000D_
            fn = res;_x000D_
            res = undefined;_x000D_
        }_x000D_
        if (typeof hi === 'function') {_x000D_
            fn = hi;_x000D_
            hi = lo;_x000D_
            lo = 0;_x000D_
            st = 1;_x000D_
        }_x000D_
        if (typeof st === 'function') {_x000D_
            fn = st;_x000D_
            st = 1;_x000D_
        }_x000D_
        return new Promise(function(resolve, reject) {_x000D_
_x000D_
            (function loop(i) {_x000D_
                if (i >= hi) return resolve(res);_x000D_
                const promise = new Promise(function(nxt, brk) {_x000D_
                    try {_x000D_
                        fn(i, nxt, brk);_x000D_
                    } catch (ouch) {_x000D_
                        return reject(ouch);_x000D_
                    }_x000D_
                });_x000D_
                promise._x000D_
                catch (function(brkres) {_x000D_
                    hi = lo - st;_x000D_
                    resolve(brkres)_x000D_
                }).then(function(el) {_x000D_
                    if (res) res.push(el);_x000D_
                    loop(i + st)_x000D_
                });_x000D_
            })(lo);_x000D_
_x000D_
        });_x000D_
    }_x000D_
_x000D_
_x000D_
    //no result returned, just loop from 0 thru 9_x000D_
    forpromise(0, 10, function(i, next) {_x000D_
        console.log("iterating:", i);_x000D_
        next();_x000D_
    }).then(function() {_x000D_
_x000D_
_x000D_
        console.log("test result 1", arguments);_x000D_
_x000D_
        //shortform:no result returned, just loop from 0 thru 4_x000D_
        forpromise(5, function(i, next) {_x000D_
            console.log("counting:", i);_x000D_
            next();_x000D_
        }).then(function() {_x000D_
_x000D_
            console.log("test result 2", arguments);_x000D_
_x000D_
_x000D_
_x000D_
            //collect result array, even numbers only_x000D_
            forpromise(0, 10, 2, [], function(i, collect) {_x000D_
                console.log("adding item:", i);_x000D_
                collect("result-" + i);_x000D_
            }).then(function() {_x000D_
_x000D_
                console.log("test result 3", arguments);_x000D_
_x000D_
                //collect results, even numbers, break loop early with different result_x000D_
                forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
                    console.log("adding item:", i);_x000D_
                    if (i === 8) return break_("ending early");_x000D_
                    collect("result-" + i);_x000D_
                }).then(function() {_x000D_
_x000D_
                    console.log("test result 4", arguments);_x000D_
_x000D_
                    // collect results, but break loop on exception thrown, which we catch_x000D_
                    forpromise(0, 10, 2, [], function(i, collect, break_) {_x000D_
                        console.log("adding item:", i);_x000D_
                        if (i === 4) throw new Error("failure inside loop");_x000D_
                        collect("result-" + i);_x000D_
                    }).then(function() {_x000D_
_x000D_
                        console.log("test result 5", arguments);_x000D_
_x000D_
                    })._x000D_
                    catch (function(err) {_x000D_
_x000D_
                        console.log("caught in test 5:[Error ", err.message, "]");_x000D_
_x000D_
                    });_x000D_
_x000D_
                });_x000D_
_x000D_
            });_x000D_
_x000D_
_x000D_
        });_x000D_
_x000D_
_x000D_
_x000D_
    });
_x000D_
_x000D_
_x000D_

What is a "slug" in Django?

It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in What is a "slug" in Django? the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the page served (on this site at least)

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

git revert commit

This will generate the opposite changes from the commit which you want to revert back, and then just commit that changes. I think this is the simplest way.

https://git-scm.com/docs/git-revert

Read lines from a file into a Bash array

The simplest way to read each line of a file into a bash array is this:

IFS=$'\n' read -d '' -r -a lines < /etc/passwd

Now just index in to the array lines to retrieve each line, e.g.

printf "line 1: %s\n" "${lines[0]}"
printf "line 5: %s\n" "${lines[4]}"

# all lines
echo "${lines[@]}"

ModuleNotFoundError: No module named 'sklearn'

I've tried a lot of things but finally, including uninstall with the automated tools. So, I've uninstalled manually scikit-learn.

sudo rm -R /home/ubuntu/.local/lib/python3.6/site-packages/sklearn
sudo rm -R /home/ubuntu/.local/lib/python3.6/site-packages/scikit_learn-0.20.0-py3.6.egg-info

And re-install using pip

sudo pip3.6 install -U scikit-learn

Hope that can help someone else!

How to enable Auto Logon User Authentication for Google Chrome

While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.

Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:

  • Launching Chrome with the auth-server-whitelist command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz". Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.
  • Installing, enabling, and configuring the AuthServerWhitelist/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.

Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:

  1. Download and unzip the latest Chrome policy templates
  2. Start > Run > gpedit.msc
  3. Navigate to Local Computer Policy > Computer Configuration > Administrative Templates
  4. Right-click Administrative Templates, and select Add/Remove Templates
  5. Add the windows\adm\en-US\chrome.adm template via the dialog
  6. In Computer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication enable and configure Authentication server whitelist
  7. Restart Chrome and navigate to chrome://policy to view active policies

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Boundary Control Entity pattern have two versions:
- old structural, described at 127 (entity as an data model elements, control as an functions, boundary as an application interface)
- new object pattern


As an object pattern:
- Boundary is an interface for "other world"
- Control in an any internal logic (like a service in DDD pattern)
- Entity is an an persistence serwis for objects (like a repository in DDD pattern).
All classes have operations (see Fowler anemic domain model anti-pattern)
All of them is an Model component in MVC pattern. The rules:
- Only Boundary provide services for the "other world"
- Boundary can call only to Controll
- Control can call anybody
- Entity can't call anybody (!), only be called.

jz

How to set layout_gravity programmatically?

If you want to change the layou_gravity of an existing view do this:

((FrameLayout.LayoutParams) view.getLayoutParams()).gravity = Gravity.BOTTOM;

Remember to use the right LayoutParams based on the Layout type your view is in. Ex:

LinearLayout.LayoutParams

How to run a cron job inside a docker container?

The adopted solution may be dangerous in a production environment.

In docker you should only execute one process per container because if you don't, the process that forked and went background is not monitored and may stop without you knowing it.

When you use CMD cron && tail -f /var/log/cron.log the cron process basically fork in order to execute cron in background, the main process exits and let you execute tailf in foreground. The background cron process could stop or fail you won't notice, your container will still run silently and your orchestration tool will not restart it.

You can avoid such a thing by redirecting directly the cron's commands output into your docker stdout and stderr which are located respectively in /proc/1/fd/1 and /proc/1/fd/2.

Using basic shell redirects you may want to do something like this :

* * * * * root echo hello > /proc/1/fd/1 2>/proc/1/fd/2

And your CMD will be : CMD ["cron", "-f"]

how to generate web service out of wsdl

How about using the wsdl /server or wsdl /serverinterface switches? As far as I understand the wsdl.exe command line properties, that's what you're looking for.

- ADVANCED -

/server

Server switch has been deprecated. Please use /serverInterface instead.
Generate an abstract class for an xml web service implementation using
ASP.NET based on the contracts. The default is to generate client proxy
classes.

On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this!

Marc


UPDATE:

When I use wsdl /server on a WSDL file, I get this file created:

[WebService(Namespace="http://.......")]
public abstract partial class OneCrmServiceType : System.Web.Services.WebService 
{
    /// <remarks/>
    [WebMethod]
    public abstract void OrderCreated(......);
}

This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file.

You can always add the "yourservice.asmx" manually - it doesn't really contain much:

<%@ WebService Language="C#" CodeBehind="YourService.asmx.cs" 
      Class="YourServiceNamespace.YourServiceClass" %>

How to set the value of a hidden field from a controller in mvc

Without a view model you could use a simple HTML hidden input.

<input type="hidden" name="FullName" id="FullName" value="@ViewBag.FullName" />

replace String with another in java

The replace method is what you're looking for.

For example:

String replacedString = someString.replace("HelloBrother", "Brother");

Set Windows process (or user) memory limit

Use the Application Verifier (AppVerifier) tool from Microsoft.

In my case I need to simulate memory no longer being available so I did the following in the tool:

  1. Added my application
  2. Unchecked Basic
  3. Checked Low Resource Simulation
    • Changed TimeOut to 120000 - my application will run normally for 2 minutes before anything goes into effect.
    • Changed HeapAlloc to 100 - 100% chance of heap allocation error
    • Set Stacks to true - the stack will not be able to grow any larger
  4. Save
  5. Start my application

After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.

Is there a typical state machine implementation pattern?

There is a book titled Practical Statecharts in C/C++. However, it is way too heavyweight for what we need.

405 method not allowed Web API

I tried many thing to get DELETE method work (I was getting 405 method not allowed web api) , and finally I added [Route("api/scan/{id}")] to my controller and was work fine. hope this post help some one.

     // DELETE api/Scan/5
    [Route("api/scan/{id}")]
    [ResponseType(typeof(Scan))]
    public IHttpActionResult DeleteScan(int id)
    {
        Scan scan = db.Scans.Find(id);
        if (scan == null)
        {
            return NotFound();
        }

        db.Scans.Remove(scan);
        db.SaveChanges();

        return Ok(scan);
    }

Setting width and height

Use this, it works fine.

<canvas id="totalschart" style="height:400px;width: content-box;"></canvas>

and under options,

responsive:true,

Call a PHP function after onClick HTML event

 cell1.innerHTML="<?php echo $customerDESC; ?>";
 cell2.innerHTML="<?php echo $comm; ?>";
 cell3.innerHTML="<?php echo $expressFEE; ?>";
 cell4.innerHTML="<?php echo $totao_unit_price; ?>";

it is working like a charm, the javascript is inside a php while loop

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Here are some more tests

True if string is not empty:

[ -n "$var" ]
[[ -n $var ]]
test -n "$var"
[ "$var" ]
[[ $var ]]
(( ${#var} ))
let ${#var}
test "$var"

True if string is empty:

[ -z "$var" ]
[[ -z $var ]]
test -z "$var"
! [ "$var" ]
! [[ $var ]]
! (( ${#var} ))
! let ${#var}
! test "$var"

DB query builder toArray() laravel 4

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);

How can I do factory reset using adb in android?

I have made it from fastboot mode (Phone - Xiomi Mi5 Android 6.0.1)

Here is steps:

# check if device available
fastboot devices
# remove user data
fastboot erase userdata
# remove cache
fastboot erase cache 
# reboot device
fastboot reboot

How to obtain the start time and end time of a day?

I think the easiest would be something like:

// Joda Time

DateTime dateTime=new DateTime(); 

StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();

These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.

How can I enable CORS on Django REST Framework

The link you referenced in your question recommends using django-cors-headers, whose documentation says to install the library

pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

Please browse the configuration section of its documentation, paying particular attention to the various CORS_ORIGIN_ settings. You'll need to set some of those based on your needs.

Header and footer in CodeIgniter

Or more complex, but makes life easy is to use more constants in boot. So subclasses can be defined freely, and a single method to show view. Also selected constants can be passed to javascript in the header.

<?php
/*
 * extends codeigniter main controller
 */

class CH_Controller extends CI_Controller {

    protected $viewdata;

public function __construct() {
    parent::__construct();
            //hard code / override and transfer only required constants (for security) server constants
            //such as domain name to client - this is for code porting and no passwords or database details
            //should be used - ajax is for this

    $this->viewdata = array(
                "constants_js" => array(
                    "TOP_DOMAIN"=>TOP_DOMAIN,
                    "C_UROOT" => C_UROOT,
                    "UROOT" => UROOT,
                    "DOMAIN"=> DOMAIN
                )
            );

}

public function show($viewloc) {
            $this->load->view('templates/header', $this->viewdata);
    $this->load->view($viewloc, $this->viewdata);
    $this->load->view('templates/footer', $this->viewdata);
}

//loads custom class objects if not already loaded
public function loadplugin($newclass) {
    if (!class_exists("PL_" . $newclass)) {
        require(CI_PLUGIN . "PL_" . $newclass . ".php");
    }
}

then simply:

$this->show("<path>/views/viewname/whatever_V.php");

will load header, view and footer.

CSS rounded corners in IE8

I didnt know about css3pie.com, a very useful site after seeing this post:

But what after testing it out it didnt work for me either. However I found that wrapping it in the .PHP file worked fine. So instead of:

behavior: url(PIE.htc);

use this:

behavior: url(PIE.php);

I put mine in a folder called jquery, so mine was:

 behavior: url(jquery/PIE.php);

So goto their downloads or get it here:

http://css3pie.com/download-latest

And use their PHP file. Inside the PHP file it explains that some servers are not configured for proper .HTC usage. And that was the problem I had.

Try it! I did, it works. Hope this helps others out too.

How to rollback everything to previous commit

I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.

I generally use this to reset the git to the specific commit in source tree.

  1. select commit to reset on sourcetree.

  2. In dropdowns select the active branch , first Parent Only

  3. And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)

  4. and then go to terminal git push -f

You should be all set!

MIN and MAX in C

The maximum of two integers a and b is (int)(0.5((a+b)+abs(a-b))). This may also work with (double) and fabs(a-b) for doubles (similar for floats)

Renaming a branch in GitHub

The following commands rename the branch locally, delete the old branch on the remote location and push the new branch, setting the local branch to track the new remote:

git branch -m old_branch new_branch
git push origin :old_branch
git push --set-upstream origin new_branch

Convert char array to a int number in C

Why not just use atoi? For example:

char myarray[4] = {'-','1','2','3'};

int i = atoi(myarray);

printf("%d\n", i);

Gives me, as expected:

-123

Update: why not - the character array is not null terminated. Doh!

how to display excel sheet in html page

You can use iPushPull to push live data direct from an Excel session to the web where you can display it in an IFRAME (or using a WordPress plugin, if applicable). The data in the frame will update whenever the data on the sheet updates.

The iPush(...) in-cell function pushes data from Excel to the web.

This support page describes how to embed your Excel data in your website.

Disclaimer - I work for iPushPull.

Absolute vs relative URLs

Assume we are creating a subsite whose files are in the folder http://site.ru/shop.

1. Absolute URL

Link to home page
href="http://sites.ru/shop/"

Link to the product page
href="http://sites.ru/shop/t-shirts/t-shirt-life-is-good/"

2. Relative URL

Link from home page to product page
href="t-shirts/t-shirt-life-is-good/"

Link from product page to home page
href="../../"

Although relative URL look shorter than absolute one, but the absolute URLs are more preferable, since a link can be used unchanged on any page of site.

Intermediate cases

We have considered two extreme cases: "absolutely" absolute and "absolutely" relative URLs. But everything is relative in this world. This also applies to URLs. Every time you say about absolute URL, you should always specify relative to what.

3. Protocol-relative URL

Link to home page
href="//sites.ru/shop/"

Link to product page
href="//sites.ru/shop/t-shirts/t-shirt-life-is-good/"

Google recommends such URL. Now, however, it is generally considered that http:// and https:// are different sites.

4. Root-relative URL

I.e. relative to the root folder of the domain.

Link to home page
href="/shop/"

Link to product page
href="/shop/t-shirts/t-shirt-life-is-good/"

It is a good choice if all pages are within the same domain. When you move your site to another domain, you don't have to do a mass replacements of the domain name in the URLs.

5. Base-relative URL (home-page-relative)

The tag <base> specifies the base URL, which is automatically added to all relative links and anchors. The base tag does not affect absolute links. As a base URL we'll specify the home page: <base href="http://sites.ru/shop/">.

Link to home page
href=""

Link to product page
href="t-shirts/t-shirt-life-is-good/"

Now you can move your site not only to any domain, but in any subfolder. Just keep in mind that, although URLs look like relative, in fact they are absolute. Especially pay attention to anchors. To navigate within the current page we have to write href="t-shirts/t-shirt-life-is-good/#comments" not href="#comments". The latter will throw on home page.

Conclusion

For internal links I use base-relative URLs (5). For external links and newsletters I use absolute URLs (1).

VSCode regex find & replace submatch math?

Just to add another example:

I was replacing src attr in img html tags, but i needed to replace only the src and keep any text between the img declaration and src attribute.

I used the find+replace tool (ctrl+h) as in the image: Find and replace

How do I run a simple bit of code in a new thread?

Try using the BackgroundWorker class. You give it delegates for what to run, and to be notified when work has finished. There is an example on the MSDN page that I linked to.

Create a view with ORDER BY clause

Error is: FROM (SELECT empno,name FROM table1 where location = 'A' ORDER BY emp_no)

And solution is : FROM (SELECT empno,name FROM table1 where location = 'A') ORDER BY emp_no

Effective method to hide email from spam bots

Another option, I perefer font awesome icons

Fa implementation:

<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">

Mail Address:

<a href="mailto:[email protected]"><span class="label">info<i class="fa fa-at"></i>uploadimage.club</span></a>

Align the form to the center in Bootstrap 4

You need to use the various Bootstrap 4 centering methods...

  • Use text-center for inline elements.
  • Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="[email protected]">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
                </div>
            </div>
        </div>
    </div>
</section>

Pythonic way to find maximum value and its index in a list?

Maybe you need a sorted list anyway?

Try this:

your_list = [13, 352, 2553, 0.5, 89, 0.4]
sorted_list = sorted(your_list)
index_of_higher_value = your_list.index(sorted_list[-1])

'ls' in CMD on Windows is not recognized

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

How to set up a PostgreSQL database in Django

The immediate problem seems to be that you're missing the psycopg2 module.

Calculate time difference in Windows batch file

If you do not mind using powershell within batch script:

@echo off
set start_date=%date% %time%
:: Simulate some type of processing using ping
ping 127.0.0.1  
set end_date=%date% %time%
powershell -command "&{$start_date1 = [datetime]::parse('%start_date%'); $end_date1 = [datetime]::parse('%date% %time%'); echo (-join('Duration in seconds: ', ($end_date1 - $start_date1).TotalSeconds)); }"

Height equal to dynamic width (CSS fluid layout)

really this belongs as a comment to Nathan's answer, but I'm not allowed to do that yet...
I wanted to maintain the aspect ratio, even if there is too much stuff to fit in the box. His example expands the height, changing the aspect ratio. I found adding

overflow: hidden;
overflow-x: auto;
overflow-y: auto;

to the .element helped. See http://jsfiddle.net/B8FU8/3111/

Get program execution time in the shell

If you only need precision to the second, you can use the builtin $SECONDS variable, which counts the number of seconds that the shell has been running.

while true; do
    start=$SECONDS
    some_long_running_command
    duration=$(( SECONDS - start ))
    echo "This run took $duration seconds"
    if some_condition; then break; fi
done

Getting value of HTML Checkbox from onclick/onchange events

Use this

<input type="checkbox" onclick="onClickHandler()" id="box" />

<script>
function onClickHandler(){
    var chk=document.getElementById("box").value;

    //use this value

}
</script>

Git Clone - Repository not found

If you are using cygwin for git and trying to clone a git repository from a network drive you need to add the cygdrive path.

For example if you are cloning a git repo from z:/

$ git clone /cygdrive/z/[repo].git

parent & child with position fixed, parent overflow:hidden bug

Fixed position elements are positioned relative to the browser window, so the parent element is basically irrelevant.

To get the effect you want, where the overflow on the parent clips the child, use position: absolute instead: http://jsfiddle.net/DBHUv/1/

What is the difference between LATERAL and a subquery in PostgreSQL?

One thing no one has pointed out is that you can use LATERAL queries to apply a user-defined function on every selected row.

For instance:

CREATE OR REPLACE FUNCTION delete_company(companyId varchar(255))
RETURNS void AS $$
    BEGIN
        DELETE FROM company_settings WHERE "company_id"=company_id;
        DELETE FROM users WHERE "company_id"=companyId;
        DELETE FROM companies WHERE id=companyId;
    END; 
$$ LANGUAGE plpgsql;

SELECT * FROM (
    SELECT id, name, created_at FROM companies WHERE created_at < '2018-01-01'
) c, LATERAL delete_company(c.id);

That's the only way I know how to do this sort of thing in PostgreSQL.

Given an RGB value, how do I create a tint (or shade)?

Among several options for shading and tinting:

  • For shades, multiply each component by 1/4, 1/2, 3/4, etc., of its previous value. The smaller the factor, the darker the shade.

  • For tints, calculate (255 - previous value), multiply that by 1/4, 1/2, 3/4, etc. (the greater the factor, the lighter the tint), and add that to the previous value (assuming each.component is a 8-bit integer).

Note that color manipulations (such as tints and other shading) should be done in linear RGB. However, RGB colors specified in documents or encoded in images and video are not likely to be in linear RGB, in which case a so-called inverse transfer function needs to be applied to each of the RGB color's components. This function varies with the RGB color space. For example, in the sRGB color space (which can be assumed if the RGB color space is unknown), this function is roughly equivalent to raising each sRGB color component (ranging from 0 through 1) to a power of 2.2. (Note that "linear RGB" is not an RGB color space.)

See also Violet Giraffe's comment about "gamma correction".

How to do a recursive find/replace of a string with awk or sed?

to change multiple files (and saving a backup as *.bak):

perl -p -i -e "s/\|/x/g" *

will take all files in directory and replace | with x called a “Perl pie” (easy as a pie)

Setting a system environment variable from a Windows batch file?

The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe:

C:\Program Files\Support Tools>setx /?

SETX: This program is used to set values in the environment
of the machine or currently logged on user using one of three modes.

1) Command Line Mode: setx variable value [-m]
   Optional Switches:
    -m  Set value in the Machine environment. Default is User.

...
For more information and example use: SETX -i

I think Windows 7 actually comes with setx as part of a standard install.

Add a summary row with totals

This is the more powerful grouping / rollup syntax you'll want to use in SQL Server 2008+. Always useful to specify the version you're using so we don't have to guess.

SELECT 
  [Type] = COALESCE([Type], 'Total'), 
  [Total Sales] = SUM([Total Sales])
FROM dbo.Before
GROUP BY GROUPING SETS(([Type]),());

Craig Freedman wrote a great blog post introducing GROUPING SETS.

sorting dictionary python 3

I like python numpy for this kind of stuff! eg:

r=readData()
nsorted = np.lexsort((r.calls, r.slow_requests, r.very_slow_requests, r.stalled_requests))

I have an example of importing CSV data into a numpy and ordering by column priorities. https://github.com/unixunion/toolbox/blob/master/python/csv-numpy.py

Kegan

What to do on TransactionTooLargeException

I faced with the same issue when I tried to send bitmap via Intent and at the same time when it happens I folded the application.

How it described in this article enter link description here it happens when an Activity is in the process of stopping, that means that the Activity was trying to send its saved state Bundles to the system OS for safe keeping for restoration later (after a config change or process death) but that one or more of the Bundles it sent were too large.

I solved it via hack by overriding onSaveInstanceState in my Activity:

@Override
protected void onSaveInstanceState(Bundle outState) {
    // super.onSaveInstanceState(outState);
}

and comment call super. It is a dirty hack but it is working perfectly. Bitmap was successfully sent without crashes. Hope this will help someone.

How Big can a Python List Get?

As the Python documentation says:

sys.maxsize

The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.

In my computer (Linux x86_64):

>>> import sys
>>> print sys.maxsize
9223372036854775807

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

How to call base.base.method()?

You can also make a simple function in first level derived class, to call grand base function

Why use @Scripts.Render("~/bundles/jquery")

Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

As example you could create your own bundle:

bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
            "~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
            "~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))

And render it like this:

@Scripts.Render("~/bundles/mybundle")

One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

  <system.web>
    <compilation debug="true|false" />

If debug="true" then it will instead render individual script tags for each source script, without any minification.

For stylesheets you will have to use a StyleBundle and @Styles.Render().

Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

use this code

  while ($rows = mysql_fetch_array($query)):

   $name = $rows['Name'];
   $address = $rows['Address'];
   $email = $rows['Email'];
   $subject = $rows['Subject'];
   $comment = $rows['Comment'];

   echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";

   endwhile;

   ?>

how to use php DateTime() function in Laravel 5

DateTime is not a function, but the class.

When you just reference a class like new DateTime() PHP searches for the class in your current namespace. However the DateTime class obviously doesn't exists in your controllers namespace but rather in root namespace.

You can either reference it in the root namespace by prepending a backslash:

$now = new \DateTime();

Or add an import statement at the top:

use DateTime;

$now = new DateTime();

Create parameterized VIEW in SQL Server 2008

in fact there exists one trick:

create view view_test as

select
  * 
from 
  table 
where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
where
spid = @@spid)

... in sql-query:

set context_info 2
select * from view_test

will be the same with

select * from table where id = 2

but using udf is more acceptable

MySQL Error 1215: Cannot add foreign key constraint

For others same error may not always be due to column type mismatch, you can find out more information about a mysql foriegn key error by issuing command

SHOW ENGINE INNODB STATUS;

you may find a error near the top of the printed message something like

Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint.

What's the difference between isset() and array_key_exists()?

Complementing (as an algebraic curiosity) the @deceze answer with the @ operator, and indicating cases where is "better" to use @ ... Not really better if you need (no log and) micro-performance optimization:

  • array_key_exists: is true if a key exists in an array;
  • isset: is true if the key/variable exists and is not null [faster than array_key_exists];
  • @$array['key']: is true if the key/variable exists and is not (null or '' or 0); [so much slower?]
$a = array('k1' => 'HELLO', 'k2' => null, 'k3' => '', 'k4' => 0);

print isset($a['k1'])? "OK $a[k1].": 'NO VALUE.';            // OK
print array_key_exists('k1', $a)? "OK $a[k1].": 'NO VALUE.'; // OK
print @$a['k1']? "OK $a[k1].": 'NO VALUE.';                  // OK
// outputs OK HELLO.  OK HELLO. OK HELLO.

print isset($a['k2'])? "OK $a[k2].": 'NO VALUE.';            // NO
print array_key_exists('k2', $a)? "OK $a[k2].": 'NO VALUE.'; // OK
print @$a['k2']? "OK $a[k2].": 'NO VALUE.';                  // NO
// outputs NO VALUE.  OK .  NO VALUE.

print isset($a['k3'])? "OK $a[k3].": 'NO VALUE.';            // OK
print array_key_exists('k3', $a)? "OK $a[k3].": 'NO VALUE.'; // OK
print @$a['k3']? "OK $a[k3].": 'NO VALUE.';                  // NO
// outputs OK . OK . NO VALUE.

print isset($a['k4'])? "OK $a[k4].": 'NO VALUE.';            // OK
print array_key_exists('k4', $a)? "OK $a[k4].": 'NO VALUE.'; // OK
print @$a['k4']? "OK $a[k4].": 'NO VALUE.';                  // NO
// outputs OK 0. OK 0. NO VALUE

PS: you can change/correct/complement this text, it is a Wiki.

android asynctask sending callbacks to ui

I will repeat what the others said, but will just try to make it simpler...

First, just create the Interface class

public interface PostTaskListener<K> {
    // K is the type of the result object of the async task 
    void onPostTask(K result);
}

Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.

public static class LoadData extends AsyncTask<Void, Void, String> {

    private PostTaskListener<String> postTaskListener;

    protected LoadData(PostTaskListener<String> postTaskListener){
        this.postTaskListener = postTaskListener;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null && postTaskListener != null)
            postTaskListener.onPostTask(result);
    }
}

Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:

...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
    @Override
    public void onPostTask(String result) {
        //Your post execution task code
    }
}

// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);

Done!

How to convert int to float in C?

integer division in C truncates the result so 50/100 will give you 0

If you want to get the desired result try this :

((float)number/total)*100

or

50.0/100

ValidateAntiForgeryToken purpose, explanation and example

Microsoft provides us built-in functionality which we use in our application for security purposes, so no one can hack our site or invade some critical information.

From Purpose Of ValidateAntiForgeryToken In MVC Application by Harpreet Singh:

Use of ValidateAntiForgeryToken

Let’s try with a simple example to understand this concept. I do not want to make it too complicated, that’s why I am going to use a template of an MVC application, already available in Visual Studio. We will do this step by step. Let’s start.

  1. Step 1 - Create two MVC applications with default internet template and give those names as CrossSite_RequestForgery and Attack_Application respectively.

  2. Now, open CrossSite_RequestForgery application's Web Config and change the connection string with the one given below and then save.

`

<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF;
Integrated Security=true;" providerName="System.Data.SqlClient" /> 
 </connectionStrings>
  1. Now, click on Tools >> NuGet Package Manager, then Package Manager Console

  2. Now, run the below mentioned three commands in Package Manager Console to create the database.

Enable-Migrations add-migration first update-database

Important Notes - I have created database with code first approach because I want to make this example in the way developers work. You can create database manually also. It's your choice.

  1. Now, open Account Controller. Here, you will see a register method whose type is post. Above this method, there should be an attribute available as [ValidateAntiForgeryToken]. Comment this attribute. Now, right click on register and click go to View. There again, you will find an html helper as @Html.AntiForgeryToken() . Comment this one also. Run the application and click on register button. The URL will be open as:

http://localhost:52269/Account/Register

Notes- I know now the question being raised in all readers’ minds is why these two helpers need to be commented, as everyone knows these are used to validate request. Then, I just want to let you all know that this is just because I want to show the difference after and before applying these helpers.

  1. Now, open the second application which is Attack_Application. Then, open Register method of Account Controller. Just change the POST method with the simple one, shown below.

    Registration Form
    1. @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
    2. @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
    3. @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)

7.Now, suppose you are a hacker and you know the URL from where you can register user in CrossSite_RequestForgery application. Now, you created a Forgery site as Attacker_Application and just put the same URL in post method.

8.Run this application now and fill the register fields and click on register. You will see you are registered in CrossSite_RequestForgery application. If you check the database of CrossSite_RequestForgery application then you will see and entry you have entered.

  1. Important - Now, open CrossSite_RequestForgery application and comment out the token in Account Controller and register the View. Try to register again with the same process. Then, an error will occur as below.

Server Error in '/' Application. ________________________________________ The required anti-forgery cookie "__RequestVerificationToken" is not present.

This is what the concept says. What we add in View i.e. @Html.AntiForgeryToken() generates __RequestVerificationToken on load time and [ValidateAntiForgeryToken] available on Controller method. Match this token on post time. If token is the same, then it means this is a valid request.

How can you dynamically create variables via a while loop?

vars()['meta_anio_2012'] = 'translate'

How to print an exception in Python?

(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)

I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:

except Exception as e:
    print(e)

will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:

except Exception as e:
    print(e, file=sys.stderr)

(Note that you have to import sys for this to work.) This way, the error is printed to STDERR instead of STDOUT, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.

I haven't used the traceback module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.

What is an AssertionError? In which case should I throw it from my own code?

An assertion Error is thrown when say "You have written a code that should not execute at all costs because according to you logic it should not happen. BUT if it happens then throw AssertionError. And you don't catch it." In such a case you throw an Assertion error.

new IllegalStateException("Must not instantiate an element of this class")' // Is an Exception not error.

Note: Assertion Error comes under java.lang.Error And Errors not meant to be caught.

How do I append text to a file?

How about:

echo "hello" >> <filename>

Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.

You could also use printf in the same way:

printf "hello" >> <filename>

Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc:

set -o noclobber

Now when you try to do echo "hello" > file.txt you will get a warning saying cannot overwrite existing file.

To force writing to the file you must now use the special syntax:

echo "hello" >| <filename>

You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:

echo -n "hello" >> <filename>

References

HTML-encoding lost when attribute read from input field

The jQuery trick doesn't encode quote marks and in IE it will strip your whitespace.

Based on the escape templatetag in Django, which I guess is heavily used/tested already, I made this function which does what's needed.

It's arguably simpler (and possibly faster) than any of the workarounds for the whitespace-stripping issue - and it encodes quote marks, which is essential if you're going to use the result inside an attribute value for example.

function htmlEscape(str) {
    return str
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

// I needed the opposite function today, so adding here too:
function htmlUnescape(str){
    return str
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&');
}

Update 2013-06-17:
In the search for the fastest escaping I have found this implementation of a replaceAll method:
http://dumpsite.com/forum/index.php?topic=4.msg29#msg29
(also referenced here: Fastest method to replace all instances of a character in a string)
Some performance results here:
http://jsperf.com/htmlencoderegex/25

It gives identical result string to the builtin replace chains above. I'd be very happy if someone could explain why it's faster!?

Update 2015-03-04:
I just noticed that AngularJS are using exactly the method above:
https://github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js#L435

They add a couple of refinements - they appear to be handling an obscure Unicode issue as well as converting all non-alphanumeric characters to entities. I was under the impression the latter was not necessary as long as you have an UTF8 charset specified for your document.

I will note that (4 years later) Django still does not do either of these things, so I'm not sure how important they are:
https://github.com/django/django/blob/1.8b1/django/utils/html.py#L44

Update 2016-04-06:
You may also wish to escape forward-slash /. This is not required for correct HTML encoding, however it is recommended by OWASP as an anti-XSS safety measure. (thanks to @JNF for suggesting this in comments)

        .replace(/\//g, '&#x2F;');

How to update specific key's value in an associative array in PHP?

This a single solution, in where your_field is a field that will set and new_value is a new value field, that can a function or a single value

foreach ($array as $key => $item) {
   $item["your_field"] = "new_value";
   $array[$key] = $item;
}

In your case new_value will be a date() function

.prop() vs .attr()

One thing .attr() can do that .prop() can't: affect CSS selectors

Here's an issue I didn't see in the other answers.

CSS selector [name=value]

  • will respond to .attr('name', 'value')
  • but not always to .prop('name', 'value')

.prop() affects only a few attribute-selectors

.attr() affects all attribute-selectors

Best way to determine user's locale within browser

I did a bit of research regarding this & I have summarised my findings so far in below table

enter image description here

So the recommended solution is to write a a server side script to parse the Accept-Language header & pass it to client for setting the language of the website. It's weird that why the server would be needed to detect the language preference of client but that's how it is as of now There are other various hacks available to detect the language but reading the Accept-Language header is the recommended solution as per my understanding.

Center image horizontally within a div

To center an image horizontally, this works:

<p style="text-align:center"><img src=""></p>

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

Rails ActiveRecord date between

There should be a default active record behavior on this I reckon. Querying dates is hard, especially when timezones are involved.

Anyway, I use:

  scope :between, ->(start_date=nil, end_date=nil) {
    if start_date && end_date
      where("#{self.table_name}.created_at BETWEEN :start AND :end", start: start_date.beginning_of_day, end: end_date.end_of_day)
    elsif start_date
      where("#{self.table_name}.created_at >= ?", start_date.beginning_of_day)
    elsif end_date
      where("#{self.table_name}.created_at <= ?", end_date.end_of_day)
    else
      all
    end
  }

Auto refresh page every 30 seconds

Use setInterval instead of setTimeout. Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

Select only rows if its value in a particular column is less than the value in the other column

If you use dplyr package you can do:

library(dplyr)
filter(df, aged <= laclen)

Try-catch speeding up my code?

This looks like a case of inlining gone bad. On an x86 core, the jitter has the ebx, edx, esi and edi register available for general purpose storage of local variables. The ecx register becomes available in a static method, it doesn't have to store this. The eax register often is needed for calculations. But these are 32-bit registers, for variables of type long it must use a pair of registers. Which are edx:eax for calculations and edi:ebx for storage.

Which is what stands out in the disassembly for the slow version, neither edi nor ebx are used.

When the jitter can't find enough registers to store local variables then it must generate code to load and store them from the stack frame. That slows down code, it prevents a processor optimization named "register renaming", an internal processor core optimization trick that uses multiple copies of a register and allows super-scalar execution. Which permits several instructions to run concurrently, even when they use the same register. Not having enough registers is a common problem on x86 cores, addressed in x64 which has 8 extra registers (r9 through r15).

The jitter will do its best to apply another code generation optimization, it will try to inline your Fibo() method. In other words, not make a call to the method but generate the code for the method inline in the Main() method. Pretty important optimization that, for one, makes properties of a C# class for free, giving them the perf of a field. It avoids the overhead of making the method call and setting up its stack frame, saves a couple of nanoseconds.

There are several rules that determine exactly when a method can be inlined. They are not exactly documented but have been mentioned in blog posts. One rule is that it won't happen when the method body is too large. That defeats the gain from inlining, it generates too much code that doesn't fit as well in the L1 instruction cache. Another hard rule that applies here is that a method won't be inlined when it contains a try/catch statement. The background behind that one is an implementation detail of exceptions, they piggy-back onto Windows' built-in support for SEH (Structure Exception Handling) which is stack-frame based.

One behavior of the register allocation algorithm in the jitter can be inferred from playing with this code. It appears to be aware of when the jitter is trying to inline a method. One rule it appears to use that only the edx:eax register pair can be used for inlined code that has local variables of type long. But not edi:ebx. No doubt because that would be too detrimental to the code generation for the calling method, both edi and ebx are important storage registers.

So you get the fast version because the jitter knows up front that the method body contains try/catch statements. It knows it can never be inlined so readily uses edi:ebx for storage for the long variable. You got the slow version because the jitter didn't know up front that inlining wouldn't work. It only found out after generating the code for the method body.

The flaw then is that it didn't go back and re-generate the code for the method. Which is understandable, given the time constraints it has to operate in.

This slow-down doesn't occur on x64 because for one it has 8 more registers. For another because it can store a long in just one register (like rax). And the slow-down doesn't occur when you use int instead of long because the jitter has a lot more flexibility in picking registers.

How do I display todays date on SSRS report?

date column 1:

=formatdatetime(today)

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

Im my case the problem was that I cretead sertificates without entering any data in cli interface. When I regenerated cretificates and enetered all fields: City, State, etc all became fine.

 sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt

Select columns in PySpark dataframe

The dataset in ss.csv contains some columns I am interested in:

ss_ = spark.read.csv("ss.csv", header= True, 
                      inferSchema = True)
ss_.columns
['Reporting Area', 'MMWR Year', 'MMWR Week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017, flag', 'Shiga toxin-producing Escherichia coli, Current week', 'Shiga toxin-producing Escherichia coli, Current week, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max, flag', 'Shiga toxin-producing Escherichia coli, Cum 2018', 'Shiga toxin-producing Escherichia coli, Cum 2018, flag', 'Shiga toxin-producing Escherichia coli, Cum 2017', 'Shiga toxin-producing Escherichia coli, Cum 2017, flag', 'Shigellosis, Current week', 'Shigellosis, Current week, flag', 'Shigellosis, Previous 52 weeks Med', 'Shigellosis, Previous 52 weeks Med, flag', 'Shigellosis, Previous 52 weeks Max', 'Shigellosis, Previous 52 weeks Max, flag', 'Shigellosis, Cum 2018', 'Shigellosis, Cum 2018, flag', 'Shigellosis, Cum 2017', 'Shigellosis, Cum 2017, flag']

but I only need a few:

columns_lambda = lambda k: k.endswith(', Current week') or k == 'Reporting Area' or k == 'MMWR Year' or  k == 'MMWR Week'

The filter returns the list of desired columns, list is evaluated:

sss = filter(columns_lambda, ss_.columns)
to_keep = list(sss)

the list of desired columns is unpacked as arguments to dataframe select function that return dataset containing only columns in the list:

dfss = ss_.select(*to_keep)
dfss.columns

The result:

['Reporting Area',
 'MMWR Year',
 'MMWR Week',
 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week',
 'Shiga toxin-producing Escherichia coli, Current week',
 'Shigellosis, Current week']

The df.select() has a complementary pair: http://spark.apache.org/docs/2.4.1/api/python/pyspark.sql.html#pyspark.sql.DataFrame.drop

to drop the list of columns.

Apache Spark: map vs mapPartitions?

Map :

  1. It processes one row at a time , very similar to map() method of MapReduce.
  2. You return from the transformation after every row.

MapPartitions

  1. It processes the complete partition in one go.
  2. You can return from the function only once after processing the whole partition.
  3. All intermediate results needs to be held in memory till you process the whole partition.
  4. Provides you like setup() map() and cleanup() function of MapReduce

Map Vs mapPartitions http://bytepadding.com/big-data/spark/spark-map-vs-mappartitions/

Spark Map http://bytepadding.com/big-data/spark/spark-map/

Spark mapPartitions http://bytepadding.com/big-data/spark/spark-mappartitions/

Display string multiple times

The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.

print(*3*('-',), sep='_')

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
  end

Can't import javax.servlet.annotation.WebServlet

I had the same issue, it turns that I had my project configured as many of you stated above, yet the problem persisted, so I went deeper and came across that I was using Apache Tomcat 6 as my Runtime Server, so the fix was simple, I just upgraded the project to use Apache Tomcat 7 and that's all, finally the IDE recognized javax.servlet.annotation.WebServlet annotation.

How to mkdir only if a directory does not already exist?

if [ !-d $dirName ];then
     if ! mkdir $dirName; then  # Shorter version. Shell will complain if you put braces here though
     echo "Can't make dir: $dirName"
     fi
fi

How to hash some string with sha256 in Java?

This is what i have been used for hashing:

String pass = "password";

MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte hashBytes[] = messageDigest.digest(pass.getBytes(StandardCharsets.UTF_8));
BigInteger noHash = new BigInteger(1, hashBytes);
String hashStr = noHash.toString(16);

Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

Load json from local file with http.get() in angular 2

For Angular 5+ only preform steps 1 and 4


In order to access your file locally in Angular 2+ you should do the following (4 steps):

[1] Inside your assets folder create a .json file, example: data.json

[2] Go to your angular.cli.json (angular.json in Angular 6+) inside your project and inside the assets array put another object (after the package.json object) like this:

{ "glob": "data.json", "input": "./", "output": "./assets/" }

full example from angular.cli.json

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        { "glob": "package.json", "input": "../", "output": "./assets/" },
        { "glob": "data.json", "input": "./", "output": "./assets/" }
      ],

Remember, data.json is just the example file we've previously added in the assets folder (you can name your file whatever you want to)

[3] Try to access your file via localhost. It should be visible within this address, http://localhost:your_port/assets/data.json

If it's not visible then you've done something incorrectly. Make sure you can access it by typing it in the URL field in your browser before proceeding to step #4.

[4] Now preform a GET request to retrieve your .json file (you've got your full path .json URL and it should be simple)

 constructor(private http: HttpClient) {}
        // Make the HTTP request:
        this.http.get('http://localhost:port/assets/data.json')
                 .subscribe(data => console.log(data));

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

How to access single elements in a table in R

Maybe not so perfect as above ones, but I guess this is what you were looking for.

data[1:1,3:3]    #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j]    #given that i and j are positive integers

Here indexing will work from 1, i.e,

data[1:1,1:1]    #means the top-leftmost element

Adding CSRFToken to Ajax request

I had this problem in a list of post in a blog, the post are in a view inside a foreach, then is difficult select it in javascript, and the problem of post method and token also exists.

This the code for javascript at the end of the view, I generate the token in javascript functión inside the view and not in a external js file, then is easy use php lavarel to generate it with csrf_token() function, and send the "delete" method directly in params. You can see that I don´t use in var route: {{ route('post.destroy', $post->id}} because I don´t know the id I want delete until someone click in destroy button, if you don´t have this problem you can use {{ route('post.destroy', $post->id}} or other like this.

  $(function(){
    $(".destroy").on("click", function(){
         var vid = $(this).attr("id");
         var v_token = "{{csrf_token()}}";
         var params = {_method: 'DELETE', _token: v_token};
         var route = "http://imagica.app/posts/" + vid + "";
    $.ajax({
         type: "POST",
         url: route,
         data: params
    });
   });
  });

and this the code of content in view (inside foreach there are more forms and the data of each post but is not inportant by this example), you can see I add a class "delete" to button and I call class in javascript.

      @foreach($posts as $post)
          <form method="POST">
            <button id="{{$post->id}}" class="btn btn-danger btn-sm pull-right destroy" type="button" >eliminar</button>
          </form>
      @endforeach

Android studio logcat nothing to show

enter image description here

  1. First make Sure developer option is enabled in your device.
  2. Device is connected.
  3. Verbose.
  4. Show Only Selected application.

jQuery.ajax handling continue responses: "success:" vs ".done"?

From JQuery Documentation

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); 

(added in jQuery 1.6) An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

C# Macro definitions in Preprocessor

Luckily, C# has no C/C++-style preprocessor - only conditional compilation and pragmas (and possibly something else I cannot recall) are supported. Unfortunatelly, C# has no metaprogramming capabilities (this may actually relate to your question to some extent).

The Eclipse executable launcher was unable to locate its companion launcher jar windows

In my case I had to redownload it, something was wrong with the one I downloaded. Its size was far much less than the one on the website.

Android SeekBar setOnSeekBarChangeListener

onProgressChanged() should be called on every progress changed, not just on first and last touch (that why you have onStartTrackingTouch() and onStopTrackingTouch() methods).

Make sure that your SeekBar have more than 1 value, that is to say your MAX>=3.

In your onCreate:

 yourSeekBar=(SeekBar) findViewById(R.id.yourSeekBar);
 yourSeekBar.setOnSeekBarChangeListener(new yourListener());

Your listener:

private class yourListener implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
                            // Log the progress
            Log.d("DEBUG", "Progress is: "+progress);
                            //set textView's text
            yourTextView.setText(""+progress);
        }

        public void onStartTrackingTouch(SeekBar seekBar) {}

        public void onStopTrackingTouch(SeekBar seekBar) {}

    }

Please share some code and the Log results for furter help.

Browser Timeouts

You can see the default value in Chrome in this link

int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes

In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.

How to put wildcard entry into /etc/hosts?

use dnsmasq

pretending you're using a debian-based dist(ubuntu,mint..), check if it's installed with

(sudo) systemctl status dnsmasq

If it is just disabled start it with

(sudo) systemctl start dnsmasq

If you have to install it, write

(sudo) apt-get install dnsmasq

To define domains to resolve edit /etc/dnsmasq.conf like this

address=/example.com/127.0.0.1

to resolve *.example.com

! You need to reload dnsmasq to take effect for the changes !

systemctl reload dnsmasq

Setting focus on an HTML input box on page load

And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.

<input type="text" name="fname" autofocus>

Android Studio - How to increase Allocated Heap Size

On Mac OSX one can easily change heap size by going to first menu item, Android Studio > preference > System Settings (left menu) > Memory Settings and change heap size there in the dialog.

enter image description here

Get current batchfile directory

Very simple:

setlocal
cd /d %~dp0
File.exe

How to determine if .NET Core is installed

It doesn't need a installation process.

I have pinned "VSCore" on my taskbar (win10), so open it, and open a task manager choose "Visual Studio Core" process expand left arrow and over any of them child process right button over it and click in "Open File Location" menu.

If you don't remember where is installed search "Code.exe" file in all your hard drives.

Boto3 to download all files from a S3 Bucket

If you want to call a bash script using python, here is a simple method to load a file from a folder in S3 bucket to a local folder (in a Linux machine) :

import boto3
import subprocess
import os

###TOEDIT###
my_bucket_name = "your_my_bucket_name"
bucket_folder_name = "your_bucket_folder_name"
local_folder_path = "your_local_folder_path"
###TOEDIT###

# 1.Load thes list of files existing in the bucket folder
FILES_NAMES = []
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('{}'.format(my_bucket_name))
for object_summary in my_bucket.objects.filter(Prefix="{}/".format(bucket_folder_name)):
#     print(object_summary.key)
    FILES_NAMES.append(object_summary.key)

# 2.List only new files that do not exist in local folder (to not copy everything!)
new_filenames = list(set(FILES_NAMES )-set(os.listdir(local_folder_path)))

# 3.Time to load files in your destination folder 
for new_filename in new_filenames:
    upload_S3files_CMD = """aws s3 cp s3://{}/{}/{} {}""".format(my_bucket_name,bucket_folder_name,new_filename ,local_folder_path)

    subprocess_call = subprocess.call([upload_S3files_CMD], shell=True)
    if subprocess_call != 0:
        print("ALERT: loading files not working correctly, please re-check new loaded files")

How to check if Thread finished execution

Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.

Convert bytes to a string

You need to decode the bytes object to produce a string:

>>> b"abcde"
b'abcde'

# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8") 
'abcde'

Initialize static variables in C++ class?

Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.

// MyClass.cpp

#include "MyClass.h"

// anonymous namespace
namespace
{
    string RE_ANY = "([^\\n]*)";
    string RE_ANY_RELUCTANT = "([^\\n]*?)";
}

// member function (static or not)
bool MyClass::foo()
{
    // logic that uses constants
    return RE_ANY_RELUCTANT.size() > 0;
}

How can I select item with class within a DIV?

If you want to select every element that has class attribute "myclass" use

$('#mydiv .myclass');

If you want to select only div elements that has class attribute "myclass" use

$("div#mydiv div.myclass");

find more about jquery selectors refer these articles

Prevent browser caching of AJAX call result

All the answers here leave a footprint on the requested URL which will show up in the access logs of server.

I needed a header based solution with no side effect and I found it can be achieved by setting up the headers mentioned in How to control web page caching, across all browsers?.

The result, working for Chrome at least, would be:

_x000D_
_x000D_
$.ajax({_x000D_
   url: url, _x000D_
   headers: {_x000D_
     'Cache-Control': 'no-cache, no-store, must-revalidate', _x000D_
     'Pragma': 'no-cache', _x000D_
     'Expires': '0'_x000D_
   }_x000D_
});
_x000D_
_x000D_
_x000D_

How to increase code font size in IntelliJ?

In IntellJ 13

File 
 |
  ---- Settings 
       |
        ------- Editor
                 |
                  ------- Colors & Fonts
                          |
                           ------ Font -> [Size]

enter image description here

How can I convert an integer to a hexadecimal string in C?

To convert an integer to a string also involves char array or memory management.

To handle that part for such short arrays, code could use a compound literal, since C99, to create array space, on the fly. The string is valid until the end of the block.

#define UNS_HEX_STR_SIZE ((sizeof (unsigned)*CHAR_BIT + 3)/4 + 1)
//                         compound literal v--------------------------v
#define U2HS(x) unsigned_to_hex_string((x), (char[UNS_HEX_STR_SIZE]) {0}, UNS_HEX_STR_SIZE)

char *unsigned_to_hex_string(unsigned x, char *dest, size_t size) {
  snprintf(dest, size, "%X", x);
  return dest;
}

int main(void) {
  // 3 array are formed v               v        v
  printf("%s %s %s\n", U2HS(UINT_MAX), U2HS(0), U2HS(0x12345678));
  char *hs = U2HS(rand());
  puts(hs);
  // `hs` is valid until the end of the block
}

Output

FFFFFFFF 0 12345678
5851F42D

Stopping a JavaScript function when a certain condition is met

Try using a return statement. It works best. It stops the function when the condition is met.

function anything() {
    var get = document.getElementsByClassName("text ").value;
    if (get == null) {
        alert("Please put in your name");
    }

    return;

    var random = Math.floor(Math.random() * 100) + 1;
    console.log(random);
}

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.

How to animate CSS Translate

I too was looking for a good way to do this, I found the best way was to set a transition on the "transform" property and then change the transform and then remove the transition.

I put it all together in a jQuery plugin

https://gist.github.com/dustinpoissant/8a4837c476e3939a5b3d1a2585e8d1b0

You would use the code like this:

$("#myElement").animateTransform("rotate(180deg)", 750, function(){
  console.log("animation completed after 750ms");
});

IIS - can't access page by ip address instead of localhost

In my case it was because I was using a port other than the default port 80. I was able to access the site locally using localhost but not on another machine using the IP address.

To solve the issue I had to add a firewall inbound rule to allow the port. enter image description here

Check if my SSL Certificate is SHA1 or SHA2

You can check by visiting the site in your browser and viewing the certificate that the browser received. The details of how to do that can vary from browser to browser, but generally if you click or right-click on the lock icon, there should be an option to view the certificate details.

In the list of certificate fields, look for one called "Certificate Signature Algorithm". (For StackOverflow's certificate, its value is "PKCS #1 SHA-1 With RSA Encryption".)

How to execute a program or call a system command from Python

After some research, I have the following code which works very well for me. It basically prints both stdout and stderr in real time.

stdout_result = 1
stderr_result = 1


def stdout_thread(pipe):
    global stdout_result
    while True:
        out = pipe.stdout.read(1)
        stdout_result = pipe.poll()
        if out == '' and stdout_result is not None:
            break

        if out != '':
            sys.stdout.write(out)
            sys.stdout.flush()


def stderr_thread(pipe):
    global stderr_result
    while True:
        err = pipe.stderr.read(1)
        stderr_result = pipe.poll()
        if err == '' and stderr_result is not None:
            break

        if err != '':
            sys.stdout.write(err)
            sys.stdout.flush()


def exec_command(command, cwd=None):
    if cwd is not None:
        print '[' + ' '.join(command) + '] in ' + cwd
    else:
        print '[' + ' '.join(command) + ']'

    p = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
    )

    out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
    err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))

    err_thread.start()
    out_thread.start()

    out_thread.join()
    err_thread.join()

    return stdout_result + stderr_result

How do I remove the space between inline/inline-block elements?

There is a easy solution in CSS. For example:

HTML

<p class="parent">
    <span class="children"> Foo </span>
    <span class="children"> Bar </span>
</p>

CSS

.parent {
    letter-spacing: -.31em;
    *letter-spacing: normal;
    *word-spacing: -.43em;
}
.children {
    display: inline-block;
    *display: inline;
    zoom: 1;
    letter-spacing: normal;
    word-spacing: normal;
}

In my opinion writing font-size: 0 is not safe when you use it in a project like em, so I prefer purecss' solution.

You can check this framework in this link purecss. Enjoy :)

_x000D_
_x000D_
.row {_x000D_
    letter-spacing: -.31em;_x000D_
    *letter-spacing: normal;_x000D_
    *word-spacing: -.43em;_x000D_
_x000D_
    /* For better view */_x000D_
    background: #f9f9f9;_x000D_
    padding: 1em .5em;_x000D_
}_x000D_
_x000D_
.col {_x000D_
    display: inline-block;_x000D_
    *display: inline;_x000D_
    zoom: 1;_x000D_
    letter-spacing: normal;_x000D_
    word-spacing: normal;_x000D_
_x000D_
    /* For better view */_x000D_
    padding: 16px;_x000D_
    background: #dbdbdb;_x000D_
    border: 3px #bdbdbd solid;_x000D_
    box-sizing: border-box;_x000D_
    width: 25%;_x000D_
}
_x000D_
<div class="row">_x000D_
_x000D_
    <div class="col">1</div>_x000D_
    <div class="col">2</div>_x000D_
    <div class="col">3</div>_x000D_
    <div class="col">4</div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

cannot redeclare block scoped variable (typescript)

Use IIFE(Immediately Invoked Function Expression), IIFE

(function () {
    all your code is here...

 })();

How can I have Github on my own server?

Yes, there's GitHub Enterprise :)

https://enterprise.github.com

Only problem is it's a bit pricey :(

Java Delegates?

Yes & No, but delegate pattern in Java could be thought of this way. This video tutorial is about data exchange between activity - fragments, and it has great essence of delegate sorta pattern using interfaces.

Java Interface

Getting and removing the first character of a string

Another alternative is to use capturing sub-expressions with the regular expression functions regmatches and regexec.

# the original example
x <- 'hello stackoverflow'

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))

This returns the entire string, the first character, and the "popped" result in a list of length 1.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x)))). That is, it contains the super set of the desired elements as well as the full string.


Adding sapply will allow this method to work for a character vector of length > 1.

# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))

This returns a list with the matched full string as the first element and the matching subexpressions captured by () as the following elements. So in the regular expression '(^.)(.*)', (^.) matches the first character and (.*) matches the remaining characters.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

[[2]]
[1] "right back" "r"          "ight back" 

[[3]]
[1] "at yah" "a"      "t yah" 

Now, we can use the trusty sapply + [ method to pull out the desired substrings.

myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back"          "t yah"

How do I display image in Alert/confirm box in Javascript?

As other have mentioned you can't display an image in an alert. The solution is to show it on the webpage.

If I have my webpage paused in the debugger and I already have an image loaded, I can display it. There is no need to use jQuery; with this native 14 lines of Javascript it will work from code or the debugger command line:

function show(img){
 var _=document.getElementById('_'); 
 if(!_){_=document.createElement('canvas');document.body.appendChild(_);}
 _.id='_';
 _.style.top=0;
 _.style.left=0;
 _.width=img.width;
 _.height=img.height;
 _.style.zIndex=9999; 
 _.style.position='absolute';
 _.getContext('2d').drawImage(img,0,0);
}

Usage:

show( myimage );

C++ deprecated conversion from string constant to 'char*'

A reason for this problem (which is even harder to detect than the issue with char* str = "some string" - which others have explained) is when you are using constexpr.

constexpr char* str = "some string";

It seems that it would behave similar to const char* str, and so would not cause a warning, as it occurs before char*, but it instead behaves as char* const str.

Details

Constant pointer, and pointer to a constant. The difference between const char* str, and char* const str can be explained as follows.

  1. const char* str : Declare str to be a pointer to a const char. This means that the data to which this pointer is pointing to it constant. The pointer can be modified, but any attempt to modify the data would throw a compilation error.
    1. str++ ; : VALID. We are modifying the pointer, and not the data being pointed to.
    2. *str = 'a'; : INVALID. We are trying to modify the data being pointed to.
  2. char* const str : Declare str to be a const pointer to char. This means that point is now constant, but the data being pointed too is not. The pointer cannot be modified but we can modify the data using the pointer.
    1. str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
    2. *str = 'a'; : VALID. We are trying to modify the data being pointed to. In our case this will not cause a compilation error, but will cause a runtime error, as the string will most probably will go into a read only section of the compiled binary. This statement would make sense if we had dynamically allocated memory, eg. char* const str = new char[5];.
  3. const char* const str : Declare str to be a const pointer to a const char. In this case we can neither modify the pointer, nor the data being pointed to.
    1. str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
    2. *str = 'a'; : INVALID. We are trying to modify the data pointed by this pointer, which is also constant.

In my case the issue was that I was expecting constexpr char* str to behave as const char* str, and not char* const str, since visually it seems closer to the former.

Also, the warning generated for constexpr char* str = "some string" is slightly different from char* str = "some string".

  1. Compiler warning for constexpr char* str = "some string": ISO C++11 does not allow conversion from string literal to 'char *const'
  2. Compiler warning for char* str = "some string": ISO C++11 does not allow conversion from string literal to 'char *'.

Tip

You can use C gibberish ? English converter to convert C declarations to easily understandable English statements, and vice versa. This is a C only tool, and thus wont support things (like constexpr) which are exclusive to C++.

How to initialize weights in PyTorch?

Iterate over parameters

If you cannot use apply for instance if the model does not implement Sequential directly:

Same for all

# see UNet at https://github.com/milesial/Pytorch-UNet/tree/master/unet


def init_all(model, init_func, *params, **kwargs):
    for p in model.parameters():
        init_func(p, *params, **kwargs)

model = UNet(3, 10)
init_all(model, torch.nn.init.normal_, mean=0., std=1) 
# or
init_all(model, torch.nn.init.constant_, 1.) 

Depending on shape

def init_all(model, init_funcs):
    for p in model.parameters():
        init_func = init_funcs.get(len(p.shape), init_funcs["default"])
        init_func(p)

model = UNet(3, 10)
init_funcs = {
    1: lambda x: torch.nn.init.normal_(x, mean=0., std=1.), # can be bias
    2: lambda x: torch.nn.init.xavier_normal_(x, gain=1.), # can be weight
    3: lambda x: torch.nn.init.xavier_uniform_(x, gain=1.), # can be conv1D filter
    4: lambda x: torch.nn.init.xavier_uniform_(x, gain=1.), # can be conv2D filter
    "default": lambda x: torch.nn.init.constant(x, 1.), # everything else
}

init_all(model, init_funcs)

You can try with torch.nn.init.constant_(x, len(x.shape)) to check that they are appropriately initialized:

init_funcs = {
    "default": lambda x: torch.nn.init.constant_(x, len(x.shape))
}

Change Twitter Bootstrap Tooltip content on click

The following worked the best for me, basically I'm scrapping any existing tooltip and not bothering to show the new tooltip. If calling show on the tooltip like in other answers, it pops up even if the cursor isn't hovering above it.

The reason I went for this solution is that the other solutions, re-using the existing tooltip, led to some strange issues with the tooltip sometimes not showing when hovering the cursor above the element.

function updateTooltip(element, tooltip) {
    if (element.data('tooltip') != null) {
        element.tooltip('hide');
        element.removeData('tooltip');
    }
    element.tooltip({
        title: tooltip
    });
}

How to check empty object in angular 2 template using *ngIf

You could also use something like that:

<div class="comeBack_up" *ngIf="isEmptyObject(previous_info)"  >

with the isEmptyObject method defined in your component:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

How to change column order in a table using sql query in sql server 2005?

You cannot. The column order is just a "cosmetic" thing we humans care about - to SQL Server, it's almost always absolutely irrelevant.

What SQL Server Management Studio does in the background when you change column order there is recreating the table from scratch with a new CREATE TABLE command, copying over the data from the old table, and then dropping it.

There is no SQL command to define the column ordering.

disable viewport zooming iOS 10+ safari?

I tried the previous answer about pinch-to-zoom

document.documentElement.addEventListener('touchstart', function (event) {
    if (event.touches.length > 1) {
        event.preventDefault();
    }
}, false);

however sometime the screen still zoom when the event.touches.length > 1 I found out the best way is using touchmove event, to avoid any finger moving on the screen. The code will be something like this:

document.documentElement.addEventListener('touchmove', function (event) {
    event.preventDefault();      
}, false);

Hope it will help.