Programs & Examples On #Murky

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

The simplest general function to find the positive modulo would be this- It would work on both positive and negative values of x.

int modulo(int x,int N){
    return (x % N + N) %N;
}

Storing Python dictionaries

For completeness, we should include ConfigParser and configparser which are part of the standard library in Python 2 and 3, respectively. This module reads and writes to a config/ini file and (at least in Python 3) behaves in a lot of ways like a dictionary. It has the added benefit that you can store multiple dictionaries into separate sections of your config/ini file and recall them. Sweet!

Python 2.7.x example.

import ConfigParser

config = ConfigParser.ConfigParser()

dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}

# Make each dictionary a separate section in the configuration
config.add_section('dict1')
for key in dict1.keys():
    config.set('dict1', key, dict1[key])
   
config.add_section('dict2')
for key in dict2.keys():
    config.set('dict2', key, dict2[key])

config.add_section('dict3')
for key in dict3.keys():
    config.set('dict3', key, dict3[key])

# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()

# Read the configuration from a file
config2 = ConfigParser.ConfigParser()
config2.read('config.ini')

dictA = {}
for item in config2.items('dict1'):
    dictA[item[0]] = item[1]

dictB = {}
for item in config2.items('dict2'):
    dictB[item[0]] = item[1]

dictC = {}
for item in config2.items('dict3'):
    dictC[item[0]] = item[1]

print(dictA)
print(dictB)
print(dictC)

Python 3.X example.

import configparser

config = configparser.ConfigParser()

dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}

# Make each dictionary a separate section in the configuration
config['dict1'] = dict1
config['dict2'] = dict2
config['dict3'] = dict3

# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()

# Read the configuration from a file
config2 = configparser.ConfigParser()
config2.read('config.ini')

# ConfigParser objects are a lot like dictionaries, but if you really
# want a dictionary you can ask it to convert a section to a dictionary
dictA = dict(config2['dict1'] )
dictB = dict(config2['dict2'] )
dictC = dict(config2['dict3'])

print(dictA)
print(dictB)
print(dictC)

Console output

{'key2': 'keyinfo2', 'key1': 'keyinfo'}
{'k1': 'hot', 'k2': 'cross', 'k3': 'buns'}
{'z': '3', 'y': '2', 'x': '1'}

Contents of config.ini

[dict1]
key2 = keyinfo2
key1 = keyinfo

[dict2]
k1 = hot
k2 = cross
k3 = buns

[dict3]
z = 3
y = 2
x = 1

Check if XML Element exists

 string name = "some node name";
    var xDoc = XDocument.Load("yourFile");
    var docRoot = xDoc.Element("your docs root name");

     var aNode = docRoot.Elements().Where(x => x.Name == name).FirstOrDefault();
                if (aNode == null)
                {
                    return $"file has no {name}";
                }

Using a cursor with dynamic SQL in a stored procedure

Another option in SQL Server is to do all of your dynamic querying into table variable in a stored proc, then use a cursor to query and process that. As to the dreaded cursor debate :), I have seen studies that show that in some situations, a cursor can actually be faster if properly set up. I use them myself when the required query is too complex, or just not humanly (for me ;) ) possible.

(grep) Regex to match non-ASCII characters?

This will match a single non-ASCII character:

[^\x00-\x7F]

This is a valid PCRE (Perl-Compatible Regular Expression).

You can also use the POSIX shorthands:

  • [[:ascii:]] - matches a single ASCII char
  • [^[:ascii:]] - matches a single non-ASCII char

[^[:print:]] will probably suffice for you.**

How to instantiate a javascript class in another js file?

It depends on what environment you're running in. In a web browser you simply need to make sure that file1.js is loaded before file2.js:

<script src="file1.js"></script>
<script src="file2.js"></script>

In node.js, the recommended way is to make file1 a module then you can load it with the require function:

require('path/to/file1.js');

It's also possible to use node's module style in HTML using the require.js library.

Remove all whitespace from C# string with regex

Using REGEX you can remove the spaces in a string.

The following namespace is mandatory.

using System.Text.RegularExpressions;

Syntax:

Regex.Replace(text, @"\s", "")

foreach loop in angularjs

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

How to convert data.frame column from Factor to numeric

As an alternative to $dollarsign notation, use a within block:

breast <- within(breast, {
  class <- as.numeric(as.character(class))
})

Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class) will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.

How to Get JSON Array Within JSON Object?

Your int length = jsonObj.length(); should be int length = ja_data.length();

HTTP requests and JSON parsing in Python

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module's documentation:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

So there is no use of having to use some separate module for decoding JSON.

PHP - print all properties of an object

As no one has not provided an OO approach yet here is like it would be done.

class Person {
    public $name = 'Alex Super Tramp';

    public $age = 100;

    private $property = 'property';
}


$r = new ReflectionClass(new Person);
print_r($r->getProperties());

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => name
            [class] => Person
        )

    [1] => ReflectionProperty Object
        (
            [name] => age
            [class] => Person
        )

    [2] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

The advantage when using reflection is that you can filter by visibility of property, like this:

print_r($r->getProperties(ReflectionProperty::IS_PRIVATE));

Since Person::$property is private it's returned when filtering by IS_PRIVATE:

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

Read the docs!

Apache POI error loading XSSFWorkbook class

commons-collections4-x.x.jar definitely solve this problem but Apache has removed the Interface ListValuedMap from commons-Collections4-4.0.jar so use updated version 4.1 it has the required classes and Interfaces.

Refer here if you want to read Excel (2003 or 2007+) using java code.

http://www.codejava.net/coding/how-to-read-excel-files-in-java-using-apache-poi

How to send image to PHP file using Ajax?

Post both multiple text inputs plus multiple files via Ajax in one Ajax request

HTML

<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">

Jquery Code

$(document).on('click','#btnSendData',function (event) {
    event.preventDefault();
    var form = $('#myform')[0];
    var formData = new FormData(form);
    // Set header if need any otherwise remove setup part
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
        }
    });
    $.ajax({
        url: "{{route('sendFormWithImage')}}",// your request url
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (data) {
            console.log(data);
        },
        error: function () {

        }
    });

});

How to terminate a thread when main program ends?

If you spawn a Thread like so - myThread = Thread(target = function) - and then do myThread.start(); myThread.join(). When CTRL-C is initiated, the main thread doesn't exit because it is waiting on that blocking myThread.join() call. To fix this, simply put in a timeout on the .join() call. The timeout can be as long as you wish. If you want it to wait indefinitely, just put in a really long timeout, like 99999. It's also good practice to do myThread.daemon = True so all the threads exit when the main thread(non-daemon) exits.

What is the best Java email address validation method?

Late answer, but I think it is simple and worthy:

    public boolean isValidEmailAddress(String email) {
           String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
           java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
           java.util.regex.Matcher m = p.matcher(email);
           return m.matches();
    }

Test Cases:

enter image description here

For production purpose, Domain Name validations should be performed network-wise.

What's wrong with overridable method calls in constructors?

Here's an example which helps to understand this:

public class Main {
    static abstract class A {
        abstract void foo();
        A() {
            System.out.println("Constructing A");
            foo();
        }
    }

    static class C extends A {
        C() { 
            System.out.println("Constructing C");
        }
        void foo() { 
            System.out.println("Using C"); 
        }
    }

    public static void main(String[] args) {
        C c = new C(); 
    }
}

If you run this code, you get the following output:

Constructing A
Using C
Constructing C

You see? foo() makes use of C before C's constructor has been run. If foo() requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo() expects, you get a warning.

Increasing the maximum post size

; Maximum allowed size for uploaded files.
upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M

How to upgrade all Python packages with pip

A JSON + jq answer:

pip list -o --format json | jq '.[] | .name' | xargs pip install -U

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

R dplyr: Drop multiple columns

Another way is to mutate the undesired columns to NULL, this avoids the embedded parentheses :

head(iris,2) %>% mutate_at(drop.cols, ~NULL)
#   Petal.Length Petal.Width Species
# 1          1.4         0.2  setosa
# 2          1.4         0.2  setosa

Fatal error: Call to undefined function mysqli_connect()

If you host the server yourself, in the php.ini file remove the semicolon in front of the extension extension=php_mysqli.dll

Case vs If Else If: Which is more efficient?

I believe because cases must be constant values, the switch statement does the equivelent of a goto, so based on the value of the variable it jumps to the right case, whereas in the if/then statement it must evaluate each expression.

Parsing Query String in node.js

node -v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

So I would suggest use JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

SQL Server Profiler - How to filter trace to only display events from one database?

Create a new template and check DBname. Use that template for your tracefile.

React - How to pass HTML tags in props?

Have appended the html in componentDidMount using jQuery append. This should solve the problem.

 var MyComponent = React.createClass({
    render: function() {

        return (
           <div>

           </div>
        );
    },
    componentDidMount() {
        $(ReactDOM.findDOMNode(this)).append(this.props.text);
    }
});

I cannot access tomcat admin console?

This is all I did and restarted the server.

<tomcat-users>

  <role rolename="tomcat"/>
  <user username="tomcat" password="tomcat" roles="manager-gui"/>

</tomcat-users>

Is there a way to get the git root directory in one command?

To amend the "git config" answer just a bit:

git config --global --add alias.root '!pwd -P'

and get the path cleaned up. Very nice.

Angular 5 - Copy to clipboard

You can achieve this using Angular modules:

navigator.clipboard.writeText('your text').then().catch(e => console.error(e));

Android notification is not showing

You also need to change the build.gradle file, and add the used Android SDK version into it:

implementation 'com.android.support:appcompat-v7:28.0.0'

This worked like a charm in my case.

Entity Framework 6 Code first Default value

After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.

1- Create custom code generator and override Generate for a ColumnModel.

   public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{

    protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
    {

        if (column.Annotations.Keys.Contains("Default"))
        {
            var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
            column.DefaultValue = value;
        }


        base.Generate(column, writer, emitName);
    }

}

2- Assign the new code generator:

public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
    public Configuration()
    {
        CodeGenerator = new ExtendedMigrationCodeGenerator();
        AutomaticMigrationsEnabled = false;
    }
}

3- Use fluent api to created the Annotation:

public static void Configure(DbModelBuilder builder){    
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);            
}

How to convert a string to lower case in Bash?

In bash 4 you can use typeset

Example:

A="HELLO WORLD"
typeset -l A=$A

get parent's view from a layout

You can get ANY view by using the code below

view.rootView.findViewById(R.id.*name_of_the_view*)

EDIT: This works on Kotlin. In Java, you may need to do something like this=

this.getCurrentFocus().getRootView().findViewById(R.id.*name_of_the_view*);

I learned getCurrentFocus() function from: @JFreeman 's answer

How to pass variable number of arguments to printf/sprintf

have a look at vsnprintf as this will do what ya want http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/

you will have to init the va_list arg array first, then call it.

Example from that link: /* vsprintf example */

#include <stdio.h>
#include <stdarg.h>

void Error (char * format, ...)
{
  char buffer[256];
  va_list args;
  va_start (args, format);
  vsnprintf (buffer, 255, format, args);


  //do something with the error

  va_end (args);
}

laravel foreach loop in controller

Is sku just a property of the Product model? If so:

$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();

foreach ($products as $product ) {
  // Access $product->sku here...
}

Or is sku a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

Catching access violation exceptions?

As stated, there is no non Microsoft / compiler vendor way to do this on the windows platform. However, it is obviously useful to catch these types of exceptions in the normal try { } catch (exception ex) { } way for error reporting and more a graceful exit of your app (as JaredPar says, the app is now probably in trouble). We use _se_translator_function in a simple class wrapper that allows us to catch the following exceptions in a a try handler:

DECLARE_EXCEPTION_CLASS(datatype_misalignment)
DECLARE_EXCEPTION_CLASS(breakpoint)
DECLARE_EXCEPTION_CLASS(single_step)
DECLARE_EXCEPTION_CLASS(array_bounds_exceeded)
DECLARE_EXCEPTION_CLASS(flt_denormal_operand)
DECLARE_EXCEPTION_CLASS(flt_divide_by_zero)
DECLARE_EXCEPTION_CLASS(flt_inexact_result)
DECLARE_EXCEPTION_CLASS(flt_invalid_operation)
DECLARE_EXCEPTION_CLASS(flt_overflow)
DECLARE_EXCEPTION_CLASS(flt_stack_check)
DECLARE_EXCEPTION_CLASS(flt_underflow)
DECLARE_EXCEPTION_CLASS(int_divide_by_zero)
DECLARE_EXCEPTION_CLASS(int_overflow)
DECLARE_EXCEPTION_CLASS(priv_instruction)
DECLARE_EXCEPTION_CLASS(in_page_error)
DECLARE_EXCEPTION_CLASS(illegal_instruction)
DECLARE_EXCEPTION_CLASS(noncontinuable_exception)
DECLARE_EXCEPTION_CLASS(stack_overflow)
DECLARE_EXCEPTION_CLASS(invalid_disposition)
DECLARE_EXCEPTION_CLASS(guard_page)
DECLARE_EXCEPTION_CLASS(invalid_handle)
DECLARE_EXCEPTION_CLASS(microsoft_cpp)

The original class came from this very useful article:

http://www.codeproject.com/KB/cpp/exception.aspx

Calling stored procedure with return value

I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah

Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

ExpressJS How to structure an application?

This may be of interest:

https://github.com/flatiron/nconf

Hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Load HTML File Contents to Div [without the use of iframes]

http://www.boutell.com/newfaq/creating/include.html

this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

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

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

Showing all errors and warnings

Display errors could be turned off in the php.ini or your Apache configuration file.

You can turn it on in the script:

error_reporting(E_ALL);
ini_set('display_errors', '1');

You should see the same messages in the PHP error log.

Hibernate Auto Increment ID

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

and you leave it null (0) when persisting. (null if you use the Integer / Long wrappers)

In some cases the AUTO strategy is resolved to SEQUENCE rathen than to IDENTITY or TABLE, so you might want to manually set it to IDENTITY or TABLE (depending on the underlying database).

It seems SEQUENCE + specifying the sequence name worked for you.

How do I get the calling method name and type using reflection?

It's actually something that can be done using a combination of the current stack-trace data, and reflection.

public void MyMethod()
{
     StackTrace stackTrace = new System.Diagnostics.StackTrace();
     StackFrame frame = stackTrace.GetFrames()[1];
     MethodInfo method = frame.GetMethod();
     string methodName = method.Name;
     Type methodsClass = method.DeclaringType;
}

The 1 index on the StackFrame array will give you the method which called MyMethod

How to create permanent PowerShell Aliases

2018, Windows 10

You can link to any file or directory with the help of a simple PowerShell script.

Writing a file shortcut script

Open Windows PowerShell ISE. In the script pane write:

New-Alias ${shortcutName} ${fullFileLocation}

Then head to the command-line pane. Find your PowerShell user profile address with echo $profile. Save the script in this address.

enter image description here

The script in PowerShell's profile address will run each time you open powershell. The shortcut should work with every new PowerShell window.

Writing a directory shortcut script

It requires another line in our script.

function ${nameOfFunction} {set-location ${directory_location}}
New-Alias ${shortcut} ${nameOfFunction} 

The rest is exactly the same.

enter image description here

Enable PowerShell Scripts

By default PowerShell scripts are blocked. To enable them, open settings -> Update & Security -> For developers. Select Developer Mode (might require restart). Selecting Developer Mode Windows 10.

Scroll down to the PowerShell section, tick the "Change execution policy ..." option, and apply.

Enabling PowerShell scripts

Check if a PHP cookie exists and if not set its value

Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

Source

Define variable to use with IN operator (T-SQL)

I know this is old now but TSQL => 2016, you can use STRING_SPLIT:

DECLARE @InList varchar(255) = 'This;Is;My;List';

WITH InList (Item) AS (
    SELECT value FROM STRING_SPLIT(@InList, ';')
)

SELECT * 
FROM [Table]
WHERE [Item] IN (SELECT Tag FROM InList)

Handling JSON Post Request in Go

Please use json.Decoder instead of json.Unmarshal.

func test(rw http.ResponseWriter, req *http.Request) {
    decoder := json.NewDecoder(req.Body)
    var t test_struct
    err := decoder.Decode(&t)
    if err != nil {
        panic(err)
    }
    log.Println(t.Test)
}

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

All of the functionality of our lightweight IDEs can be found within IntelliJ IDEA (you need to install the corresponding plug-ins from the repository).

It includes support for all technologies developed for our more specific products such as Web/PhpStorm, RubyMine and PyCharm.

The specific feature missing from IntelliJ IDEA is simplified project creation ("Open Directory") used in lighter products as it is not applicable to the IDE that support such a wide range of languages and technologies. It also means that you can't create projects directly from the remote hosts in IDEA.

If you are missing any other feature that is available in lighter products, but is not available in IntelliJ IDEA Ultimate, you are welcome to report it and we'll consider adding it.

While PHP, Python and Ruby IDEA plug-ins are built from the same source code as used in PhpStorm, PyCharm and RubyMine, product release cycles are not synchronized. It means that some features may be already available in the lighter products, but not available in IDEA plug-ins at certain periods, they are added with the plug-in and IDEA updates later.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

How can one tell the version of React running at runtime in the browser?

Open Chrome Dev Tools or equivalent and run require('React').version in the console.

That works on websites like Facebook as well to find out what version they are using.

How to input matrix (2D list) in Python?

This code takes number of row and column from user then takes elements and displays as a matrix.

m = int(input('number of rows, m : '))
n = int(input('number of columns, n : '))
a=[]
for i in range(1,m+1):
  b = []
  print("{0} Row".format(i))
  for j in range(1,n+1):
    b.append(int(input("{0} Column: " .format(j))))
  a.append(b)
print(a)

Call Class Method From Another Class

In Python function are first class citezens, so you can just assign it to a property like any other value. Here we are assigning the method of A's hello to a property on B. After __init__, hello will be attached to B as self.hello, which is actually a reference to A's hello:

class A:
    def hello(self, msg):
        print(f"Hello {msg}")
    
class B:
    hello = A.hello

print(A.hello)
print(B.hello)

b = B()
b.hello("good looking!")

Prints:

<function A.hello at 0x7fcce55b9e50>
<function A.hello at 0x7fcce55b9e50>
Hello good looking!

convert string into array of integers

us the split function:

var splitresult = "14 2".split(" ");

How to install PIP on Python 3.6?

There are situations when your pip doesn't get downloaded along with python installation. Even your whole script folder can be empty.

You can do so manually as well.

Just head to Command Prompt and type python -m ensurepip --default-pip Press Enter.

Make sure that value of path variable is updated.

This will do the Trick

EL access a map value by Integer key

You can use all functions from Long, if you put the number into "(" ")". That way you can cast the long to an int:

<c:out value="${map[(1).intValue()]}"/>

Find a class somewhere inside dozens of JAR files?

Filename: searchForFiles.py

import os, zipfile, glob, sys

def main():
    searchFile = sys.argv[1] #class file to search for, sent from batch file below (optional, see second block of code below)
    listOfFilesInJar = []
    for file in glob.glob("*.jar"):
        archive = zipfile.ZipFile(file, 'r')
        for x in archive.namelist():
            if str(searchFile) in str(x):
                listOfFilesInJar.append(file)

    for something in listOfFilesInJar:
        print("location of "+str(searchFile)+": ",something)

if __name__ == "__main__":
    sys.exit(main())

You can easily run this by making a .bat file with the following text (replace "AddWorkflows.class" with the file you are searching for):

(File: CallSearchForFiles.bat)

@echo off
python -B -c "import searchForFiles;x=searchForFiles.main();" AddWorkflows.class
pause

You can double-click CallSearchForFiles.bat to run it, or call it from the command line "CallSearchForFiles.bat SearchFile.class"

Click to See Example Output

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

Counting how many times a certain char appears in a string before any other char appears

You could use the Count method

var count = mystring.Count(x => x == '$')

What should my Objective-C singleton look like?

I know there are a lot of comments on this "question", but I don't see many people suggesting using a macro to define the singleton. It's such a common pattern and a macro greatly simplifies the singleton.

Here are the macros I wrote based on several Objc implementations I've seen.

Singeton.h

/**
 @abstract  Helps define the interface of a singleton.
 @param  TYPE  The type of this singleton.
 @param  NAME  The name of the singleton accessor.  Must match the name used in the implementation.
 @discussion
 Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.
 */
#define SingletonInterface(TYPE, NAME) \
+ (TYPE *)NAME;


/**
 @abstract  Helps define the implementation of a singleton.
 @param  TYPE  The type of this singleton.
 @param  NAME  The name of the singleton accessor.  Must match the name used in the interface.
 @discussion
 Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.
 */
#define SingletonImplementation(TYPE, NAME) \
static TYPE *__ ## NAME; \
\
\
+ (void)initialize \
{ \
    static BOOL initialized = NO; \
    if(!initialized) \
    { \
        initialized = YES; \
        __ ## NAME = [[TYPE alloc] init]; \
    } \
} \
\
\
+ (TYPE *)NAME \
{ \
    return __ ## NAME; \
}

Example of use:

MyManager.h

@interface MyManager

SingletonInterface(MyManager, sharedManager);

// ...

@end

MyManager.m

@implementation MyManager

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

SingletonImplementation(MyManager, sharedManager);

// ...

@end

Why a interface macro when it's nearly empty? Code consistency between the header and code files; maintainability in case you want to add more automatic methods or change it around.

I'm using the initialize method to create the singleton as is used in the most popular answer here (at time of writing).

How do I make a dictionary with multiple keys to one value?

Your example creates multiple key: value pairs if using fromkeys. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.

>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True

Uploading multiple files using formData()

Adding [] when appending to fd works, but if you prefer to have your data grouped by file then I'd suggest doing it this way:

var files= document.getElementById('inpFile').files
var fd = new FormData()

for (let i = 0; i < files.length; i++) {
  fd.append(i, files[i])
}

Now your data will be sent grouped by file instead of grouped by attribute.

Array of PHP Objects

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
    public $color;
    public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
    echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.

Create a view model class like this:

public class EmployeeAddViewModel
{
    public Employee employee { get; set; }
    public Dictionary<int, string> staffTypes { get; set; }
    // really? a 1-to-many for genders
    public Dictionary<int, string> genderTypes { get; set; }

    public EmployeeAddViewModel() { }
    public EmployeeAddViewModel(int id)
    {
        employee = someEntityContext.Employees
            .Where(e => e.ID == id).SingleOrDefault();

        // instantiate your dictionaries

        foreach(var staffType in someEntityContext.StaffTypes)
        {
            staffTypes.Add(staffType.ID, staffType.Type);
        }

        // repeat similar loop for gender types
    }
}

Controller:

[HttpGet]
public ActionResult Add()
{
    return View(new EmployeeAddViewModel());
}

[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
    if(ModelState.IsValid)
    {
        Employee.Add(vm.Employee);
        return View("Index"); // or wherever you go after successful add
    }

    return View(vm);
}

Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:

@Html.DropDownListFor(model => model.employee.staffTypeID,
    new SelectList(model.staffTypes, "ID", "Type"))

and similarly for the gender dropdown

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(model.genderTypes, "ID", "Gender"))

Update per comments

For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList... below, you would use your IEnumerable.

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(new SelectList()
    {
        new { ID = 1, Gender = "Male" },
        new { ID = 2, Gender = "Female" }
    }, "ID", "Gender"))

Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:

ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1  | Gender     | 1         | Male        | male gender       | 1
2  | State      | 50        | Hawaii      | 50th state        | 1
3  | Gender     | 2         | Female      | female gender     | 1
4  | State      | 49        | Alaska      | 49th state        | 1
5  | OrderType  | 1         | Web         | online order      | 1

I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.

Hope this helps!

Web.Config Debug/Release

It is possible using ConfigTransform build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/

All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.

The same applies to "app.*.config" transform files in non-web projects.

and then adding the following target to your *.csproj.

<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
    <TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>

Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.

Fatal error: Class 'SoapClient' not found

To install SOAP in PHP-7 run following in your Ubuntu terminal:

sudo apt-get install php7.0-soap

To install SOAP in PHP-7.1 run following in your Ubuntu terminal:

sudo apt-get install php7.1-soap

To install SOAP in PHP-7.2 run following in your Ubuntu terminal:

sudo apt-get install php7.2-soap

To install SOAP in PHP-7.3 run following in your Ubuntu terminal:

sudo apt-get install php7.3-soap

How to download an entire directory and subdirectories using wget?

You can use this in a shell:

wget -r -nH --cut-dirs=7 --reject="index.html*" \
      http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r recursively download

-nH (--no-host-directories) cuts out hostname 

--cut-dirs=X (cuts out X directories)

How to add images to README.md on GitHub?

Just add an <img> tag to your README.md with relative src to your repository. If you're not using relative src, make sure the server supports CORS.

It works because GitHub support inline-html

<img src="/docs/logo.png" alt="My cool logo"/>
# My cool project and above is the logo of it

Observe here

Keylistener in Javascript

JSFIDDLE DEMO

If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup

window.onkeydown = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 38) { //up key
        alert('up');
    } else if (code === 40) { //down key
        alert('down');
    }
};

Amazon S3 direct file upload from client browser - private key disclosure

Adding more info to the accepted answer, you can refer to my blog to see a running version of the code, using AWS Signature version 4.

Will summarize here:

As soon as the user selects a file to be uploaded, do the followings: 1. Make a call to the web server to initiate a service to generate required params

  1. In this service, make a call to AWS IAM service to get temporary cred

  2. Once you have the cred, create a bucket policy (base 64 encoded string). Then sign the bucket policy with the temporary secret access key to generate final signature

  3. send the necessary parameters back to the UI

  4. Once this is received, create a html form object, set the required params and POST it.

For detailed info, please refer https://wordpress1763.wordpress.com/2016/10/03/browser-based-upload-aws-signature-version-4/

Detect If Browser Tab Has Focus

I would do it this way (Reference http://www.w3.org/TR/page-visibility/):

    window.onload = function() {

        // check the visiblility of the page
        var hidden, visibilityState, visibilityChange;

        if (typeof document.hidden !== "undefined") {
            hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
        }
        else if (typeof document.mozHidden !== "undefined") {
            hidden = "mozHidden", visibilityChange = "mozvisibilitychange", visibilityState = "mozVisibilityState";
        }
        else if (typeof document.msHidden !== "undefined") {
            hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";
        }
        else if (typeof document.webkitHidden !== "undefined") {
            hidden = "webkitHidden", visibilityChange = "webkitvisibilitychange", visibilityState = "webkitVisibilityState";
        }


        if (typeof document.addEventListener === "undefined" || typeof hidden === "undefined") {
            // not supported
        }
        else {
            document.addEventListener(visibilityChange, function() {
                console.log("hidden: " + document[hidden]);
                console.log(document[visibilityState]);

                switch (document[visibilityState]) {
                case "visible":
                    // visible
                    break;
                case "hidden":
                    // hidden
                    break;
                }
            }, false);
        }

        if (document[visibilityState] === "visible") {
            // visible
        }

    };  

Java 8 stream's .min() and .max(): why does this compile?

I had an error with an array getting the max and the min so my solution was:

int max = Arrays.stream(arrayWithInts).max().getAsInt();
int min = Arrays.stream(arrayWithInts).min().getAsInt();

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

Even if you do xcode-select --install it was not fixing that for me as it showed some network error. The problem was that it could not connect to the app store. I did the following to fix it.

  1. Open keystore
  2. Go to system root and select certificates.
  3. Open digicert high assurance EV.
  4. Expand the trust section, mark it as never trust.
  5. Restart system now repeat step 1, 2, 3. and mark the trust policy as back to use system defaults.

Your app store should work now and you should be able to run xcode-select --install

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

Can I get image from canvas element and use it in img src tag?

canvas.toDataURL() will provide you a data url which can be used as source:

var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);

Complete example

Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.

_x000D_
_x000D_
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");

// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");

ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
  ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();

// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();

document.getElementById('result').appendChild(target);
_x000D_
canvas { border: 1px solid black; }
img    { border: 1px solid blue;  }
body   { display: flex; }
div + div {margin-left: 1ex; }
_x000D_
<div>
  <p>Original:</p>
  <canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
  <p>Result via &lt;img&gt;:</p>
</div>
_x000D_
_x000D_
_x000D_

See also:

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Open Form2 from Form1, close Form1 from Form2

private void button1_Click(object sender, EventArgs e)
{
      Form2 m = new Form2();
      m.Show();
      this.Visible = false;
}

How to subtract 30 days from the current date using SQL Server

TRY THIS:

Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

SELECT DATEADD(dd, -30, 
       CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
       AS DATETIME))

How can you debug a CORS request with cURL?

Seems like just this works:

curl -I http://example.com

Look for Access-Control-Allow-Origin: * in the returned headers

Best place to insert the Google Analytics code

Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.

Is there a Pattern Matching Utility like GREP in Windows?

I also found one more way of utilizing GREP like functionality in Windows 7 and above without any extra application to install and on older systems you can use install Powershell.

In Powershell, User can use Where-Object it has quite comprehensive set of feature that provides all the functionality of GREP plus more.

Hope It helps.

How can I add a hint text to WPF textbox?

Do it in the code-behind by setting the text color initially to gray and adding event handlers for gaining and losing keyboard focus.

TextBox tb = new TextBox();
tb.Foreground = Brushes.Gray;
tb.Text = "Text";
tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus);
tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus);

Then the event handlers:

private void tb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if(sender is TextBox)
    {
        //If nothing has been entered yet.
        if(((TextBox)sender).Foreground == Brushes.Gray)
        {
            ((TextBox)sender).Text = "";
            ((TextBox)sender).Foreground = Brushes.Black;
        }
    }
}


private void tb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    //Make sure sender is the correct Control.
    if(sender is TextBox)
    {
        //If nothing was entered, reset default text.
        if(((TextBox)sender).Text.Trim().Equals(""))
        {
            ((TextBox)sender).Foreground = Brushes.Gray;
            ((TextBox)sender).Text = "Text";
        }
    }
}

Android - Handle "Enter" in an EditText

Using Kotlin I've made a function that handles all kinds of "done"-like actions for EditText, including the keyboard, and it's possible to modify it and also handle other keys as you wish, too :

private val DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT = arrayListOf(EditorInfo.IME_ACTION_SEND, EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE)
private val DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT = arrayListOf(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)

fun EditText.setOnDoneListener(function: () -> Unit, onKeyListener: OnKeyListener? = null, onEditorActionListener: TextView.OnEditorActionListener? = null,
                               actionsToHandle: Collection<Int> = DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT,
                               keysToHandle: Collection<Int> = DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT) {
    setOnEditorActionListener { v, actionId, event ->
        if (onEditorActionListener?.onEditorAction(v, actionId, event) == true)
            return@setOnEditorActionListener true
        if (actionsToHandle.contains(actionId)) {
            function.invoke()
            return@setOnEditorActionListener true
        }
        return@setOnEditorActionListener false
    }
    setOnKeyListener { v, keyCode, event ->
        if (onKeyListener?.onKey(v, keyCode, event) == true)
            return@setOnKeyListener true
        if (event.action == KeyEvent.ACTION_DOWN && keysToHandle.contains(keyCode)) {
            function.invoke()
            return@setOnKeyListener true
        }
        return@setOnKeyListener false
    }
}

So, sample usage:

        editText.setOnDoneListener({
            //do something
        })

As for changing the label, I think it depends on the keyboard app, and that it usually change only on landscape, as written here. Anyway, example usage for this:

        editText.imeOptions = EditorInfo.IME_ACTION_DONE
        editText.setImeActionLabel("ASD", editText.imeOptions)

Or, if you want in XML:

    <EditText
        android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:imeActionLabel="ZZZ" android:imeOptions="actionDone" />

And the result (shown in landscape) :

enter image description here

How do you auto format code in Visual Studio?

Just to further Starwfanatic and Ewan's answers above. You can customise your IDE to add any button to any toolbar - so you can add the Format button (as the HTML Source Editing toolbar has) to any other toolbar (like Text Editing with all the other edit controls like increase/decrease indent).

Click the arrow to the right of the toolbar > Add or Remove Buttons > Customize... > Commands tab > Add Command... button.

Document Format and Selection Format are both under the Edit group.

(Tested in VS2010 and VS2013)

count distinct values in spreadsheet

=UNIQUE({filter(Core!L8:L27,isblank(Core!L8:L27)=false),query(ArrayFormula(countif(Core!L8:L27,Core!L8:L27)),"select Col1 where Col1 <> 0")})

Core!L8:L27 = list

How can I add a line to a file in a shell script?

This adds custom text at the beginning of your file:

echo 'your_custom_escaped_content' > temp_file.csv
cat testfile.csv >> temp_file.csv
mv temp_file.csv testfile.csv

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I encountered the same issue and lateron found out that, I have missed call to super.onCreate( savedInstanceState ); in onCreate() of FragmentActivity.

How to tell if a JavaScript function is defined

All of the current answers use a literal string, which I prefer to not have in my code if possible - this does not (and provides valuable semantic meaning, to boot):

function isFunction(possibleFunction) {
  return typeof(possibleFunction) === typeof(Function);
}

Personally, I try to reduce the number of strings hanging around in my code...


Also, while I am aware that typeof is an operator and not a function, there is little harm in using syntax that makes it appear as the latter.

Allow scroll but hide scrollbar

Try this:

HTML:

<div id="container">
    <div id="content">
        // Content here
    </div>
</div>

CSS:

#container{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#content{
    width: 100%;
    height: 99%;
    overflow: auto;
    padding-right: 15px;
}

html, body{
    height: 99%;
    overflow:hidden;
}

JSFiddle Demo

Tested on FF and Safari.

regex error - nothing to repeat

It's not only a Python bug with * actually, it can also happen when you pass a string as a part of your regular expression to be compiled, like ;

import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)

this will cause an error if processed line contained some "(+)" for example, like you can find in chemical formulae, or such chains of characters. the solution is to escape but when you do it on the fly, it can happen that you fail to do it properly...

Bootstrap number validation

You should use jquery validation because if you use type="number" then you can also enter "E" character in input type, which is not correct.

Solution:

HTML

<input class="form-control floatNumber" name="energy1_total_power_generated" type="text" required="" > 

JQuery

//integer value validation
$('input.floatNumber').on('input', function() {
    this.value = this.value.replace(/[^0-9.]/g,'').replace(/(\..*)\./g, '$1');
});

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

Its easy go to File - Data Modeler - Import - Data Dictionary - DB connection - OK

move a virtual machine from one vCenter to another vCenter

For moving a virtual machine you need not clone the VM, just copy the VM files (after powering the VM off) to external HDD and register the same on destination host.

convert big endian to little endian in C [without using provided func]

This code snippet can convert 32bit little Endian number to Big Endian number.

#include <stdio.h>
main(){    
    unsigned int i = 0xfafbfcfd;
    unsigned int j;    
    j= ((i&0xff000000)>>24)| ((i&0xff0000)>>8) | ((i&0xff00)<<8) | ((i&0xff)<<24);    
    printf("unsigned int j = %x\n ", j);    
}

How to create an object property from a variable value in JavaScript?

You could just use this:

function createObject(propName, propValue){
    this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');

Anything you pass as the first parameter will be the property name, and the second parameter is the property value.

Appending a list to a list of lists in R

This answer is similar to the accepted one, but a bit less convoluted.

L<-list()
for (i in 1:3) {
L<-c(L, list(list(sample(1:3))))
}

how to set the query timeout from SQL connection string

No. It's per command, not per connection.

Edit, May 2013

As requested in comment:

Some more notes about commands and execution time outs in SQL Server (DBA.SE). And more SO stuff: What happens to an uncommitted transaction when the connection is closed?

Execute another jar in a Java program

If you are java 1.6 then the following can also be done:

import javax.tools.JavaCompiler; 
import javax.tools.ToolProvider; 

public class CompilerExample {

    public static void main(String[] args) {
        String fileToCompile = "/Users/rupas/VolatileExample.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compilationResult = compiler.run(null, null, null, fileToCompile);

        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
    }
}

How to connect to LocalDb

You can connect with MSSMS to LocalDB. Type only in SERVER NAME: (localdb)\v11.0 and leave it by Windows Authentication and it connects to your LocalDB server and shows you the databases in it.

Nth word in a string variable

A file containing some statements :

cat test.txt

Result :

This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement

So, to print the 4th word of this statement type :

cat test.txt |awk '{print $4}'

Output :

1st
2nd
3rd
4th
5th

System.currentTimeMillis vs System.nanoTime

If you're just looking for extremely precise measurements of elapsed time, use System.nanoTime(). System.currentTimeMillis() will give you the most accurate possible elapsed time in milliseconds since the epoch, but System.nanoTime() gives you a nanosecond-precise time, relative to some arbitrary point.

From the Java Documentation:

public static long nanoTime()

Returns the current value of the most precise available system timer, in nanoseconds.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

For example, to measure how long some code takes to execute:

long startTime = System.nanoTime();    
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;

See also: JavaDoc System.nanoTime() and JavaDoc System.currentTimeMillis() for more info.

how to convert an RGB image to numpy array?

When using the answer from David Poole I get a SystemError with gray scale PNGs and maybe other files. My solution is:

import numpy as np
from PIL import Image

img = Image.open( filename )
try:
    data = np.asarray( img, dtype='uint8' )
except SystemError:
    data = np.asarray( img.getdata(), dtype='uint8' )

Actually img.getdata() would work for all files, but it's slower, so I use it only when the other method fails.

Deleting Row in SQLite in Android

Try this code...

private static final String mname = "'USERNAME'";
public void deleteContact()
{
    db.delete(TABLE_CONTACTS, KEY_NAME + "=" + mname, null);
}

How to order a data frame by one descending and one ascending column?

In @dudusan's example, you could also reverse the order of I1, and then sort ascending:

> rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
+   2   3   5   52  43  61  6   b
+   6   4   3   72  NA  59  1   a
+   1   5   6   55  48  60  6   f
+   2   4   4   65  64  58  2   b
+   1   5   6   55  48  60  6   c"), header = TRUE)
> f=factor(rum$I1)   
> levels(f) <- sort(levels(f), decreasing = TRUE)
> rum[order(as.character(f), rum$I2), ]
  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a
> 

This seems a bit shorter, you don't reverse the order of I2 twice.

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

How to post JSON to PHP with curl

Normally the parameter -d is interpreted as form-encoded. You need the -H parameter:

curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

If you are on a mac check if you for a hidden file, .DS_Store. After removing the file my program worked.

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

I can give you two advices:

  1. It seems you are using "LoadXml" instead of "Load" method. In some cases, it helps me.
  2. You have an encoding problem. Could you check the encoding of the XML file and write it?

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Split a string by another string in C#

The easiest way is to use String.Replace:

string myString = "THExxQUICKxxBROWNxxFOX";
mystring = mystring.Replace("xx", ", ");

Or more simply:

string myString = "THExxQUICKxxBROWNxxFOX".Replace("xx", ", ");

Java 8 - Best way to transform a list: map or foreach?

If you use Eclipse Collections you can use the collectIf() method.

MutableList<Integer> source =
    Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);

MutableList<String> result = source.collectIf(Objects::nonNull, String::valueOf);

Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);

It evaluates eagerly and should be a bit faster than using a Stream.

Note: I am a committer for Eclipse Collections.

Running python script inside ipython

How to run a script in Ipython

import os
filepath='C:\\Users\\User\\FolderWithPythonScript' 
os.chdir(filepath)
%run pyFileInThatFilePath.py

That should do it

What languages are Windows, Mac OS X and Linux written in?

The Linux kernel is mostly written in C (and a bit of assembly language, I'd imagine), but some of the important userspace utilities (programs) are shell scripts written in the Bash scripting language. Beyond that, it's sort of hard to define "Linux" since you basically build a Linux system by picking bits and pieces you want and putting them together, and depending on what an individual Linux user wants, you can get pretty much any language involved. (As Paul said, Python and C++ play important roles)

Finding modified date of a file/folder

Here's what worked for me:

$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}  
#Im using the -gt switch instead of -ge
{}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}


$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)))}
{}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}

How to add hyperlink in JLabel?

Use a JEditorPane with a HyperlinkListener.

MySQL: Can't create table (errno: 150)

Error 150 means you have a problem with your foreign key. Possibly the key on the foreign table isn't the exact same type?

change html text from link with jquery

The method you are looking for is jQuery's .text() and you can used it in the following fashion:

$('#a_tbnotesverbergen').text('text here');

How to ftp with a batch file?

This is an old post however, one alternative is to use the command options:

ftp -n -s:ftpcmd.txt

the -n will suppress the initial login and then the file contents would be: (replace the 127.0.0.1 with your FTP site url)

open 127.0.0.1
user myFTPuser myftppassword
other commands here...

This avoids the user/password on separate lines

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

How would I extract a single file (or changes to a file) from a git stash?

The simplest concept to understand, although maybe not the best, is you have three files changed and you want to stash one file.

If you do git stash to stash them all, git stash apply to bring them back again and then git checkout f.c on the file in question to effectively reset it.

When you want to unstash that file run do a git reset --hard and then run git stash apply again, taking advantage ofthe fact that git stash apply doesn't clear the diff from the stash stack.

How do I get a button to open another activity?

Button T=(Button)findViewById(R.id.button_timer);
T.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i=new Intent(getApplicationContext(),YOURACTIVITY.class);
        startActivity(i);
    }
});

"The public type <<classname>> must be defined in its own file" error in Eclipse

Save this class in the file StaticDemo.java. Also you cant have more than one public classes in one file.

Reading and displaying data from a .txt file

Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).

import java.io.*;
import java.util.Scanner;
import java.io.*;

public class TestRead
{
public static void main(String[] input)
{
    String fname;
    Scanner scan = new Scanner(System.in);

    /* enter filename with extension to open and read its content */

    System.out.print("Enter File Name to Open (with extension like file.txt) : ");
    fname = scan.nextLine();

    /* this will reference only one line at a time */

    String line = null;
    try
    {
        /* FileReader reads text files in the default encoding */
        FileReader fileReader = new FileReader(fname);

        /* always wrap the FileReader in BufferedReader */
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null)
        {
            System.out.println(line);
        }

        /* always close the file after use */
        bufferedReader.close();
    }
    catch(IOException ex)
    {
        System.out.println("Error reading file named '" + fname + "'");
    }
}

}

Apply global variable to Vuejs

In VueJS 3 with createApp() you can use app.config.globalProperties

Like this:

const app = createApp(App);

app.config.globalProperties.foo = 'bar';

app.use(store).use(router).mount('#app');

and call your variable like this:

app.component('child-component', {
  mounted() {
    console.log(this.foo) // 'bar'
  }
})

doc: https://v3.vuejs.org/api/application-config.html#warnhandler

If your data is reactive, you may want to use VueX.

Angularjs ng-model doesn't work inside ng-if

You can use $parent to refer to the model defined in the parent scope like this

<input type="checkbox" ng-model="$parent.testb" />

Sorting objects by property values

I have wrote this simple function for myself:

function sortObj(list, key) {
    function compare(a, b) {
        a = a[key];
        b = b[key];
        var type = (typeof(a) === 'string' ||
                    typeof(b) === 'string') ? 'string' : 'number';
        var result;
        if (type === 'string') result = a.localeCompare(b);
        else result = a - b;
        return result;
    }
    return list.sort(compare);
}

for example you have list of cars:

var cars= [{brand: 'audi', speed: 240}, {brand: 'fiat', speed: 190}];
var carsSortedByBrand = sortObj(cars, 'brand');
var carsSortedBySpeed = sortObj(cars, 'speed');

How can I zoom an HTML element in Firefox and Opera?

I've been swearing at this for a while. Zoom is definitely not the solutions, it works in chrome, it works partially in IE but moves the entire html div, firefox doesnt do a thing.

My solution that worked for me was using both a scaling and a translation, and also adding the original height and weight and then setting the height and weight of the div itself:

#miniPreview {
transform: translate(-710px, -1000px) rotate(0rad) skewX(0rad) scale(0.3, 0.3);
transform-origin: 1010px 1429px 0px;
width: 337px;
height: 476px;

Obviously change these to your own needs. It gave me the same result in all browsers.

Swift - Integer conversion to Hours/Minutes/Seconds

Swift 5 & String Response, In presentable format

public static func secondsToHoursMinutesSecondsStr (seconds : Int) -> String {
      let (hours, minutes, seconds) = secondsToHoursMinutesSeconds(seconds: seconds);
      var str = hours > 0 ? "\(hours) h" : ""
      str = minutes > 0 ? str + " \(minutes) min" : str
      str = seconds > 0 ? str + " \(seconds) sec" : str
      return str
  }

public static func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
        return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
 }

Usage:

print(secondsToHoursMinutesSecondsStr(seconds: 20000)) // Result = "5 h 33 min 20 sec"

GDB: break if variable equal value

in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.

(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4

Breakpoint 2, main () at iter.c:6
6           printf("%d\n", i);

If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:

#include <stdio.h>
main()
{ 
     int i = 0;
     for(i=0;i<7;++i) {
       looping:
        printf("%d\n", i);
     }
     return 0;
}

(gdb) break main:looping if i == 5

How to sum up an array of integers in C#

In one of my apps I used :

public class ClassBlock
{
    public int[] p;
    public int Sum
    {
        get { int s = 0;  Array.ForEach(p, delegate (int i) { s += i; }); return s; }
    }
}

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

Try doing a rebuild. I've found that the red x's don't always disappear until a rebuild is done.

RE error: illegal byte sequence on Mac OS X

A sample command that exhibits the symptom: sed 's/./@/' <<<$'\xfc' fails, because byte 0xfc is not a valid UTF-8 char.
Note that, by contrast, GNU sed (Linux, but also installable on macOS) simply passes the invalid byte through, without reporting an error.

Using the formerly accepted answer is an option if you don't mind losing support for your true locale (if you're on a US system and you never need to deal with foreign characters, that may be fine.)

However, the same effect can be had ad-hoc for a single command only:

LC_ALL=C sed -i "" 's|"iphoneos-cross","llvm-gcc:-O3|"iphoneos-cross","clang:-Os|g' Configure

Note: What matters is an effective LC_CTYPE setting of C, so LC_CTYPE=C sed ... would normally also work, but if LC_ALL happens to be set (to something other than C), it will override individual LC_*-category variables such as LC_CTYPE. Thus, the most robust approach is to set LC_ALL.

However, (effectively) setting LC_CTYPE to C treats strings as if each byte were its own character (no interpretation based on encoding rules is performed), with no regard for the - multibyte-on-demand - UTF-8 encoding that OS X employs by default, where foreign characters have multibyte encodings.

In a nutshell: setting LC_CTYPE to C causes the shell and utilities to only recognize basic English letters as letters (the ones in the 7-bit ASCII range), so that foreign chars. will not be treated as letters, causing, for instance, upper-/lowercase conversions to fail.

Again, this may be fine if you needn't match multibyte-encoded characters such as é, and simply want to pass such characters through.

If this is insufficient and/or you want to understand the cause of the original error (including determining what input bytes caused the problem) and perform encoding conversions on demand, read on below.


The problem is that the input file's encoding does not match the shell's.
More specifically, the input file contains characters encoded in a way that is not valid in UTF-8 (as @Klas Lindbäck stated in a comment) - that's what the sed error message is trying to say by invalid byte sequence.

Most likely, your input file uses a single-byte 8-bit encoding such as ISO-8859-1, frequently used to encode "Western European" languages.

Example:

The accented letter à has Unicode codepoint 0xE0 (224) - the same as in ISO-8859-1. However, due to the nature of UTF-8 encoding, this single codepoint is represented as 2 bytes - 0xC3 0xA0, whereas trying to pass the single byte 0xE0 is invalid under UTF-8.

Here's a demonstration of the problem using the string voilà encoded as ISO-8859-1, with the à represented as one byte (via an ANSI-C-quoted bash string ($'...') that uses \x{e0} to create the byte):

Note that the sed command is effectively a no-op that simply passes the input through, but we need it to provoke the error:

  # -> 'illegal byte sequence': byte 0xE0 is not a valid char.
sed 's/.*/&/' <<<$'voil\x{e0}'

To simply ignore the problem, the above LCTYPE=C approach can be used:

  # No error, bytes are passed through ('á' will render as '?', though).
LC_CTYPE=C sed 's/.*/&/' <<<$'voil\x{e0}'

If you want to determine which parts of the input cause the problem, try the following:

  # Convert bytes in the 8-bit range (high bit set) to hex. representation.
  # -> 'voil\x{e0}'
iconv -f ASCII --byte-subst='\x{%02x}' <<<$'voil\x{e0}'

The output will show you all bytes that have the high bit set (bytes that exceed the 7-bit ASCII range) in hexadecimal form. (Note, however, that that also includes correctly encoded UTF-8 multibyte sequences - a more sophisticated approach would be needed to specifically identify invalid-in-UTF-8 bytes.)


Performing encoding conversions on demand:

Standard utility iconv can be used to convert to (-t) and/or from (-f) encodings; iconv -l lists all supported ones.

Examples:

Convert FROM ISO-8859-1 to the encoding in effect in the shell (based on LC_CTYPE, which is UTF-8-based by default), building on the above example:

  # Converts to UTF-8; output renders correctly as 'voilà'
sed 's/.*/&/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

Note that this conversion allows you to properly match foreign characters:

  # Correctly matches 'à' and replaces it with 'ü': -> 'voilü'
sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

To convert the input BACK to ISO-8859-1 after processing, simply pipe the result to another iconv command:

sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')" | iconv -t ISO-8859-1

How do I post form data with fetch api?

You can set body to an instance of URLSearchParams with query string passed as argument

fetch("/path/to/server", {
  method:"POST"
, body:new URLSearchParams("[email protected]&password=pw")
})

_x000D_
_x000D_
document.forms[0].onsubmit = async(e) => {_x000D_
  e.preventDefault();_x000D_
  const params = new URLSearchParams([...new FormData(e.target).entries()]);_x000D_
  // fetch("/path/to/server", {method:"POST", body:params})_x000D_
  const response = await new Response(params).text();_x000D_
  console.log(response);_x000D_
}
_x000D_
<form>_x000D_
  <input name="email" value="[email protected]">_x000D_
  <input name="password" value="pw">_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do I clear all variables in the middle of a Python script?

The following sequence of commands does remove every name from the current module:

>>> import sys
>>> sys.modules[__name__].__dict__.clear()

I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a "variable" -- there are objects, of many kinds (including modules, functions, class, numbers, strings, ...), and there are names, bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).

Maybe you want to be more selective, but it's hard to guess exactly what you mean unless you want to be more specific. But, just to give an example:

>>> import sys
>>> this = sys.modules[__name__]
>>> for n in dir():
...   if n[0]!='_': delattr(this, n)
... 
>>>

This sequence leaves alone names that are private or magical, including the __builtins__ special name which houses all built-in names. So, built-ins still work -- for example:

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n']
>>> 

As you see, name n (the control variable in that for) also happens to stick around (as it's re-bound in the for clause every time through), so it might be better to name that control variable _, for example, to clearly show "it's special" (plus, in the interactive interpreter, name _ is re-bound anyway after every complete expression entered at the prompt, to the value of that expression, so it won't stick around for long;-).

Anyway, once you have determined exactly what it is you want to do, it's not hard to define a function for the purpose and put it in your start-up file (if you want it only in interactive sessions) or site-customize file (if you want it in every script).

String escape into XML

Using a third-party library (Newtonsoft.Json) as alternative:

public static string XmlEscape(string unescaped)
{
    if (unescaped == null) return null;
    return JsonConvert.SerializeObject(unescaped); ;
}

public static string XmlUnescape(string escaped)
{
    if (escaped == null) return null;
    return JsonConvert.DeserializeObject(escaped, typeof(string)).ToString();
}

Examples of escaped string:

a<b ==> "a&lt;b"

<foo></foo> ==> "foo&gt;&lt;/foo&gt;"

NOTE: In newer versions, the code written above may not work with escaping, so you need to specify how the strings will be escaped:

public static string XmlEscape(string unescaped)
{
    if (unescaped == null) return null;
    return JsonConvert.SerializeObject(unescaped, new JsonSerializerSettings()
    {
        StringEscapeHandling = StringEscapeHandling.EscapeHtml
    });
}

Examples of escaped string:

a<b ==> "a\u003cb"

<foo></foo> ==> "\u003cfoo\u003e\u003c/foo\u003e"

How to include Javascript file in Asp.Net page

add like

<head runat="server">
<script src="Registration.js" type="text/javascript"></script>
</head>

OR can add in code behind.

Page.ClientScript.RegisterClientScriptInclude("Registration", ResolveUrl("~/js/Registration.js"));

Open Facebook Page in Facebook App (if installed) on Android

you can use this:

try {
                Intent followIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" +
                        "https://www.facebook.com/app_scoped_user_id/"+scoped user id+"/"));
                activity.startActivity(followIntent);
            } catch (Exception e) {
                activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + user name)));
                String errorMessage = (e.getMessage() == null) ? "Message is empty" : e.getMessage();
            }

attention: you can get scoped user id from "link" permission facebook api

Excel VBA: function to turn activecell to bold

A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.

Eg

Private Sub worksheet_change(ByVal target As Range)
  target.Font.Bold = True
End Sub

Getting Spring Application Context

Take a look at ContextSingletonBeanFactoryLocator. It provides static accessors to get hold of Spring's contexts, assuming they have been registered in certain ways.

It's not pretty, and more complex than perhaps you'd like, but it works.

Dynamically converting java object of Object class to a given class when class name is known

you don't, declare an interface that declares the methods you would like to call:

public interface MyInterface
{
  void doStuff();
}

public class MyClass implements MyInterface
{
  public void doStuff()
  {
    System.Console.Writeln("done!");
  }
}

then you use

MyInterface mobj = (myInterface)obj;
mobj.doStuff();

If MyClassis not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).

Node JS Promise.all and forEach

It's pretty straightforward with some simple rules:

  • Whenever you create a promise in a then, return it - any promise you don't return will not be waited for outside.
  • Whenever you create multiple promises, .all them - that way it waits for all the promises and no error from any of them are silenced.
  • Whenever you nest thens, you can typically return in the middle - then chains are usually at most 1 level deep.
  • Whenever you perform IO, it should be with a promise - either it should be in a promise or it should use a promise to signal its completion.

And some tips:

  • Mapping is better done with .map than with for/push - if you're mapping values with a function, map lets you concisely express the notion of applying actions one by one and aggregating the results.
  • Concurrency is better than sequential execution if it's free - it's better to execute things concurrently and wait for them Promise.all than to execute things one after the other - each waiting before the next.

Ok, so let's get started:

var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
    return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns

var actions = items.map(fn); // run the function over all items

// we now have a promises array and we want to wait for it

var results = Promise.all(actions); // pass array of promises

results.then(data => // or just .then(console.log)
    console.log(data) // [2, 4, 6, 8, 10]
);

// we can nest this of course, as I said, `then` chains:

var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
    data => Promise.all(data.map(fn))
).then(function(data){
    // the next `then` is executed after the promise has returned from the previous
    // `then` fulfilled, in this case it's an aggregate promise because of 
    // the `.all` 
    return Promise.all(data.map(fn));
}).then(function(data){
    // just for good measure
    return Promise.all(data.map(fn));
});

// now to get the results:

res2.then(function(data){
    console.log(data); // [16, 32, 48, 64, 80]
});

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

Look at the PHP LDAP library functions: http://us.php.net/ldap.

Active Directory [mostly] conforms to the LDAP standard.

Passing parameters to click() & bind() event in jquery?

see event.data

commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
    var data = event.data;
    alert(data.id);
    alert(data.name);
});

If your data is initialized before binding the event, then simply capture those variables in a closure.

// assuming id and name are defined in this scope
commentBtn.click(function() {
    alert(id), alert(name);
});

Fastest way to check if a string matches a regexp in ruby?

What about re === str (case compare)?

Since it evaluates to true or false and has no need for storing matches, returning match index and that stuff, I wonder if it would be an even faster way of matching than =~.


Ok, I tested this. =~ is still faster, even if you have multiple capture groups, however it is faster than the other options.

BTW, what good is freeze? I couldn't measure any performance boost from it.

getActivity() returns null in Fragment function

PJL is right. I have used his suggestion and this is what i have done:

  1. defined global variables for fragment:

    private final Object attachingActivityLock = new Object();

    private boolean syncVariable = false;

  2. implemented

@Override
public void onAttach(Activity activity) {
  super.onAttach(activity);
  synchronized (attachingActivityLock) {
      syncVariable = true;
      attachingActivityLock.notifyAll();
  }
}

3 . I wrapped up my function, where I need to call getActivity(), in thread, because if it would run on main thread, i would block the thread with the step 4. and onAttach() would never be called.

    Thread processImage = new Thread(new Runnable() {

        @Override
        public void run() {
            processImage();
        }
    });
    processImage.start();

4 . in my function where I need to call getActivity(), I use this (before the call getActivity())

    synchronized (attachingActivityLock) {
        while(!syncVariable){
            try {
                attachingActivityLock.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

If you have some UI updates, remember to run them on UI thread. I need to update ImgeView so I did:

image.post(new Runnable() {

    @Override
    public void run() {
        image.setImageBitmap(imageToShow);
    }
});

If/else else if in Jquery for a condition

See this answer. val() is comparing a string, not a numeric value.

How to remove .html from URL?

Use a hash tag.

May not be exactly what you want but it solves the problem of removing the extension.

Say you have a html page saved as about.html and you don't want that pesky extension you could use a hash tag and redirect to the correct page.

switch(window.location.hash.substring(1)){
      case 'about':
      window.location = 'about.html';
      break;
  }

Routing to yoursite.com#about will take you to yoursite.com/about.html. I used this to make my links cleaner.

Setting Short Value Java

In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L, D, F to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.

The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:

byte foo = (byte)0;
short bar = (short)0;

In your setLongValue(100L) method call, you don't have to necessarily include the L suffix because in this case the int literal is automatically widened to a long. This is called widening primitive conversion in the Java Language Specification.

Edit a text file on the console using Powershell

You could install Far Manager (a great OFM, by the way) and call its editor like that:

Far /e filename.txt

Android: Quit application when press back button

nobody seems to have recommended noHistory="true" in manifest.xml to prevent certain activity to appear after you press back button which by default calling method finish()

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Sometimes, this issue is resolved simply by running flutter pub get once again...

packages get to make sure that all packages are considered...

as when moving the project from one computer to another, this may happen, that the packages are not taken into consideration, so flutter pub get and there you go !!!

maximum value of int

#include <climits>
#include <iostream>
using namespace std;

int main() {
  cout << INT_MAX << endl;
}

Oracle comparing timestamp with date

You can truncate the date

SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')

Look at the SQL Fiddle for more examples.

How do I get a list of all subdomains of a domain?

You can use:

$ host -l domain.com

Under the hood, this uses the AXFR query mentioned above. You might not be allowed to do this though. In that case, you'll get a transfer failed message.

How do I implement interfaces in python?

As mentioned by other here:

Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don't have to have them in Python.

That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.

Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC's for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework. Here you don't subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!

Reflection - get attribute name and value on property

I have solved similar problems by writing a Generic Extension Property Attribute Helper:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class AttributeHelper
{
    public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
        Expression<Func<T, TOut>> propertyExpression, 
        Func<TAttribute, TValue> valueSelector) 
        where TAttribute : Attribute
    {
        var expression = (MemberExpression) propertyExpression.Body;
        var propertyInfo = (PropertyInfo) expression.Member;
        var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        return attr != null ? valueSelector(attr) : default(TValue);
    }
}

Usage:

var author = AttributeHelper.GetPropertyAttributeValue<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
// author = "AuthorName"

Multiline input form field using Bootstrap

I think the problem is that you are using type="text" instead of textarea. What you want is:

<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>

To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

How to change value of object which is inside an array using JavaScript or jQuery?

Let you want to update value of array[2] = "data"

    for(i=0;i<array.length;i++){
      if(i == 2){
         array[i] = "data";
        }
    }

How to display my location on Google Maps for Android API v2

To show the "My Location" button you have to call

map.getUiSettings().setMyLocationButtonEnabled(true);

on your GoogleMap object.

How might I schedule a C# Windows Service to perform a task daily?

I would suggest that you use a timer, but set it to check every 45 seconds, not minute. Otherwise you can run into situations where with heavy load, the check for a particular minute is missed, because between the time the timer triggers and the time your code runs and checks the current time, you might have missed the target minute.

How do pointer-to-pointer's work in C? (and when might you use them?)

A pointer to pointer is, well, a pointer to pointer.

A meaningfull example of someType** is a bidimensional array: you have one array, filled with pointers to other arrays, so when you write

dpointer[5][6]

you access at the array that contains pointers to other arrays in his 5th position, get the pointer (let fpointer his name) and then access the 6th element of the array referenced to that array (so, fpointer[6]).

Disabling enter key for form

Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:

<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>

This code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".

Here are some highlights:

  1. It is in pure javascript (no library required).
  2. Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
  3. Together with the above, user can use "Enter" key anywhere else.
  4. It is short, clean, fast and straight to the point.

If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...

Bootstrap 4 navbar color

You can just use "!important" to get your custom color

.navbar {
 background-color: yourcolor !important;
 }

Regex matching beginning AND end strings

^dbo\..*_fn$

This should work you.

How to apply `git diff` patch without Git installed?

git diff > patchfile

and

patch -p1 < patchfile

work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile if you need handle file adds, deletes and renames.


EDIT December 2015

Latest versions of patch command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).

So provided one uses current/latest version of patch there is no need to use git to be able to apply its diff as a patch.

Jquery select this + class

Use find()

$(this).find(".subclass").css("visibility","visible");

Programmatically create a UIView with color gradient

My solution is to create UIView subclass with CAGradientLayer accessible as a readonly property. This will allow you to customize your gradient how you want and you don't need to handle layout changes yourself. Subclass implementation:

@interface GradientView : UIView

@property (nonatomic, readonly) CAGradientLayer *gradientLayer;

@end

@implementation GradientView

+ (Class)layerClass
{
    return [CAGradientLayer class];
}

- (CAGradientLayer *)gradientLayer
{
    return (CAGradientLayer *)self.layer;
}

@end

Usage:

self.iconBackground = [GradientView new];
[self.background addSubview:self.iconBackground];
self.iconBackground.gradientLayer.colors = @[(id)[UIColor blackColor].CGColor, (id)[UIColor whiteColor].CGColor];
self.iconBackground.gradientLayer.startPoint = CGPointMake(1.0f, 1.0f);
self.iconBackground.gradientLayer.endPoint = CGPointMake(0.0f, 0.0f);

Possible to iterate backwards through a foreach?

This works pretty well

List<string> list = new List<string>();

list.Add("Hello");
list.Add("Who");
list.Add("Are");
list.Add("You");

foreach (String s in list)
{
    Console.WriteLine(list[list.Count - list.IndexOf(s) - 1]);
}

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

What's is the difference between include and extend in use case diagram?

Diagram Elements

  • Actors: Also referred to as Roles. Name and stereotype of an actor can be changed in its Properties tab.

  • Inheritance: Refinement relations between actors. This relation can carry a name and a stereotype.

  • Use cases: These can have Extension Points.

  • Extension Points: This defines a location where an extension can be added.

  • Associations: Between roles and use cases. It is useful to give associations speaking names.

  • Dependencies: Between use cases. Dependencies often have a stereotype to better define the role of the dependency. To select a stereotype, select the dependency from the diagram or the Navigation pane, then change the stereotype in the Properties tab. There are two special kinds of dependencies: <<extend>> and <<include>>, for which Poseidon offers own buttons (see below).

  • Extend relationship: A uni-directional relationship between two use cases. An extend relationship between use case B and use case A means that the behavior of B can be included in A.

  • Include relationship: A uni-directional relationship between two use cases. Such a relationship between use cases A and B means, that the behavior of B is always included in A.

  • System border: The system border is actually not implemented as model element in Poseidon for UML. You can simply draw a rectangle, send it to the background and use it as system border by putting all corresponding use cases inside the rectangle.

What do I use for a max-heap implementation in Python?

This is a simple MaxHeap implementation based on heapq. Though it only works with numeric values.

import heapq
from typing import List


class MaxHeap:
    def __init__(self):
        self.data = []

    def top(self):
        return -self.data[0]

    def push(self, val):
        heapq.heappush(self.data, -val)

    def pop(self):
        return -heapq.heappop(self.data)

Usage:

max_heap = MaxHeap()
max_heap.push(3)
max_heap.push(5)
max_heap.push(1)
print(max_heap.top())  # 5

Sorting arraylist in alphabetical order (case insensitive)

Custom Comparator should help

Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }
});

Or if you are using Java 8:

list.sort(String::compareToIgnoreCase);

adding noise to a signal in python

AWGN Similar to Matlab Function

def awgn(sinal):
    regsnr=54
    sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
    sigpower=sigpower/len(sinal)
    noisepower=sigpower/(math.pow(10,regsnr/10))
    noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
    return noise

SQL Server: UPDATE a table by using ORDER BY

Edit

Following solution could have problems with clustered indexes involved as mentioned here. Thanks to Martin for pointing this out.

The answer is kept to educate those (like me) who don't know all side-effects or ins and outs of SQL Server.


Expanding on the answer gaven by Quassnoi in your link, following works

DECLARE @Test TABLE (Number INTEGER, AText VARCHAR(2), ID INTEGER)
DECLARE @Number INT

INSERT INTO @Test VALUES (1, 'A', 1)
INSERT INTO @Test VALUES (2, 'B', 2)
INSERT INTO @Test VALUES (1, 'E', 5)
INSERT INTO @Test VALUES (3, 'C', 3)
INSERT INTO @Test VALUES (2, 'D', 4)

SET @Number = 0

;WITH q AS (
    SELECT  TOP 1000000 *
    FROM    @Test
    ORDER BY
            ID
)            
UPDATE  q
SET     @Number = Number = @Number + 1

Change the value in app.config file dynamically

Expanding on Adis H's example to include the null case (got bit on this one)

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings["HostName"] != null)
                config.AppSettings.Settings["HostName"].Value = hostName;
            else                
                config.AppSettings.Settings.Add("HostName", hostName);                
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

How to align checkboxes and their labels consistently cross-browsers

If you're using Twitter Bootstrap, you can just use the checkbox class on the <label>:

<label class="checkbox">
    <input type="checkbox"> Remember me
</label>

catching stdout in realtime from subprocess

I've noticed that there is no mention of using a temporary file as intermediate. The following gets around the buffering issues by outputting to a temporary file and allows you to parse the data coming from rsync without connecting to a pty. I tested the following on a linux box, and the output of rsync tends to differ across platforms, so the regular expressions to parse the output may vary:

import subprocess, time, tempfile, re

pipe_output, file_name = tempfile.TemporaryFile()
cmd = ["rsync", "-vaz", "-P", "/src/" ,"/dest"]

p = subprocess.Popen(cmd, stdout=pipe_output, 
                     stderr=subprocess.STDOUT)
while p.poll() is None:
    # p.poll() returns None while the program is still running
    # sleep for 1 second
    time.sleep(1)
    last_line =  open(file_name).readlines()
    # it's possible that it hasn't output yet, so continue
    if len(last_line) == 0: continue
    last_line = last_line[-1]
    # Matching to "[bytes downloaded]  number%  [speed] number:number:number"
    match_it = re.match(".* ([0-9]*)%.* ([0-9]*:[0-9]*:[0-9]*).*", last_line)
    if not match_it: continue
    # in this case, the percentage is stored in match_it.group(1), 
    # time in match_it.group(2).  We could do something with it here...

Setting width of spreadsheet cell using PHPExcel

This worked for me:

$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);

be sure to add setAuzoSize(false), before the setWidth(); as Rolland mentioned

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

Here is what you do in Excel 2003:

  1. In your sheet of interest, go to Format -> Sheet -> Hide and hide your sheet.
  2. Go to Tools -> Protection -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Here is what you do in Excel 2007:

  1. In your sheet of interest, go to Home ribbon -> Format -> Hide & Unhide -> Hide Sheet and hide your sheet.
  2. Go to Review ribbon -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?


If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.

Convert datatable to JSON in C#

Convert datatable to JSON using C#.net

 public static object DataTableToJSON(DataTable table)
    {
        var list = new List<Dictionary<string, object>>();

        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();

            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = (Convert.ToString(row[col]));
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        return serializer.Serialize(list);
    }

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

Insert some string into given string at given index in Python

line='Name Age Group Class Profession'
arr = line.split()
for i in range(3):
    arr.insert(2, arr[2])
print(' '.join(arr))

What exceptions should be thrown for invalid or unexpected parameters in .NET?

I voted for Josh's answer, but would like to add one more to the list:

System.InvalidOperationException should be thrown if the argument is valid, but the object is in a state where the argument shouldn't be used.

Update Taken from MSDN:

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.

Let's say that your object has a PerformAction(enmSomeAction action) method, valid enmSomeActions are Open and Close. If you call PerformAction(enmSomeAction.Open) twice in a row then the second call should throw the InvalidOperationException (since the arugment was valid, but not for the current state of the control)

Since you're already doing the right thing by programming defensively I have one other exception to mention is ObjectDisposedException. If your object implements IDisposable then you should always have a class variable tracking the disposed state; if your object has been disposed and a method gets called on it you should raise the ObjectDisposedException:

public void SomeMethod()
{
    If (m_Disposed) {
          throw new ObjectDisposedException("Object has been disposed")
     }
    // ... Normal execution code
}

Update: To answer your follow-up: It is a bit of an ambiguous situation, and is made a little more complicated by a generic (not in the .NET Generics sense) data type being used to represent a specific set of data; an enum or other strongly typed object would be a more ideal fit--but we don't always have that control.

I would personally lean towards the ArgumentOutOfRangeException and provide a message that indicates the valid values are 1-12. My reasoning is that when you talk about months, assuming all integer representations of months are valid, then you are expecting a value in the range of 1-12. If only certain months (like months that had 31 days) were valid then you would not be dealing with a Range per-se and I would throw a generic ArgumentException that indicated the valid values, and I would also document them in the method's comments.

How to Apply Gradient to background view of iOS Swift App

Xcode 11 • Swift 5.1


You can design your own Gradient View as follow:

@IBDesignable
public class Gradient: UIView {
    @IBInspectable var startColor:   UIColor = .black { didSet { updateColors() }}
    @IBInspectable var endColor:     UIColor = .white { didSet { updateColors() }}
    @IBInspectable var startLocation: Double =   0.05 { didSet { updateLocations() }}
    @IBInspectable var endLocation:   Double =   0.95 { didSet { updateLocations() }}
    @IBInspectable var horizontalMode:  Bool =  false { didSet { updatePoints() }}
    @IBInspectable var diagonalMode:    Bool =  false { didSet { updatePoints() }}

    override public class var layerClass: AnyClass { CAGradientLayer.self }

    var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }

    func updatePoints() {
        if horizontalMode {
            gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
        } else {
            gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
        }
    }
    func updateLocations() {
        gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
    }
    func updateColors() {
        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
    }
    override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updatePoints()
        updateLocations()
        updateColors()
    }

}

enter image description here

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

downloading all the files in a directory with cURL

OK, considering that you are using Windows, the most simple way to do that is to use the standard ftp tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.

First of all, you need to create a batch (script) file for the ftp program, containing instructions for it. Name it as you want, and put into it:

curl -u login:pass ftp.myftpsite.com/iiumlabs* -O

open ftp.myftpsite.com
login
pass
mget *
quit

The first line opens a connection to the ftp server at ftp.myftpsite.com. The two following lines specify the login, and the password which ftp will ask for (replace login and pass with just the login and password, without any keywords). Then, you use mget * to get all files. Instead of the *, you can use any wildcard. Finally, you use quit to close the ftp program without interactive prompt.

If you needed to enter some directory first, add a cd command before mget. It should be pretty straightforward.

Finally, write that file and run ftp like this:

ftp -i -s:yourscript

where -i disables interactivity (asking before downloading files), and -s specifies path to the script you created.


Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use PuTTy tools anyway. The one of particular interest for this case would be pscp which is practically the PuTTy counter-part of the openssh scp command.

The syntax is similar to copy command, and it supports wildcards:

pscp -batch [email protected]:iiumlabs* .

If you authenticate using a key file, you should pass it using -i path-to-key-file. If you use password, -pw pass. It can also reuse sessions saved using PuTTy, using the load -load your-session-name argument.

Why do some functions have underscores "__" before and after the function name?

From the Python PEP 8 -- Style Guide for Python Code:

Descriptive: Naming Styles

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

Find out free space on tablespace

Unless I'm mistaken, the above code does not take unallocated space into account, so if you really want to know when you'll hit a hard limit, you should use maxbytes.

I think the code below does that. It calculates free space as "freespace" + unallocated space.

select 
     free.tablespace_name,
     free.bytes,
     reserv.maxbytes,
     reserv.bytes,
     reserv.maxbytes - reserv.bytes + free.bytes "max free bytes",
     reserv.datafiles
from
    (select tablespace_name, count(1) datafiles, sum(maxbytes) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
    (select tablespace_name, sum(bytes) bytes from dba_free_space group by tablespace_name) free
where free.tablespace_name = reserv.tablespace_name;

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob 
WHERE fileid NOT IN 
       (SELECT id 
        FROM files 
        WHERE id is NOT NULL/*This line is unlikely to be needed 
                               but using NOT IN...*/
      )

Return index of greatest value in an array

Unless I'm mistaken, I'd say it's to write your own function.

function findIndexOfGreatest(array) {
  var greatest;
  var indexOfGreatest;
  for (var i = 0; i < array.length; i++) {
    if (!greatest || array[i] > greatest) {
      greatest = array[i];
      indexOfGreatest = i;
    }
  }
  return indexOfGreatest;
}

How to use OpenSSL to encrypt/decrypt files?

As mentioned in the other answers, previous versions of openssl used a weak key derivation function to derive an AES encryption key from the password. However, openssl v1.1.1 supports a stronger key derivation function, where the key is derived from the password using pbkdf2 with a randomly generated salt, and multiple iterations of sha256 hashing (10,000 by default).

To encrypt a file:

 openssl aes-256-cbc -e -salt -pbkdf2 -iter 10000 -in plaintextfilename -out encryptedfilename

To decrypt a file:

  openssl aes-256-cbc -d -salt -pbkdf2 -iter 10000 -in encryptedfilename -out plaintextfilename

How to compare two dates along with time in java

An Alternative is....

Convert both dates into milliseconds as below

Date d = new Date();
long l = d.getTime();

Now compare both long values