Programs & Examples On #Cakephp 1.2

This tag relates to the 1.2.x branch of CakePHP MVC framework

What size should apple-touch-icon.png be for iPad and iPhone?

Yes, bigger than 60x60 are supported. For simplicity, create icons of these 4 sizes:

1) 60x60  <= default
2) 76x76
3) 120x120
4) 152x152

Now, it's preferable to add them as links in your HTML as:

<link rel="apple-touch-icon" href="touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png">

You can choose to not declare the 4 links above but just declare a single link, in which case give the highest size of 152x152 or even a size higher than that, say 196x196. It will always trim down the size for re-purposing. Ensure you mention the size.

You can also choose not to declare even a single link. Apple mentions that in this scenario, it will lookup the server root first for the size immediately higher that the size it wants (naming format: apple-touch-icon-<size>.png), and if that's not found then it will next look for the default file: apple-touch-icon.png. It's preferable that you define the link(s) as that will minimize the browser querying your server.

Icon necessities:

- use PNG, avoid interlaced
- use 24-bit PNG
- not necessary to use web-safe colors

In versions older than iOS 7, if you don't want it to add effects to your icons, then just add the suffix -precomposed.png to the file name. (iOS 7 doesn't add effects even without it).

How to use filesaver.js

https://github.com/koffsyrup/FileSaver.js#examples

Saving text(All Browsers)

saveTextAs("Hi,This,is,a,CSV,File", "test.csv");
saveTextAs("<div>Hello, world!</div>", "test.html");

Saving text(HTML 5)

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

Yahoo Finance All Currencies quote API Documentation

I have used this URL to obtain multiple currency market quotes.

http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X

"USD",1.0000
"CAD",1.2458
"EUR",0.8396

They can be parsed in PHP like this:

$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');

$quote = array_map( 'str_getcsv', file($url) );

foreach ($quote as $key => $symb) {
    $symbol = $quote[$key][0];
    $value = $quote[$key][1];
}

using wildcards in LDAP search filters/queries

This should work, at least according to the Search Filter Syntax article on MSDN network.

The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.

You may also try separating the filter into two parts:

(|(displayName=*searchstring)(displayName=searchstring*))

Make a number a percentage

Most answers suggest appending '%' at the end. I would rather prefer Intl.NumberFormat() with { style: 'percent'}

_x000D_
_x000D_
var num = 25;_x000D_
_x000D_
var option = {_x000D_
  style: 'percent'_x000D_
_x000D_
};_x000D_
var formatter = new Intl.NumberFormat("en-US", option);_x000D_
var percentFormat = formatter.format(num / 100);_x000D_
console.log(percentFormat);
_x000D_
_x000D_
_x000D_

Custom UITableViewCell from nib in Swift

swift 4.1.2

xib.

Create ImageCell2.swift

Step 1

import UIKit

class ImageCell2: UITableViewCell {

    @IBOutlet weak var imgBookLogo: UIImageView!
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var lblPublisher: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

step 2 . According Viewcontroller class

  import UIKit

    class ImageListVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet weak var tblMainVC: UITableView!

    var arrBook : [BookItem] = [BookItem]()

    override func viewDidLoad() {
        super.viewDidLoad()
         //Regester Cell
        self.tblMainVC.register(UINib.init(nibName: "ImageCell2", bundle: nil), forCellReuseIdentifier: "ImageCell2")
        // Response Call adn Disply Record
        APIManagerData._APIManagerInstance.getAPIBook { (itemInstance) in
            self.arrBook = itemInstance.arrItem!
            self.tblMainVC.reloadData()
        }
    }
    //MARK: DataSource & delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrBook.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//    [enter image description here][2]
        let cell  = tableView.dequeueReusableCell(withIdentifier: "ImageCell2") as! ImageCell2
        cell.lblTitle.text = self.arrBook[indexPath.row].title
        cell.lblPublisher.text = self.arrBook[indexPath.row].publisher
        if let authors = self.arrBook[indexPath.row].author {
            for item in authors{
                print(" item \(item)")
            }
        }
        let  url  = self.arrBook[indexPath.row].imageURL
        if url == nil {
            cell.imgBookLogo.kf.setImage(with: URL.init(string: ""), placeholder: UIImage.init(named: "download.jpeg"))
        }
        else{
            cell.imgBookLogo.kf.setImage(with: URL(string: url!)!, placeholder: UIImage.init(named: "download.jpeg"))
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    } 

}

Math operations from string

Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.

Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.

And fight the temptation of using eval, that's not safe.

How to calculate the intersection of two sets?

Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

Executing <script> injected by innerHTML after AJAX call

My conclusion is HTML doesn't allows NESTED SCRIPT tags. If you are using javascript for injecting HTML code that include script tags inside is not going to work because the javascript goes in a script tag too. You can test it with the next code and you will be that it's not going to work. The use case is you are calling a service with AJAX or similar, you are getting HTML and you want to inject it in the HTML DOM straight forward. If the injected HTML code has inside SCRIPT tags is not going to work.

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"></head><body></body><script>document.getElementsByTagName("body")[0].innerHTML = "<script>console.log('hi there')</script>\n<div>hello world</div>\n"</script></html>

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If anyone is coming here looking to do this with Font Awesome Icons (like I was) view here: https://fontawesome.com/how-to-use/on-the-web/styling/icons-in-a-list

<ul class="fa-ul">
  <li><i class="fa-li fa fa-check-square"></i>List icons</li>
  <li><i class="fa-li fa fa-check-square"></i>can be used</li>
  <li><i class="fa-li fa fa-spinner fa-spin"></i>as bullets</li>
  <li><i class="fa-li fa fa-square"></i>in lists</li>
</ul>

The fa-ul and fa-li classes easily replace default bullets in unordered lists.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Regex Explanation ^.*$

  • ^ matches position just before the first character of the string
  • $ matches position just after the last character of the string
  • . matches a single character. Does not matter what character it is, except newline
  • * matches preceding match zero or more times

So, ^.*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.

Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones and Matthew's last name is Jones. The pattern ^Matt.*Jones$ will match Matthew's last name is Jones. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.

Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.

Python - abs vs fabs

abs() : Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float. Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() : It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

Jinja2 shorthand conditional

Yes, it's possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}

H2 database error: Database may be already in use: "Locked by another process"

Simple step: Go to the task manager and kill the java process

then start your apllication

Replace None with NaN in pandas dataframe

You can use DataFrame.fillna or Series.fillna which will replace the Python object None, not the string 'None'.

import pandas as pd
import numpy as np

For dataframe:

df = df.fillna(value=np.nan)

For column or series:

df.mycol.fillna(value=np.nan, inplace=True)

Using CMake with GNU Make: How can I see the exact commands?

Or simply export VERBOSE environment variable on the shell like this: export VERBOSE=1

JSON array get length

The below snippet works fine for me(I used the size())

String itemId;
            for (int i = 0; i < itemList.size(); i++) {
            JSONObject itemObj = (JSONObject)itemList.get(i);
            itemId=(String) itemObj.get("ItemId");
            System.out.println(itemId);
            }

If it is wrong to use use size() kindly advise

Server.Transfer Vs. Response.Redirect

There are many differences as specified above. Apart from above all, there is one more difference. Response.Redirect() can be used to redirect user to any page which is not part of the application but Server.Transfer() can only be used to redirect user within the application.

//This will work.
Response.Redirect("http://www.google.com");

//This will not work.
Server.Transfer("http://www.google.com");

displaying a string on the textview when clicking a button in android

Check this:

hello.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View paramView) {
        text.setText("hello");
    }
});

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

Has an event handler already been added?

The only way that worked for me is creating a Boolean variable that I set to true when I add the event. Then I ask: If the variable is false, I add the event.

bool alreadyAdded = false;

This variable can be global.

if(!alreadyAdded)
{
    myClass.MyEvent += MyHandler;
    alreadyAdded = true;
}

YouTube: How to present embed video with sound muted

<iframe width="560" height="315" src="https://www.youtube.com/embed/ULzr7JsFp0k?list=PLF8tTShmRC6vp9YTjkVdm1qKuTimC6K3e&rel=0&amp;autoplay=1&controls=1&loop=1" rel=0&amp frameborder="0" allowfullscreen></iframe>

Get value from JToken that may not exist (best practices)

You can simply typecast, and it will do the conversion for you, e.g.

var with = (double?) jToken[key] ?? 100;

It will automatically return null if said key is not present in the object, so there's no need to test for it.

What does `dword ptr` mean?

The dword ptr part is called a size directive. This page explains them, but it wasn't possible to direct-link to the correct section.

Basically, it means "the size of the target operand is 32 bits", so this will bitwise-AND the 32-bit value at the address computed by taking the contents of the ebp register and subtracting four with 0.

What is the difference between user variables and system variables?

Environment variables are 'evaluated' (ie. they are attributed) in the following order:

  1. System variables
  2. Variables defined in autoexec.bat
  3. User variables

Every process has an environment block that contains a set of environment variables and their values. There are two types of environment variables: user environment variables (set for each user) and system environment variables (set for everyone). A child process inherits the environment variables of its parent process by default.

Programs started by the command processor inherit the command processor's environment variables.

Environment variables specify search paths for files, directories for temporary files, application-specific options, and other similar information. The system maintains an environment block for each user and one for the computer. The system environment block represents environment variables for all users of the particular computer. A user's environment block represents the environment variables the system maintains for that particular user, including the set of system environment variables.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

A general answer

select * from [dbo].[SplitString]('1,2',',') -- Will work 

but

select [dbo].[SplitString]('1,2',',')  -- will not work and throws this error

Efficiently convert rows to columns in sql server

This is rather a method than just a single script but gives you much more flexibility.

First of all There are 3 objects:

  1. User defined TABLE type [ColumnActionList] -> holds data as parameter
  2. SP [proc_PivotPrepare] -> prepares our data
  3. SP [proc_PivotExecute] -> execute the script

CREATE TYPE [dbo].[ColumnActionList] AS TABLE ( [ID] [smallint] NOT NULL, [ColumnName] nvarchar NOT NULL, [Action] nchar NOT NULL ); GO

    CREATE PROCEDURE [dbo].[proc_PivotPrepare] 
    (
    @DB_Name        nvarchar(128),
    @TableName      nvarchar(128)
    )
    AS
            SELECT @DB_Name = ISNULL(@DB_Name,db_name())
    DECLARE @SQL_Code nvarchar(max)

    DECLARE @MyTab TABLE (ID smallint identity(1,1), [Column_Name] nvarchar(128), [Type] nchar(1), [Set Action SQL] nvarchar(max));

    SELECT @SQL_Code        =   'SELECT [<| SQL_Code |>] = '' '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Declare user defined type [ID] / [ColumnName] / [PivotAction] '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''DECLARE @ColumnListWithActions ColumnActionList;'''
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Set [PivotAction] (''''S'''' as default) to select dimentions and values '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----|'''
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| ''''S'''' = Stable column || ''''D'''' = Dimention column || ''''V'''' = Value column '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''INSERT INTO  @ColumnListWithActions VALUES ('' + CAST( ROW_NUMBER() OVER (ORDER BY [NAME]) as nvarchar(10)) + '', '' + '''''''' + [NAME] + ''''''''+ '', ''''S'''');'''
                                        + 'FROM [' + @DB_Name + '].sys.columns  '
                                        + 'WHERE object_id = object_id(''[' + @DB_Name + ']..[' + @TableName + ']'') '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Execute sp_PivotExecute with parameters: columns and dimentions and main table name'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''EXEC [dbo].[sp_PivotExecute] @ColumnListWithActions, ' + '''''' + @TableName + '''''' + ';'''
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '                            
EXECUTE SP_EXECUTESQL @SQL_Code;

GO

CREATE PROCEDURE [dbo].[sp_PivotExecute]
(
@ColumnListWithActions  ColumnActionList ReadOnly
,@TableName                     nvarchar(128)
)
AS


--#######################################################################################################################
--###| Step 1 - Select our user-defined-table-variable into temp table
--#######################################################################################################################

IF OBJECT_ID('tempdb.dbo.#ColumnListWithActions', 'U') IS NOT NULL DROP TABLE #ColumnListWithActions; 
SELECT * INTO #ColumnListWithActions FROM @ColumnListWithActions;

--#######################################################################################################################
--###| Step 2 - Preparing lists of column groups as strings:
--#######################################################################################################################

DECLARE @ColumnName                     nvarchar(128)
DECLARE @Destiny                        nchar(1)

DECLARE @ListOfColumns_Stable           nvarchar(max)
DECLARE @ListOfColumns_Dimension    nvarchar(max)
DECLARE @ListOfColumns_Variable     nvarchar(max)
--############################
--###| Cursor for List of Stable Columns
--############################

DECLARE ColumnListStringCreator_S CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'S'
OPEN ColumnListStringCreator_S;
FETCH NEXT FROM ColumnListStringCreator_S
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Stable = ISNULL(@ListOfColumns_Stable, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_S INTO @ColumnName
   END

CLOSE ColumnListStringCreator_S;
DEALLOCATE ColumnListStringCreator_S;

--############################
--###| Cursor for List of Dimension Columns
--############################

DECLARE ColumnListStringCreator_D CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'D'
OPEN ColumnListStringCreator_D;
FETCH NEXT FROM ColumnListStringCreator_D
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Dimension = ISNULL(@ListOfColumns_Dimension, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_D INTO @ColumnName
   END

CLOSE ColumnListStringCreator_D;
DEALLOCATE ColumnListStringCreator_D;

--############################
--###| Cursor for List of Variable Columns
--############################

DECLARE ColumnListStringCreator_V CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'V'
OPEN ColumnListStringCreator_V;
FETCH NEXT FROM ColumnListStringCreator_V
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Variable = ISNULL(@ListOfColumns_Variable, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_V INTO @ColumnName
   END

CLOSE ColumnListStringCreator_V;
DEALLOCATE ColumnListStringCreator_V;

SELECT @ListOfColumns_Variable      = LEFT(@ListOfColumns_Variable, LEN(@ListOfColumns_Variable) - 1);
SELECT @ListOfColumns_Dimension = LEFT(@ListOfColumns_Dimension, LEN(@ListOfColumns_Dimension) - 1);
SELECT @ListOfColumns_Stable            = LEFT(@ListOfColumns_Stable, LEN(@ListOfColumns_Stable) - 1);

--#######################################################################################################################
--###| Step 3 - Preparing table with all possible connections between Dimension columns excluding NULLs
--#######################################################################################################################
DECLARE @DIM_TAB TABLE ([DIM_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @DIM_TAB 
SELECT [DIM_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'D';

DECLARE @DIM_ID smallint;
SELECT      @DIM_ID = 1;


DECLARE @SQL_Dimentions nvarchar(max);

IF OBJECT_ID('tempdb.dbo.##ALL_Dimentions', 'U') IS NOT NULL DROP TABLE ##ALL_Dimentions; 

SELECT @SQL_Dimentions      = 'SELECT [xxx_ID_xxx] = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Dimension + '), ' + @ListOfColumns_Dimension
                                            + ' INTO ##ALL_Dimentions '
                                            + ' FROM (SELECT DISTINCT' + @ListOfColumns_Dimension + ' FROM  ' + @TableName
                                            + ' WHERE ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
                                            SELECT @DIM_ID = @DIM_ID + 1;
            WHILE @DIM_ID <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
            BEGIN
            SELECT @SQL_Dimentions = @SQL_Dimentions + 'AND ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) +  ' IS NOT NULL ';
            SELECT @DIM_ID = @DIM_ID + 1;
            END

SELECT @SQL_Dimentions   = @SQL_Dimentions + ' )x';

EXECUTE SP_EXECUTESQL  @SQL_Dimentions;

--#######################################################################################################################
--###| Step 4 - Preparing table with all possible connections between Stable columns excluding NULLs
--#######################################################################################################################
DECLARE @StabPos_TAB TABLE ([StabPos_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @StabPos_TAB 
SELECT [StabPos_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'S';

DECLARE @StabPos_ID smallint;
SELECT      @StabPos_ID = 1;


DECLARE @SQL_MainStableColumnTable nvarchar(max);

IF OBJECT_ID('tempdb.dbo.##ALL_StableColumns', 'U') IS NOT NULL DROP TABLE ##ALL_StableColumns; 

SELECT @SQL_MainStableColumnTable       = 'SELECT xxx_ID_xxx = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Stable + '), ' + @ListOfColumns_Stable
                                            + ' INTO ##ALL_StableColumns '
                                            + ' FROM (SELECT DISTINCT' + @ListOfColumns_Stable + ' FROM  ' + @TableName
                                            + ' WHERE ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
                                            SELECT @StabPos_ID = @StabPos_ID + 1;
            WHILE @StabPos_ID <= (SELECT MAX([StabPos_ID]) FROM @StabPos_TAB)
            BEGIN
            SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + 'AND ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) +  ' IS NOT NULL ';
            SELECT @StabPos_ID = @StabPos_ID + 1;
            END

SELECT @SQL_MainStableColumnTable    = @SQL_MainStableColumnTable + ' )x';

EXECUTE SP_EXECUTESQL  @SQL_MainStableColumnTable;

--#######################################################################################################################
--###| Step 5 - Preparing table with all options ID
--#######################################################################################################################

DECLARE @FULL_SQL_1 NVARCHAR(MAX)
SELECT @FULL_SQL_1 = ''

DECLARE @i smallint

IF OBJECT_ID('tempdb.dbo.##FinalTab', 'U') IS NOT NULL DROP TABLE ##FinalTab; 

SELECT @FULL_SQL_1 = 'SELECT t.*, dim.[xxx_ID_xxx] '
                                    + ' INTO ##FinalTab '
                                    +   'FROM ' + @TableName + ' t '
                                    +   'JOIN ##ALL_Dimentions dim '
                                    +   'ON t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1);
                                SELECT @i = 2                               
                                WHILE @i <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
                                    BEGIN
                                    SELECT @FULL_SQL_1 = @FULL_SQL_1 + ' AND t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i)
                                    SELECT @i = @i +1
                                END
EXECUTE SP_EXECUTESQL @FULL_SQL_1

--#######################################################################################################################
--###| Step 6 - Selecting final data
--#######################################################################################################################
DECLARE @STAB_TAB TABLE ([STAB_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @STAB_TAB 
SELECT [STAB_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'S';

DECLARE @VAR_TAB TABLE ([VAR_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @VAR_TAB 
SELECT [VAR_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'V';

DECLARE @y smallint;
DECLARE @x smallint;
DECLARE @z smallint;


DECLARE @FinalCode nvarchar(max)

SELECT @FinalCode = ' SELECT ID1.*'
                                        SELECT @y = 1
                                        WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
                                            BEGIN
                                                SELECT @z = 1
                                                WHILE @z <= (SELECT MAX([VAR_ID]) FROM @VAR_TAB)
                                                    BEGIN
                                                        SELECT @FinalCode = @FinalCode +    ', [ID' + CAST((@y) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z) + '] =  ID' + CAST((@y + 1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z)
                                                        SELECT @z = @z + 1
                                                    END
                                                    SELECT @y = @y + 1
                                                END
        SELECT @FinalCode = @FinalCode + 
                                        ' FROM ( SELECT * FROM ##ALL_StableColumns)ID1';
                                        SELECT @y = 1
                                        WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
                                        BEGIN
                                            SELECT @x = 1
                                            SELECT @FinalCode = @FinalCode 
                                                                                + ' LEFT JOIN (SELECT ' +  @ListOfColumns_Stable + ' , ' + @ListOfColumns_Variable 
                                                                                + ' FROM ##FinalTab WHERE [xxx_ID_xxx] = ' 
                                                                                + CAST(@y as varchar(10)) + ' )ID' + CAST((@y + 1) as varchar(10))  
                                                                                + ' ON 1 = 1' 
                                                                                WHILE @x <= (SELECT MAX([STAB_ID]) FROM @STAB_TAB)
                                                                                BEGIN
                                                                                    SELECT @FinalCode = @FinalCode + ' AND ID1.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x) + ' = ID' + CAST((@y+1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x)
                                                                                    SELECT @x = @x +1
                                                                                END
                                            SELECT @y = @y + 1
                                        END

SELECT * FROM ##ALL_Dimentions;
EXECUTE SP_EXECUTESQL @FinalCode;

From executing the first query (by passing source DB and table name) you will get a pre-created execution query for the second SP, all you have to do is define is the column from your source: + Stable + Value (will be used to concentrate values based on that) + Dim (column you want to use to pivot by)

Names and datatypes will be defined automatically!

I cant recommend it for any production environments but does the job for adhoc BI requests.

Converting String to "Character" array in Java

I used the StringReader class in java.io. One of it's functions read(char[] cbuf) reads a string's contents into an array.

String str = "hello";
char[] array = new char[str.length()];
StringReader read = new StringReader(str);

try {
    read.read(array); //Reads string into the array. Throws IOException
} catch (IOException e) {
    e.printStackTrace();
}

for (int i = 0; i < str.length(); i++) {
        System.out.println("array["+i+"] = "+array[i]);
}

Running this gives you the output:

array[0] = h
array[1] = e
array[2] = l
array[3] = l
array[4] = o

How to calculate the width of a text string of a specific font and font-size?

Swift-5

Use intrinsicContentSize to find the text height and width.

yourLabel.intrinsicContentSize.width

This will work even you have custom spacing between your string like "T E X T"

How to center horizontal table-cell

Just add this class in your css

.column p{
   text-align:center;
}

Returning JSON from a PHP Script

Yeah, you'll need to use echo to display output. Mimetype: application/json

How to access accelerometer/gyroscope data from Javascript?

Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation

function orientationhandler(evt){


  // For FF3.6+
  if (!evt.gamma && !evt.beta) {
    evt.gamma = -(evt.x * (180 / Math.PI));
    evt.beta = -(evt.y * (180 / Math.PI));
  }

  // use evt.gamma, evt.beta, and evt.alpha 
  // according to dev.w3.org/geo/api/spec-source-orientation


}

window.addEventListener('deviceorientation',  orientationhandler, false);
window.addEventListener('MozOrientation',     orientationhandler, false);

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Git on Mac OS X v10.7 (Lion)

It's part of Xcode. You'll need to reinstall the developer tools.

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

PyLint "Unable to import" error - how to set PYTHONPATH?

First, go to your VS Code then press "ctrl + shift + p"

Then search settings.json

Then paste the below code inside the settings.jason.I hope the problem will be solved.

{

"python.pythonPath": "venv/bin/python",
"python.linting.pylintPath": "venv/bin/pylint"

}

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

Do I need <class> elements in persistence.xml?

You can provide for jar-file element path to a folder with compiled classes. For example I added something like that when I prepared persistence.xml to some integration tests:

 <jar-file>file:../target/classes</jar-file>

Reading and writing binary file

You should pass length into fwrite instead of sizeof(buffer).

How do I use a regex in a shell script?

I think this is what you want:

REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'

echo "$1" | grep -P -q $REGEX_DATE
echo $?

I've used the -P switch to get perl regex.

Default behavior of "git push" without a branch specified

Here is a very handy and helpful information about Git Push: Git Push: Just the Tip

The most common use of git push is to push your local changes to your public upstream repository. Assuming that the upstream is a remote named "origin" (the default remote name if your repository is a clone) and the branch to be updated to/from is named "master" (the default branch name), this is done with: git push origin master

git push origin will push changes from all local branches to matching branches the origin remote.

git push origin master will push changes from the local master branch to the remote master branch.

git push origin master:staging will push changes from the local master branch to the remote staging branch if it exists.

Pointer vs. Reference

You should pass a pointer if you are going to modify the value of the variable. Even though technically passing a reference or a pointer are the same, passing a pointer in your use case is more readable as it "advertises" the fact that the value will be changed by the function.

Convert INT to VARCHAR SQL

You can use CAST function:

SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name

How to access the content of an iframe with jQuery?

You have to use the contents() method:

$("#myiframe").contents().find("#myContent")

Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

API Doc: https://api.jquery.com/contents/

Iterate through 2 dimensional array

These functions should work.

// First, cache your array dimensions so you don't have to
//  access them during each iteration of your for loops.
int rowLength = array.length,       // array width (# of columns)
    colLength = array[0].length;    // array height (# of rows)

//     This is your function:
// Prints array elements row by row
var rowString = "";
for(int x = 0; x < rowLength; x++){     // x is the column's index
    for(int y = 0; y < colLength; y++){ // y is the row's index
        rowString += array[x][y];
    } System.out.println(rowString)
}

//      This is the one you want:
// Prints array elements column by column
var colString = "";
for(int y = 0; y < colLength; y++){      // y is the row's index
    for(int x = 0; x < rowLength; x++){  // x is the column's index
        colString += array[x][y];
    } System.out.println(colString)
}

In the first block, the inner loop iterates over each item in the row before moving to the next column.

In the second block (the one you want), the inner loop iterates over all the columns before moving to the next row.

tl;dr: Essentially, the for() loops in both functions are switched. That's it.

I hope this helps you to understand the logic behind iterating over 2-dimensional arrays.

Also, this works whether you have a string[,] or string[][]

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

When your function is deterministic, you are safe to declare it to be deterministic. The location of "DETERMINISTIC" keyword is as follows.

enter image description here

How do I get the directory from a file's full path?

Use below mentioned code to get the folder path

Path.GetDirectoryName(filename);

This will return "C:\MyDirectory" in your case

Spring Rest POST Json RequestBody Content type not supported

Really! after spending 4 hours and insane debugging I found this very strange code at com.fasterxml.jackson.databind.deser.DeserializerCache

if (deser == null) {
    try {
        deser = _createAndCacheValueDeserializer(ctxt, factory, type);
    } catch (Exception e) {
        return false;
    }
}

Ya, the problem was double setter.

Syntax behind sorted(key=lambda: ...)

Simple and not time consuming answer with an example relevant to the question asked Follow this example:

 user = [{"name": "Dough", "age": 55}, 
            {"name": "Ben", "age": 44}, 
            {"name": "Citrus", "age": 33},
            {"name": "Abdullah", "age":22},
            ]
    print(sorted(user, key=lambda el: el["name"]))
    print(sorted(user, key= lambda y: y["age"]))

Look at the names in the list, they starts with D, B, C and A. And if you notice the ages, they are 55, 44, 33 and 22. The first print code

print(sorted(user, key=lambda el: el["name"]))

Results to:

[{'name': 'Abdullah', 'age': 22}, 
{'name': 'Ben', 'age': 44}, 
{'name': 'Citrus', 'age': 33}, 
{'name': 'Dough', 'age': 55}]

sorts the name, because by key=lambda el: el["name"] we are sorting the names and the names return in alphabetical order.

The second print code

print(sorted(user, key= lambda y: y["age"]))

Result:

[{'name': 'Abdullah', 'age': 22},
 {'name': 'Citrus', 'age': 33},
 {'name': 'Ben', 'age': 44}, 
 {'name': 'Dough', 'age': 55}]

sorts by age, and hence the list returns by ascending order of age.

Try this code for better understanding.

XMLHttpRequest module not defined/found

XMLHttpRequest is a built-in object in web browsers.

It is not distributed with Node; you have to install it separately,

  1. Install it with npm,

    npm install xmlhttprequest
    
  2. Now you can require it in your code.

    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    

That said, the http module is the built-in tool for making HTTP requests from Node.

Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I faced a similar issue. I checked for the below:

  1. if ssh is not installed on your machine, you will have to install it firstly. (You will get a message saying ssh is not recognized as a command).
  2. Port 22 is open or not on the server you are trying to ssh.
  3. If the control of remote server is in your hands and you have permissions, try to disable firewall on it.
  4. Try to ssh again.

If port is not an issue then you would have to check for firewall settings as it is the one that is blocking your connection.

For me too it was a firewall issue between my machine and remote server.I disabled the firewall on the remote server and I was able to make a connection using ssh.

What does -1 mean in numpy reshape?

numpy.reshape(a,newshape,order{})

check the below link for more info. https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

for the below example you mentioned the output explains the resultant vector to be a single row.(-1) indicates the number of rows to be 1. if the

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

output:

matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

this can be explained more precisely with another example:

b = np.arange(10).reshape((-1,1))

output:(is a 1 dimensional columnar array)

array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

or

b = np.arange(10).reshape((1,-1))

output:(is a 1 dimensional row array)

array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

Can PHP cURL retrieve response headers AND body in a single request?

If you don't really need to use curl;

$body = file_get_contents('http://example.com');
var_export($http_response_header);
var_export($body);

Which outputs

array (
  0 => 'HTTP/1.0 200 OK',
  1 => 'Accept-Ranges: bytes',
  2 => 'Cache-Control: max-age=604800',
  3 => 'Content-Type: text/html',
  4 => 'Date: Tue, 24 Feb 2015 20:37:13 GMT',
  5 => 'Etag: "359670651"',
  6 => 'Expires: Tue, 03 Mar 2015 20:37:13 GMT',
  7 => 'Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT',
  8 => 'Server: ECS (cpm/F9D5)',
  9 => 'X-Cache: HIT',
  10 => 'x-ec-custom-error: 1',
  11 => 'Content-Length: 1270',
  12 => 'Connection: close',
)'<!doctype html>
<html>
<head>
    <title>Example Domain</title>...

See http://php.net/manual/en/reserved.variables.httpresponseheader.php

List only stopped Docker containers

The typical command is:

docker container ls -f 'status=exited'

However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:

  • created
  • restarting
  • running
  • removing
  • paused
  • exited
  • dead

You can filter on multiple statuses by passing multiple filters on the status:

docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'

If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q, and you can also limit to just the containers that exited successfully with an exit code filter:

docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')

For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering

Javascript Date - set just the date, ignoring time?

If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.

What are some good Python ORM solutions?

This seems to be the canonical reference point for high-level database interaction in Python: http://wiki.python.org/moin/HigherLevelDatabaseProgramming

From there, it looks like Dejavu implements Martin Fowler's DataMapper pattern fairly abstractly in Python.

Reset push notification settings for app

I recently ran into the similar issue with react-native application. iPhone OS version was 13.1 I uninstalled the application and tried to install the app and noticed both location and notification permissions were not prompted.

On checking the settings, I could see my application was enabled for location(from previous installation) however there was no corresponding entry against the notification Tried uninstalling and rebooting without setting the time, it didn't work. Btw, I also tried to download the Appstore app, still same behavior.

The issue was resolved only after setting the device time.

How do you get AngularJS to bind to the title attribute of an A tag?

Sometimes it is not desirable to use interpolation on title attribute or on any other attributes as for that matter, because they get parsed before the interpolation takes place. So:

<!-- dont do this -->
<!-- <a title="{{product.shortDesc}}" ...> -->

If an attribute with a binding is prefixed with the ngAttr prefix (denormalized as ng-attr-) then during the binding will be applied to the corresponding unprefixed attribute. This allows you to bind to attributes that would otherwise be eagerly processed by browsers. The attribute will be set only when the binding is done. The prefix is then removed:

<!-- do this -->
<a ng-attr-title="{{product.shortDesc}}" ...>

(Ensure that you are not using a very earlier version of Angular). Here's a demo fiddle using v1.2.2:

Fiddle

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

How can I let a user download multiple files when a button is clicked?

Found the easiest way to do this. Works even with div!

<div onclick="downloadFiles()">
  <!--do not put any text in <a>, it should be invisible-->
  <a href="path/file1" id="a1" download></a>
  <a href="path/file2" id="a2" download></a>
  <a href="path/file3" id="a3" download></a>
  <script>
    function downloadFiles() {
      document.getElementById("a1").click();
      document.getElementById("a2").click();
      document.getElementById("a3").click();
    }
  </script>
  Download
</div>

That's all, hope it helps.

Get current application physical path within Application_Start

You can use this code:

AppDomain.CurrentDomain.BaseDirectory

Slide a layout up from bottom of screen

Here is what worked in the end for me.

Layouts:

activity_main.xml

<RelativeLayout
    android:id="@+id/main_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        android:layout_alignParentTop="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_centerInParent="true" />

    <Button
        android:id="@+id/slideButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Slide up / down"
        android:layout_alignParentBottom="true" 
        android:onClick="slideUpDown"/>

</RelativeLayout>

hidden_panel.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/hidden_panel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Test" />
</LinearLayout>

Java: package com.example.slideuplayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;

public class MainActivity extends Activity {

private ViewGroup hiddenPanel;
private ViewGroup mainScreen;
private boolean isPanelShown;
private ViewGroup root;

int screenHeight = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mainScreen = (ViewGroup)findViewById(R.id.main_screen);
    ViewTreeObserver vto = mainScreen.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            screenHeight = mainScreen.getHeight();
            mainScreen.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        } 
    }); 

    root = (ViewGroup)findViewById(R.id.root);

    hiddenPanel = (ViewGroup)getLayoutInflater().inflate(R.layout.hidden_panel, root, false);
    hiddenPanel.setVisibility(View.INVISIBLE);

    root.addView(hiddenPanel);

    isPanelShown = false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void slideUpDown(final View view) {
    if(!isPanelShown) {
        // Show the panel
        mainScreen.layout(mainScreen.getLeft(),
                          mainScreen.getTop() - (screenHeight * 25/100), 
                          mainScreen.getRight(),
                          mainScreen.getBottom() - (screenHeight * 25/100));



        hiddenPanel.layout(mainScreen.getLeft(), mainScreen.getBottom(), mainScreen.getRight(), screenHeight);
        hiddenPanel.setVisibility(View.VISIBLE);

        Animation bottomUp = AnimationUtils.loadAnimation(this,
                R.anim.bottom_up);

        hiddenPanel.startAnimation(bottomUp);

        isPanelShown = true;
    }
    else {
        isPanelShown = false;

        // Hide the Panel
        Animation bottomDown = AnimationUtils.loadAnimation(this,
                R.anim.bottom_down);
        bottomDown.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                isPanelShown = false;

                mainScreen.layout(mainScreen.getLeft(),
                          mainScreen.getTop() + (screenHeight * 25/100), 
                          mainScreen.getRight(),
                          mainScreen.getBottom() + (screenHeight * 25/100));

                hiddenPanel.layout(mainScreen.getLeft(), mainScreen.getBottom(), mainScreen.getRight(), screenHeight);
            }
        });
        hiddenPanel.startAnimation(bottomDown);
    }
}
}

Java default constructor

default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.

If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super(), has no throws clause as well no formal parameters.

E.g.

class Klass {
      // Default Constructor gets generated
} 

new Klass();  // Correct
-------------------------------------

class KlassParameterized {

    KlassParameterized ( String str ) {   //// Parameterized Constructor
        // do Something
    }
} 

new KlassParameterized(); //// Wrong  - you need to explicitly provide no-arg constructor. The compiler now never declares default one.


--------------------------------

class KlassCorrected {

    KlassCorrected (){    // No-arg Constructor
       /// Safe to Invoke
    }
    KlassCorrected ( String str ) {   //// Parameterized Constructor
        // do Something
    }
} 

new KlassCorrected();    /// RIGHT  -- you can instantiate

How to set a value for a span using jQuery

You can use this:

$("#submittername").html(submitter_name);

AttributeError: 'str' object has no attribute 'append'

What you are trying to do is add additional information to each item in the list that you already created so

    alist[ 'from form', 'stuff 2', 'stuff 3']

    for j in range( 0,len[alist]):
        temp= []
        temp.append(alist[j]) # alist[0] is 'from form' 
        temp.append('t') # slot for first piece of data 't'
        temp.append('-') # slot for second piece of data

    blist.append(temp)      # will be alist with 2 additional fields for extra stuff assocated with each item in alist  

How to insert pandas dataframe via mysqldb into database?

This has worked for me. At first I've created only the database, no predefined table I created.

from platform import python_version
print(python_version())
3.7.3

path='glass.data'
df=pd.read_csv(path)
df.head()


!conda install sqlalchemy
!conda install pymysql

pd.__version__
    '0.24.2'

sqlalchemy.__version__
'1.3.20'

restarted the Kernel after installation.

from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://USER:PASSWORD@HOST:PORT/DATABASE_NAME', echo=False)

try:
df.to_sql(name='glasstable',con=engine,index=False, if_exists='replace')
print('Sucessfully written to Database!!!')

except Exception as e:
    print(e)

How to change the buttons text using javascript

If the HTMLElement is input[type='button'], input[type='submit'], etc.

<input id="ShowButton" type="button" value="Show">
<input id="ShowButton" type="submit" value="Show">

change it using this code:

document.querySelector('#ShowButton').value = 'Hide';

If, the HTMLElement is button[type='button'], button[type='submit'], etc:

<button id="ShowButton" type="button">Show</button>
<button id="ShowButton" type="submit">Show</button>

change it using any of these methods,

document.querySelector('#ShowButton').innerHTML = 'Hide';
document.querySelector('#ShowButton').innerText = 'Hide';
document.querySelector('#ShowButton').textContent = 'Hide';

Please note that

  • input is an empty tag and cannot have innerHTML, innerText or textContent
  • button is a container tag and can have innerHTML, innerText or textContent

Ignore this answer if you ain't using asp.net-web-forms, asp.net-ajax and rad-grid

You must use value instead of innerHTML.

Try this.

document.getElementById("ShowButton").value= "Hide Filter";

And since you are running the button at server the ID may get mangled in the framework. I so, try

document.getElementById('<%=ShowButton.ClientID %>').value= "Hide Filter";

Another better way to do this is like this.

On markup, change your onclick attribute like this. onclick="showFilterItem(this)"

Now use it like this

function showFilterItem(objButton) {
    if (filterstatus == 0) {
        filterstatus = 1;
        $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
        objButton.value = "Hide Filter";
    }
    else {
        filterstatus = 0;
        $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
        objButton.value = "Show filter";
    }
}

How to make a HTTP request using Ruby on Rails?

You can use Ruby's Net::HTTP class:

require 'net/http'

url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
  http.request(req)
}
puts res.body

HttpClient does not exist in .net 4.0: what can I do?

Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):

    HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
    http.Referer = referrer;
    HttpWebResponse response = (HttpWebResponse )http.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        string responseJson = sr.ReadToEnd();
        // more stuff
    }

Heap space out of memory

No. The heap is cleared by the garbage collector whenever it feels like it. You can ask it to run (with System.gc()) but it is not guaranteed to run.

First try increasing the memory by setting -Xmx256m

Could not commit JPA transaction: Transaction marked as rollbackOnly

For those who can't (or don't want to) setup a debugger to track down the original exception which was causing the rollback-flag to get set, you can just add a bunch of debug statements throughout your code to find the lines of code which trigger the rollback-only flag:

logger.debug("Is rollbackOnly: " + TransactionAspectSupport.currentTransactionStatus().isRollbackOnly());

Adding this throughout the code allowed me to narrow down the root cause, by numbering the debug statements and looking to see where the above method goes from returning "false" to "true".

How to check file input size with jQuery?

If you want to use jQuery's validate you can by creating this method:

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param) 
});

You would use it:

$('#formid').validate({
    rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }},
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});

C# DataRow Empty-check

I prefer approach of Tommy Carlier, but with a little change.

foreach (DataColumn column in row.Table.Columns)
    if (!row.IsNull(column))
      return false;

  return true;

I suppose this approach looks more simple and bright.

How do I filter query objects by date range in Django?

you can use "__range" for example :

from datetime import datetime
start_date=datetime(2009, 12, 30)
end_end=datetime(2020,12,30)
Sample.objects.filter(date__range=[start_date,end_date])

When should I use Memcache instead of Memcached?

Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.

After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.

Python foreach equivalent

Like this:

for pet in pets :
  print(pet)

In fact, Python only has foreach style for loops.

addClass and removeClass in jQuery - not removing class

What happens is that your close button is placed inside your .clickable div, so the click event will be triggered in both elements.

The event bubbling will make the click event propagate from the child nodes to their parents. So your .close_button callback will be executed first, and when .clickable is reached, it will toggle the classes again. As this run very fast you can't notice the two events happened.

                    / \
--------------------| |-----------------
| .clickable        | |                |
|   ----------------| |-----------     |
|   | .close_button | |          |     |
|   ------------------------------     |
|             event bubbling           |
----------------------------------------

To prevent your event from reaching .clickable, you need to add the event parameter to your callback function and then call the stopPropagation method on it.

$(".close_button").click(function (e) { 
    $("#spot1").addClass("spot");
    $("#spot1").removeClass("grown");
    e.stopPropagation();
});

Fiddle: http://jsfiddle.net/u4GCk/1/

More info about event order in general: http://www.quirksmode.org/js/events_order.html (that's where I picked that pretty ASCII art =])

Excel how to find values in 1 column exist in the range of values in another

Use the formula by tigeravatar:

=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50

as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).

To find all of those values, highlight col A. Data > Filter and choose Filter by color.

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

how to convert string to numerical values in mongodb

db.user.find().toArray().filter(a=>a.age>40)

Javascript - How to extract filename from a file input control

If you are using jQuery then

$("#fileupload").val();

"Debug only" code that should run only when "turned on"

An instance variable would probably be the way to do what you want. You could make it static to persist the same value for the life of the program (or thread depending on your static memory model), or make it an ordinary instance var to control it over the life of an object instance. If that instance is a singleton, they'll behave the same way.

#if DEBUG
private /*static*/ bool s_bDoDebugOnlyCode = false;
#endif

void foo()
{   
  // ...
#if DEBUG
  if (s_bDoDebugOnlyCode)
  {
      // Code here gets executed only when compiled with the DEBUG constant, 
      // and when the person debugging manually sets the bool above to true.  
      // It then stays for the rest of the session until they set it to false.
  }
#endif
 // ...
}

Just to be complete, pragmas (preprocessor directives) are considered a bit of a kludge to use to control program flow. .NET has a built-in answer for half of this problem, using the "Conditional" attribute.

private /*static*/ bool doDebugOnlyCode = false; 
[Conditional("DEBUG")]
void foo()
{   
  // ...    
  if (doDebugOnlyCode)
  {
      // Code here gets executed only when compiled with the DEBUG constant, 
      // and when the person debugging manually sets the bool above to true.  
      // It then stays for the rest of the session until they set it to false.
  }    
  // ...
}

No pragmas, much cleaner. The downside is that Conditional can only be applied to methods, so you'll have to deal with a boolean variable that doesn't do anything in a release build. As the variable exists solely to be toggled from the VS execution host, and in a release build its value doesn't matter, it's pretty harmless.

mysql select from n last rows

Take advantage of SORT and LIMIT as you would with pagination. If you want the ith block of rows, use OFFSET.

SELECT val FROM big_table
where val = someval
ORDER BY id DESC
LIMIT n;

In response to Nir: The sort operation is not necessarily penalized, this depends on what the query planner does. Since this use case is crucial for pagination performance, there are some optimizations (see link above). This is true in postgres as well "ORDER BY ... LIMIT can be done without sorting " E.7.1. Last bullet

explain extended select id from items where val = 48 order by id desc limit 10;
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref   | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
|  1 | SIMPLE      | items | const | PRIMARY       | PRIMARY | 4       | const |    1 | Using index | 
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+

INNER JOIN vs INNER JOIN (SELECT . FROM)

There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it

--Version 2 
SELECT p.Name, s.OrderQty 
FROM Product p 
INNER JOIN 
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s 
on p.ProductID = s.ProdctId 

How do I parse JSON into an int?

At first, you create a BufferedReader on a FileReader to the file.

Then, you create a new `JSONParser()´ object that parses the content read from the file.

You cast the parsed Object to a JSONObject and get the id field.

FileReader file=new FileReader("1.json");
BufferedReader write=new BufferedReader(file);
Object obj=new JSONParser().parse(write);
JSONObject jo = (JSONObject) obj;
long id=(long)jo.get("id");

Pass variable to function in jquery AJAX success callback

You can't pass parameters like this - the success object maps to an anonymous function with one parameter and that's the received data. Create a function outside of the for loop which takes (data, i) as parameters and perform the code there:

function image_link(data, i) {
   $(data).find("a:contains(.jpg)").each(function(){                                
       new Image().src = url[i] + $(this).attr("href");
   }
}
...
success: function(data){
    image_link(data, i)
}

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

What is the equivalent of "!=" in Excel VBA?

In VBA, the != operator is the Not operator, like this:

If Not strTest = "" Then ...

Get environment variable value in Dockerfile

Load environment variables from a file you create at runtime.

export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF

... then in the Dockerfile

ADD build /build
RUN /build/test.sh

where test.sh loads MYVAR from env.sh

#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile

How to select last one week data from today's date

Yes, the syntax is accurate and it should be fine.

Here is the SQL Fiddle Demo I created for your particular case

create table sample2
(
    id int primary key,
    created_date date,
    data varchar(10)
  )

insert into sample2 values (1,'2012-01-01','testing');

And here is how to select the data

SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())

How to set the UITableView Section title programmatically (iPhone/iPad)?

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   return 45.0f; 
//set height according to row or section , whatever you want to do!
}

section label text are set.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionHeaderView;

        sectionHeaderView = [[UIView alloc] initWithFrame:
                             CGRectMake(0, 0, tableView.frame.size.width, 120.0)];


    sectionHeaderView.backgroundColor = kColor(61, 201, 247);

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:
                            CGRectMake(sectionHeaderView.frame.origin.x,sectionHeaderView.frame.origin.y - 44, sectionHeaderView.frame.size.width, sectionHeaderView.frame.size.height)];

    headerLabel.backgroundColor = [UIColor clearColor];
    [headerLabel setTextColor:kColor(255, 255, 255)];
    headerLabel.textAlignment = NSTextAlignmentCenter;
    [headerLabel setFont:kFont(20)];
    [sectionHeaderView addSubview:headerLabel];

    switch (section) {
        case 0:
            headerLabel.text = @"Section 1";
            return sectionHeaderView;
            break;
        case 1:
            headerLabel.text = @"Section 2";
            return sectionHeaderView;
            break;
        case 2:
            headerLabel.text = @"Section 3";
            return sectionHeaderView;
            break;
        default:
            break;
    }

    return sectionHeaderView;
}

How do I keep CSS floats in one line?

The way I got around this was to use some jQuery. The reason I did it this way was because A and B were percent widths.

HTML:

<div class="floatNoWrap">
    <div id="A" style="float: left;">
        Content A
    </div>
    <div id="B" style="float: left;">
        Content B
    </div>
    <div style="clear: both;"></div>
</div>

CSS:

.floatNoWrap
{
    width: 100%;
    height: 100%;
}

jQuery:

$("[class~='floatNoWrap']").each(function () {
    $(this).css("width", $(this).outerWidth());
});

Detect WebBrowser complete page loading

Note the url in DocumentCompleted can be different than navigating url due to server transfer or url normalization (e.g. you navigate to www.microsoft.com and got http://www.microsoft.com in documentcomplete)

In pages with no frames, this event fires one time after loading is complete. In pages with multiple frames, this event fires for each navigating frame (note navigation is supported inside a frame, for instance clicking a link in a frame could navigate the frame to another page). The highest level navigating frame, which may or may not be the top level browser, fires the final DocumentComplete event.

In native code you would compare the sender of the DocumentComplete event to determine if the event is the final event in the navigation or not. However in Windows Forms the sender parameter is not wrapped by WebBrowserDocumentCompletedEventArgs. You can either sink the native event to get the parameter's value, or check the readystate property of the browser or frame documents in the DocumentCompleted event handler to see if all frames are in the ready state.

There is a prolblem with the readystate method as if a download manager is present and the navigation is to a downloadable file, the navigation could be cancelled by the download manager and the readystate won't become complete.

Is it correct to use alt tag for an anchor link?

No, an alt attribute (it would be an attribute, not a tag) is not allowed for an a element in any HTML specification or draft. And it does not seem to be recognized by any browser either as having any significance.

It’s a bit mystery why people try to use it, then, but the probable explanation is that they are doing so in analog with alt attribute for img elements, expecting to see a “tooltip” on mouseover. There are two things wrong with this. First, each element has attributes of its own, defined in the specs for each element. Second, the “tooltip” rendering of alt attributes in some ancient browsers is/was a quirk or even a bug, rather than something to be expected; the alt attribute is supposed to be presented to the user if and only if the image itself is not presented, for whatever reason.

To create a “tooltip”, use the title attribute instead or, much better, Google for "CSS tooltips" and use CSS-based tooltips of your preference (they can be characterized as hidden “layers” that become visible on mouseover).

How do I make a newline after a twitter bootstrap element?

Using br elements is fine, and as long as you don't need a lot of space between elements, is actually a logical thing to do as anyone can read your code and understand what spacing logic you are using.

The alternative is to create a custom class for white space. In bootstrap 4 you can use

<div class="w-100"></div>

to make a blank row across the page, but this is no different to using the <br> tag. The downside to creating a custom class for white space is that it can be a pain to read for others who view your code. A custom class would also apply the same amount of white space each time you used it, so if you wanted different amounts of white space on the same page, then you would need to create several white space classes.

In most cases, it is just easier to use <br> or <div class="w-100"></div> for the sake of ease and readability. it doesn't look pretty, but it works.

What does map(&:name) mean in Ruby?

It basically execute the method call tag.name on each tags in the array.

It is a simplified ruby shorthand.

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If you load a page in your browser using HTTPS, the browser will refuse to load any resources over HTTP. As you've tried, changing the API URL to have HTTPS instead of HTTP typically resolves this issue. However, your API must not allow for HTTPS connections. Because of this, you must either force HTTP on the main page or request that they allow HTTPS connections.

Note on this: The request will still work if you go to the API URL instead of attempting to load it with AJAX. This is because the browser is not loading a resource from within a secured page, instead it's loading an insecure page and it's accepting that. In order for it to be available through AJAX, though, the protocols should match.

What is the best way to trigger onchange event in react js

Expanding on the answer from Grin/Dan Abramov, this works across multiple input types. Tested in React >= 15.5

const inputTypes = [
    window.HTMLInputElement,
    window.HTMLSelectElement,
    window.HTMLTextAreaElement,
];

export const triggerInputChange = (node, value = '') => {

    // only process the change on elements we know have a value setter in their constructor
    if ( inputTypes.indexOf(node.__proto__.constructor) >-1 ) {

        const setValue = Object.getOwnPropertyDescriptor(node.__proto__, 'value').set;
        const event = new Event('input', { bubbles: true });

        setValue.call(node, value);
        node.dispatchEvent(event);

    }

};

Why does python use 'else' after for and while loops?

I was just trying to make sense of it again myself. I found that the following helps!

• Think of the else as being paired with the if inside the loop (instead of with the for) - if condition is met then break the loop, else do this - except it's one else paired with multiple ifs!
• If no ifs were satisfied at all, then do the else.
• The multiple ifs can also actually be thought of as if-elifs!

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

How do I pass a variable by reference?

There is a little trick to pass an object by reference, even though the language doesn't make it possible. It works in Java too, it's the list with one item. ;-)

class PassByReference:
    def __init__(self, name):
        self.name = name

def changeRef(ref):
    ref[0] = PassByReference('Michael')

obj = PassByReference('Peter')
print obj.name

p = [obj] # A pointer to obj! ;-)
changeRef(p)

print p[0].name # p->name

It's an ugly hack, but it works. ;-P

vertical alignment of text element in SVG

After looking at the SVG Recommendation I've come to the understanding that the baseline properties are meant to position text relative to other text, especially when mixing different fonts and or languages. If you want to postion text so that it's top is at y then you need use dy = "y + the height of your text".

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Spark : how to run spark file from spark shell

Just to give more perspective to the answers

Spark-shell is a scala repl

You can type :help to see the list of operation that are possible inside the scala shell

scala> :help
All commands can be abbreviated, e.g., :he instead of :help.
:edit <id>|<line>        edit history
:help [command]          print this summary or command-specific help
:history [num]           show the history (optional num is commands to show)
:h? <string>             search the history
:imports [name name ...] show import history, identifying sources of names
:implicits [-v]          show the implicits in scope
:javap <path|class>      disassemble a file or class name
:line <id>|<line>        place line(s) at the end of history
:load <path>             interpret lines in a file
:paste [-raw] [path]     enter paste mode or paste a file
:power                   enable power user mode
:quit                    exit the interpreter
:replay [options]        reset the repl and replay all previous commands
:require <path>          add a jar to the classpath
:reset [options]         reset the repl to its initial state, forgetting all session entries
:save <path>             save replayable session to a file
:sh <command line>       run a shell command (result is implicitly => List[String])
:settings <options>      update compiler options, if possible; see reset
:silent                  disable/enable automatic printing of results
:type [-v] <expr>        display the type of an expression without evaluating it
:kind [-v] <expr>        display the kind of expression's type
:warnings                show the suppressed warnings from the most recent line which had any

:load interpret lines in a file

Insert into a MySQL table or update if exists

Any of these solution will work regarding your question:

INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);

or

INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19) 
    ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;  

or

REPLACE INTO table (id, name, age) VALUES(1, "A", 19);

If you want to know in details regarding these statement visit this link

How can I set a css border on one side only?

You can specify border separately for all borders, for example:

#testdiv{
  border-left: 1px solid #000;
  border-right: 2px solid #FF0;
}

You can also specify the look of the border, and use separate style for the top, right, bottom and left borders. for example:

#testdiv{
  border: 1px #000;
  border-style: none solid none solid;
}

How to Set OnClick attribute with value containing function in ie8?

You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div>
<script type="text/javascript" >
    (function() {
        document.getElementById("something").onclick = function() { 
            alert('hello'); 
        };
    })();
</script>

How to lay out Views in RelativeLayout programmatically?

call

tv1.setId(1) 

after

tv1.setText("A");

Converting Stream to String and back...what are we missing?

I wrote a useful method to call any action that takes a StreamWriter and write it out to a string instead. The method is like this;

static void SendStreamToString(Action<StreamWriter> action, out string destination)
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream, Encoding.Unicode))
    {
        action(writer);
        writer.Flush();
        stream.Position = 0;
        destination = Encoding.Unicode.GetString(stream.GetBuffer(), 0, (int)stream.Length);
    }
}

And you can use it like this;

string myString;

SendStreamToString(writer =>
{
    var ints = new List<int> {1, 2, 3};
    writer.WriteLine("My ints");
    foreach (var integer in ints)
    {
        writer.WriteLine(integer);
    }
}, out myString);

I know this can be done much easier with a StringBuilder, the point is that you can call any method that takes a StreamWriter.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Use collections.Counter:

>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})

Counters are basically a subclass of dict, so you can still do everything else with them you'd normally do with that type, such as iterate over their keys and values.

When is the @JsonProperty property used and what is it used for?

In addition to all the answers above, don't forget the part of the documentation that says

Marker annotation that can be used to define a non-static method as a "setter" or "getter" for a logical property (depending on its signature), or non-static object field to be used (serialized, deserialized) as a logical property.

If you have a non-static method in your class that is not a conventional getter or setter then you can make it act like a getter and setter by using the annotation on it. See the example below

public class Testing {
    private Integer id;
    private String username;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getIdAndUsername() {
        return id + "." + username; 
    }

    public String concatenateIdAndUsername() {
        return id + "." + username; 
    }
}

When the above object is serialized, then response will contain

  • username from getUsername()
  • id from getId()
  • idAndUsername from getIdAndUsername*

Since the method getIdAndUsername starts with get then it's treated as normal getter hence, why you could annotate such with @JsonIgnore.

If you have noticed the concatenateIdAndUsername is not returned and that's because it name does not start with get and if you wish the result of that method to be included in the response then you can use @JsonProperty("...") and it would be treated as normal getter/setter as mentioned in the above highlighted documentation.

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

How to read if a checkbox is checked in PHP?

Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set

Example:

    if(isset($_POST["testvariabel"]))
     {
       echo "testvariabel has been set!";
     }

How can I create an array/list of dictionaries in python?

This is how I did it and it works:

dictlist = [dict() for x in range(n)]

It gives you a list of n empty dictionaries.

What is the difference between String.slice and String.substring?

Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:

String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn't.

Here is his article about this.

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

Namenode not getting started

Add hadoop.tmp.dir property in core-site.xml

<configuration>
  <property>
    <name>fs.defaultFS</name>
    <value>hdfs://localhost:9000</value>
  </property>
  <property>
    <name>hadoop.tmp.dir</name>
    <value>/home/yourname/hadoop/tmp/hadoop-${user.name}</value>
  </property>
</configuration>

and format hdfs (hadoop 2.7.1):

$ hdfs namenode -format

The default value in core-default.xml is /tmp/hadoop-${user.name}, which will be deleted after reboot.

Can't find bundle for base name

When you create an initialization of the ResourceBundle, you can do this way also.

For testing and development I have created a properties file under \src with the name prp.properties.

Use this way:

ResourceBundle rb = ResourceBundle.getBundle("prp");

Naming convention and stuff:

http://192.9.162.55/developer/technicalArticles/Intl/ResourceBundles/

Reading data from DataGridView in C#

string[,] myGridData = new string[dataGridView1.Rows.Count,3];

int i = 0;

foreach(DataRow row in dataGridView1.Rows)

{

    myGridData[i][0] = row.Cells[0].Value.ToString();
    myGridData[i][1] = row.Cells[1].Value.ToString();
    myGridData[i][2] = row.Cells[2].Value.ToString();

    i++;
}

Hope this helps....

Set output of a command as a variable (with pipes)

THIS DOESN'T USE PIPEs, but requires a single tempfile
I used this to put simplified timestamps into a lowtech daily maintenance batfile

We have already Short-formatted our System-Time to HHmm, (which is 2245 for 10:45PM)
I direct output of Maint-Routines to logfiles with a $DATE%@%TIME% timestamp;
. . . but %TIME% is a long ugly string (ex. 224513.56, for down to the hundredths of a sec)

SOLUTION OVERVIEW:
1. Use redirection (">") to send the command "TIME /T" everytime to OVERWRITE a temp-file in the %TEMP% DIRECTORY
2. Then use that tempfile as the input to set a new variable (I called it NOW)
3. Replace

echo $DATE%@%TIME% blah-blah-blah >> %logfile%
      with
echo $DATE%@%NOW% blah-blah-blah >> %logfile%


====DIFFERENCE IN OUTPUT:
BEFORE:
SUCCESSFUL TIMESYNCH [email protected]
AFTER:
SUCCESSFUL TIMESYNCH 29Dec14@2252


ACTUAL CODE:

TIME /T > %TEMP%\DailyTemp.txt
SET /p NOW=<%TEMP%\DailyTemp.txt
echo $DATE%@%NOW% blah-blah-blah >> %logfile%


AFTERMATH:
All that remains afterwards is the appended logfile, and constantly overwritten tempfile. And if the Tempfile is ever deleted, it will be re-created as necessary.

CSS Grid Layout not working in IE11 even with prefixes

IE11 uses an older version of the Grid specification.

The properties you are using don't exist in the older grid spec. Using prefixes makes no difference.

Here are three problems I see right off the bat.


repeat()

The repeat() function doesn't exist in the older spec, so it isn't supported by IE11.

You need to use the correct syntax, which is covered in another answer to this post, or declare all row and column lengths.

Instead of:

.grid {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: repeat( 4, 1fr );
      grid-template-columns: repeat( 4, 1fr );
  -ms-grid-rows: repeat( 4, 270px );
      grid-template-rows: repeat( 4, 270px );
  grid-gap: 30px;
}

Use:

.grid {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: 1fr 1fr 1fr 1fr;             /* adjusted */
      grid-template-columns:  repeat( 4, 1fr );
  -ms-grid-rows: 270px 270px 270px 270px;        /* adjusted */
      grid-template-rows: repeat( 4, 270px );
  grid-gap: 30px;
}

Older spec reference: https://www.w3.org/TR/2011/WD-css3-grid-layout-20110407/#grid-repeating-columns-and-rows


span

The span keyword doesn't exist in the older spec, so it isn't supported by IE11. You'll have to use the equivalent properties for these browsers.

Instead of:

.grid .grid-item.height-2x {
  -ms-grid-row: span 2;
      grid-row: span 2;
}
.grid .grid-item.width-2x {
  -ms-grid-column: span 2;
      grid-column: span 2;
}

Use:

.grid .grid-item.height-2x {
  -ms-grid-row-span: 2;          /* adjusted */
      grid-row: span 2;
}
.grid .grid-item.width-2x {
  -ms-grid-column-span: 2;       /* adjusted */
      grid-column: span 2;
}

Older spec reference: https://www.w3.org/TR/2011/WD-css3-grid-layout-20110407/#grid-row-span-and-grid-column-span


grid-gap

The grid-gap property, as well as its long-hand forms grid-column-gap and grid-row-gap, don't exist in the older spec, so they aren't supported by IE11. You'll have to find another way to separate the boxes. I haven't read the entire older spec, so there may be a method. Otherwise, try margins.


grid item auto placement

There was some discussion in the old spec about grid item auto placement, but the feature was never implemented in IE11. (Auto placement of grid items is now standard in current browsers).

So unless you specifically define the placement of grid items, they will stack in cell 1,1.

Use the -ms-grid-row and -ms-grid-column properties.

How to restore SQL Server 2014 backup in SQL Server 2008

It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

Angular JS POST request not sending JSON data

try to use absolute url. if it not works, check if service's response has headers:

Access-Control-Allow-Origin and Access-Control-Allow-Headers

for example:

"Access-Control-Allow-Origin": "*"
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"

Add a duration to a moment (moment.js)

I think you missed a key point in the documentation for .add()

Mutates the original moment by adding time.

You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)

If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.

You can work around this behavior by cloning the moment, as described here.

Also, you cannot just use == to test. You could format each moment to the same output and compare those, or you could just use the .isSame() method.

Your code is now:

var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours');  // see the cloning?
returned_endate.isSame(expected_enddate)  // true

SSL cert "err_cert_authority_invalid" on mobile chrome only

For those having this problem on IIS servers.

Explanation: sometimes certificates carry an URL of an intermediate certificate instead of the actual certificate. Desktop browsers can DOWNLOAD the missing intermediate certificate using this URL. But older mobile browsers are unable to do that. So they throw this warning.

You need to

1) make sure all intermediate certificates are served by the server

2) disable unneeded certification paths in IIS - Under "Trusted Root Certification Authorities", you need to "disable all purposes" for the certificate that triggers the download.

PS. my colleague has wrote a blog post with more detailed steps: https://www.jitbit.com/maxblog/21-errcertauthorityinvalid-on-android-and-iis/

How to grep, excluding some patterns?

Simply use! grep -v multiple times.

Content of file

[root@server]# cat file
1
2
3
4
5

Exclude the line or match

[root@server]# cat file |grep -v 3
1
2
4
5

Exclude the line or match multiple

[root@server]# cat file |grep -v 3 |grep -v 5
1
2
4

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I had this issue when using the history API.

window.history.pushState(null, null, URL);

Even with a local server (localhost), you want to add 'http://' to your URL so that you have something similar to:

http://localhost...

Disable spell-checking on HTML textfields

An IFrame WILL "trigger" the spell checker (if it has content-editable set to true) just as a textfield, at least in Chrome.

How to hide soft keyboard on android after clicking outside EditText?

I thought this problem. first, I think that setOnTouchListener is not simple solution. so I believe dispatchTouchEvent is best simple solution.

public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_UP) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
    return super.dispatchKeyEvent(event);
}

in here, a important is ACTION_UP.

I assumed EditText only show soft keyboard otherwise not show the keyboard. I have tested on Android5.0.1 (G3.cat6 of LG).

if you need drag checking, long click, ..., show comments above.

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

This has to be done during your exe4j configuration. In the fourth step of Exe4j wizard which is Executable Info select> Advanced options select 32-bit or 64-bit. This worked well for me. or else install both JDK tool-kits x64 and x32 in your machine.

Maven: Failed to read artifact descriptor

I had this problem in eclipse, mvn -U clean install didn't work but right clicking the project and selecting Maven->Update Project fixed it.

Replace X-axis with own values

Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)

Detailed explanation here

Image with rotated labels

Why aren't programs written in Assembly more often?

Ditto most of what others have said.

In the good old days before C was invented, when the only high level languages were things like COBOL and FORTRAN, there were lots of things that just weren't possible to do without resorting to assembler. It was the only way to get the full breadth of flexibility, to be able to access all the devices, etc. But then C was invented, and almost anything that was possible in assembly was possible in C. I have written very little assembly since then.

That said, I think it is a very useful exercise for new programmers to learn to write in assembler. Not because they would actually use it much, but because then you understand what is really happening inside the computer. I've seen lots of programming errors and inefficient code from programmers who clearly have no idea what's really happening with the bits and bytes and registers.

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

For those using OpenSSL you can retrieve the SHA1 fingerprint this way:

OpenSSL> dgst -sha1 my-release-key.keystore

Which would result in the following output:

enter image description here

Is this the proper way to do boolean test in SQL?

With Postgres, you may use

select * from users where active

or

select * from users where active = 't'

If you want to use integer value, you have to consider it as a string. You can't use integer value.

select * from users where active = 1   -- Does not work

select * from users where active = '1' -- Works 

Why do table names in SQL Server start with "dbo"?

dbo is the default schema in SQL Server. You can create your own schemas to allow you to better manage your object namespace.

Upgrade python in a virtualenv

How to upgrade the Python version for an existing virtualenvwrapper project and keep the same name

I'm adding an answer for anyone using Doug Hellmann's excellent virtualenvwrapper specifically since the existing answers didn't do it for me.

Some context:

  • I work on some projects that are Python 2 and some that are Python 3; while I'd love to use python3 -m venv, it doesn't support Python 2 environments
  • When I start a new project, I use mkproject which creates the virtual environment, creates an empty project directory, and cds into it
  • I want to continue using virtualenvwrapper's workon command to activate any project irrespective of Python version

Directions:

Let's say your existing project is named foo and is currently running Python 2 (mkproject -p python2 foo), though the commands are the same whether upgrading from 2.x to 3.x, 3.6.0 to 3.6.1, etc. I'm also assuming you're currently inside the activated virtual environment.

1. Deactivate and remove the old virtual environment:

$ deactivate
$ rmvirtualenv foo

Note that if you've added any custom commands to the hooks (e.g., bin/postactivate) you'd need to save those before removing the environment.

2. Stash the real project in a temp directory:

$ cd ..
$ mv foo foo-tmp

3. Create the new virtual environment (and project dir) and activate:

$ mkproject -p python3 foo

4. Replace the empty generated project dir with real project, change back into project dir:

$ cd ..
$ mv -f foo-tmp foo
$ cdproject

5. Re-install dependencies, confirm new Python version, etc:

$ pip install -r requirements.txt
$ python --version

If this is a common use case, I'll consider opening a PR to add something like $ upgradevirtualenv / $ upgradeproject to virtualenvwrapper.

How to set a cron job to run every 3 hours

The unix setup should be like the following:

 0 */3 * * * sh cron/update_old_citations.sh

good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/

How do you run a Python script as a service in Windows?

The accepted answer using win32serviceutil works but is complicated and makes debugging and changes harder. It is far easier to use NSSM (the Non-Sucking Service Manager). You write and comfortably debug a normal python program and when it finally works you use NSSM to install it as a service in less than a minute:

From an elevated (admin) command prompt you run nssm.exe install NameOfYourService and you fill-in these options:

  • path: (the path to python.exe e.g. C:\Python27\Python.exe)
  • Arguments: (the path to your python script, e.g. c:\path\to\program.py)

By the way, if your program prints useful messages that you want to keep in a log file NSSM can also handle this and a lot more for you.

Remove Style on Element

Update: For a better approach, please refer to Blackus's answer in the same thread.


If you are not averse to using JavaScript and Regex, you can use the below solution to find all width and height properties in the style attribute and replace them with nothing.

//Get the value of style attribute based on element's Id
var originalStyle = document.getElementById('sample_id').getAttribute('style'); 

var regex = new RegExp(/(width:|height:).+?(;[\s]?|$)/g);
//Replace matches with null
var modStyle = originalStyle.replace(regex, ""); 

//Set the modified style value to element using it's Id
document.getElementById('sample_id').setAttribute('style', modStyle); 

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

This expression 12-4-2005 is a calculated int and the value is -1997. You should do like this instead '2005-04-12' with the ' before and after.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I had the same error. My issue was using the wrong parameter name when binding.

Notice :tokenHash in the query, but :token_hash when binding. Fixing one or the other resolves the error in this instance.

// Prepare DB connection
$sql = 'INSERT INTO rememberedlogins (token_hash,user_id,expires_at)
        VALUES (:tokenHash,:user_id,:expires_at)';
$db = static::getDB();
$stmt = $db->prepare($sql);

// Bind values
$stmt->bindValue(':token_hash',$hashed_token,PDO::PARAM_STR);

How to implement a material design circular progress bar in android

With the Material Components library you can use the CircularProgressIndicator:

Something like:

<com.google.android.material.progressindicator.CircularProgressIndicator
      android:indeterminate="true"          
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:indicatorColor="@array/progress_colors"
      app:indicatorSize="xxdp"
      app:showAnimationBehavior="inward"/>

where array/progress_colors is an array with the colors:

  <integer-array name="progress_colors">
    <item>@color/yellow_500</item>
    <item>@color/blue_700</item>
    <item>@color/red_500</item>
  </integer-array>

enter image description here

Note: it requires at least the version 1.3.0

How to create a batch file to run cmd as administrator

You can use a shortcut that links to the batch file. Just go into properties for the shortcut and select advanced, then "run as administrator".

Then just make the batch file hidden, and run the shortcut.

This way, you can even set your own icon for the shortcut.

Add a auto increment primary key to existing table in oracle

You can use the Oracle Data Modeler to create auto incrementing surrogate keys.

Step 1. - Create a Relational Diagram

You can first create a Logical Diagram and Engineer to create the Relational Diagram or you can straightaway create the Relational Diagram.

Add the entity (table) that required to have auto incremented PK, select the type of the PK as Integer.

Step 2. - Edit PK Column Property

Get the properties of the PK column. You can double click the name of the column or click on the 'Properties' button.

Column Properties dialog box appears.

Select the General Tab (Default Selection for the first time). Then select both the 'Auto Increment' and 'Identity Column' check boxes.

Step 3. - Additional Information

Additional information relating to the auto increment can be specified by selecting the 'Auto Increment' tab.

  • Start With
  • Increment By
  • Min Value
  • Max Value
  • Cycle
  • Disable Cache
  • Order
  • Sequence Name
  • Trigger Name
  • Generate Trigger

It is usually a good idea to mention the sequence name, so that it will be useful in PL/SQL.

Click OK (Apply) to the Column Properties dialog box.

Click OK (Apply) to the Table Properties dialog box.

Table appears in the Relational Diagram.

ITSAppUsesNonExemptEncryption export compliance while internal testing?

There are basically 2 things to bear in mind. You are only allowed to set it to NO if you either don't use encryption at all, or you are part of the exempt regulations. This applies to the following kind of applications:

Source: Chamber of Commerce: https://www.bis.doc.gov/index.php/policy-guidance/encryption/encryption-faqs#15

Consumer applications

  • piracy and theft prevention for software or music;
  • music, movies, tunes/music, digital photos – players, recorders and organizers
  • games/gaming – devices, runtime software, HDMI and other component interfaces, development tools
  • LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing);
  • printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies
  • household utilities and appliances

Business / systems applications: systems operations, integration and control. Some examples

  • business process automation (BPA) – process planning and scheduling, supply chain management, inventory and delivery

  • transportation – safety and maintenance, systems monitoring and on-board controllers (including aviation, railway, and commercial automotive systems), ‘smart highway’ technologies, public transit operations and fare collection, etc.

  • industrial, manufacturing or mechanical systems - including robotics, plant safety, utilities, factory and other heavy equipment, facilities systems controllers such as fire alarms and HVAC

  • medical / clinical – including diagnostic applications, patient scheduling, and medical data records confidentiality

  • applied geosciences – mining / drilling, atmospheric sampling / weather monitoring, mapping / surveying, dams / hydrology

Research /scientific /analytical. Some examples:

  • business process management (BPM) – business process abstraction and modeling

  • scientific visualization / simulation / co-simulation (excluding such tools for computing, networking, cryptanalysis, etc.)

  • data synthesis tools for social, economic, and political sciences (e.g., economic, population, global climate change, public opinion polling, etc. forecasting and modeling)

Secure intellectual property delivery and installation. Some examples

  • software download auto-installers and updaters

  • license key product protection and similar purchase validation

  • software and hardware design IP protection

  • computer aided design (CAD) software and other drafting tools

Note: These regulations are also true for testing your app using TestFlight

Clearing <input type='file' /> using jQuery

Easy: you wrap a <form> around the element, call reset on the form, then remove the form using .unwrap(). Unlike the .clone() solutions otherwise in this thread, you end up with the same element at the end (including custom properties that were set on it).

Tested and working in Opera, Firefox, Safari, Chrome and IE6+. Also works on other types of form elements, with the exception of type="hidden".

_x000D_
_x000D_
window.reset = function(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <input id="file" type="file">
  <br>
  <input id="text" type="text" value="Original">
</form>

<button onclick="reset($('#file'))">Reset file</button>
<button onclick="reset($('#text'))">Reset text</button>
_x000D_
_x000D_
_x000D_

JSFiddle

As Timo notes below, if you have the buttons to trigger the reset of the field inside of the <form>, you must call .preventDefault() on the event to prevent the <button> from triggering a submit.


EDIT

Does not work in IE 11 due to an unfixed bug. The text (file name) is cleared on the input, but its File list remains populated.

How to select a drop-down menu value with Selenium using Python?

It works with option value:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()

How do you implement a class in C?

I will give a simple example of how OOP should be done in C. I realise this thead is from 2009 but would like to add this anyway.

/// Object.h
typedef struct Object {
    uuid_t uuid;
} Object;

int Object_init(Object *self);
uuid_t Object_get_uuid(Object *self);
int Object_clean(Object *self);

/// Person.h
typedef struct Person {
    Object obj;
    char *name;
} Person;

int Person_init(Person *self, char *name);
int Person_greet(Person *self);
int Person_clean(Person *self);

/// Object.c
#include "object.h"

int Object_init(Object *self)
{
    self->uuid = uuid_new();

    return 0;
}
uuid_t Object_get_uuid(Object *self)
{ // Don't actually create getters in C...
    return self->uuid;
}
int Object_clean(Object *self)
{
    uuid_free(self->uuid);

    return 0;
}

/// Person.c
#include "person.h"

int Person_init(Person *self, char *name)
{
    Object_init(&self->obj); // Or just Object_init(&self);
    self->name = strdup(name);

    return 0;
}
int Person_greet(Person *self)
{
    printf("Hello, %s", self->name);

    return 0;
}
int Person_clean(Person *self)
{
    free(self->name);
    Object_clean(self);

    return 0;
}

/// main.c
int main(void)
{
    Person p;

    Person_init(&p, "John");
    Person_greet(&p);
    Object_get_uuid(&p); // Inherited function
    Person_clean(&p);

    return 0;
}

The basic concept involves placing the 'inherited class' at the top of the struct. This way, accessing the first 4 bytes in the struct also accesses the first 4 bytes in the 'inherited class' (Asuming non-crazy optimalisations). Now, when the pointer of the struct is cast to the 'inherited class', the 'inherited class' can access the 'inherited values' in the same way it would access it's members normally.

This and some naming conventions for constructors, destructors, allocation and deallocarion functions (I recommend init, clean, new, free) will get you a long way.

As for Virtual functions, use function pointers in the struct, possibly with Class_func(...); wrapper too. As for (simple) templates, add a size_t parameter to determine size, require a void* pointer, or require a 'class' type with just the functionality you care about. (e.g. int GetUUID(Object *self); GetUUID(&p);)

Write HTML file using Java

It really depends on the type of HTML file you're creating.

For such tasks, I use to create an object, serialize it to XML, then transform it with XSL. The pros of this approach are:

  • The strict separation between source code and HTML template,
  • The possibility to edit HTML without having to recompile the application,
  • The ability to serve different HTML in different cases based on the same XML, or even serve XML directly when needed (for a further deserialization for example),
  • The shorter amount of code to write.

The cons are:

  • You must know XSLT and know how to implement it in Java.
  • You must write XSLT (and it's torture for many developers).
  • When transforming XML to HTML with XSLT, some parts may be tricky. Few examples: <textarea/> tags (which make the page unusable), XML declaration (which can cause problems with IE), whitespace (with <pre></pre> tags etc.), HTML entities (&nbsp;), etc.
  • The performance will be reduced, since serialization to XML wastes lots of CPU resources and XSL transformation is very costly too.

Now, if your HTML is very short or very repetitive or if the HTML has a volatile structure which changes dynamically, this approach must not be taken in account. On the other hand, if you serve HTML files which have all a similar structure and you want to reduce the amount of Java code and use templates, this approach may work.

How to use RecyclerView inside NestedScrollView?

I have used this awesome extension (written in kotlin but can be also used in Java)

https://github.com/Widgetlabs/expedition-nestedscrollview

Basically you get the NestedRecyclerView inside any package lets say utils in your project, then just create your recyclerview like

 <com.your_package.utils.NestedRecyclerView
      android:id="@+id/rv_test"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

Check this awesome article by Marc Knaup

https://medium.com/widgetlabs-engineering/scrollable-nestedscrollviews-inside-recyclerview-ca65050d828a

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

I have faced the same issue you have mentioned and could solve it by just deleting the current avd and creating a new one.It's working perfectly well now.

How to get the mobile number of current sim card in real device?

You can use the TelephonyManager to do this:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = tm.getLine1Number();

The documentation for getLine1Number() says this method will return null if the number is "unavailable", but it does not say when the number might be unavailable.

You'll need to give your application permission to make this query by adding the following to your Manifest:

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

(You shouldn't use TelephonyManager.getDefault() to get the TelephonyManager as that is a private undocumented API call and may change in future.)

Programmatically change the src of an img tag

With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

document.querySelector('img[name="edit-save"]');

and change the src with

document.querySelector('img[name="edit-save"]').src = "..."

so you could achieve the desired effect with

var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
    this.src = "..." // this is the reference to the image itself
};

otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

CSS Selector "(A or B) and C"?

is there a better syntax?

No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

How to open the default webbrowser using java

Here is my code. It'll open given url in default browser (cross platform solution).

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Browser {
    public static void main(String[] args) {
        String url = "http://www.google.com";

        if(Desktop.isDesktopSupported()){
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(new URI(url));
            } catch (IOException | URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

PDO Prepared Inserts multiple rows in single query

Same answer as Mr. Balagtas, slightly clearer...

Recent versions MySQL and PHP PDO do support multi-row INSERT statements.

SQL Overview

The SQL will look something like this, assuming a 3-column table you'd like to INSERT to.

INSERT INTO tbl_name
            (colA, colB, colC)
     VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?) [,...]

ON DUPLICATE KEY UPDATE works as expected even with a multi-row INSERT; append this:

ON DUPLICATE KEY UPDATE colA = VALUES(colA), colB = VALUES(colB), colC = VALUES(colC)

PHP Overview

Your PHP code will follow the usual $pdo->prepare($qry) and $stmt->execute($params) PDO calls.

$params will be a 1-dimensional array of all the values to pass to the INSERT.

In the above example, it should contain 9 elements; PDO will use every set of 3 as a single row of values. (Inserting 3 rows of 3 columns each = 9 element array.)

Implementation

Below code is written for clarity, not efficiency. Work with the PHP array_*() functions for better ways to map or walk through your data if you'd like. Whether you can use transactions obviously depends on your MySQL table type.

Assuming:

  • $tblName - the string name of the table to INSERT to
  • $colNames - 1-dimensional array of the column names of the table These column names must be valid MySQL column identifiers; escape them with backticks (``) if they are not
  • $dataVals - mutli-dimensional array, where each element is a 1-d array of a row of values to INSERT

Sample Code

// setup data values for PDO
// memory warning: this is creating a copy all of $dataVals
$dataToInsert = array();

foreach ($dataVals as $row => $data) {
    foreach($data as $val) {
        $dataToInsert[] = $val;
    }
}

// (optional) setup the ON DUPLICATE column names
$updateCols = array();

foreach ($colNames as $curCol) {
    $updateCols[] = $curCol . " = VALUES($curCol)";
}

$onDup = implode(', ', $updateCols);

// setup the placeholders - a fancy way to make the long "(?, ?, ?)..." string
$rowPlaces = '(' . implode(', ', array_fill(0, count($colNames), '?')) . ')';
$allPlaces = implode(', ', array_fill(0, count($dataVals), $rowPlaces));

$sql = "INSERT INTO $tblName (" . implode(', ', $colNames) . 
    ") VALUES " . $allPlaces . " ON DUPLICATE KEY UPDATE $onDup";

// and then the PHP PDO boilerplate
$stmt = $pdo->prepare ($sql);

$stmt->execute($dataToInsert);

$pdo->commit();

Convert array to string in NodeJS

In node, you can just say

console.log(aa)

and it will format it as it should.

If you need to use the resulting string you should use

JSON.stringify(aa)

Retrieving parameters from a URL

I didn't want to mess with additional libraries. Simple ways suggested here didn't work out either. Finally, not on the request object, but I could get a GET parameter w/o all that hassle via self.GET.get('XXX'):

...
def get_context_data(self, **kwargs):
    context = super(SomeView, self).get_context_data(**kwargs)
    context['XXX'] = self.GET.get('XXX')
...

Python 2.7.18, Django 1.11.20

Input Type image submit form value?

well if i was in your place i would do this.I would have an hidden field and based on the input image field i would change the hidden field value(jQuery), and then finally submit the hidden field whose value reflects the image field.

How to get substring in C

If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

strncpy(sub1, baseString, 4);
strncpy(sub1, baseString+4, 4);
strncpy(sub1, baseString+8, 4);

or

for(int i=0; i<4; i++)
    sub1[i] = baseString[i];
sub1[4] = 0;
for(int i=0; i<4; i++)
    sub2[i] = baseString[i+4];
sub2[4] = 0;
for(int i=0; i<4; i++)
    sub3[i] = baseString[i+8];
sub3[4] = 0;

Prefer strncpy if possible.

How to get keyboard input in pygame?

To slow down your game, use pygame.clock.tick(10)

Can't use modulus on doubles?

You can implement your own modulus function to do that for you:

double dmod(double x, double y) {
    return x - (int)(x/y) * y;
}

Then you can simply use dmod(6.3, 2) to get the remainder, 0.3.

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

I've got the same problem, and what worked for me is in THIS OTHER ANSWER.

I didn't replicated it here because it is NOT A CORRECT THING TO DO.

Basically is a re-install being sure to delete everything very well and using 32 bit versions.

Serializing a list to JSON

.NET already supports basic Json serialization through the System.Runtime.Serialization.Json namespace and the DataContractJsonSerializer class since version 3.5. As the name implies, DataContractJsonSerializer takes into account any data annotations you add to your objects to create the final Json output.

That can be handy if you already have annotated data classes that you want to serialize Json to a stream, as described in How To: Serialize and Deserialize JSON Data. There are limitations but it's good enough and fast enough if you have basic needs and don't want to add Yet Another Library to your project.

The following code serializea a list to the console output stream. As you see it is a bit more verbose than Json.NET and not type-safe (ie no generics)

        var list = new List<string> {"a", "b", "c", "d"};

        using(var output = Console.OpenStandardOutput())                
        {                
            var writer = new DataContractJsonSerializer(typeof (List<string>));
            writer.WriteObject(output,list);
        }

On the other hand, Json.NET provides much better control over how you generate Json. This will come in VERY handy when you have to map javascript-friendly names names to .NET classes, format dates to json etc.

Another option is ServiceStack.Text, part of the ServicStack ... stack, which provides a set of very fast serializers for Json, JSV and CSV.

Convert time span value to format "hh:mm Am/Pm" using C#

Parse timespan to DateTime and then use Format ("hh:mm:tt"). For example.

TimeSpan ts = new TimeSpan(16, 00, 00);
DateTime dtTemp = DateTime.ParseExact(ts.ToString(), "HH:mm:ss", CultureInfo.InvariantCulture);
string str = dtTemp.ToString("hh:mm tt");

str will be:

str = "04:00 PM"

Launch Bootstrap Modal on page load

Like others have mentioned, create your modal with display:block

<div class="modal in" tabindex="-1" role="dialog" style="display:block">
...

Place the backdrop anywhere on your page, it does not necesarily need to be at the bottom of the page

<div class="modal-backdrop fade show"></div> 

Then, to be able to close the dialog again, add this

<script>
    $("button[data-dismiss=modal]").click(function () {
        $(".modal.in").removeClass("in").addClass("fade").hide();
        $(".modal-backdrop").remove();
    });
</script>

Hope this helps

sql searching multiple words in a string

Oracle SQL :

select * 
from MY_TABLE
where REGEXP_LIKE (company , 'Microsodt industry | goglge auto car | oracles    database')
  • company - is the database column name.
  • results - this SQL will show you if company column rows contain one of those companies (OR phrase) please note that : no wild characters are needed, it's built in.

more info at : http://www.techonthenet.com/oracle/regexp_like.php

Removing NA observations with dplyr::filter()

If someone is here in 2020, after making all the pipes, if u pipe %>% na.exclude will take away all the NAs in the pipe!

How to implement an android:background that doesn't stretch?

I had a background image, not big in size, but with weird dimensions - therefore the stretching and bad performance. I made a method with parameters Context, a View and a drawable ID(int) that will match the device screen size. Use this in e.g a Fragments onCreateView to set the background.

public void setBackground(Context context, View view, int drawableId){
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),drawableId);

    bitmap = Bitmap.createScaledBitmap(bitmap, Resources.getSystem().
             getDisplayMetrics().widthPixels,
             Resources.getSystem().getDisplayMetrics().heightPixels,
             true);

    BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), 
                                    bitmap);

    view.setBackground(bitmapDrawable);
}

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

Redis: How to access Redis log file

Check your error log file and then use the tail command as:

tail -200f /var/log/redis_6379.log

or

 tail -200f /var/log/redis.log

According to your error file name..

Getting the class of the element that fired an event using JQuery

Try:

$(document).ready(function() {
    $("a").click(function(event) {
       alert(event.target.id+" and "+$(event.target).attr('class'));
    });
});

Using querySelectorAll to retrieve direct children

I created a function to handle this situation, thought I would share it.

getDirectDecendent(elem, selector, all){
    const tempID = randomString(10) //use your randomString function here.
    elem.dataset.tempid = tempID;

    let returnObj;
    if(all)
        returnObj = elem.parentElement.querySelectorAll(`[data-tempid="${tempID}"] > ${selector}`);
    else
        returnObj = elem.parentElement.querySelector(`[data-tempid="${tempID}"] > ${selector}`);

    elem.dataset.tempid = '';
    return returnObj;
}

In essence what you are doing is generating a random-string (randomString function here is an imported npm module, but you can make your own.) then using that random string to guarantee that you get the element you are expecting in the selector. Then you are free to use the > after that.

The reason I am not using the id attribute is that the id attribute may already be used and I don't want to override that.

window.open target _self v window.location.href?

Definitely the second method is preferred because you don't have the overhead of another function invocation:

window.location.href = "webpage.htm";

Remove duplicate rows in MySQL

To Delete the duplicate record in a table.

delete from job s 
where rowid < any 
(select rowid from job k 
where s.site_id = k.site_id and 
s.title = k.title and 
s.company = k.company);

or

delete from job s 
where rowid not in 
(select max(rowid) from job k 
where s.site_id = k.site_id and
s.title = k.title and 
s.company = k.company);

git status (nothing to commit, working directory clean), however with changes commited

Small hint which other people didn't talk about: git doesn't record changes if you add empty folders in your project folder. That's it, I was adding empty folders with random names to check wether it was recording changes, it wasn't. But it started to do it as soon as I began adding files in them. Cheers.

Indentation shortcuts in Visual Studio

Just hit Tab to push it over or on the menu bar Edit --> Advanced --> Format Selection and that will auto indent, the keyboard shortcut is also shown in the menu.

How do I set hostname in docker-compose?

Based on docker documentation: https://docs.docker.com/compose/compose-file/#/command

I simply put hostname: <string> in my docker-compose file.

E.g.:

[...]

lb01:
  hostname: at-lb01
  image: at-client-base:v1

[...]

and container lb01 picks up at-lb01 as hostname.

Disabled form inputs do not appear in the request

Using Jquery and sending the data with ajax, you can solve your problem:

<script>

$('#form_id').submit(function() {
    $("#input_disabled_id").prop('disabled', false);

    //Rest of code
    })
</script>

SQL Select between dates

Change your data to that formats to use sqlite datetime formats.

YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD

SELECT * FROM test WHERE date BETWEEN '2011-01-11' AND '2011-08-11'

How do I run a Python program in the Command Prompt in Windows 7?

All the steps you have performed are correct, except one step, instead creating one separate variable, try below steps.

  1. Search for python.exe file, find the parent folder.
  2. Copy the folder path like on which python installation files resides
  3. Now go to the control panel-system-advanced settings-environment variables
  4. Find Path variable paste the copied folder path here and add ;
  5. Now all set for the execution goto cmd type python you must see the version details

RequiredIf Conditional Validation Attribute

I got it to work on ASP.NET MVC 5

I saw many people interested in and suffering from this code and i know it's really confusing and disrupting for the first time.

Notes

  • worked on MVC 5 on both server and client side :D
  • I didn't install "ExpressiveAnnotations" library at all.
  • I'm taking about the Original code from "@Dan Hunex", Find him above

Tips To Fix This Error

"The type System.Web.Mvc.RequiredAttributeAdapter must have a public constructor which accepts three parameters of types System.Web.Mvc.ModelMetadata, System.Web.Mvc.ControllerContext, and ExpressiveAnnotations.Attributes.RequiredIfAttribute Parameter name: adapterType"

Tip #1: make sure that you're inheriting from 'ValidationAttribute' not from 'RequiredAttribute'

 public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { ...}

Tip #2: OR remove this entire line from 'Global.asax', It is not needed at all in the newer version of the code (after edit by @Dan_Hunex), and yes this line was a must in the old version ...

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredAttributeAdapter));

Tips To Get The Javascript Code Part Work

1- put the code in a new js file (ex:requiredIfValidator.js)

2- warp the code inside a $(document).ready(function(){........});

3- include our js file after including the JQuery validation libraries, So it look like this now :

@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>

4- Edit the C# code

from

rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);

to

rule.ValidationParameters["dependentproperty"] = PropertyName;

and from

if (dependentValue.ToString() == DesiredValue.ToString())

to

if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())

My Entire Code Up and Running

Global.asax

Nothing to add here, keep it clean

requiredIfValidator.js

create this file in ~/content or in ~/scripts folder

    $.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options)
{
    options.rules['requiredif'] = options.params;
    options.messages['requiredif'] = options.message;
});


$(document).ready(function ()
{

    $.validator.addMethod('requiredif', function (value, element, parameters) {
        var desiredvalue = parameters.desiredvalue;
        desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
        var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
        var actualvalue = {}
        if (controlType == "checkbox" || controlType == "radio") {
            var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
            actualvalue = control.val();
        } else {
            actualvalue = $("#" + parameters.dependentproperty).val();
        }
        if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
            var isValid = $.validator.methods.required.call(this, value, element, parameters);
            return isValid;
        }
        return true;
    });
});

_Layout.cshtml or the View

@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>

RequiredIfAttribute.cs Class

create it some where in your project, For example in ~/models/customValidation/

    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Your_Project_Name.Models.CustomValidation
{
    public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    {
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }
        private readonly RequiredAttribute _innerAttribute;

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
        {
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
            _innerAttribute = new RequiredAttribute();
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

            if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "requiredif",
            };
            rule.ValidationParameters["dependentproperty"] = PropertyName;
            rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

            yield return rule;
        }
    }
}

The Model

    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Your_Project_Name.Models.CustomValidation;

namespace Your_Project_Name.Models.ViewModels
{

    public class CreateOpenActivity
    {
        public Nullable<int> ORG_BY_CD { get; set; }

        [RequiredIf("ORG_BY_CD", "5", ErrorMessage = "Coordinator ID is required")] // This means: IF 'ORG_BY_CD' is equal 5 (for the example)  > make 'COR_CI_ID_NUM' required and apply its all validation / data annotations
        [RegularExpression("[0-9]+", ErrorMessage = "Enter Numbers Only")]
        [MaxLength(9, ErrorMessage = "Enter a valid ID Number")]
        [MinLength(9, ErrorMessage = "Enter a valid ID Number")]
        public string COR_CI_ID_NUM { get; set; }
    }
}

The View

Nothing to note here actually ...

    @model Your_Project_Name.Models.ViewModels.CreateOpenActivity
@{
    ViewBag.Title = "Testing";
}

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>CreateOpenActivity</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.ORG_BY_CD, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ORG_BY_CD, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ORG_BY_CD, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.COR_CI_ID_NUM, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.COR_CI_ID_NUM, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.COR_CI_ID_NUM, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

I may upload a project sample for this later ...

Hope this was helpful

Thank You

How to get overall CPU usage (e.g. 57%) on Linux

Take a look at cat /proc/stat

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

Python strptime() and timezones?

The datetime module documentation says:

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.

Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.

It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:

When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.

Note that this doesn't work with %Z, so the case is important. See the following example:

In [1]: from datetime import datetime

In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')

In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None

In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')

In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

I tried all the above and it did not work.

I found that in spite of uninstalling the app a new version of the app still gives the same error.

This is what solved it: go to Settings -> General -> application Manager -> choose your app -> click on the three dots on the top -> uninstall for all users

Once you do this, now it is actually uninstalled and will now allow your new version to install.

Hope this helps.

How can I disable all views inside the layout?

Actully what work for me is:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

and to undo it:

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

How to see which flags -march=native will activate?

You can use the -Q --help=target options:

gcc -march=native -Q --help=target ...

The -v option may also be of use.

You can see the documentation on the --help option here.

Spring cron expression for every after 30 minutes

<property name="cronExpression" value="0 0/30 * * * ?" />

Spark - Error "A master URL must be set in your configuration" when submitting an app

try this

make trait

import org.apache.spark.sql.SparkSession
trait SparkSessionWrapper {
   lazy val spark:SparkSession = {
      SparkSession
        .builder()
        .getOrCreate()
    }
}

extends it

object Preprocess extends SparkSessionWrapper {

How to auto adjust the <div> height according to content in it?

simply set the height to auto, that should fix the problem, because div are block elements so they stretch out to full width and height of any element contained in it. if height set to auto not working then simple don't add the height, it should adjust and make sure that the div is not inheriting any height from it's parent element as well...

Spring Boot @Value Properties

Your problem is that you need a static PropertySourcesPlaceholderConfigurer Bean definition in your configuration. I say static with emphasis, because I had a non-static one and it didn't work.

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

Show an image preview before upload

_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
    var files = evt.target.files;_x000D_
_x000D_
    // Loop through the FileList and render image files as thumbnails._x000D_
    for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
      // Only process image files._x000D_
      if (!f.type.match('image.*')) {_x000D_
        continue;_x000D_
      }_x000D_
_x000D_
      var reader = new FileReader();_x000D_
_x000D_
      // Closure to capture the file information._x000D_
      reader.onload = (function(theFile) {_x000D_
        return function(e) {_x000D_
          // Render thumbnail._x000D_
          var span = document.createElement('span');_x000D_
          span.innerHTML = _x000D_
          [_x000D_
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
            e.target.result,_x000D_
            '" title="', escape(theFile.name), _x000D_
            '"/>'_x000D_
          ].join('');_x000D_
          _x000D_
          document.getElementById('list').insertBefore(span, null);_x000D_
        };_x000D_
      })(f);_x000D_
_x000D_
      // Read in the image file as a data URL._x000D_
      reader.readAsDataURL(f);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
_x000D_
_x000D_

Creating a new ArrayList in Java

If you just want a list:

ArrayList<Class> myList = new ArrayList<Class>();

If you want an arraylist of a certain length (in this case size 10):

List<Class> myList = new ArrayList<Class>(10);

If you want to program against the interfaces (better for abstractions reasons):

List<Class> myList = new ArrayList<Class>();

Programming against interfaces is considered better because it's more abstract. You can change your Arraylist with a different list implementation (like a LinkedList) and the rest of your application doesn't need any changes.

Change background position with jQuery

You guys are complicating things. You can simple do this from CSS.

#carousel li { background-position:0px 0px; }
#carousel li:hover { background-position:100px 0px; }