Programs & Examples On #Data integrity

What's wrong with foreign keys?

I echo the answer by Dmitriy - very well put.

For those who are worried about the performance overhead FK's often bring, there's a way (in Oracle) you can get the query optimiser advantage of the FK constraint without the cost overhead of constraint validation during insert, delete or update. That is to create the FK constraint with the attributes RELY DISABLE NOVALIDATE. This means the query optimiser ASSUMES that the constraint has been enforced when building queries, without the database actually enforcing the constraint. You have to be very careful here to take the responsibility when you populate a table with an FK constraint like this to make absolutely sure you don't have data in your FK column(s) that violate the constraint, as if you do so you could get unreliable results from queries that involve the table this FK constraint is on.

I usually use this strategy on some tables in my data mart schema, but not in my integrated staging schema. I make sure the tables I am copying data from already have the same constraint enforced, or the ETL routine enforces the constraint.

jquery get height of iframe content when loaded

Accepted answer's $('iframe').load will now produce a.indexOf is not a function error. Can be updated to:

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

Few others similar to .load deprecated since jQuery 1.8: "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

Why use a READ UNCOMMITTED isolation level?

My favorite use case for read uncommited is to debug something that is happening inside a transaction.

Start your software under a debugger, while you are stepping through the lines of code, it opens a transaction and modifies your database. While the code is stopped, you can open a query analyzer, set on the read uncommited isolation level and make queries to see what is going on.

You also can use it to see if long running procedures are stuck or correctly updating your database.

It is great if your company loves to make overly complex stored procedures.

How to add row of data to Jtable from values received from jtextfield and comboboxes

String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);

Here;this is the solution.

How do I rename a column in a SQLite database table?

Say you have a table and need to rename "colb" to "col_b":

First you rename the old table:

ALTER TABLE orig_table_name RENAME TO tmp_table_name;

Then create the new table, based on the old table but with the updated column name:

CREATE TABLE orig_table_name (
  col_a INT
, col_b INT
);

Then copy the contents across from the original table.

INSERT INTO orig_table_name(col_a, col_b)
SELECT col_a, colb
FROM tmp_table_name;

Lastly, drop the old table.

DROP TABLE tmp_table_name;

Wrapping all this in a BEGIN TRANSACTION; and COMMIT; is also probably a good idea.

How to make an Android device vibrate? with different frequency?

Kotlin update for more type safety

Use it as a top level function in some common class of your project such as Utils.kt

// Vibrates the device for 100 milliseconds.
fun vibrateDevice(context: Context) {
    val vibrator = getSystemService(context, Vibrator::class.java)
    vibrator?.let {
        if (Build.VERSION.SDK_INT >= 26) {
            it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            @Suppress("DEPRECATION")
            it.vibrate(100)
        }
    }
}

And then call it anywhere in your code as following:

vibrateDevice(requireContext())

Explanation

Using Vibrator::class.java is more type safe than using String constants.

We check the vibrator for nullability using let { }, because if the vibration is not available for the device, the vibrator will be null.

It's ok to supress deprecation in else clause, because the warning is from newer SDK.

We don't need to ask for permission at runtime for using vibration. But we need to declare it in AndroidManifest.xml as following:

<uses-permission android:name="android.permission.VIBRATE"/>

How to output in CLI during execution of PHP Unit tests?

This was taken from PHPUnit Docs about Fixtures.

This should allow you to dump information at any point durring the phpunit test life cycle.

Just replace __METHOD__ in the code below with whatever you want to output

Example 4.2: Example showing all template methods available

<?php
class TemplateMethodsTest extends PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    protected function setUp()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    protected function assertPreConditions()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    public function testOne()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
        $this->assertTrue(TRUE);
    }

    public function testTwo()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
        $this->assertTrue(FALSE);
    }

    protected function assertPostConditions()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    protected function tearDown()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    public static function tearDownAfterClass()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    protected function onNotSuccessfulTest(Exception $e)
    {
        fwrite(STDOUT, __METHOD__ . "\n");
        throw $e;
    }
}
?>

Create a 3D matrix

If you want to define a 3D matrix containing all zeros, you write

A = zeros(8,4,20);

All ones uses ones, all NaN's uses NaN, all false uses false instead of zeros.

If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.

For example

B = magic(3); %# creates a 3x3 magic square
B(2,1,2) = 1; %# and you have a 3x3x2 array

Recursively looping through an object to build a property list

Here is a simple solution. This is a late answer but may be simple one-

_x000D_
_x000D_
const data = {
  city: 'foo',
  year: 2020,
  person: {
    name: {
      firstName: 'john',
      lastName: 'doe'
    },
    age: 20,
    type: {
      a: 2,
      b: 3,
      c: {
        d: 4,
        e: 5
      }
    }
  },
}

function getKey(obj, res = [], parent = '') {
  const keys = Object.keys(obj);
  
  /** Loop throw the object keys and check if there is any object there */
  keys.forEach(key => {
    if (typeof obj[key] !== 'object') {
      // Generate the heirarchy
      parent ? res.push(`${parent}.${key}`) : res.push(key);
    } else {
      // If object found then recursively call the function with updpated parent
      let newParent = parent ? `${parent}.${key}` : key;
      getKey(obj[key], res, newParent);
    }
    
  });
}

const result = [];

getKey(data, result, '');

console.log(result);
_x000D_
.as-console-wrapper{min-height: 100%!important; top: 0}
_x000D_
_x000D_
_x000D_

Format a Go string without printing?

In your case, you need to use Sprintf() for format string.

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

s := fmt.Sprintf("Good Morning, This is %s and I'm living here from last %d years ", "John", 20)

Your output will be :

Good Morning, This is John and I'm living here from last 20 years.

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

jQuery - determine if input element is textbox or select list

If you just want to check the type, you can use jQuery's .is() function,

Like in my case I used below,

if($("#id").is("select")) {
 alert('Select'); 
else if($("#id").is("input")) {
 alert("input");
}

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

Downgrading the iOS development Target from 12.1 to 12 fix the issue for me as I don't have a dev team configured.

How to uninstall Eclipse?

The steps are very simple and it'll take just few mins. 1.Go to your C drive and in that go to the 'USER' section. 2.Under 'USER' section go to your 'name(e.g-'user1') and then find ".eclipse" folder and delete that folder 3.Along with that folder also delete "eclipse" folder and you can find that you're work has been done completely.

What are the lengths of Location Coordinates, latitude and longitude?

Valid longitudes are from -180 to 180 degrees.

Latitudes are supposed to be from -90 degrees to 90 degrees, but areas very near to the poles are not indexable.

So exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following:

  • Valid longitudes are from -180 to 180 degrees.
  • Valid latitudes are from -85.05112878 to 85.05112878 degrees.

CSS3 Box Shadow on Top, Left, and Right Only

I know this is very old, but none of these answers helped me, so I'm adding my answer. This, like @yichengliu's answer, uses the Pseudo ::after element.

#div {
    position: relative;
}



#div::after {
    content: '';
    position: absolute;
    right: 0;
    width: 1px;
    height: 100%;
    z-index: -1;

    -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
    -moz-box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
    box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
}

/*or*/

.filter.right::after {
    content: '';
    position: absolute;
    right: 0;
    top: 0;
    width: 1px;
    height: 100%;
    background: white;
    z-index: -1;

    -webkit-filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 1));
    filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 1));
}

Fiddle

If you decide to change the X of the drop shadow (first pixel measurement of the drop-shadow or box-shadow), changing the width will help so it doesn't look like there is a white gap between the div and the shadow.

If you decide to change the Y of the drop shadow (second pixel measurement of the drop-shadow or box-shadow), changing the height will help for the same reason as above.

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

Does it have to be an actual service? Can you just use the built in scheduled tasks in the windows control panel.

Replace HTML Table with Divs

This ought to do the trick.

<style>
div.block{
  overflow:hidden;
}
div.block label{
  width:160px;
  display:block;
  float:left;
  text-align:left;
}
div.block .input{
  margin-left:4px;
  float:left;
}
</style>

<div class="block">
  <label>First field</label>
  <input class="input" type="text" id="txtFirstName"/>
</div>
<div class="block">
  <label>Second field</label>
  <input class="input" type="text" id="txtLastName"/>
</div>

I hope you get the concept.

How to convert a string with Unicode encoding to a string of letters

An alternate way of accomplishing this could be to make use of chars() introduced with Java 9, this can be used to iterate over the characters making sure any char which maps to a surrogate code point is passed through uninterpreted. This can be used as:-

String myString = "\u0048\u0065\u006C\u006C\u006F World";
myString.chars().forEach(a -> System.out.print((char)a));
// would print "Hello World"

How to align absolutely positioned element to center?

try this method, working fine for me

position: absolute;
left: 50%;
transform: translateX(-50%); 

Conditionally change img src based on model data

Instead of src you need ng-src.

AngularJS views support binary operators

condition && true || false

So your img tag would look like this

<img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/>

Note : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes.

plunker here (open dev tools to see the produced HTML)

Is it possible to hide/encode/encrypt php source code and let others have the system?

You could just split the frontend and backend. The frontend is hosted on the customers server with an API that makes calls to the backend on your server. This keeps all of the proprietary code proprietary and forces users to sign up / pay for subscriptions.

SQL is null and = null

First is correct way of checking whether a field value is null while later won't work the way you expect it to because null is special value which does not equal anything, so you can't use equality comparison using = for it.

So when you need to check if a field value is null or not, use:

where x is null

instead of:

where x = null

Python MYSQL update statement

It should be:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))

You can also do it with basic string manipulation,

cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID))

but this way is discouraged because it leaves you open for SQL Injection. As it's so easy (and similar) to do it the right waytm. Do it correctly.

The only thing you should be careful, is that some database backends don't follow the same convention for string replacement (SQLite comes to mind).

push() a two-dimensional array

Create am array and put inside the first, in this case i get data from JSON response

$.getJSON('/Tool/GetAllActiviesStatus/',
   var dataFC = new Array();
   function (data) {
      for (var i = 0; i < data.Result.length; i++) {
          var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true);
          dataFC.push(serie);
       });

How to create JSON object using jQuery

A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.

If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);

If you want to create a javascript object, simply do it like this :

var yourObject = {
          test:'test 1',
          testData: [ 
                {testName: 'do',testId:''}
          ],
          testRcd:'value'   
};

What primitive data type is time_t?

Unfortunately, it's not completely portable. It's usually integral, but it can be any "integer or real-floating type".

Laravel Unknown Column 'updated_at'

For those who are using laravel 5 or above must use public modifier other wise it will throw an exception

Access level to App\yourModelName::$timestamps must be
public (as in class Illuminate\Database\Eloquent\Model)

public $timestamps = false;

Is there a way to define a min and max value for EditText in Android?

You can do this with an an InputFilter. Apparently ther is just this Input Filter Interface you can use. Before you do it the annoying way an create a new Class that extends Input filter, u can use this shortcut with a innerclass Interface instantiation.

Therefore you just do this:

EditText subTargetTime = (EditText) findViewById(R.id.my_time);
subTargetTime.setFilters( new InputFilter[] {
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                        int t = Integer.parseInt(source.toString());
                        if(t <8) { t = 8; }
                        return t+"";

                    }
                }
        });

In this example I check if the value of the EditText is greater than 8. If not it shall be set to 8. So apaprently you need to com up with the min max or whatever filter logic by yourself. But at least u can write the filter logic pretty neat and short directly into the EditText.

Hope this helps

How to copy files between two nodes using ansible

In 2021 you should install wrapper:

ansible-galaxy collection install ansible.posix

And use

- name: Synchronize two directories on one remote host.
  ansible.posix.synchronize:
    src: /first/absolute/path
    dest: /second/absolute/path
  delegate_to: "{{ inventory_hostname }}"

Read more:

https://docs.ansible.com/ansible/latest/collections/ansible/posix/synchronize_module.html

Checked on:

ansible --version                          
ansible 2.10.5
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/daniel/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.9/site-packages/ansible
  executable location = /sbin/ansible
  python version = 3.9.1 (default, Dec 13 2020, 11:55:53) [GCC 10.2.0]

How can I get just the first row in a result set AFTER ordering?

An alternative way:

SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1

Shell script to check if file exists

One liner to check file exist or not -

awk 'BEGIN {print getline < "file.txt" < 0 ? "File does not exist" : "File Exists"}'

How can I delay a method call for 1 second?

Swift 2.x

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
 dispatch_after(delayTime, dispatch_get_main_queue()) {
 print("do some work")
}

Swift 3.x --&-- Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
    print("do some work")
}

or pass a escaping closure

func delay(seconds: Double, completion: @escaping()-> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: completion)
}

Normalize numpy array columns in python

If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.

Starting with your example array:

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

x.max(0) takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,) containing the maximum value in each column. You can then divide x by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.


If x contains negative values you would need to subtract the minimum first:

x_normed = (x - x.min(0)) / x.ptp(0)

Here, x.ptp(0) returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.

Differences between Microsoft .NET 4.0 full Framework and Client Profile

Cameron MacFarland nailed it.

I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.

SQL Query NOT Between Two Dates

What you are currently doing is checking whether neither the start_date nor the end_date fall within the range of the dates given.

I guess what you are really looking for is a record which does not fit in the date range given. If so, use the query below.

SELECT * 
    FROM `test_table` 
    WHERE  CAST('2009-12-15' AS DATE) > start_date  AND  CAST('2010-01-02' AS DATE) < end_date

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

For example, to set the background to your favorite/Branding color

Add Below Meta property to your HTML code in HEAD Section

<head>
  ...
  <meta name="theme-color" content="Your Hexadecimal Code">
  ...
</head>

Example

<head>
  ...
  <meta name="theme-color" content="#444444">
  ...
</head>

In Below Image, I just mentioned How Chrome taken your theme-color Property

enter image description here

Firefox OS, Safari, Internet Explorer and Opera Coast allow you to define colors for elements of the browser, and even the platform using meta tags.

<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

Safari specific styling

From the guidelinesDocuments Here

Hiding Safari User Interface Components

Set the apple-mobile-web-app-capable meta tag to yes to turn on standalone mode. For example, the following HTML displays web content using standalone mode.

<meta name="apple-mobile-web-app-capable" content="yes">

Changing the Status Bar Appearance

You can change the appearance of the default status bar to either black or black-translucent. With black-translucent, the status bar floats on top of the full screen content, rather than pushing it down. This gives the layout more height, but obstructs the top. Here’s the code required:

<meta name="apple-mobile-web-app-status-bar-style" content="black">

For more on status bar appearance, see apple-mobile-web-app-status-bar-style.

For Example:

Screenshot using black-translucent

Screenshot using black-translucent

Screenshot using black

Screenshot using black

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

How to load image (and other assets) in Angular an project?

Normally "app" is the root of your application -- have you tried app/path/to/assets/img.png?

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

How do I determine if my python shell is executing in 32bit or 64bit?

Do a python -VV in the command line. It should return the version.

How do I find a default constraint using INFORMATION_SCHEMA?

Necromancing.
If you only need to check if a default-constraint exists
(default-constraint(s) may have different name in poorly-managed DBs),
use INFORMATION_SCHEMA.COLUMNS (column_default):

IF NOT EXISTS(
    SELECT * FROM INFORMATION_SCHEMA.COLUMNS
    WHERE (1=1) 
    AND TABLE_SCHEMA = 'dbo' 
    AND TABLE_NAME = 'T_VWS_PdfBibliothek' 
    AND COLUMN_NAME = 'PB_Text'
    AND COLUMN_DEFAULT IS NOT NULL  
)
BEGIN 
    EXECUTE('ALTER TABLE dbo.T_VWS_PdfBibliothek 
                ADD CONSTRAINT DF_T_VWS_PdfBibliothek_PB_Text DEFAULT (N''image'') FOR PB_Text; 
    '); 
END 

If you want to check by the constraint-name only:

-- Alternative way: 
IF OBJECT_ID('DF_CONSTRAINT_NAME', 'D') IS NOT NULL 
BEGIN
    -- constraint exists, deal with it.
END 

And last but not least, you can just create a view called
INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS:

CREATE VIEW INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS 
AS 
SELECT 
     DB_NAME() AS CONSTRAINT_CATALOG 
    ,csch.name AS CONSTRAINT_SCHEMA
    ,dc.name AS CONSTRAINT_NAME 
    ,DB_NAME() AS TABLE_CATALOG 
    ,sch.name AS TABLE_SCHEMA 
    ,syst.name AS TABLE_NAME 
    ,sysc.name AS COLUMN_NAME 
    ,COLUMNPROPERTY(sysc.object_id, sysc.name, 'ordinal') AS ORDINAL_POSITION 
    ,dc.type_desc AS CONSTRAINT_TYPE 
    ,dc.definition AS COLUMN_DEFAULT 

    -- ,dc.create_date 
    -- ,dc.modify_date 
FROM sys.columns AS sysc -- 46918 / 3892 with inner joins + where 
-- FROM sys.all_columns AS sysc -- 55429 / 3892 with inner joins + where 

INNER JOIN sys.tables AS syst 
    ON syst.object_id = sysc.object_id 

INNER JOIN sys.schemas AS sch
    ON sch.schema_id = syst.schema_id 

INNER JOIN sys.default_constraints AS dc 
    ON sysc.default_object_id = dc.object_id

INNER JOIN sys.schemas AS csch
    ON csch.schema_id = dc.schema_id 

WHERE (1=1) 
AND dc.is_ms_shipped = 0 

/*
WHERE (1=1) 
AND sch.name = 'dbo'
AND syst.name = 'tablename'
AND sysc.name = 'columnname'
*/

jQuery .get error response function?

You can chain .fail() callback for error response.

$.get('http://example.com/page/2/', function(data){ 
   $(data).find('#reviews .card').appendTo('#reviews');
})
.fail(function() {
  //Error logic
})

How do I start a program with arguments when debugging?

Go to Project-><Projectname> Properties. Then click on the Debug tab, and fill in your arguments in the textbox called Command line arguments.

How to get file path in iPhone app

Since it is your files in your app bundle, I think you can use pathForResource:ofType: to get the full pathname of your file.

Here is an example:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name" 
                                            ofType:@"the_file_extension"];

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

This may be a little late; but someone will find it useful.

There's a Nuget Package for integrating AdminLTE - a popular Bootstrap template - to MVC5

Simply run this command in your Visual Studio Package Manager console

Install-Package AdminLteMvc

NB: It may take a while to install because it downloads all necessary files as well as create sample full and partial views (.cshtml files) that can guide you as you develop. A sample layout file _AdminLteLayout.cshtml is also provided.

You'll find the files in ~/Views/Shared/ folder

Left Join without duplicate rows from left table

Try an OUTER APPLY

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M 
        WHERE M.Content_Id = C.Content_Id 
    ) m
ORDER BY 
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.

The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

jQuery UI Dialog OnBeforeUnload

You can also make an exception for leaving the page via submitting a particular form:

$(window).bind('beforeunload', function(){
    return "Do you really want to leave now?";
});

$("#form_id").submit(function(){
    $(window).unbind("beforeunload");
});

urllib2 and json

Messa's answer only works if the server isn't bothering to check the content-type header. You'll need to specify a content-type header if you want it to really work. Here's Messa's answer modified to include a content-type header:

import json
import urllib2
data = json.dumps([1, 2, 3])
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()

Float vs Decimal in ActiveRecord

In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.

The lesson learned is "always use homogeneous development and deployment databases!"

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<context:component-scan base-package="" /> 

tells Spring to scan those packages for Annotations.

<mvc:annotation-driven> 

registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.

This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.

You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.

Check out the 3.1 documentation to learn more.

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config

HTML CSS How to stop a table cell from expanding

It's entirely possible if your code has enough relative logic to work with.

Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.

ol {max-width: 10vw; padding: 0; overflow: hidden;}

Apparently max-width on colgroup elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.

Make just one slide different size in Powerpoint

True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.

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

All the space elimination techniques for display:inline-block are nasty hacks...

Use Flexbox

It's awesome, solves all this inline-block layout bs, and as of 2017 has 98% browser support (more if you don't care about old IEs).

How do I toggle an element's class in pure JavaScript?

Try this (hopefully it will work):

// mixin (functionality) for toggle class 
function hasClass(ele, clsName) {
    var el = ele.className;
    el = el.split(' ');
    if(el.indexOf(clsName) > -1){
        var cIndex = el.indexOf(clsName);
        el.splice(cIndex, 1);
        ele.className = " ";
        el.forEach(function(item, index){
          ele.className += " " + item;
        })
    }
    else {
        el.push(clsName);
        ele.className = " ";
        el.forEach(function(item, index){
          ele.className += " " + item;
        })
    }
}

// get all DOM element that we need for interactivity.

var btnNavbar =  document.getElementsByClassName('btn-navbar')[0];
var containerFluid =  document.querySelector('.container-fluid:first');
var menu = document.getElementById('menu');

// on button click job
btnNavbar.addEventListener('click', function(){
    hasClass(containerFluid, 'menu-hidden');
    hasClass(menu, 'hidden-phone');
})`enter code here`

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
{
    if ( argc < 2 )
    {
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;
    }

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
    {
        printf( "%s: not found\n" );
        return -1;
    }

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
    {
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;
    }

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
    {
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            zipfile,
            &file_info,
            filename,
            MAX_FILENAME,
            NULL, 0, NULL, 0 ) != UNZ_OK )
        {
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;
        }

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
        {
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
        }
        else
        {
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
            {
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;
            }

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
            {
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;
            }

            int error = UNZ_OK;
            do    
            {
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                {
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;
                }

                // Write data to file.
                if ( error > 0 )
                {
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
                }
            } while ( error > 0 );

            fclose( out );
        }

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
        {
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
            {
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;
            }
        }
    }

    unzClose( zipfile );

    return 0;
}

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip

How to select rows from a DataFrame based on column values

For selecting only specific columns out of multiple columns for a given value in Pandas:

select col_name1, col_name2 from table where column_name = some_value.

Options:

df.loc[df['column_name'] == some_value][[col_name1, col_name2]]

or

df.query['column_name' == 'some_value'][[col_name1, col_name2]]

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

Perhaps something that's not been mentioned is that of locality.

A MAC address or time-based ordering (UUID1) can afford increased database performance, since it's less work to sort numbers closer-together than those distributed randomly (UUID4) (see here).

A second related issue, is that using UUID1 can be useful in debugging, even if origin data is lost or not explicitly stored (this is obviously in conflict with the privacy issue mentioned by the OP).

iPhone App Icons - Exact Radius?

When designing my app icons with Photoshop, I have found that no integer corner radius fits the device's mask exactly.

What I do now is create an empty project with Xcode, set a completely white PNG file as the icon, and turn off the preset bevel & gloss. Then, I run the app and take a screenshot of the home screen. Now, you can easily create a mask from that image, which you can use in Photoshop. This will get you perfectly rounded corners.

How do I programmatically click a link with javascript?

You can't make the user's mouse do anything. But you have full control over what happens when an event triggers.

What you can do is do a click on body load. W3Schools has an example here.

Create a new txt file using VB.NET

You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:

Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
   System.IO.File.Create(filepath).Dispose()
End If

C# LINQ find duplicates in List

You can do this:

var list = new[] {1,2,3,1,4,2};
var duplicateItems = list.Duplicates();

With these extension methods:

public static class Extensions
{
    public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
    {
        var grouped = source.GroupBy(selector);
        var moreThan1 = grouped.Where(i => i.IsMultiple());
        return moreThan1.SelectMany(i => i);
    }

    public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source)
    {
        return source.Duplicates(i => i);
    }

    public static bool IsMultiple<T>(this IEnumerable<T> source)
    {
        var enumerator = source.GetEnumerator();
        return enumerator.MoveNext() && enumerator.MoveNext();
    }
}

Using IsMultiple() in the Duplicates method is faster than Count() because this does not iterate the whole collection.

How to open .dll files to see what is written inside?

Open .dll file with visual studio. Or resource editor.

How to paste yanked text into the Vim command line

For pasting something that is the system clipboard you can just use SHIFT - INS.

It works in Windows, but I am guessing it works well in Linux too.

.NET / C# - Convert char[] to string

Another alternative

char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );

Debug.Assert( s.Equals( "Rock-&-Roll" ) );

How to hide elements without having them take space on the page?

display:none to hide and set display:block to show.

Generate signed apk android studio

I had the same problem. I populated the field with /home/tim/android.jks file from tutorial thinking that file would be created. and when i would click enter it would say cant find the file. but when i would try to create the file, it would not let me create the jks file. I closed out of android studio and ran it again and it worked fine. I had to hit the ... to correctly add my file. generate signed apk wizard-->new key store-->hit ... choose key store file. enter filename I was thinking i was going to have to use openjdk and create my own keyfile, but it is built into android studio

How to remove an element from an array in Swift

Regarding @Suragch's Alternative to "Remove element of unknown index":

There is a more powerful version of "indexOf(element)" that will match on a predicate instead of the object itself. It goes by the same name but it called by myObjects.indexOf{$0.property = valueToMatch}. It returns the index of the first matching item found in myObjects array.

If the element is an object/struct, you may want to remove that element based on a value of one of its properties. Eg, you have a Car class having car.color property, and you want to remove the "red" car from your carsArray.

if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
  carsArray.removeAtIndex(validIndex)
}

Foreseeably, you could rework this to remove "all" red cars by embedding the above if statement within a repeat/while loop, and attaching an else block to set a flag to "break" out of the loop.

"ImportError: no module named 'requests'" after installing with pip

Run in command prompt.

pip list

Check what version you have installed on your system if you have an old version.

Try to uninstall the package...

pip uninstall requests

Try after to install it:

pip install requests

You can also test if pip does not do the job.

easy_install requests

Swift - How to detect orientation changes

Another way to detect device orientations is with the function traitCollectionDidChange(_:). The system calls this method when the iOS interface environment changes.

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
{
    super.traitCollectionDidChange(previousTraitCollection)
    //...
}

Furthermore, you can use function willTransition(to:with:) ( which is called before traitCollectionDidChange(_:) ), to get information just before the orientation is applied.

 override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{
    super.willTransition(to: newCollection, with: coordinator)
    //...
}

how to find 2d array size in c++

Here is one possible solution of first part

#include<iostream>

using namespace std;
int main()
{
    int marks[][4] = {
                      10, 20, 30, 50,
                      40, 50, 60, 60,
                      10, 20, 10, 70
                     };

int rows =  sizeof(marks)/sizeof(marks[0]);
int cols = sizeof(marks)/(sizeof(int)*rows);


    for(int i=0; i<rows; i++)
    {
        for(int j=0; j<cols; j++)
        {
            cout<<marks[i][j]<<" ";
        }
        cout<<endl;
    }



    return 0;
}

Reading content from URL with Node.js

try using the on error event of the client to find the issue.

var http = require('http');

var options = {
    host: 'google.com',
    path: '/'
}
var request = http.request(options, function (res) {
    var data = '';
    res.on('data', function (chunk) {
        data += chunk;
    });
    res.on('end', function () {
        console.log(data);

    });
});
request.on('error', function (e) {
    console.log(e.message);
});
request.end();

How to convert a const char * to std::string

There is a constructor accepting two pointer parameters, so the code is simply

 std::string cppstr(cstr, cstr + min(max_length, strlen(cstr)));

this is also going to be as efficient as std::string cppstr(cstr) if the length is smaller than max_length.

I would like to see a hash_map example in C++

The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":

#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;

int main() {
    unordered_map <string, int> m;
    m["foo"] = 42;
    cout << m["foo"] << endl;
}

In order to get this compile, you need to tell g++ that you are using C++0x:

g++ -std=c++0x main.cpp

These maps work pretty much as std::map does, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.

What does it mean if a Python object is "subscriptable" or not?

The meaning of subscript in computing is: "a symbol (notionally written as a subscript but in practice usually not) used in a program, alone or with others, to specify one of the elements of an array."

Now, in the simple example given by @user2194711 we can see that the appending element is not able to be a part of the list because of two reasons:-

1) We are not really calling the method append; because it needs () to call it.

2) The error is indicating that the function or method is not subscriptable; means they are not indexable like a list or sequence.

Now see this:-

>>> var = "myString"
>>> def foo(): return 0
... 
>>> var[3]
't'
>>> foo[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable

That means there are no subscripts or say elements in function like they occur in sequences; and we cannot access them like we do, with the help of [].

Also; as mipadi said in his answer; It basically means that the object implements the __getitem__() method. (if it is subscriptable). Thus the error produced:

arr.append["HI"]

TypeError: 'builtin_function_or_method' object is not subscriptable

How can I delete using INNER JOIN with SQL Server?

Try this query:

DELETE WorkRecord2, Employee 
FROM WorkRecord2 
INNER JOIN Employee ON (tbl_name.EmployeeRun=tbl_name.EmployeeNo)
WHERE tbl_name.Company = '1' 
AND tbl_name.Date = '2013-05-06';

How to SUM two fields within an SQL query

Try the following:

SELECT *, (FieldA + FieldB) AS Sum
FROM Table

Add an object to an Array of a custom class

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.

What is the better API to Reading Excel sheets in java - JXL or Apache POI

I have used both JXL (now "JExcel") and Apache POI. At first I used JXL, but now I use Apache POI.

First, here are the things where both APIs have the same end functionality:

  • Both are free
  • Cell styling: alignment, backgrounds (colors and patterns), borders (types and colors), font support (font names, colors, size, bold, italic, strikeout, underline)
  • Formulas
  • Hyperlinks
  • Merged cell regions
  • Size of rows and columns
  • Data formatting: Numbers and Dates
  • Text wrapping within cells
  • Freeze Panes
  • Header/Footer support
  • Read/Write existing and new spreadsheets
  • Both attempt to keep existing objects in spreadsheets they read in intact as far as possible.

However, there are many differences:

  • Perhaps the most significant difference is that Java JXL does not support the Excel 2007+ ".xlsx" format; it only supports the old BIFF (binary) ".xls" format. Apache POI supports both with a common design.
  • Additionally, the Java portion of the JXL API was last updated in 2009 (3 years, 4 months ago as I write this), although it looks like there is a C# API. Apache POI is actively maintained.
  • JXL doesn't support Conditional Formatting, Apache POI does, although this is not that significant, because you can conditionally format cells with your own code.
  • JXL doesn't support rich text formatting, i.e. different formatting within a text string; Apache POI does support it.
  • JXL only supports certain text rotations: horizontal/vertical, +/- 45 degrees, and stacked; Apache POI supports any integer number of degrees plus stacked.
  • JXL doesn't support drawing shapes; Apache POI does.
  • JXL supports most Page Setup settings such as Landscape/Portrait, Margins, Paper size, and Zoom. Apache POI supports all of that plus Repeating Rows and Columns.
  • JXL doesn't support Split Panes; Apache POI does.
  • JXL doesn't support Chart creation or manipulation; that support isn't there yet in Apache POI, but an API is slowly starting to form.
  • Apache POI has a more extensive set of documentation and examples available than JXL.

Additionally, POI contains not just the main "usermodel" API, but also an event-based API if all you want to do is read the spreadsheet content.

In conclusion, because of the better documentation, more features, active development, and Excel 2007+ format support, I use Apache POI.

How to set Spinner Default by its Value instead of Position?

You can do it easily like this.

String cls=student.getStudentClass();
class_spinner.setSelection(classArray.indexOf(cls),true);

How to check if element has any children in Javascript?

You could also do the following:

if (element.innerHTML.trim() !== '') {
    // It has at least one
} 

This uses the trim() method to treat empty elements which have only whitespaces (in which case hasChildNodes returns true) as being empty.

NB: The above method doesn't filter out comments. (so a comment would classify a a child)

To filter out comments as well, we could make use of the read-only Node.nodeType property where Node.COMMENT_NODE (A Comment node, such as <!-- … -->) has the constant value - 8

if (element.firstChild?.nodeType !== 8 && element.innerHTML.trim() !== '' {
   // It has at least one
}

_x000D_
_x000D_
let divs = document.querySelectorAll('div');
for(element of divs) {
  if (element.firstChild?.nodeType !== 8 && element.innerHTML.trim() !== '') {
   console.log('has children')
  } else { console.log('no children') }
}
_x000D_
<div><span>An element</span>
<div>some text</div>
<div>     </div> <!-- whitespace -->
<div><!-- A comment --></div>
<div></div>
_x000D_
_x000D_
_x000D_

Value does not fall within the expected range

In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.

Stopping a thread after a certain amount of time

This will work if you are not blocking.

If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep() your thread will only stop after it wakes up.

import threading
import time

duration = 2

def main():
    t1_stop = threading.Event()
    t1 = threading.Thread(target=thread1, args=(1, t1_stop))

    t2_stop = threading.Event()
    t2 = threading.Thread(target=thread2, args=(2, t2_stop))

    time.sleep(duration)
    # stops thread t2
    t2_stop.set()

def thread1(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

def thread2(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

Best practices for styling HTML emails

'Fraid so. I'd make an HTML page with a stylesheet, then use jQuery to apply the stylesheet to the style attr of each element. Something like this:

var styleAttributes = ['color','font-size']; // all the attributes you've applied in your stylesheet
for (i in styleAttributes) {
    $('body *').css(styleAttributes[i],function () {
        $(this).css(styleAttributes[i]);
    });
}

Then copy the DOM and use that in the email.

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

I've recently stumbled upon the following solution to this problem:

Source: Multiple versions of Chrome

...this is registry data problem: How to do it then (this is an example for 2.0.172.39 and 3.0.197.11, I'll try it with next versions as they will come, let's assume I've started with Chrome 2):

  1. Install Chrome 2, you'll find it Application Data folder, since I'm from Czech Republic and my name is Bronislav Klucka the path looks like this:

    C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome
    

    and run Chrome

  2. Open registry and save

    [HKEY_CURRENT_USER\Software\Google\Update\Clients\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    [HKEY_CURRENT_USER\Software\Google\Update\ClientState\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    

    keys, put them into one chrome2.reg file and copy this file next to chrome.exe (ChromeDir\Application)

  3. Rename Chrome folder to something else (e.g. Chrome2)

  4. Install Chrome 3, it will install to Chrome folder again and run Chrome

  5. Save the same keys (there are changes due to different version) and save it to the chrome3.reg file next to chrome.exe file of this new version again
  6. Rename the folder again (e.g. Chrome3)

    the result would be that there is no Chrome dir (only Chrome2 and Chrome3)

  7. Go to the Application folder of Chrome2, create chrome.bat file with this content:

    @echo off
    regedit /S chrome2.reg
    START chrome.exe -user-data-dir="C:\Docume~1\Bronis~1\LocalS~1\Dataap~1\Google\Chrome2\User Data"
    rem START chrome.exe -user-data-dir="C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome2\User Data"
    

    the first line is generic batch command, the second line will update registry with the content of chrome2.reg file, the third lines starts Chrome pointing to passed directory, the 4th line is commented and will not be run.

    Notice short name format passed as -user-data-dir parameter (the full path is at the 4th line), the problem is that Chrome using this parameter has a problem with diacritics (Czech characters)

  8. Do 7. again for Chrome 3, update paths and reg file name in bat file for Chrome 3

Try running both bat files, seems to be working, both versions of Chrome are running simultaneously.

Updating: Running "About" dialog displays correct version, but an error while checking for new one. To correct that do (I'll explain form Chrome2 folder): 1. rename Chrome2 to Chrome 2. Go to Chrome/Application folder 3. run chrome2.reg file 4. run chrome.exe (works the same for Chrome3) now the version checking works. There has been no new version of Chrome since I've find this whole solution up. But I assume that update will be downloaded to this folder so all you need to do is to update reg file after update and rename Chrome folder back to Chrome2. I'll update this post after successful Chrome update.

Bronislav Klucka

How to get absolute value from double - c-language

It's worth noting that Java can overload a method such as abs so that it works with an integer or a double. In C, overloading doesn't exist, so you need different functions for integer versus double.

Save PHP variables to a text file

Okay, so I needed a solution to this, and I borrowed heavily from the answers to this question and made a library: https://github.com/rahuldottech/varDx (Licensed under the MIT license).

It uses serialize() and unserialize() and writes data to a file. It can read and write multiple objects/variables/whatever to and from the same file.

Usage:

<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file

See the github page for more information. It has functions to read, write, check, modify and delete data.

Using Case/Switch and GetType to determine the object

This won't directly solve your problem as you want to switch on your own user-defined types, but for the benefit of others who only want to switch on built-in types, you can use the TypeCode enumeration:

switch (Type.GetTypeCode(node.GetType()))
{
    case TypeCode.Decimal:
        // Handle Decimal
        break;

    case TypeCode.Int32:
        // Handle Int32
        break;
     ...
}

Pointer vs. Reference

Pointers

  • A pointer is a variable that holds a memory address.
  • A pointer declaration consists of a base type, an *, and the variable name.
  • A pointer can point to any number of variables in lifetime
  • A pointer that does not currently point to a valid memory location is given the value null (Which is zero)

    BaseType* ptrBaseType;
    BaseType objBaseType;
    ptrBaseType = &objBaseType;
    
  • The & is a unary operator that returns the memory address of its operand.

  • Dereferencing operator (*) is used to access the value stored in the variable which pointer points to.

       int nVar = 7;
       int* ptrVar = &nVar;
       int nVar2 = *ptrVar;
    

Reference

  • A reference (&) is like an alias to an existing variable.

  • A reference (&) is like a constant pointer that is automatically dereferenced.

  • It is usually used for function argument lists and function return values.

  • A reference must be initialized when it is created.

  • Once a reference is initialized to an object, it cannot be changed to refer to another object.

  • You cannot have NULL references.

  • A const reference can refer to a const int. It is done with a temporary variable with value of the const

    int i = 3;    //integer declaration
    int * pi = &i;    //pi points to the integer i
    int& ri = i;    //ri is refers to integer i – creation of reference and initialization
    

enter image description here

enter image description here

react-native: command not found

Install react-native globally by using the following command

npm i -g react-native-cli

How do you convert epoch time in C#?

With all credit to LukeH, I've put together some extension methods for easy use:

public static DateTime FromUnixTime(this long unixTime)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.AddSeconds(unixTime);
}

public static long ToUnixTime(this DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date - epoch).TotalSeconds);
}

Note the comment below from CodesInChaos that the above FromUnixTime returns a DateTime with a Kind of Utc, which is fine, but the above ToUnixTime is much more suspect in that doesn't account for what kind of DateTime the given date is. To allow for date's Kind being either Utc or Local, use ToUniversalTime:

public static long ToUnixTime(this DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}

ToUniversalTime will convert a Local (or Unspecified) DateTime to Utc.

if you dont want to create the epoch DateTime instance when moving from DateTime to epoch you can also do:

public static long ToUnixTime(this DateTime date)
{
    return (date.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}

How to keep one variable constant with other one changing with row in excel

To make your formula more readable, you could assign a Name to cell A0, and then use that name in the formula.

The easiest way to define a Name is to highlight the cell or range, then click on the Name box in the formula bar.

Then, if you named A0 "Rate" you can use that name like this:

=(B0+4)/(Rate)

See, much easier to read.

If you want to find Rate, click F5 and it appears in the GoTo list.

Keep only date part when using pandas.to_datetime

This worked for me on UTC Timestamp (2020-08-19T09:12:57.945888)

for di, i in enumerate(df['YourColumnName']):
    df['YourColumnName'][di] = pd.Timestamp(i)

How do I center content in a div using CSS?

with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center

Good NumericUpDown equivalent in WPF?

A control that is missing from the original set of WPF controls, but much used, is the NumericUpDown control. It is a neat way to get users to select a number from a fixed range, in a small area. A slider could be used, but for compact forms with little horizontal real-estate, the NumericUpDown is essential.

Solution A (via WindowsFormsHost)

You can use the Windows Forms NumericUpDown control in WPF by hosting it in a WindowsFormsHost. Pay attention that you have to include a reference to System.Windows.Forms.dll assembly.

<Window x:Class="WpfApplication61.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" 
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>    
        <WindowsFormsHost>
            <wf:NumericUpDown/>
        </WindowsFormsHost>
...

Solution B (custom)

There are several commercial and codeplex versions around, but both involve installing 3rd party dlls and overheads to your project. Far simpler to build your own, and a aimple way to do that is with the ScrollBar.

A vertical ScrollBar with no Thumb (just the repeater buttons) is in fact just what we want. It inherits rom RangeBase, so it has all the properties we need, like Min, Max, and SmallChange (set to 1, to restrict it to Integer values)

So we change the ScrollBar ControlTemplate. First we remove the Thumb and Horizontal trigger actions. Then we group the remains into a grid and add a TextBlock for the number:

<Grid Margin="2">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <TextBlock VerticalAlignment="Center" FontSize="20" MinWidth="25" Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}"/>
    <Grid Grid.Column="1" x:Name="GridRoot" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Background="{TemplateBinding Background}">
        <Grid.RowDefinitions>
            <RowDefinition MaxHeight="18"/>
            <RowDefinition Height="0.00001*"/>
            <RowDefinition MaxHeight="18"/>
        </Grid.RowDefinitions>
        <RepeatButton x:Name="DecreaseRepeat" Command="ScrollBar.LineDownCommand" Focusable="False">
            <Grid>
                <Path x:Name="DecreaseArrow" Stroke="{TemplateBinding Foreground}" StrokeThickness="1" Data="M 0 4 L 8 4 L 4 0 Z"/>
            </Grid>
        </RepeatButton>
        <RepeatButton Grid.Row="2" x:Name="IncreaseRepeat" Command="ScrollBar.LineUpCommand" Focusable="False">
            <Grid>
                <Path x:Name="IncreaseArrow" Stroke="{TemplateBinding Foreground}" StrokeThickness="1" Data="M 0 0 L 4 4 L 8 0 Z"/>
            </Grid>
        </RepeatButton>
    </Grid>
</Grid>

Sources:

Maximum concurrent connections to MySQL

As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections

 maximum range: 4,294,967,295  (e.g. 2**32 - 1)

You'd probably run out of memory, file handles, and network sockets, on your server long before you got anywhere close to that limit.

UL has margin on the left

I don't see any margin or margin-left declarations for #footer-wrap li.

This ought to do the trick:

#footer-wrap ul,
#footer-wrap li {
    margin-left: 0;
    list-style-type: none;
}

Scroll to bottom of div with Vue.js

In the related question you posted, we already have a way to achieve that in plain javascript, so we only need to get the js reference to the dom node we want to scroll.

The ref attribute can be used to declare reference to html elements to make them available in vue's component methods.

Or, if the method in the component is a handler for some UI event, and the target is related to the div you want to scroll in space, you can simply pass in the event object along with your wanted arguments, and do the scroll like scroll(event.target.nextSibling).

Get width in pixels from element with style set with %?

You want to get the computed width. Try: .offsetWidth

(I.e: this.offsetWidth='50px' or var w=this.offsetWidth)

You might also like this answer on SO.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

Android: how to parse URL String with spaces to URI object?

You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes / should be taken into account and which not. You cannot predict that on a raw String beforehand. The problem really needs to be solved at a higher level. Where does that String come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.

At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20:

URI uri = new URI(string.replace(" ", "%20"));

Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri utility class:

int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));

Do note that URLEncoder is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded rules (as used in HTML forms). See also Java URL encoding of query string parameters.

Convert HTML Character Back to Text Using Java Standard Library

You can use the class org.apache.commons.lang.StringEscapeUtils:

String s = StringEscapeUtils.unescapeHtml("Happy &amp; Sad")

It is working.

In Bootstrap open Enlarge image in modal

So I have put together a very rough modal in jsfiddle for you to take hints from.

JSFiddle

$("#pop").on("click", function(e) {
  // e.preventDefault() this is stopping the redirect to the image its self
  e.preventDefault();
  // #the-modal is the img tag that I use as the modal.
  $('#the-modal').modal('toggle');
});

The part that you are missing is the hidden modal that you want to display when the link is clicked. In the example I used a second image as the modal and added the Bootstap classes.

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops

GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:

alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.

It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.

Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

Android API 21 Toolbar Padding

Make your toolbar like:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/menuToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:background="@color/white"
android:contentInsetLeft="10dp"
android:contentInsetRight="10dp"
android:contentInsetStart="10dp"
android:minHeight="?attr/actionBarSize"
android:padding="0dp"
app:contentInsetLeft="10dp"
app:contentInsetRight="10dp"
app:contentInsetStart="10dp"></android.support.v7.widget.Toolbar>

You need to add

contentInset

attribute to add spacing

please follow this link for more - Android Tips

Regular Expression For Duplicate Words

Try this with below RE

  • \b start of word word boundary
  • \W+ any word character
  • \1 same word matched already
  • \b end of word
  • ()* Repeating again

    public static void main(String[] args) {
    
        String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";//  "/* Write a RegEx matching repeated words here. */";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE/* Insert the correct Pattern flag here.*/);
    
        Scanner in = new Scanner(System.in);
    
        int numSentences = Integer.parseInt(in.nextLine());
    
        while (numSentences-- > 0) {
            String input = in.nextLine();
    
            Matcher m = p.matcher(input);
    
            // Check for subsequences of input that match the compiled pattern
            while (m.find()) {
                input = input.replaceAll(m.group(0),m.group(1));
            }
    
            // Prints the modified sentence.
            System.out.println(input);
        }
    
        in.close();
    }
    

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

Official way to ask jQuery wait for all images to load before executing something

I wrote a plugin that can fire callbacks when images have loaded in elements, or fire once per image loaded.

It is similar to $(window).load(function() { .. }), except it lets you define any selector to check. If you only want to know when all images in #content (for example) have loaded, this is the plugin for you.

It also supports loading of images referenced in the CSS, such as background-image, list-style-image, etc.

waitForImages jQuery plugin

Example Usage

$('selector').waitForImages(function() {
    alert('All images are loaded.');
});

Example on jsFiddle.

More documentation is available on the GitHub page.

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

May be your Plesk panel or other panel subscription has been expired....please check subscription End.

Dynamic loading of images in WPF

This is strange behavior and although I am unable to say why this is occurring, I can recommend some options.

First, an observation. If you include the image as Content in VS and copy it to the output directory, your code works. If the image is marked as None in VS and you copy it over, it doesn't work.

Solution 1: FileStream

The BitmapImage object accepts a UriSource or StreamSource as a parameter. Let's use StreamSource instead.

        FileStream stream = new FileStream("picture.png", FileMode.Open, FileAccess.Read);
        Image i = new Image();
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.StreamSource = stream;
        src.EndInit();
        i.Source = src;
        i.Stretch = Stretch.Uniform;
        panel.Children.Add(i);

The problem: stream stays open. If you close it at the end of this method, the image will not show up. This means that the file stays write-locked on the system.

Solution 2: MemoryStream

This is basically solution 1 but you read the file into a memory stream and pass that memory stream as the argument.

        MemoryStream ms = new MemoryStream();
        FileStream stream = new FileStream("picture.png", FileMode.Open, FileAccess.Read);
        ms.SetLength(stream.Length);
        stream.Read(ms.GetBuffer(), 0, (int)stream.Length);

        ms.Flush();
        stream.Close();

        Image i = new Image();
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.StreamSource = ms;
        src.EndInit();
        i.Source = src;
        i.Stretch = Stretch.Uniform;
        panel.Children.Add(i);

Now you are able to modify the file on the system, if that is something you require.

Where do I put my php files to have Xampp parse them?

in XAMPP the default root is "htdocs" inside the XAMPP folder, if you followed the instructions on the xampp homepage it would be "/opt/lampp/htdocs"

Could not connect to React Native development server on Android

This is applicable to Android 9.0+ according to the Network Security Configuration. Well, so after trying all possible solutions I found on the web, I decided to investigate the native Android logcat manually. Even after adding android:usesCleartextTraffic="true", I found this in the logcat:

06-25 02:32:34.561 32001 32001 E unknown:ReactNative: Caused by: java.net.UnknownServiceException: CLEARTEXT communication to 192.168.29.96 not permitted by network security policy

So, I tried to inspect my react-native app's source. I found that in debug variant, there is already a network-security-config which is defined by react-native guys, that conflicts with the main variant.

There's an easy solution to this. Go to <app-src>/android/app/src/debug/res/xml/react_native_config.xml Add a new line with your own IP address in the like:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
    ***<domain includeSubdomains="false">192.168.29.96</domain>***
  </domain-config>
</network-security-config>

As my computer's local IP (check from ifconfig for linux) is 192.168.29.96, I added the above line in ***

Then, you need to clean and rebuild for Android!

cd <app-src>/android
./gradlew clean
cd <app-src>
react-native run-android

I hope this works for you.

Why is HttpClient BaseAddress not working?

Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.

i.e.

var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
                inventory = inventoryId
            });

SQL Server Script to create a new user

Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.

Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:

CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO

Here is how you create a User with db_owner privileges using the Login you just declared:

Use YourDatabase;
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
    CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
    EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO

Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).

However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.

UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.

Obtain smallest value from array in Javascript?

Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.

const findMin = (arr, min, i) => arr.length === i ? min :
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)

Code snippet:

_x000D_
_x000D_
const findMin = (arr, min, i) => arr.length === i ? min :_x000D_
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)_x000D_
  _x000D_
const arr = [5, 34, 2, 1, 6, 7, 9, 3];_x000D_
const min = findMin(arr, arr[0], 0)_x000D_
console.log(min);
_x000D_
_x000D_
_x000D_

How to avoid the "Circular view path" exception with Spring MVC test

This is happening because Spring is removing "preference" and appending the "preference" again making the same path as the request Uri.

Happening like this : request Uri: "/preference"

remove "preference": "/"

append path: "/"+"preference"

end string: "/preference"

This is getting into a loop which the Spring notifies you by throwing exception.

Its best in your interest to give a different view name like "preferenceView" or anything you like.

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

Looking for simple Java in-memory cache

You can easily use imcache. A sample code is below.

void example(){
    Cache<Integer,Integer> cache = CacheBuilder.heapCache().
    cacheLoader(new CacheLoader<Integer, Integer>() {
        public Integer load(Integer key) {
            return null;
        }
    }).capacity(10000).build(); 
}

Can I get div's background-image url?

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

Change default timeout for mocha

In current versions of Mocha, the timeout can be changed globally like this:

mocha.timeout(5000);

Just add the line above anywhere in your test suite, preferably at the top of your spec or in a separate test helper.


In older versions, and only in a browser, you could change the global configuration using mocha.setup.

mocha.setup({ timeout: 5000 });

The documentation does not cover the global timeout setting, but offers a few examples on how to change the timeout in other common scenarios.

TypeError: 'int' object is not subscriptable

If you want to sum the digit of a number, one way to do it is using sum() + a generator expression:

sum(int(i) for i in str(155))

I modified a little your code using sum(), maybe you want to take a look at it:

birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = sum(int(i) for i in birthday[0:2])
sumd = sum(int(i) for i in birthday[3:5])
sumy = sum(int(i) for i in birthday[6:10])
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = sum(int(c) for c in str(sumall)))
print "Your lucky number is", sumln

Fast ceiling of an integer division in C / C++

How about this? (requires y non-negative, so don't use this in the rare case where y is a variable with no non-negativity guarantee)

q = (x > 0)? 1 + (x - 1)/y: (x / y);

I reduced y/y to one, eliminating the term x + y - 1 and with it any chance of overflow.

I avoid x - 1 wrapping around when x is an unsigned type and contains zero.

For signed x, negative and zero still combine into a single case.

Probably not a huge benefit on a modern general-purpose CPU, but this would be far faster in an embedded system than any of the other correct answers.

Python : Trying to POST form using requests

You can use the Session object

import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}

session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')

Boolean vs tinyint(1) for boolean values in MySQL

boolean isn't a distinct datatype in MySQL; it's just a synonym for tinyint. See this page in the MySQL manual.

Personally I would suggest use tinyint as a preference, because boolean doesn't do what you think it does from the name, so it makes for potentially misleading code. But at a practical level, it really doesn't matter -- they both do the same thing, so you're not gaining or losing anything by using either.

Conda environments not showing up in Jupyter Notebook

The nb_conda_kernels package is the best way to use jupyter with conda. With minimal dependencies and configuration, it allows you to use other conda environments from a jupyter notebook running in a different environment. Quoting its documentation:

Installation

This package is designed to be managed solely using conda. It should be installed in the environment from which you run Jupyter Notebook or JupyterLab. This might be your base conda environment, but it need not be. For instance, if the environment notebook_env contains the notebook package, then you would run

conda install -n notebook_env nb_conda_kernels

Any other environments you wish to access in your notebooks must have an appropriate kernel package installed. For instance, to access a Python environment, it must have the ipykernel package; e.g.

conda install -n python_env ipykernel

To utilize an R environment, it must have the r-irkernel package; e.g.

conda install -n r_env r-irkernel

For other languages, their corresponding kernels must be installed.

Then all you need to do is start the jupyter notebook server:

conda activate notebook_env  # only needed if you are not using the base environment for the server
# conda install jupyter # in case you have not installed it already
jupyter

enter image description here


Despite the plethora of answers and @merv's efforts to improve them, it still hard to find a good one. I made this one CW, so please vote it to the top or improve it!

Delete files older than 3 months old in a directory using .NET

An SSIS type of example .. (if this helps anyone)

          public void Main()
          {
                 // TODO: Add your code here
        // Author: Allan F 10th May 2019

        //first part of process .. put any files of last Qtr (or older) in Archive area 
        //e.g. if today is 10May2019 then last quarter is 1Jan2019 to 31March2019 .. any files earlier than 31March2019 will be archived

        //string SourceFileFolder = "\\\\adlsaasf11\\users$\\aford05\\Downloads\\stage\\";
        string SourceFilesFolder = (string)Dts.Variables["SourceFilesFolder"].Value;
        string ArchiveFolder = (string)Dts.Variables["ArchiveFolder"].Value;
        string FilePattern = (string)Dts.Variables["FilePattern"].Value;
        string[] files = Directory.GetFiles(SourceFilesFolder, FilePattern);

        //DateTime date = new DateTime(2019, 2, 15);//commented out line .. just for testing the dates .. 

        DateTime date = DateTime.Now;
        int quarterNumber = (date.Month - 1) / 3 + 1;
        DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber - 1) * 3 + 1, 1);
        DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);

        DateTime LastDayOfPriorQuarter = firstDayOfQuarter.AddDays(-1);
        int PrevQuarterNumber = (LastDayOfPriorQuarter.Month - 1) / 3 + 1;
        DateTime firstDayOfLastQuarter = new DateTime(LastDayOfPriorQuarter.Year, (PrevQuarterNumber - 1) * 3 + 1, 1);
        DateTime lastDayOfLastQuarter = firstDayOfLastQuarter.AddMonths(3).AddDays(-1);

        //MessageBox.Show("debug pt2: firstDayOfQuarter" + firstDayOfQuarter.ToString("dd/MM/yyyy"));
        //MessageBox.Show("debug pt2: firstDayOfLastQuarter" + firstDayOfLastQuarter.ToString("dd/MM/yyyy"));


        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);

            //MessageBox.Show("debug pt2:" + fi.Name + " " + fi.CreationTime.ToString("dd/MM/yyyy HH:mm") + " " + fi.LastAccessTime.ToString("dd/MM/yyyy HH:mm") + " " + fi.LastWriteTime.ToString("dd/MM/yyyy HH:mm"));
            if (fi.LastWriteTime < firstDayOfQuarter)
            {

                try
                {

                    FileInfo fi2 = new FileInfo(ArchiveFolder);

                    //Ensure that the target does not exist.
                    //fi2.Delete();

                    //Copy the file.
                    fi.CopyTo(ArchiveFolder + fi.Name);
                    //Console.WriteLine("{0} was copied to {1}.", path, ArchiveFolder);

                    //Delete the old location file.
                    fi.Delete();
                    //Console.WriteLine("{0} was successfully deleted.", ArchiveFolder);

                }
                catch (Exception e)
                {
                    //do nothing
                    //Console.WriteLine("The process failed: {0}", e.ToString());
                }
            }
        }

        //second part of process .. delete any files in Archive area dated earlier than last qtr ..
        //e.g. if today is 10May2019 then last quarter is 1Jan2019 to 31March2019 .. any files earlier than 1Jan2019 will be deleted

        string[] archivefiles = Directory.GetFiles(ArchiveFolder, FilePattern);
        foreach (string archivefile in archivefiles)
        {
            FileInfo fi = new FileInfo(archivefile);
            if (fi.LastWriteTime < firstDayOfLastQuarter )
            {
                try
                {
                    fi.Delete();
                }
                catch (Exception e)
                {
                    //do nothing
                }
            }
        }


                 Dts.TaskResult = (int)ScriptResults.Success;
          }

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

's up guys i read every single forum about this topic i still had problem (occurred trying to project from git)

after 4 hours and a lot of swearing i solved this issue by myself just by changing target framework setting in project properties (right click on project -> properties) -> application and changed target framework from .net core 3.0 to .net 5.0 i hope it will help anybody

happy coding gl hf nerds

Drawing a dot on HTML5 canvas

For performance reasons, don't draw a circle if you can avoid it. Just draw a rectangle with a width and height of one:

ctx.fillRect(10,10,1,1); // fill in the pixel at (10,10)

In Typescript, How to check if a string is Numeric

if var sum=0; var x;

then, what about this? sum+=(x|0);

How to display JavaScript variables in a HTML page without document.write

If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.

?var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);??????

SQL Server ORDER BY date and nulls last

According to Itzik Ben-Gan, author of T-SQL Fundamentals for MS SQL Server 2012, "By default, SQL Server sorts NULL marks before non-NULL values. To get NULL marks to sort last, you can use a CASE expression that returns 1 when the" Next_Contact_Date column is NULL, "and 0 when it is not NULL. Non-NULL marks get 0 back from the expression; therefore, they sort before NULL marks (which get 1). This CASE expression is used as the first sort column." The Next_Contact_Date column "should be specified as the second sort column. This way, non-NULL marks sort correctly among themselves." Here is the solution query for your example for MS SQL Server 2012 (and SQL Server 2014):

ORDER BY 
   CASE 
        WHEN Next_Contact_Date IS NULL THEN 1
        ELSE 0
   END, Next_Contact_Date;

Equivalent code using IIF syntax:

ORDER BY 
   IIF(Next_Contact_Date IS NULL, 1, 0),
   Next_Contact_Date;

Hash table in JavaScript

You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.

Linux cmd to search for a class file among jars irrespective of jar path

Use deepgrep and deepfind. On debian-based systems you can install them by:

sudo apt-get install strigi-utils

Both commands search for nested archives as well. In your case the command would look like:

find . -name "*.jar" | xargs -I {} deepfind {} | grep Hello.class

How to set up googleTest as a shared library on Linux

For 1.8.1 based on @ManuelSchneid3r 's answer I had to do:

wget github.com/google/googletar xf release-1.8.1.tar.gz 
tar xf release-1.8.1.tar.gz
cd googletest-release-1.8.1/
cmake -DBUILD_SHARED_LIBS=ON .
make

I then did make install which seemed to work for 1.8.1, but following @ManuelSchneid3r it would mean:

sudo cp -a googletest/include/gtest /usr/include
sudo cp -a googlemock/include/gmock /usr/include
sudo cp `find .|grep .so$` /usr/lib/

Running Node.js in apache?

Although there are a lot of good tips here I'd like to answer the question you asked:

So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..

YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here http://www.cgi-node.org/ .

The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.

I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.

A quick example from cgi-node.org site:

<? include('myJavaScriptFile.js'); ?>
<html>
   <body>
      <? var helloWorld = 'Hello World!'; ?>
      <b><?= helloWorld ?><br/>
      <? for( var index = 0; index < 10; index++) write(index + ' '); ?>
   </body>
</html>

This outputs:

Hello World!
0 1 2 3 4 5 6 7 8 9

You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.

I am currently running Node.js through the cgi-node module on Godaddy.

CGI-Node.org site has all the documentation to get started.

I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.

Hope this helps.

How to Execute SQL Script File in Java?

The Apache iBatis solution worked like a charm.

The script example I used was exactly the script I was running from MySql workbench.

There is an article with examples here: https://www.tutorialspoint.com/how-to-run-sql-script-using-jdbc#:~:text=You%20can%20execute%20.,to%20pass%20a%20connection%20object.&text=Register%20the%20MySQL%20JDBC%20Driver,method%20of%20the%20DriverManager%20class.

This is what I did:

pom.xml dependency

<!-- IBATIS SQL Script runner from Apache (https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-core) -->
<dependency>
    <groupId>org.apache.ibatis</groupId>
    <artifactId>ibatis-core</artifactId>
    <version>3.0</version>
</dependency>

Code to execute script:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;   
import org.apache.ibatis.jdbc.ScriptRunner;   
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SqlScriptExecutor {

    public static void executeSqlScript(File file, Connection conn) throws Exception {
        Reader reader = new BufferedReader(new FileReader(file));
        log.info("Running script from file: " + file.getCanonicalPath());
        ScriptRunner sr = new ScriptRunner(conn);
        sr.setAutoCommit(true);
        sr.setStopOnError(true);
        sr.runScript(reader);
        log.info("Done.");
    }
    
}

How to remove special characters from a string?

To Remove Special character

String t2 = "!@#$%^&*()-';,./?><+abdd";

t2 = t2.replaceAll("\\W+","");

Output will be : abdd.

This works perfectly.

Changing CSS for last <li>

2015 Answer: CSS last-of-type allows you to style the last item.

ul li:last-of-type { color: red; }

Android: Unable to add window. Permission denied for this window type

LayoutParams.TYPE_PHONE is deprecated. I have updated my code like these.

parameters = if (Build.VERSION.SDK_INT > 25) {
        LayoutParams(
                minHW * 2 / 3, minHW * 2 / 3,
                LayoutParams.TYPE_APPLICATION_OVERLAY,
                LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT)
    }else {
        LayoutParams(
                minHW * 2 / 3, minHW * 2 / 3,
                LayoutParams.TYPE_PHONE,
                LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT)
    }

LayoutParams.TYPE_APPLICATION_OVERLAY requires api level 26 or above.

How to change the application launcher icon on Flutter?

Follow simple steps:

1. Add flutter_launcher_icons Plugin to pubspec.yaml

e.g.

dev_dependencies: 
  flutter_test:
    sdk: flutter

  flutter_launcher_icons: "^0.8.1"

flutter_icons:
  image_path: "icon/icon.png" 
  android: true
  ios: true

2. Prepare an app icon for the specified path. e.g. icon/icon.png

3. Execute command on the terminal to Create app icons:

$ flutter pub get

$ flutter pub run flutter_launcher_icons:main

To check check all available options and to set different icons for android and iOS please refer this

Update:

flutter_launcher_icons 0.8.0 Version (12th Sept 2020) has Added flavours support

Flavors are typically used to build your app for different environments such as dev and prod

The community has written some articles and packages you might find useful. These articles address flavors for both iOS and Android.

Hope this will helps others.

Excel 2013 VBA Clear All Filters macro

I am using this approach for a multi table and range sheet as a unique way.

Sub RemoveFilters(Ws As Worksheet)
Dim LO As ListObject
On Error Resume Next
    Ws.ShowAllData
    For Each LO In Ws.ListObjects
        LO.ShowAutoFilter = True
        LO.AutoFilter.ShowAllData
    Next
    Ws.ShowAllData
End Sub

AddRange to a Collection

The C5 Generic Collections Library classes all support the AddRange method. C5 has a much more robust interface that actually exposes all of the features of its underlying implementations and is interface-compatible with the System.Collections.Generic ICollection and IList interfaces, meaning that C5's collections can be easily substituted as the underlying implementation.

How to identify unused CSS definitions from multiple CSS files in a project

Chrome Developer Tools has an Audits tab which can show unused CSS selectors.

Run an audit, then, under Web Page Performance see Remove unused CSS rules

enter image description here

Sometimes adding a WCF Service Reference generates an empty reference.cs

I also had the issue of broken service references when working with project references on both sides (the service project and the project having a reference to the service). If the the .dll of the referenced project for example is called "Contoso.Development.Common", but the projects name is simply shortened to "Common", also project references to this project are named just "Common". The service however expects a reference to "Contoso.Development.Common" for resolving classes (if this option is activated in the service reference options).

So with explorer I opened the folder of the project which is referencing the service and the "Common"-project. There I editet the VS project file (.csproj) with notepad. Search for the name of the refernced project (which is "Common.csproj" in this example) and you will quickly find the configuration entry representing the project reference.

I changed

<ProjectReference Include="..\Common\Common.csproj"> <Project>{C90AAD45-6857-4F83-BD1D-4772ED50D44C}</Project> <Name>Common</Name> </ProjectReference>

to

<ProjectReference Include="..\Common\Common.csproj"> <Project>{C90AAD45-6857-4F83-BD1D-4772ED50D44C}</Project> <Name>Contoso.Development.Common</Name> </ProjectReference>

The important thing is to change the name of the reference to the name of the dll the referenced project has as output.

Then switch back to VS. There you will be asked to reload the project since it has been modified outside of VS. Click the reload button.

After doing so adding und updating the service reference worked just as expected.

Hope this also helps someone else.

Regards MH

Updating a JSON object using Javascript

var i = jsonObj.length;
while ( i --> 0 ) {
    if ( jsonObj[i].Id === 3 ) {
        jsonObj[ i ].Username = 'Thomas';
        break;
    }
}

Or, if the array is always ordered by the IDs:

jsonObj[ 2 ].Username = 'Thomas';

Android button background color

If you don't mind hardcoding it you can do this ~> android:background="#eeeeee" and drop any hex color # you wish.

Looks like this....

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView1"
    android:text="@string/ClickMe"
    android:background="#fff"/>

Making a div vertically scrollable using CSS

The problem with all of these answers for me was they weren't responsive. I had to have a fixed height for a parent div which i didn't want. I also didn't want to spend a ton of time dinking around with media queries. If you are using angular, you can use bootstraps tabset and it will do all of the hard work for you. You'll be able to scroll the inner content and it will be responsive. When you setup the tab, do it like this: $scope.tab = { title: '', url: '', theclass: '', ative: true }; ... the point is, you don't want a title or image icon. then hide the outline of the tab in cs like this:

.nav-tabs {
   border-bottom:none; 
} 

and also this .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {border:none;} and finally to remove the invisible tab that you can still click on if you don't implement this: .nav > li > a {padding:0px;margin:0px;}

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

Sometimes, the database will not be mounted correctly, so we need to mount it manually. For that, shut it down and start it up then mount. Log in as oracle user, then run the following commands:

sqlplus / as sysdba;
shutdown immediate;
startup nomount;
alter database mount;
alter database open;

How to use adb command to push a file on device without sd card

My solution (example with a random mp4 video file):

  1. Set a file to device:

    adb push /home/myuser/myVideoFile.mp4 /storage/emulated/legacy/
    
  2. Get a file from device:

    adb pull /storage/emulated/legacy/myVideoFile.mp4 
    

For retrieve the path in the code:

String myFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myVideoFile.mp4";

This is all. This solution doesn't give permission problems and it works fine.

Last point: I wanted to change the video metadata information. If you want to write into your device you should change the permission in the AndroidManifest.xml. Add this line:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to set page content to the middle of screen?

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Center</title>        
    </head>
    <body>
        <div id="main_body">
          some text
        </div>
    </body>
</html>

CSS

body
{
   width: 100%;
   Height: 100%;
}
#main_body
{
    background: #ff3333;
    width: 200px;
    position: absolute;
}?

JS ( jQuery )

$(function(){
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var main = $("#main_body");    
    $("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
                          left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});

See example here

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

I ran into this same issue but found out that there is a JSON encoder that can be used to move these objects between processes.

from pyVmomi.VmomiSupport import VmomiJSONEncoder

Use this to create your list:

jsonSerialized = json.dumps(pfVmomiObj, cls=VmomiJSONEncoder)

Then in the mapped function, use this to recover the object:

pfVmomiObj = json.loads(jsonSerialized)

HTML for the Pause symbol in audio and video control

I found it, it’s in the Miscellaneous Technical block. ? (U+23F8)

Sum up a column from a specific row down

This seems like the easiest (but not most robust) way to me. Simply compute the sum from row 6 to the maximum allowed row number, as specified by Excel. According to this site, the maximum is currently 1048576, so the following should work for you:

=sum(c6:c1048576)

For more robust solutions, see the other answers.

Copy output of a JavaScript variable to the clipboard

I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.

Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.

_x000D_
_x000D_
    function doCopy() {_x000D_
_x000D_
        try{_x000D_
            var unique = document.querySelectorAll('.unique');_x000D_
            var msg ="";_x000D_
_x000D_
            unique.forEach(function (unique) {_x000D_
                msg+=unique.value;_x000D_
            });_x000D_
_x000D_
            var temp =document.createElement("textarea");_x000D_
            var tempMsg = document.createTextNode(msg);_x000D_
            temp.appendChild(tempMsg);_x000D_
_x000D_
            document.body.appendChild(temp);_x000D_
            temp.select();_x000D_
            document.execCommand("copy");_x000D_
            document.body.removeChild(temp);_x000D_
            console.log("Success!")_x000D_
_x000D_
_x000D_
        }_x000D_
        catch(err) {_x000D_
_x000D_
            console.log("There was an error copying");_x000D_
        }_x000D_
    }
_x000D_
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>_x000D_
<input type="text" class="unique" size="18" value="">_x000D_
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>
_x000D_
_x000D_
_x000D_

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

Recommended way to embed PDF in HTML?

FDView combines PDF2SWF (which itself is based on xpdf) with an SWF viewer so you can convert and embed PDF documents on the fly on your server.

xpdf is not a perfect PDF converter. If you need better results then Ghostview has some ability to convert PDF documents into other formats which you may be able to more easily build a Flash viewer for.

But for simple PDF documents, FDView should work reasonably well.

How do I use CREATE OR REPLACE?

If you are doing in code then first check for table in database by using query SELECT table_name FROM user_tables WHERE table_name = 'XYZ'

if record found then truncate table otherwise create Table

Work like Create or Replace.

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

Java Error: "Your security settings have blocked a local application from running"

I am using an older Data Structure and Algs book that comes with Java Applets for practice. So I needed to store and run some applets locally. I am currently running Windows 10 OS with Edge, Chrome, and IE 11.

Running applets seem to only be allowed in IE11, and as other have mentioned you have to add the applet to the exception list. My issue was since I am storing these locally, and opening them in IE, it opened with path starting with "C:\..." Adding the full path using, "file///..." like mentioned in one of the other answers didn't work for me.

The fix: So, I just added(without the quotes), "file:///" to the exception site list and finally got it working. This also allows me to run any applet stored locally, and I do not have to explicitly add an exception for each applet path.

I plan to remove the exception from the list once I am done using the programs, and only add it back as necessary.

Use multiple custom fonts using @font-face?

You simply add another @font-face rule:

@font-face {
    font-family: CustomFont;
    src: url('CustomFont.ttf');
}

@font-face {
    font-family: CustomFont2;
    src: url('CustomFont2.ttf');
}

If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

Pro JavaScript programmer interview questions (with answers)

Because JavaScript is such a small language, yet with incredible complexity, you should be able to ask relatively basic questions and find out if they are really that good based on their answers. For instance, my standard first question to gauge the rest of the interview is:

In JavaScript, what is the difference between var x = 1 and x = 1? Answer in as much or as little detail as you feel comfortable.

Novice JS programmers might have a basic answer about locals vs globals. Intermediate JS guys should definitely have that answer, and should probably mention function-level scope. Anyone calling themselves an "advanced" JS programmer should be prepared to talk about locals, implied globals, the window object, function-scope, declaration hoisting, and scope chains. Furthermore, I'd love to hear about [[DontDelete]], hoisting precedence (parameters vs var vs function), and undefined.

Another good question is to ask them to write a sum() function that accepts any number of arguments, and returns their sum. Then, ask them to use that function (without modification) to sum all the values in an array. They should write a function that looks like this:

function sum() {
  var i, l, result = 0;
  for (i = 0, l = arguments.length; i < l; i++) {
    result += arguments[i];
  }
  return result;
}
sum(1,2,3); // 6

And they should invoke it on your array like this (context for apply can be whatever, I usually use null in that case):

var data = [1,2,3];
sum.apply(null, data); // 6

If they've got those answers, they probably know their JavaScript. You should then proceed to asking them about non-JS specific stuff like testing, workflows, version control, etc. to find out if they're a good programmer.

Unable to use Intellij with a generated sources folder

Solved it by removing the "Excluded" in the module setting (right click on project, "Open module settings"). enter image description here

preventDefault() on an <a> tag

Alternatively, you could just return false from the click event:

 $('div.toggle').hide();
 $('ul.product-info li a').click(function(event){
  $(this).next('div').slideToggle(200);
+ return false; 
 });

Which would stop the A-Href being triggered.

Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)

Is it possible to put CSS @media rules inline?

Inline styles cannot currently contain anything other than declarations (property: value pairs).

You can use style elements with appropriate media attributes in head section of your document.

Help needed with Median If in Excel

Expanding on Brian Camire's Answer:

Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))

Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

Switch statement fall-through...should it be allowed?

It's a double-edged sword. It is sometimes very useful, but often dangerous.

When is it good? When you want 10 cases all processed the same way...

switch (c) {
  case 1:
  case 2:
            ... Do some of the work ...
            /* FALLTHROUGH */
  case 17:
            ... Do something ...
            break;
  case 5:
  case 43:
            ... Do something else ...
            break;
}

The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.

How to drop all user tables?

The easiest way would be to drop the tablespace then build the tablespace back up. But I'd rather not have to do that. This is similar to Henry's except that I just do a copy/paste on the resultset in my gui.

SELECT
  'DROP'
  ,object_type
  ,object_name
  ,CASE(object_type)
     WHEN 'TABLE' THEN 'CASCADE CONSTRAINTS;'
     ELSE ';'
   END
 FROM user_objects
 WHERE
   object_type IN ('TABLE','VIEW','PACKAGE','PROCEDURE','FUNCTION','SEQUENCE')

Passive Link in Angular 2 - <a href=""> equivalent

Here are some ways to do it:

  • <a href="" (click)="false">Click Me</a>

  • <a style="cursor: pointer;">Click Me</a>

  • <a href="javascript:void(0)">Click Me</a>

How can I define colors as variables in CSS?

CSS supports this natively with CSS Variables.

Example CSS file

:root {
    --main-color:#06c;
}

#foo {
    color: var(--main-color);
}

For a working example, please see this JSFiddle (the example shows one of the CSS selectors in the fiddle has the color hard coded to blue, the other CSS selector uses CSS variables, both original and current syntax, to set the color to blue).

Manipulating a CSS variable in JavaScript/client side

document.body.style.setProperty('--main-color',"#6c0")

Support is in all the modern browsers

Firefox 31+, Chrome 49+, Safari 9.1+, Microsoft Edge 15+ and Opera 36+ ship with native support for CSS variables.

Get Client Machine Name in PHP

What's this "other information"? An IP address?

In PHP, you use $_SERVER['REMOTE_ADDR'] to get the IP address of the remote client, then you can use gethostbyaddr() to try and conver that IP into a hostname - but not all IPs have a reverse mapping configured.

What are metaclasses in Python?

Classes as objects

Before understanding metaclasses, you need to master classes in Python. And Python has a very peculiar idea of what classes are, borrowed from the Smalltalk language.

In most languages, classes are just pieces of code that describe how to produce an object. That's kinda true in Python too:

>>> class ObjectCreator(object):
...       pass
...

>>> my_object = ObjectCreator()
>>> print(my_object)
<__main__.ObjectCreator object at 0x8974f2c>

But classes are more than that in Python. Classes are objects too.

Yes, objects.

As soon as you use the keyword class, Python executes it and creates an OBJECT. The instruction

>>> class ObjectCreator(object):
...       pass
...

creates in memory an object with the name "ObjectCreator".

This object (the class) is itself capable of creating objects (the instances), and this is why it's a class.

But still, it's an object, and therefore:

  • you can assign it to a variable
  • you can copy it
  • you can add attributes to it
  • you can pass it as a function parameter

e.g.:

>>> print(ObjectCreator) # you can print a class because it's an object
<class '__main__.ObjectCreator'>
>>> def echo(o):
...       print(o)
...
>>> echo(ObjectCreator) # you can pass a class as a parameter
<class '__main__.ObjectCreator'>
>>> print(hasattr(ObjectCreator, 'new_attribute'))
False
>>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class
>>> print(hasattr(ObjectCreator, 'new_attribute'))
True
>>> print(ObjectCreator.new_attribute)
foo
>>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable
>>> print(ObjectCreatorMirror.new_attribute)
foo
>>> print(ObjectCreatorMirror())
<__main__.ObjectCreator object at 0x8997b4c>

Creating classes dynamically

Since classes are objects, you can create them on the fly, like any object.

First, you can create a class in a function using class:

>>> def choose_class(name):
...     if name == 'foo':
...         class Foo(object):
...             pass
...         return Foo # return the class, not an instance
...     else:
...         class Bar(object):
...             pass
...         return Bar
...
>>> MyClass = choose_class('foo')
>>> print(MyClass) # the function returns a class, not an instance
<class '__main__.Foo'>
>>> print(MyClass()) # you can create an object from this class
<__main__.Foo object at 0x89c6d4c>

But it's not so dynamic, since you still have to write the whole class yourself.

Since classes are objects, they must be generated by something.

When you use the class keyword, Python creates this object automatically. But as with most things in Python, it gives you a way to do it manually.

Remember the function type? The good old function that lets you know what type an object is:

>>> print(type(1))
<type 'int'>
>>> print(type("1"))
<type 'str'>
>>> print(type(ObjectCreator))
<type 'type'>
>>> print(type(ObjectCreator()))
<class '__main__.ObjectCreator'>

Well, type has a completely different ability, it can also create classes on the fly. type can take the description of a class as parameters, and return a class.

(I know, it's silly that the same function can have two completely different uses according to the parameters you pass to it. It's an issue due to backward compatibility in Python)

type works this way:

type(name, bases, attrs)

Where:

  • name: name of the class
  • bases: tuple of the parent class (for inheritance, can be empty)
  • attrs: dictionary containing attributes names and values

e.g.:

>>> class MyShinyClass(object):
...       pass

can be created manually this way:

>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
>>> print(MyShinyClass)
<class '__main__.MyShinyClass'>
>>> print(MyShinyClass()) # create an instance with the class
<__main__.MyShinyClass object at 0x8997cec>

You'll notice that we use "MyShinyClass" as the name of the class and as the variable to hold the class reference. They can be different, but there is no reason to complicate things.

type accepts a dictionary to define the attributes of the class. So:

>>> class Foo(object):
...       bar = True

Can be translated to:

>>> Foo = type('Foo', (), {'bar':True})

And used as a normal class:

>>> print(Foo)
<class '__main__.Foo'>
>>> print(Foo.bar)
True
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x8a9b84c>
>>> print(f.bar)
True

And of course, you can inherit from it, so:

>>>   class FooChild(Foo):
...         pass

would be:

>>> FooChild = type('FooChild', (Foo,), {})
>>> print(FooChild)
<class '__main__.FooChild'>
>>> print(FooChild.bar) # bar is inherited from Foo
True

Eventually, you'll want to add methods to your class. Just define a function with the proper signature and assign it as an attribute.

>>> def echo_bar(self):
...       print(self.bar)
...
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})
>>> hasattr(Foo, 'echo_bar')
False
>>> hasattr(FooChild, 'echo_bar')
True
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
True

And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object.

>>> def echo_bar_more(self):
...       print('yet another method')
...
>>> FooChild.echo_bar_more = echo_bar_more
>>> hasattr(FooChild, 'echo_bar_more')
True

You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.

This is what Python does when you use the keyword class, and it does so by using a metaclass.

What are metaclasses (finally)

Metaclasses are the 'stuff' that creates classes.

You define classes in order to create objects, right?

But we learned that Python classes are objects.

Well, metaclasses are what create these objects. They are the classes' classes, you can picture them this way:

MyClass = MetaClass()
my_object = MyClass()

You've seen that type lets you do something like this:

MyClass = type('MyClass', (), {})

It's because the function type is in fact a metaclass. type is the metaclass Python uses to create all classes behind the scenes.

Now you wonder why the heck is it written in lowercase, and not Type?

Well, I guess it's a matter of consistency with str, the class that creates strings objects, and int the class that creates integer objects. type is just the class that creates class objects.

You see that by checking the __class__ attribute.

Everything, and I mean everything, is an object in Python. That includes ints, strings, functions and classes. All of them are objects. And all of them have been created from a class:

>>> age = 35
>>> age.__class__
<type 'int'>
>>> name = 'bob'
>>> name.__class__
<type 'str'>
>>> def foo(): pass
>>> foo.__class__
<type 'function'>
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
<class '__main__.Bar'>

Now, what is the __class__ of any __class__ ?

>>> age.__class__.__class__
<type 'type'>
>>> name.__class__.__class__
<type 'type'>
>>> foo.__class__.__class__
<type 'type'>
>>> b.__class__.__class__
<type 'type'>

So, a metaclass is just the stuff that creates class objects.

You can call it a 'class factory' if you wish.

type is the built-in metaclass Python uses, but of course, you can create your own metaclass.

The __metaclass__ attribute

In Python 2, you can add a __metaclass__ attribute when you write a class (see next section for the Python 3 syntax):

class Foo(object):
    __metaclass__ = something...
    [...]

If you do so, Python will use the metaclass to create the class Foo.

Careful, it's tricky.

You write class Foo(object) first, but the class object Foo is not created in memory yet.

Python will look for __metaclass__ in the class definition. If it finds it, it will use it to create the object class Foo. If it doesn't, it will use type to create the class.

Read that several times.

When you do:

class Foo(Bar):
    pass

Python does the following:

Is there a __metaclass__ attribute in Foo?

If yes, create in-memory a class object (I said a class object, stay with me here), with the name Foo by using what is in __metaclass__.

If Python can't find __metaclass__, it will look for a __metaclass__ at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes).

Then if it can't find any __metaclass__ at all, it will use the Bar's (the first parent) own metaclass (which might be the default type) to create the class object.

Be careful here that the __metaclass__ attribute will not be inherited, the metaclass of the parent (Bar.__class__) will be. If Bar used a __metaclass__ attribute that created Bar with type() (and not type.__new__()), the subclasses will not inherit that behavior.

Now the big question is, what can you put in __metaclass__?

The answer is something that can create a class.

And what can create a class? type, or anything that subclasses or uses it.

Metaclasses in Python 3

The syntax to set the metaclass has been changed in Python 3:

class Foo(object, metaclass=something):
    ...

i.e. the __metaclass__ attribute is no longer used, in favor of a keyword argument in the list of base classes.

The behavior of metaclasses however stays largely the same.

One thing added to metaclasses in Python 3 is that you can also pass attributes as keyword-arguments into a metaclass, like so:

class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):
    ...

Read the section below for how python handles this.

Custom metaclasses

The main purpose of a metaclass is to change the class automatically, when it's created.

You usually do this for APIs, where you want to create classes matching the current context.

Imagine a stupid example, where you decide that all classes in your module should have their attributes written in uppercase. There are several ways to do this, but one way is to set __metaclass__ at the module level.

This way, all classes of this module will be created using this metaclass, and we just have to tell the metaclass to turn all attributes to uppercase.

Luckily, __metaclass__ can actually be any callable, it doesn't need to be a formal class (I know, something with 'class' in its name doesn't need to be a class, go figure... but it's helpful).

So we will start with a simple example, by using a function.

# the metaclass will automatically get passed the same argument
# that you usually pass to `type`
def upper_attr(future_class_name, future_class_parents, future_class_attrs):
    """
      Return a class object, with the list of its attribute turned
      into uppercase.
    """
    # pick up any attribute that doesn't start with '__' and uppercase it
    uppercase_attrs = {
        attr if attr.startswith("__") else attr.upper(): v
        for attr, v in future_class_attrs.items()
    }

    # let `type` do the class creation
    return type(future_class_name, future_class_parents, uppercase_attrs)

__metaclass__ = upper_attr # this will affect all classes in the module

class Foo(): # global __metaclass__ won't work with "object" though
    # but we can define __metaclass__ here instead to affect only this class
    # and this will work with "object" children
    bar = 'bip'

Let's check:

>>> hasattr(Foo, 'bar')
False
>>> hasattr(Foo, 'BAR')
True
>>> Foo.BAR
'bip'

Now, let's do exactly the same, but using a real class for a metaclass:

# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
    # __new__ is the method called before __init__
    # it's the method that creates the object and returns it
    # while __init__ just initializes the object passed as parameter
    # you rarely use __new__, except when you want to control how the object
    # is created.
    # here the created object is the class, and we want to customize it
    # so we override __new__
    # you can do some stuff in __init__ too if you wish
    # some advanced use involves overriding __call__ as well, but we won't
    # see this
    def __new__(upperattr_metaclass, future_class_name,
                future_class_parents, future_class_attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in future_class_attrs.items()
        }
        return type(future_class_name, future_class_parents, uppercase_attrs)

Let's rewrite the above, but with shorter and more realistic variable names now that we know what they mean:

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return type(clsname, bases, uppercase_attrs)

You may have noticed the extra argument cls. There is nothing special about it: __new__ always receives the class it's defined in, as the first parameter. Just like you have self for ordinary methods which receive the instance as the first parameter, or the defining class for class methods.

But this is not proper OOP. We are calling type directly and we aren't overriding or calling the parent's __new__. Let's do that instead:

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return type.__new__(cls, clsname, bases, uppercase_attrs)

We can make it even cleaner by using super, which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type):

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return super(UpperAttrMetaclass, cls).__new__(
            cls, clsname, bases, uppercase_attrs)

Oh, and in python 3 if you do this call with keyword arguments, like this:

class Foo(object, metaclass=MyMetaclass, kwarg1=value1):
    ...

It translates to this in the metaclass to use it:

class MyMetaclass(type):
    def __new__(cls, clsname, bases, dct, kwargs1=default):
        ...

That's it. There is really nothing more about metaclasses.

The reason behind the complexity of the code using metaclasses is not because of metaclasses, it's because you usually use metaclasses to do twisted stuff relying on introspection, manipulating inheritance, vars such as __dict__, etc.

Indeed, metaclasses are especially useful to do black magic, and therefore complicated stuff. But by themselves, they are simple:

  • intercept a class creation
  • modify the class
  • return the modified class

Why would you use metaclasses classes instead of functions?

Since __metaclass__ can accept any callable, why would you use a class since it's obviously more complicated?

There are several reasons to do so:

  • The intention is clear. When you read UpperAttrMetaclass(type), you know what's going to follow
  • You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.
  • Subclasses of a class will be instances of its metaclass if you specified a metaclass-class, but not with a metaclass-function.
  • You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.
  • You can hook on __new__, __init__ and __call__. Which will allow you to do different stuff, Even if usually you can do it all in __new__, some people are just more comfortable using __init__.
  • These are called metaclasses, damn it! It must mean something!

Why would you use metaclasses?

Now the big question. Why would you use some obscure error-prone feature?

Well, usually you don't:

Metaclasses are deeper magic that 99% of users should never worry about it. If you wonder whether you need them, you don't (the people who actually need them to know with certainty that they need them and don't need an explanation about why).

Python Guru Tim Peters

The main use case for a metaclass is creating an API. A typical example of this is the Django ORM. It allows you to define something like this:

class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

But if you do this:

person = Person(name='bob', age='35')
print(person.age)

It won't return an IntegerField object. It will return an int, and can even take it directly from the database.

This is possible because models.Model defines __metaclass__ and it uses some magic that will turn the Person you just defined with simple statements into a complex hook to a database field.

Django makes something complex look simple by exposing a simple API and using metaclasses, recreating code from this API to do the real job behind the scenes.

The last word

First, you know that classes are objects that can create instances.

Well, in fact, classes are themselves instances. Of metaclasses.

>>> class Foo(object): pass
>>> id(Foo)
142630324

Everything is an object in Python, and they are all either instance of classes or instances of metaclasses.

Except for type.

type is actually its own metaclass. This is not something you could reproduce in pure Python, and is done by cheating a little bit at the implementation level.

Secondly, metaclasses are complicated. You may not want to use them for very simple class alterations. You can change classes by using two different techniques:

99% of the time you need class alteration, you are better off using these.

But 98% of the time, you don't need class alteration at all.

Fastest way to ping a network range and return responsive hosts?

BSD's

for i in $(seq 1 254); do (ping -c1 -W5 192.168.1.$i >/dev/null && echo "192.168.1.$i" &) ;done

Wait for shell command to complete

Save the bat file on "C:\WINDOWS\system32" and use below code it is working

   Dim wsh As Object
   Set wsh = VBA.CreateObject("WScript.Shell")
   Dim waitOnReturn As Boolean: waitOnReturn = True
   Dim windowStyle As Integer: windowStyle = 1
   Dim errorCode As Integer

   errorCode = wsh.Run("runbat.bat", windowStyle, waitOnReturn)

If errorCode = 0 Then
    'Insert your code here
Else
    MsgBox "Program exited with error code " & errorCode & "."
End If   

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

Your nameContent variable is inside the function scope and not visible outside that function so if you want to use the nameContent outside of the function then declare it global inside the <script> tag and use inside functions without the var keyword as follows

<script language="javascript" type="text/javascript">
    var nameContent; // In the global scope
    function first(){
        nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

Recommended date format for REST GET API

Every datetime field in input/output needs to be in UNIX/epoch format. This avoids the confusion between developers across different sides of the API.

Pros:

  • Epoch format does not have a timezone.
  • Epoch has a single format (Unix time is a single signed number).
  • Epoch time is not effected by daylight saving.
  • Most of the Backend frameworks and all native ios/android APIs support epoch conversion.
  • Local time conversion part can be done entirely in application side depends on the timezone setting of user's device/browser.

Cons:

  • Extra processing for converting to UTC for storing in UTC format in the database.
  • Readability of input/output.
  • Readability of GET URLs.

Notes:

  • Timezones are a presentation-layer problem! Most of your code shouldn't be dealing with timezones or local time, it should be passing Unix time around.
  • If you want to store a humanly-readable time (e.g. logs), consider storing it along with Unix time, not instead of Unix time.

PHP date add 5 year to current date

To add one year to todays date use the following:

$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));

In Python, how do I iterate over a dictionary in sorted key order?

A dict's keys are stored in a hashtable so that is their 'natural order', i.e. psuedo-random. Any other ordering is a concept of the consumer of the dict.

sorted() always returns a list, not a dict. If you pass it a dict.items() (which produces a list of tuples), it will return a list of tuples [(k1,v1), (k2,v2), ...] which can be used in a loop in a way very much like a dict, but it is not in anyway a dict!

foo = {
    'a':    1,
    'b':    2,
    'c':    3,
    }

print foo
>>> {'a': 1, 'c': 3, 'b': 2}

print foo.items()
>>> [('a', 1), ('c', 3), ('b', 2)]

print sorted(foo.items())
>>> [('a', 1), ('b', 2), ('c', 3)]

The following feels like a dict in a loop, but it's not, it's a list of tuples being unpacked into k,v:

for k,v in sorted(foo.items()):
    print k, v

Roughly equivalent to:

for k in sorted(foo.keys()):
    print k, foo[k]

Why is $$ returning the same id as the parent process?

$$ is defined to return the process ID of the parent in a subshell; from the man page under "Special Parameters":

$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.

In bash 4, you can get the process ID of the child with BASHPID.

~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634

Passing ArrayList from servlet to JSP

public class myActorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String name;
    private String user;
    private String pass;
    private String given_table;
    private String tid;
    private String firstname;
    private String lastname;
    private String action;

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        response.setContentType("text/html");

        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        PrintWriter out = response.getWriter();
        name = request.getParameter("screenName");
        user = request.getParameter("username");
        pass = request.getParameter("password");
        tid = request.getParameter("tid");
        firstname = request.getParameter("firstname");
        lastname = request.getParameter("lastname");
        action = request.getParameter("action");
        given_table = request.getParameter("tableName");

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet JDBC</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello, " + name + " </h1>");
        out.println("<h1>Servlet JDBC</h1>");

        /////////////////////////
        // init connection object
        String sqlSelect = "SELECT * FROM `" + given_table + "`";
        String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
        String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
        String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";

        //////////////////////////////////////////////////////////
        out.println(
                "<p>Reading Table Data...Pass to JSP File...Okay<p>");

        ArrayList<Actor> list = new ArrayList<Actor>();
        // connecting to database
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sqlSelect);
            // displaying records

            while (rs.next()) {
                Actor actor = new Actor();
                actor.setId(rs.getInt("id"));
                actor.setLastname(rs.getString("lastname"));
                actor.setFirstname(rs.getString("firstname"));
                list.add(actor);
            }
            request.setAttribute("actors", list);
            RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
            view.forward(request, response);

        } catch (SQLException e) {
            throw new ServletException("Servlet Could not display records.", e);
        } catch (ClassNotFoundException e) {
            throw new ServletException("JDBC Driver not found.", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (con != null) {
                    con.close();
                    con = null;
                }
            } catch (SQLException e) {
            }
        }
        out.println("</body></html>");

        out.close();
    }

}

What does functools.wraps do?

In short, functools.wraps is just a regular function. Let's consider this official example. With the help of the source code, we can see more details about the implementation and the running steps as follows:

  1. wraps(f) returns an object, say O1. It is an object of the class Partial
  2. The next step is @O1... which is the decorator notation in python. It means

wrapper=O1.__call__(wrapper)

Checking the implementation of __call__, we see that after this step, (the left hand side )wrapper becomes the object resulted by self.func(*self.args, *args, **newkeywords) Checking the creation of O1 in __new__, we know self.func is the function update_wrapper. It uses the parameter *args, the right hand side wrapper, as its 1st parameter. Checking the last step of update_wrapper, one can see the right hand side wrapper is returned, with some of attributes modified as needed.

How to load GIF image in Swift?

This is working for me

Podfile:

platform :ios, '9.0'
use_frameworks!

target '<Your Target Name>' do
pod 'SwiftGifOrigin', '~> 1.7.0'
end

Usage:

// An animated UIImage
let jeremyGif = UIImage.gif(name: "jeremy")

// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "jeremy")

// A UIImageView with async loading from asset catalog(from iOS9)
let imageView = UIImageView()
imageView.loadGif(asset: "jeremy")

For more information follow this link: https://github.com/swiftgif/SwiftGif

Loading a .json file into c# program

You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.

Here's a sample of reading JSON using Newtonsoft.Json:

JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));

// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
  JObject o2 = (JObject) JToken.ReadFrom(reader);
}

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Android - R cannot be resolved to a variable

Agree it is probably due to a problem in resources that is preventing build of R.Java in gen. In my case a cut n paste had given a duplicate app name in string. Sort the fault, delete gen directory and clean.

Converting an int or String to a char array on Arduino

Just as a reference, here is an example of how to convert between String and char[] with a dynamic length -

// Define 
String str = "This is my string"; 

// Length (with one extra character for the null terminator)
int str_len = str.length() + 1; 

// Prepare the character array (the buffer) 
char char_array[str_len];

// Copy it over 
str.toCharArray(char_array, str_len);

Yes, this is painfully obtuse for something as simple as a type conversion, but sadly it's the easiest way.

Eclipse: How do I add the javax.servlet package to a project?

Go to

JBoss\jboss-eap-6.1\modules\system\layers\base\javax\servlet\api\main

include JAR

jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar

For me it worked

Are there any style options for the HTML5 Date picker?

Currently, there is no cross browser, script-free way of styling a native date picker.

As for what's going on inside WHATWG/W3C... If this functionality does emerge, it will likely be under the CSS-UI standard or some Shadow DOM-related standard. The CSS4-UI wiki page lists a few appearance-related things that were dropped from CSS3-UI, but to be honest, there doesn't seem to be a great deal of interest in the CSS-UI module.

I think your best bet for cross browser development right now, is to implement pretty controls with JavaScript based interface, and then disable the HTML5 native UI and replace it. I think in the future, maybe there will be better native control styling, but perhaps more likely will be the ability to swap out a native control for your own Shadow DOM "widget".

It is annoying that this isn't available, and petitioning for standard support is always worthwhile. Though it does seem like jQuery UI's lead has tried and was unsuccessful.

While this is all very discouraging, it's also worth considering the advantages of the HTML5 date picker, and also why custom styles are difficult and perhaps should be avoided. On some platforms, the datepicker looks extremely different and I personally can't think of any generic way of styling the native datepicker.

Fastest way to download a GitHub project

You say:

To me if a source repository is available for public it should take less than 10 seconds to have that code in my filesystem.

And of course, if you want to use Git (which GitHub is all about), then what you do to get the code onto your system is called "cloning the repository".

It's a single Git invocation on the command line, and it will give you the code just as seen when you browse the repository on the web (when getting a ZIP archive, you will need to unpack it and so on, it's not always directly browsable). For the repository you mention, you would do:

$ git clone git://github.com/SpringSource/spring-data-graph-examples.git

The git:-type URL is the one from the page you linked to. On my system just now, running the above command took 3.2 seconds. Of course, unlike ZIP, the time to clone a repository will increase when the repository's history grows. There are options for that, but let's keep this simple.

I'm just saying: You sound very frustrated when a large part of the problem is your reluctance to actually use Git.

How to strip comma in Python string

unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))

when exactly are we supposed to use "public static final String"?

Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.

JQuery: detect change in input field

Same functionality i recently achieved using below function.

I wanted to enable SAVE button on edit.

  1. Change event is NOT advisable as it will ONLY be fired if after editing, mouse is clicked somewhere else on the page before clicking SAVE button.
  2. Key Press doesnt handle Backspace, Delete and Paste options.
  3. Key Up handles everything including tab, Shift key.

Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.

Hope it helps you.

function checkAnyFormFieldEdited() {
    /*
     * If any field is edited,then only it will enable Save button
     */
    $(':text').keypress(function(e) { // text written
        enableSaveBtn();
    });

    $(':text').keyup(function(e) {
        if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
            enableSaveBtn();
        } else { // rest ignore
            e.preventDefault();
        }
    });
    $(':text').bind('paste', function(e) { // text pasted
        enableSaveBtn();
    });

    $('select').change(function(e) { // select element changed
        enableSaveBtn();
    });

    $(':radio').change(function(e) { // radio changed
        enableSaveBtn();
    });

    $(':password').keypress(function(e) { // password written
        enableSaveBtn();
    });
    $(':password').bind('paste', function(e) { // password pasted
        enableSaveBtn();
    });


}

How do I kill a VMware virtual machine that won't die?

Here's what I did based on

a) @Espo 's comments and
b) the fact that I only had Windows Task Manager to play with....

I logged onto the host machine, opened Task Manager and used the view menu to add the PID column to the Processes tab.

I wrote down (yes, with paper and a pen) the PID's for each and every instance of the vmware-wmx.exe process that was running on the box.

Using the VMWare console, I suspended the errant virtual machine.

When I resumed it, I could then identify the vmware-vmx process that corresponded to my machine and could kill it.

There doesn't seem to have been any ill effects so far.

How to use HTML to print header and footer on every printed page of a document?

the best solution came from biskrem muhammad.

but there is a little problem with its answer. when page count bigger than 1, footer not locating to the footer of the last page.

add this little css to your element collapsed by footer-info

position: fixed;
bottom: 0;

Position a div container on the right side

  • Use float: right to.. float the second column to the.. right.
  • Use overflow: hidden to clear the floats so that the background color I just put in will be visible.

Live Demo

#wrapper{
    background:#000;
    overflow: hidden
}
#c1 {
   float:left;
   background:red;
}
#c2 {
    background:green;
    float: right
}

what is <meta charset="utf-8">?

The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.

UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

Understanding "VOLUME" instruction in DockerFile

The VOLUME command in a Dockerfile is quite legit, totally conventional, absolutely fine to use and it is not deprecated in anyway. Just need to understand it.

We use it to point to any directories which the app in the container will write to a lot. We don't use VOLUME just because we want to share between host and container like a config file.

The command simply needs one param; a path to a folder, relative to WORKDIR if set, from within the container. Then docker will create a volume in its graph(/var/lib/docker) and mount it to the folder in the container. Now the container will have somewhere to write to with high performance. Without the VOLUME command the write speed to the specified folder will be very slow because now the container is using it's copy on write strategy in the container itself. The copy on write strategy is a main reason why volumes exist.

If you mount over the folder specified by the VOLUME command, the command is never run because VOLUME is only executed when the container starts, kind of like ENV.

Basically with VOLUME command you get performance without externally mounting any volumes. Data will save across container runs too without any external mounts. Then when ready simply mount something over it.

Some good example use cases:
- logs
- temp folders

Some bad use cases:
- static files
- configs
- code