Programs & Examples On #Waitone

How to wait for a JavaScript Promise to resolve before resuming function?

Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.

Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).

_x000D_
_x000D_
function append_output(suffix, value) {
  $("#output_"+suffix).append(value)
}

function kickOff() {
  let start = new Promise((resolve, reject) => {
    append_output("now", "start")
    resolve("start")
  })
  let middle = new Promise((resolve, reject) => {
    setTimeout(() => {
      append_output("now", " middle")
      resolve(" middle")
    }, 1000)
  })
  let end = new Promise((resolve, reject) => {
    append_output("now", " end")
    resolve(" end")
  })

  Promise.all([start, middle, end]).then(results => {
    results.forEach(
      result => append_output("later", result))
  })
}

kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
_x000D_
_x000D_

How to resolve this System.IO.FileNotFoundException

I've been mislead by this error more than once. After spending hours googling, updating nuget packages, version checking, then after sitting with a completely updated solution I re-realize a perfectly valid, simpler reason for the error.

If in a threaded enthronement (UI Dispatcher.Invoke for example), System.IO.FileNotFoundException is thrown if the thread manager dll (file) fails to return. So if your main UI thread A, calls the system thread manager dll B, and B calls your thread code C, but C throws for some unrelated reason (such as null Reference as in my case), then C does not return, B does not return, and A only blames B with FileNotFoundException for being lost...

Before going down the dll version path... Check closer to home and verify your thread code is not throwing.

UTF-8 output from PowerShell

Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error

fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported

I solved the problem by changing the line that generated the output file from:

out-file -FilePath GITVersion.h -InputObject $result

to:

out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result

How to increase size of DOSBox window?

  • go to dosbox installation directory (on my machine that is C:\Program Files (x86)\DOSBox-0.74 ) as you see the version number is part of the installation directory name.

  • run "DOSBox 0.74 Options.bat"

  • the script starts notepad with configuration file: here change

    windowresolution=1600x800

    output=ddraw

(the resolution can't be changed if output=surface - that's the default).

  • safe configuration file changes.

Visual Studio debugging/loading very slow

As title says, VS debugging is slow. I can't find my problem, so post it here, may be it helps someone.

In my case slow debugging was on the website hosted in IIS.

  • VS 2019 (16.4.4)
  • VS 2017 (15.9.19)
  • Windows 10 (1909)
  • IIS (10.0.18362.1)
  • Edge (44.18362.449.0)

At first time after site loading it works fine, but after 1+ minute it become lagging. Requests are pending for 1-2 minutes (F12 network tab) before my breakpoints can handle them. It was in all my active browsers.

Solution: Do not use Edge with IIS while debugging.

To understand where the problem i spent about 4-5 hours. I used Edge + Chrome for my workflow. For now i use only Chrome (with separated user profiles).

Link that helped me: https://answers.microsoft.com/en-us/windows/forum/all/iis-running-very-slowly-after-windows-10-upgrade/dae433ba-4efe-45ab-aa66-824e6fa92b51 "J Marcos" answer.

Why am I getting "Thread was being aborted" in ASP.NET?

ASP.NET spawns and kills worker processes all the time as needed. Your thread may just be getting shut down by ASP.NET.

Old Answer:

Known issue: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Response.Redirect ("bla.aspx", false);

or

try
{
    Response.Redirect("bla.aspx");
}
catch (ThreadAbortException ex)
{
}

Creating a blocking Queue<T> in .NET?

Starting with .NET 5.0/Core 3.0 you can use System.Threading.Channels
Benchmarks from this (Asynchronous Producer Consumer Pattern in .NET (C#)) article show a significant speed boost over BlockingCollection!

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Yes. This is absolutely correct.

You could see ManualResetEvent as a way to indicate state. Something is on (Set) or off (Reset). An occurrence with some duration. Any thread waiting for that state to happen can proceed.

An AutoResetEvent is more comparable to a signal. A one shot indication that something has happened. An occurrence without any duration. Typically but not necessarily the "something" that has happened is small and needs to be handled by a single thread - hence the automatic reset after a single thread have consumed the event.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Center fixed div with dynamic width (CSS)

This approach will not limit element's width when using margins in flexbox

top: 0; left: 0;
transform: translate(calc(50vw - 50%));

Also for centering it vertically

top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

get and set in TypeScript

TS offers getters and setters which allow object properties to have more control of how they are accessed (getter) or updated (setter) outside of the object. Instead of directly accessing or updating the property a proxy function is called.

Example:

class Person {
    constructor(name: string) {
        this._name = name;
    }

    private _name: string;

    get name() {
        return this._name;
    }

    // first checks the length of the name and then updates the name.
    set name(name: string) {
        if (name.length > 10) {
            throw new Error("Name has a max length of 10");
        }

        this._name = name;  
    }

    doStuff () {
        this._name = 'foofooooooofoooo';
    }


}

const person = new Person('Willem');

// doesn't throw error, setter function not called within the object method when this._name is changed
person.doStuff();  

// throws error because setter is called and name is longer than 10 characters
person.name = 'barbarbarbarbarbar';  

Adding timestamp to a filename with mv in BASH

Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's logrotate

How to match all occurrences of a regex

You can use string.scan(your_regex).flatten. If your regex contains groups, it will return in a single plain array.

string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"
your_regex = /(\d+)[m-t]/
string.scan(your_regex).flatten
=> ["54", "1", "3"]

Regex can be a named group as well.

string = 'group_photo.jpg'
regex = /\A(?<name>.*)\.(?<ext>.*)\z/
string.scan(regex).flatten

You can also use gsub, it's just one more way if you want MatchData.

str.gsub(/\d/).map{ Regexp.last_match }

Missing maven .m2 folder

Is there some command to create this folder?

If smb face this issue again, you should know the most simple way to create .m2 folder.
If you unzipped maven and set up maven path variable - just try mvn clean command from anywhere you like!
Dont be afraid of error messages when running - it works and creates needed directory.

Filtering a data frame by values in a column

The subset command is not necessary. Just use data frame indexing

studentdata[studentdata$Drink == 'water',]

Read the warning from ?subset

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like ‘[’, and in particular the non-standard evaluation of argument ‘subset’ can have unanticipated consequences.

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

August 2019

In my case I wanted to use a Swift protocol in an Objective-C header file that comes from the same target and for this I needed to use a forward declaration of the Swift protocol to reference it in the Objective-C interface. The same should be valid for using a Swift class in an Objective-C header file. To use forward declaration see the following example from the docs at Include Swift Classes in Objective-C Headers Using Forward Declarations:

// MyObjcClass.h
@class MySwiftClass; // class forward declaration
@protocol MySwiftProtocol; // protocol forward declaration

@interface MyObjcClass : NSObject
- (MySwiftClass *)returnSwiftClassInstance;
- (id <MySwiftProtocol>)returnInstanceAdoptingSwiftProtocol;
// ...
@end

Return a value if no rows are found in Microsoft tSQL

This Might be one way.

SELECT TOP 1 [Column Name] FROM (SELECT [Column Name] FROM [table]
    WHERE [conditions]
    UNION ALL
    SELECT 0 )A ORDER BY [Column Name] DESC

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

How to get the body's content of an iframe in Javascript?

Chalkey is correct, you need to use the src attribute to specify the page to be contained in the iframe. Providing you do this, and the document in the iframe is in the same domain as the parent document, you can use this:

var e = document.getElementById("id_description_iframe");
if(e != null) {
   alert(e.contentWindow.document.body.innerHTML);
}

Obviously you can then do something useful with the contents instead of just putting them in an alert.

SQL Column definition : default value and not null redundant?

Even with a default value, you can always override the column data with null.

The NOT NULL restriction won't let you update that row after it was created with null value

How to use BigInteger?

Yes it's Immutable

sum.add(BigInteger.valueOf(i));

so the method add() of BigInteger class does not add new BigIntger value to its own value ,but creates and returns a new BigInteger reference without changing the current BigInteger and this is what done even in the case of Strings

Plotting images side by side using matplotlib

One thing that I found quite helpful to use to print all images :

_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
    ax.imshow(img)
plt.show()

How to search for a string in cell array in MATLAB?

Other answers are probably simpler for this case, but for completeness I thought I would add the use of cellfun with an anonymous function

indices = find(cellfun(@(x) strcmp(x,'KU'), strs))

which has the advantage that you can easily make it case insensitive or use it in cases where you have cell array of structures:

indices = find(cellfun(@(x) strcmpi(x.stringfield,'KU'), strs))

How does one check if a table exists in an Android SQLite database?

i faced that and deal with it by try catch as simple as that i do what i want in table if it not exist will cause error so catch it by exceptions and create it :)

SQLiteDatabase db=this.getWritableDatabase();
        try{
            db.execSQL("INSERT INTO o_vacations SELECT * FROM vacations");
            db.execSQL("DELETE FROM vacations");
        }catch (SQLiteException e){
            db.execSQL("create table o_vacations (id integer primary key ,name text ,vacation text,date text,MONTH text)");
            db.execSQL("INSERT INTO o_vacations SELECT * FROM vacations");
            db.execSQL("DELETE FROM vacations");
        }

c# open a new form then close the current form?

I would solve it by doing:

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

Find object by id in an array of JavaScript objects

Another solution is to create a lookup object:

var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
    lookup[array[i].id] = array[i];
}

... now you can use lookup[id]...

This is especially interesting if you need to do many lookups.

This won't need much more memory since the IDs and objects will be shared.

What is Node.js?

I think the advantages are:

  1. Web development in a dynamic language (JavaScript) on a VM that is incredibly fast (V8). It is much faster than Ruby, Python, or Perl.

  2. Ability to handle thousands of concurrent connections with minimal overhead on a single process.

  3. JavaScript is perfect for event loops with first class function objects and closures. People already know how to use it this way having used it in the browser to respond to user initiated events.

  4. A lot of people already know JavaScript, even people who do not claim to be programmers. It is arguably the most popular programming language.

  5. Using JavaScript on a web server as well as the browser reduces the impedance mismatch between the two programming environments which can communicate data structures via JSON that work the same on both sides of the equation. Duplicate form validation code can be shared between server and client, etc.

Oracle: How to find out if there is a transaction pending?

Matthew Watson can be modified to be used in RAC

select t.inst_id 
       ,s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from gv$transaction t
inner join gv$session s on t.addr = s.taddr;

Saving a select count(*) value to an integer (SQL Server)

Declare @MyInt int
Set @MyInt = ( Select Count(*) From MyTable )

If @MyInt > 0
Begin
    Print 'There''s something in the table'
End

I'm not sure if this is your issue, but you have to esacpe the single quote in the print statement with a second single quote. While you can use SELECT to populate the variable, using SET as you have done here is just fine and clearer IMO. In addition, you can be guaranteed that Count(*) will never return a negative value so you need only check whether it is greater than zero.

What is the default access specifier in Java?

There is an access modifier called "default" in JAVA, which allows direct instance creation of that entity only within that package.

Here is a useful link:

Java Access Modifiers/Specifiers

Provide static IP to docker containers via docker-compose

I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as

KAPACITOR_BASE_URL:  http://kapacitor:9092

In above http://[**kapacitor**]:9092 would not resolve to http://172.20.0.2:9092

I resolved the static IPs issues using subnetting configurations.

version: "3.3"

networks:
  frontend:
    ipam:
      config:
        - subnet: 172.20.0.0/24
services:
    db:
        image: postgres:9.4.4
        networks:
            frontend:
                ipv4_address: 172.20.0.5
        ports:
            - "5432:5432"
        volumes:
            - postgres_data:/var/lib/postgresql/data

    redis:
        image: redis:latest
        networks:
            frontend:
                ipv4_address: 172.20.0.6
        ports:
            - "6379"

    influxdb:
        image: influxdb:latest
        ports:
            - "8086:8086"
            - "8083:8083"
        volumes:
            - ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
            - ../influxdb/inxdb:/var/lib/influxdb
        networks:
            frontend:
                ipv4_address: 172.20.0.4
        environment:
          INFLUXDB_HTTP_AUTH_ENABLED: "false"
          INFLUXDB_ADMIN_ENABLED: "true"
          INFLUXDB_USERNAME: "db_username"
          INFLUXDB_PASSWORD: "12345678"
          INFLUXDB_DB: db_customers

    kapacitor:
        image: kapacitor:latest
        ports: 
            - "9092:9092"
        networks:
            frontend:
                ipv4_address: 172.20.0.2
        depends_on:
            - influxdb
        volumes:
            - ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
            - ../kapacitor/kapdb:/var/lib/kapacitor
        environment:
          KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086

    web:
        build: .
        environment:
          RAILS_ENV: $RAILS_ENV
        command: bundle exec rails s -b 0.0.0.0
        ports:
            - "3000:3000"
        networks:
            frontend:
                ipv4_address: 172.20.0.3
        links:
            - db
            - kapacitor
        depends_on:
            - db
        volumes:
            - .:/var/app/current
        environment:
          DATABASE_URL: postgres://postgres@db
          DATABASE_USERNAME: postgres
          DATABASE_PASSWORD: postgres
          INFLUX_URL: http://influxdb:8086
          INFLUX_USER: db_username
          INFLUX_PWD: 12345678
          KAPACITOR_BASE_URL:  http://172.20.0.2:9092
          KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000

volumes:
  postgres_data:

Good tutorial for using HTML5 History API (Pushstate?)

For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, History.js provides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).

You can read more about History.js here: https://github.com/browserstate/history.js

For an article about Hashbangs VS Hashes VS HTML5 History API, see here: https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling

Python | change text color in shell

Use Curses or ANSI escape sequences. Before you start spouting escape sequences, you should check that stdout is a tty. You can do this with sys.stdout.isatty(). Here's a function pulled from a project of mine that prints output in red or green, depending on the status, using ANSI escape sequences:

def hilite(string, status, bold):
    attr = []
    if status:
        # green
        attr.append('32')
    else:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)

SQL: How do I SELECT only the rows with a unique value on certain column?

Utilizing the "dynamic table" capability in SQL Server (querying against a parenthesis-surrounded query), you can return 2000, 49 w/ the following. If your platform doesn't offer an equivalent to the "dynamic table" ANSI-extention, you can always utilize a temp table in two-steps/statement by inserting the results within the "dynamic table" to a temp table, and then performing a subsequent select on the temp table.

DECLARE  @T TABLE(
    [contract] INT,
    project INT,
    activity INT
)

INSERT INTO @T VALUES( 1000,    8000,    10 )
INSERT INTO @T VALUES( 1000,    8000,    20 )
INSERT INTO @T VALUES( 1000,    8001,    10 )
INSERT INTO @T VALUES( 2000,    9000,    49 )
INSERT INTO @T VALUES( 2000,    9001,    49 )
INSERT INTO @T VALUES( 3000,    9000,    79 )
INSERT INTO @T VALUES( 3000,    9000,    78 )

SELECT
    [contract],
    [Activity] =  max (activity)
FROM
    (
    SELECT
        [contract],
        [Activity]
    FROM
        @T
    GROUP BY
        [contract],
        [Activity]
    ) t
GROUP BY
    [contract]
HAVING count (*) = 1

How to jQuery clone() and change id?

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

How to calculate md5 hash of a file using javascript

I've made a library that implements incremental md5 in order to hash large files efficiently. Basically you read a file in chunks (to keep memory low) and hash it incrementally. You got basic usage and examples in the readme.

Be aware that you need HTML5 FileAPI, so be sure to check for it. There is a full example in the test folder.

https://github.com/satazor/SparkMD5

How to change column width in DataGridView?

You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):

dataGridView1.Columns[1].Width = 108;  // or whatever width works well for abbrev
dataGridView1.Columns[2].Width = 
    dataGridView1.Width 
    - dataGridView1.Columns[0].Width 
    - dataGridView1.Columns[1].Width 
    - 72;  // this is an extra "margin" number of pixels

If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize event handler of the DataGridView.

Creating C formatted strings (not printing them)

Don't use sprintf.
It will overflow your String-Buffer and crash your Program.
Always use snprintf

Is there any way to have a fieldset width only be as wide as the controls in them?

try this

<fieldset>
   <legend style="max-width: max-content;" >Blah</legend>
</fieldset>

Changing the image source using jQuery

Change the image source using jQuery click()

element:

    <img class="letstalk btn"  src="images/chatbuble.png" />

code:

    $(".letstalk").click(function(){
        var newsrc;
        if($(this).attr("src")=="/images/chatbuble.png")
        {
            newsrc="/images/closechat.png";
            $(this).attr("src", newsrc);
        }
        else
        {
            newsrc="/images/chatbuble.png";
            $(this).attr("src", newsrc);
        }
    });

Rewrite URL after redirecting 404 error htaccess

Try adding this rule to the top of your htaccess:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]

Then under that (or any other rules that you have):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://domain.com/404/ [L,R]

Retrieve the position (X,Y) of an HTML element relative to the browser window

Difference between small and little

function getPosition( el ) {
    var x = 0;
    var y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
    x += el.offsetLeft - el.scrollLeft;
    y += el.offsetTop - el.scrollTop;
    el = el.offsetParent;
    }
    return { top: y, left: x };
}

Look a example coordinates: http://javascript.info/tutorial/coordinates

Avoid web.config inheritance in child web application using inheritInChildApplications

We were getting an error related to this after a recent release of code to one of our development environments. We have an application that is a child of another application. This relationship has been working fine for YEARS until yesterday.

The problem:
We were getting a yellow stack trace error due to duplicate keys being entered. This is because both the web.config for the child and parent applications had this key. But this existed for many years like this without change. Why all of sudden its an issue now?

The solution:
The reason this was never a problem is because the keys AND values were always the same. Yesterday we updated our SQL connection strings to include the Application Name in the connection string. This made the string unique and all of sudden started to fail.

Without doing any research on the exact reason for this, I have to assume that when the child application inherits the parents web.config values, it ignores identical key/value pairs.

We were able to solve it by wrapping the connection string like this

    <location path="." inheritInChildApplications="false">
        <connectionStrings>
            <!-- Updated connection strings go here -->
        </connectionStrings>
    </location>

Edit: I forgot to mention that I added this in the PARENTS web.config. I didn't have to modify the child's web.config.

Thanks for everyones help on this, saved our butts.

How do I get the opposite (negation) of a Boolean in Python?

If you are trying to implement a toggle, so that anytime you re-run a persistent code its being negated, you can achieve that as following:

try:
    toggle = not toggle
except NameError:
    toggle = True

Running this code will first set the toggle to True and anytime this snippet ist called, toggle will be negated.

How to use the TextWatcher class in Android?

For use of the TextWatcher...

et1.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {

        // TODO Auto-generated method stub
    }
});

How to set a default value for an existing column

ALTER TABLE [dbo].[Employee] ADD  DEFAULT ('N') FOR [CityBorn]

SQL Server principal "dbo" does not exist,

Under Security, add the principal as a "SQL user without login", make it own the schema with the same name as the principal and then in Membership make it db_owner.

Disabling submit button until all fields have values

Check out this jsfiddle.

HTML

// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />

JavaScript

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup() which I think makes it more convenient for usability.

HTML favicon won't show on google chrome

Note if you have so many tabs open that Google Chrome is only showing the favicons then Google Chrome won't show the favicon for the selected tab, so if you keep reloading the tab with your page loaded in order to see your new favicon you will only see the text of your page's title.

You will need to reload your page, and then select a different tab in order to see your favicon.

enter image description here

Strip Leading and Trailing Spaces From Java String

trim() is your choice, but if you want to use replace method -- which might be more flexiable, you can try the following:

String stripppedString = myString.replaceAll("(^ )|( $)", "");

Java: int[] array vs int array[]

They are both basically same, there is no difference in performance of any sort, the recommended one however is the first case as it is more readable.

int[] array = new int[10];

FROM JLS:

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

Python str vs unicode types

Unicode and encodings are completely different, unrelated things.

Unicode

Assigns a numeric ID to each character:

  • 0x41 ? A
  • 0xE1 ? á
  • 0x414 ? ?

So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.

Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.

You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.

These numbers assigned to all characters by Unicode are called code points.

The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?

Note that Unicode code points are usually formatted with a leading U+, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.

Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).

The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.

Encodings

Map characters to bit patterns.

These bit patterns are used to represent the characters in computer memory or on disk.

There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:

ASCII

Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.

Example:

  • a ? 1100001 (0x61)

You can see all the mappings in this table.

ISO 8859-1 (aka Latin-1)

Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.

Example:

  • a ? 01100001 (0x61)
  • á ? 11100001 (0xE1)

You can see all the mappings in this table.

UTF-8

Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).

Example:

  • a ? 01100001 (0x61)
  • á ? 11000011 10100001 (0xC3 0xA1)
  • ? ? 11100010 10001001 10100000 (0xE2 0x89 0xA0)
  • ? 11110000 10011111 10011000 10000010 (0xF0 0x9F 0x98 0x82)

The way UTF-8 encodes characters to bit strings is very well described here.

Unicode and Encodings

Looking at the above examples, it becomes clear how Unicode is useful.

For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:

"I encode that a with an aigu (or however you call that rising bar) as 11100001"

But I can just say:

"I encode U+00E1 as 11100001"

And if I'm UTF-8, I can say:

"Me, in turn, I encode U+00E1 as 11000011 10100001"

And it's unambiguously clear to everybody which character we mean.

Now to the often arising confusion

It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.

For example:

  • ASCII encodes a as 1100001, which you can interpret as the hexadecimal number 0x61, and the Unicode code point of a is U+0061.
  • Latin-1 encodes á as 11100001, which you can interpret as the hexadecimal number 0xE1, and the Unicode code point of á is U+00E1.

Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.

Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.

Back to your question

The encoding used by your Python interpreter is UTF-8.

Here's what's going on in your examples:

Example 1

The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a.

>>> a = 'á'

When you look at the value of a, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1':

>>> a
'\xc3\xa1'

Example 2

The following saves the Unicode code point of á, which is U+00E1, in the variable ua (we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):

>>> ua = u'á'

When you look at the value of ua, Python tells you that it contains the code point U+00E1:

>>> ua
u'\xe1'

Example 3

The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:

>>> ua.encode('utf-8')
'\xc3\xa1'

Example 4

The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:

>>> ua.encode('latin1')
'\xe1'

There's no relation between the Unicode object ua and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.

Changing a specific column name in pandas DataFrame

Following short code can help:

df3 = df3.rename(columns={c: c.replace(' ', '') for c in df3.columns})

Remove spaces from columns.

How do you build a Singleton in Dart?

This is also a way to create a Singleton class

class Singleton{
  Singleton._();
  static final Singleton db = Singleton._();
}

Error 1053 the service did not respond to the start or control request in a timely fashion

open the services window as administrator,Then try to start the service.That worked for me.

compareTo() vs. equals()

equals() can be more efficient then compareTo().

A very important difference between compareTo and equals:

"myString".compareTo(null);  //Throws java.lang.NullPointerException
"myString".equals(null);     //Returns false

equals() checks if two objects are the same or not and returns a boolean.

compareTo() (from interface Comparable) returns an integer. It checks which of the two objects is "less than", "equal to" or "greater than" the other. Not all objects can be logically ordered, so a compareTo() method doesn't always make sense.

Note that equals() doesn't define the ordering between objects, which compareTo() does.

Now I advise you to review the source code of both methods to conclude that equals is preferable over compareTo that involves some Math calculations.

php_network_getaddresses: getaddrinfo failed: Name or service not known

You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.

If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.

If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:

$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n"); 

That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.

Convert a dataframe to a vector (by rows)

c(df$x, df$y)
# returns: 26 21 20 34 29 28

if the particular order is important then:

M = as.matrix(df)
c(m[1,], c[2,], c[3,])
# returns 26 34 21 29 20 28 

Or more generally:

m = as.matrix(df)
q = c()
for (i in seq(1:nrow(m))){
  q = c(q, m[i,])
}

# returns 26 34 21 29 20 28

Single vs double quotes in JSON

It truly solved my problem using eval function.

single_quoted_dict_in_string = "{'key':'value', 'key2': 'value2'}"
desired_double_quoted_dict = eval(single_quoted_dict_in_string)
# Go ahead, now you can convert it into json easily
print(desired_double_quoted_dict)

How do you reverse a string in place in C or C++?

Read Kernighan and Ritchie

#include <string.h>

void reverse(char s[])
{
    int length = strlen(s) ;
    int c, i, j;

    for (i = 0, j = length - 1; i < j; i++, j--)
    {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

How to pass arguments to Shell Script through docker run

If you want to run it @build time :

CMD /bin/bash /file.sh arg1

if you want to run it @run time :

ENTRYPOINT ["/bin/bash"]
CMD ["/file.sh", "arg1"]

Then in the host shell

docker build -t test .
docker run -i -t test

Ansible: filter a list by its attributes

Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:

- debug:
    msg: "{% for address in network.addresses.private_man %}\
        {% if address.type == 'fixed' %}\
          {{ address.addr }}\
        {% endif %}\
      {% endfor %}"

Or if you prefer to put it all on one line:

- debug:
    msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"

Which returns:

ok: [localhost] => {
    "msg": "172.16.1.100"
}

Best practices for styling HTML emails

In addition to the answers posted here, make sure you read this article:

http://24ways.org/2009/rock-solid-html-emails

Pass a variable to a PHP script running from the command line

Just pass it as normal parameters and access it in PHP using the $argv array.

php myfile.php daily

and in myfile.php

$type = $argv[1];

AngularJS format JSON string output

Angular has a built-in filter for showing JSON

<pre>{{data | json}}</pre>

Note the use of the pre-tag to conserve whitespace and linebreaks

Demo:

_x000D_
_x000D_
angular.module('app', [])_x000D_
  .controller('Ctrl', ['$scope',_x000D_
    function($scope) {_x000D_
_x000D_
      $scope.data = {_x000D_
        a: 1,_x000D_
        b: 2,_x000D_
        c: {_x000D_
          d: "3"_x000D_
        },_x000D_
      };_x000D_
_x000D_
    }_x000D_
  ]);
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="app">_x000D_
_x000D_
  <head>_x000D_
    <script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>_x000D_
  </head>_x000D_
_x000D_
  <body ng-controller="Ctrl">_x000D_
    <pre>{{data | json}}</pre>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

There's also an angular.toJson method, but I haven't played around with that (Docs)

Adding +1 to a variable inside a function

points is not within the function's scope. You can grab a reference to the variable by using nonlocal:

points = 0
def test():
    nonlocal points
    points += 1

If points inside test() should refer to the outermost (module) scope, use global:

points = 0
def test():
    global points
    points += 1

Angular 5 Scroll to top on every Route click

There are some solutions, make sure to check them all :)


The router outlet will emit the activate event any time a new component is being instantiated, so we could use (activate) to scroll (for example) to the top:

app.component.html

<router-outlet (activate)="onActivate($event)" ></router-outlet>

app.component.ts

onActivate(event) {
    window.scroll(0,0);
    //or document.body.scrollTop = 0;
    //or document.querySelector('body').scrollTo(0,0)
    ...
}

Use, for exemple, this solution for a smooth scroll:

    onActivate(event) {
        let scrollToTop = window.setInterval(() => {
            let pos = window.pageYOffset;
            if (pos > 0) {
                window.scrollTo(0, pos - 20); // how far to scroll on each step
            } else {
                window.clearInterval(scrollToTop);
            }
        }, 16);
    }

If you wish to be selective, say not every component should trigger the scrolling, you can check it in an if statement like this:

onActivate(e) {
    if (e.constructor.name)==="login"{ // for example
            window.scroll(0,0);
    }
}

Since Angular6.1, we can also use { scrollPositionRestoration: 'enabled' } on eagerly loaded modules and it will be applied to all routes:

RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })

It will also do the smooth scrolling, already. However this has the inconvenient for doing it on every routing.


An other solution is to do the top scrolling on router animation. Add this in every transition where you want to scroll to the top:

query(':enter, :leave', style({ position: 'fixed' }), { optional: true }) 

How to write to a JSON file in the correct format

Require the JSON library, and use to_json.

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(tempHash.to_json)
end

Your temp.json file now looks like:

{"key_a":"val_a","key_b":"val_b"}

ERROR 2003 (HY000): Can't connect to MySQL server (111)

I had this same error and I didn't understand but I realized that my modem was using the same port as mysql. Well, I stop apache2.service by sudo systemctl stop apache2.service and restarted the xammp, sudo /opt/lampp/lampp start

Just maybe, if you were not using a password for mysql yet you had, 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES), then you have to pass an empty string as the password

How to get a float result by dividing two integer values using T-SQL?

Use this

select cast((1*1.00)/3 AS DECIMAL(16,2)) as Result

Here in this sql first convert to float or multiply by 1.00 .Which output will be a float number.Here i consider 2 decimal places. You can choose what you need.

How can I iterate over an enum?

#include <iostream>
#include <algorithm>

namespace MyEnum
{
  enum Type
  {
    a = 100,
    b = 220,
    c = -1
  };

  static const Type All[] = { a, b, c };
}

void fun( const MyEnum::Type e )
{
  std::cout << e << std::endl;
}

int main()
{
  // all
  for ( const auto e : MyEnum::All )
    fun( e );

  // some
  for ( const auto e : { MyEnum::a, MyEnum::b } )
    fun( e );

  // all
  std::for_each( std::begin( MyEnum::All ), std::end( MyEnum::All ), fun );

  return 0;
}

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

its happen when you try to delete the same object and then again update the same object use this after delete

session.clear();

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Compiling a java program into an executable

I would use GCJ (GNU Compiler for Java) in your situation. It's an AOT (ahead of time) compiler for Java, much like GCC is for C. Instead of interpreting code, or generating intermediate java code to be run at a later time by the Java VM, it generates machine code.

GCJ is available on almost any Linux system through its respective package manager (if available). After installation, the GCJ compiler should be added to the path so that it can be invoked through the terminal. If you're using Windows, you can download and install GCJ through Cygwin or MinGW.

I would strongly recommend, however, that you rewrite your source for another language that is meant to be compiled, such as C++. Java is meant to be a portable, interpreted language. Compiling it to machine code is completely against what the language was developed for.

Upgrading Node.js to latest version

Upgrading node.js to the latest version on Windows

  1. Install chocolatey if you haven't already: Installing Chocolatey

  2. From the command prompt, type

    cup nodejs

(which is equivalent to typing choco upgrade nodejs -- assumes you already have node installed)

NOTE: You may need to run cinst nodejs.install for chocolatey to register your existing installation. (thanks for the comment, @mikecheel)


Installing node.js on Windows

If you have never installed node, you can use chocolatey to do that as well. Install chocolatey (see step 1 above). Then from a command prompt, type:

cinst nodejs.install

Chocolatey Gallery Node JS (Install)


Installing a specific version of node on Windows with chocolatey

cinst nodejs.install -Version 0.10.26

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

... right now it happens only to the website I'm testing. I can't post it here because it's confidential.

Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use --secure-protocol=TLSv1. If this does not help check if you can access the site with openssl s_client -connect ... (probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ....

Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.

The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.

Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?

The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.

Installation of SQL Server Business Intelligence Development Studio

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

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Toggle Checkboxes on/off

jQuery("#checker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = true;
    });
});
jQuery("#dechecker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = false;
    });
});
jQuery("#checktoggler").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = !this.checked;
    });
});

;)

Custom Python list sorting

I know many have already posted some good answers. However I want to suggest one nice and easy method without importing any library.

l = [(2, 3), (3, 4), (2, 4)]
l.sort(key = lambda x: (-x[0], -x[1]) )
print(l)
l.sort(key = lambda x: (x[0], -x[1]) )
print(l)

Output will be

[(3, 4), (2, 4), (2, 3)]
[(2, 4), (2, 3), (3, 4)]

The output will be sorted based on the order of the parameters we provided in the tuple format

How to convert float number to Binary?

x = float(raw_input("enter number between 0 and 1: "))

p = 0
while ((2**p)*x) %1 != 0:
    p += 1
    # print p

    num = int (x * (2 ** p))
    # print num

    result = ''
    if num == 0:
        result = '0'
    while num > 0:
        result = str(num%2) + result
        num = num / 2

    for i in range (p - len(result)):
        result = '0' + result
    result = result[0:-p] + '.' + result[-p:]

print result #this will print result for the decimal portion

Adding a new value to an existing ENUM Type

Can't add a comment to the appropriate place, but ALTER TABLE foo ALTER COLUMN bar TYPE new_enum_type USING bar::text::new_enum_type with a default on the column failed. I had to:

ALTER table ALTER COLUMN bar DROP DEFAULT;

and then it worked.

Column standard deviation R

The general idea is to sweep the function across. You have many options, one is apply():

R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269
R> 

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

Android SDK Setup under Windows 7 Pro 64 bit

I managed to run the SDK Setup by adding the location of the Java JDK to the system path. so far so good.

How to "grep" for a filename instead of the contents of a file?

Example

find <path> -name *FileName*

From manual:

find -name pattern

Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories are removed, the file names considered for a match with -name will never include a slash, so "-name a/b" will never match anything (you probably need to use -path instead). The metacharacters ("*", "?", and "[]") match a "." at the start of the base name (this is a change in find- utils-4.2.2; see section STANDARDS CONFORMANCE below). To ignore a directory and the files under it, use -prune; see an example in the description of -path. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell.

How can I view an object with an alert()

you can use toSource method like this

alert(product.toSource());

return in for loop or outside loop

There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).

This will not mess up garbage collection in any way!!

The better way to do it is to set a boolean value, if you want to listen to him.

boolean flag = false;
for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind) {
        flag = true;
        break;
    }
}
return flag;

python max function using 'key' and lambda expression

Strongly simplified version of max:

def max(items, key=lambda x: x):
    current = item[0]
    for item in items:
        if key(item) > key(current):
            current = item
    return current

Regarding lambda:

>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5

>>> times_two = lambda x: 2*x
>>> times_two(2)
4

SQL Server: Best way to concatenate multiple columns?

Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT() function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.

An alternative:

SELECT '1'+'2'+'3'

This approach requires non-string values to be cast/converted to strings, as well as NULL handling via ISNULL() or COALESCE():

SELECT  ISNULL(CAST(Col1 AS VARCHAR(50)),'')
      + COALESCE(CONVERT(VARCHAR(50),Col2),'')

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

I was getting this error while was presenting controller after the user opens the deeplink. I know this isn't the best solution, but if you are in short time frame here is a quick fix - just wrap your code in asyncAfter:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: { [weak self] in
                                navigationController.present(signInCoordinator.baseController, animated: animated, completion: completion)
                            })

It will give time for your presenting controller to call viewDidAppear.

How to get current time with jQuery

jQuery.now() Returns: Number

Description: Return a number representing the current time.

This method does not accept any arguments.

The $.now() method is a shorthand for the number returned by the expression (new Date).getTime().

http://api.jquery.com/jQuery.now/

It's simple to use Javascript:

var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
console.log(time);

How to get a div to resize its height to fit container?

you would possibbly need to specify the height of container and then set the nav's height to 100%.

Edit: had a quick look around and it seems that the height property applies to the parents height so you will indeed need to set the containers height.

NB: setting the height of the body element to 100% only scales it to the height of the browser window. Any content which goeds over one page will not have the same background etc.

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

Ted, as you probably found out, you unfortunately can't do that on Android. Dialogs are modal, but asynchronous, and it will definitely disrupt the sequence you're trying to establish as you would have done on .NET (or Windows for that matter). You will have to twist your code around and break some logic that would have been very easy to follow based on your example.

Another very simple example is to save data in a file, only to find out that the file is already there and asking to overwrite it or not. Instead of displaying a dialog and having an if statement to act upon the result (Yes/No), you will have to use callbacks (called listeners in Java) and split your logic into several functions.

On Windows, when a dialog is shown, the message pump continues in the background (only the current message being processed is on hold), and that works just fine. That allows users to move your app and let is repaint while you're displaying a dialog box for example. WinMo supports synchronous modal dialogs, so does BlackBerry but just not Android.

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

You can disable sql_mode=only_full_group_by by some command you can try this by terminal or MySql IDE

mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

How to do an Integer.parseInt() for a decimal number?

String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;

The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense. A double or a float datatype can hold rational numbers.

The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.

int i = (int) 0.9999;

i will be zero.

PHP - how to create a newline character?

Use the PHP nl2br to get the newlines in a text string..

$text = "Manu is a good boy.(Enter)He can code well.

echo nl2br($text);

Result.

Manu is a good boy.

He can code well.

Best way to combine two or more byte arrays in C#

    public static byte[] Concat(params byte[][] arrays) {
        using (var mem = new MemoryStream(arrays.Sum(a => a.Length))) {
            foreach (var array in arrays) {
                mem.Write(array, 0, array.Length);
            }
            return mem.ToArray();
        }
    }

Celery Received unregistered task of type (run example)

The solution for me to add this line to /etc/default/celeryd

CELERYD_OPTS="-A tasks"

Because when I run these commands:

celery worker --loglevel=INFO
celery worker -A tasks --loglevel=INFO

Only the latter command was showing task names at all.

I have also tried adding CELERY_APP line /etc/default/celeryd but that didn't worked either.

CELERY_APP="tasks"

Select tableview row programmatically

From reference documentation:

Calling this method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor does it send UITableViewSelectionDidChangeNotification notifications to observers.

What I would do is:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self doSomethingWithRowAtIndexPath:indexPath];
}

And then, from where you wanted to call selectRowAtIndexPath, you instead call doSomethingWithRowAtIndexPath. On top of that, you can additionally also call selectRowAtIndexPath if you want the UI feedback to happen.

WPF Binding StringFormat Short Date String

Or use this for an English (or mix it up for custom) format:

StringFormat='{}{0:dd/MM/yyyy}'

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Why does Date.parse give incorrect results?

Use moment.js to parse dates:

var caseOne = moment("Jul 8, 2005", "MMM D, YYYY", true).toDate();
var caseTwo = moment("2005-07-08", "YYYY-MM-DD", true).toDate();

The 3rd argument determines strict parsing (available as of 2.3.0). Without it moment.js may also give incorrect results.

How to COUNT rows within EntityFramework without loading contents?

Use the ExecuteStoreQuery method of the entity context. This avoids downloading the entire result set and deserializing into objects to do a simple row count.

   int count;

    using (var db = new MyDatabase()){
      string sql = "SELECT COUNT(*) FROM MyTable where FkId = {0}";

      object[] myParams = {1};
      var cntQuery = db.ExecuteStoreQuery<int>(sql, myParams);

      count = cntQuery.First<int>();
    }

How to compare two JSON objects with the same elements in a different order equal?

Decode them and compare them as mgilson comment.

Order does not matter for dictionary as long as the keys, and values matches. (Dictionary has no order in Python)

>>> {'a': 1, 'b': 2} == {'b': 2, 'a': 1}
True

But order is important in list; sorting will solve the problem for the lists.

>>> [1, 2] == [2, 1]
False
>>> [1, 2] == sorted([2, 1])
True

>>> a = '{"errors": [{"error": "invalid", "field": "email"}, {"error": "required", "field": "name"}], "success": false}'
>>> b = '{"errors": [{"error": "required", "field": "name"}, {"error": "invalid", "field": "email"}], "success": false}'
>>> a, b = json.loads(a), json.loads(b)
>>> a['errors'].sort()
>>> b['errors'].sort()
>>> a == b
True

Above example will work for the JSON in the question. For general solution, see Zero Piraeus's answer.

How do I set a value in CKEditor with Javascript?

I have used the below code and it is working fine as describing->

CKEDITOR.instances.mail_msg.insertText(obj["template"]);

Here-> CKEDITOR ->Your editor Name, mail_msg -> Id of your textarea(to which u bind the ckeditor), obj["template"]->is the value that u want to bind

SQL server stored procedure return a table

I do this frequently using Table Types to ensure more consistency and simplify code. You can't technically return "a table", but you can return a result set and using INSERT INTO .. EXEC ... syntax, you can clearly call a PROC and store the results into a table type. In the following example I'm actually passing a table into a PROC along with another param I need to add logic, then I'm effectively "returning a table" and can then work with that as a table variable.

/****** Check if my table type and/or proc exists and drop them ******/
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'returnTableTypeData')
DROP PROCEDURE returnTableTypeData
GO
IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'myTableType')
DROP TYPE myTableType
GO

/****** Create the type that I'll pass into the proc and return from it ******/
CREATE TYPE [dbo].[myTableType] AS TABLE(
    [someInt] [int] NULL,
    [somenVarChar] [nvarchar](100) NULL
)
GO

CREATE PROC returnTableTypeData
    @someInputInt INT,
    @myInputTable myTableType READONLY --Must be readonly because
AS
BEGIN

    --Return the subset of data consistent with the type
    SELECT
        *
    FROM
        @myInputTable
    WHERE
        someInt < @someInputInt

END
GO


DECLARE @myInputTableOrig myTableType
DECLARE @myUpdatedTable myTableType

INSERT INTO @myInputTableOrig ( someInt,somenVarChar )
VALUES ( 0, N'Value 0' ), ( 1, N'Value 1' ), ( 2, N'Value 2' )

INSERT INTO @myUpdatedTable EXEC returnTableTypeData @someInputInt=1, @myInputTable=@myInputTableOrig

SELECT * FROM @myUpdatedTable


DROP PROCEDURE returnTableTypeData
GO
DROP TYPE myTableType
GO

Check if a string is a palindrome

public static bool palindrome(string t)
    {
        int i = t.Length;
        for (int j = 0; j < i / 2; j++)
        {
            if (t[j] == t[i - j-1])
            {
                continue;
            }
            else
            {
                return false;
                break;
            }
        }
        return true;
    }

Call a function on click event in Angular 2

Exact transfer to Angular2+ is as below:

<button (click)="myFunc()"></button>

also in your component file:

import { Component, OnInit } from "@angular/core";

@Component({
  templateUrl:"button.html" //this is the component which has the above button html
})

export class App implements OnInit{
  constructor(){}

  ngOnInit(){

  }

  myFunc(){
    console.log("function called");
  }
}

Trying to get property of non-object - CodeIgniter

In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.

In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.

Trying to get property of non-object

For Example:

if (!empty($this->xml_data->thing1->thing2))
{
   foreach ($this->xml_data->thing1->thing2 as $thing)
   {

   }
}

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

How do I initialize a dictionary of empty lists in Python?

Passing [] as second argument to dict.fromkeys() gives a rather useless result – all values in the dictionary will be the same list object.

In Python 2.7 or above, you can use a dicitonary comprehension instead:

data = {k: [] for k in range(2)}

In earlier versions of Python, you can use

data = dict((k, []) for k in range(2))

Trying to make bootstrap modal wider

If you need this solution for only few types of modals just use style="width:90%" attribute.

example:

div class="modal-dialog modal-lg" style="width:90%"

note: this will change only this particular modal

List all devices, partitions and volumes in Powershell

Run command:

Get-PsDrive -PsProvider FileSystem

For more info see:

How can I use onItemSelected in Android?

I think this will benefit you Try this I'm using to change the language in my application

String[] districts;
Spinner sp;

......

 sp = (Spinner) findViewById(R.id.sp);
         districts = getResources().getStringArray(R.array.lang_array);
         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,districts);
         sp.setAdapter(adapter);
         sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
              @Override
             public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
                  // TODO Auto-generated method stub
                  int index = arg0.getSelectedItemPosition();
                  Toast.makeText(getBaseContext(), "You select "+districts[index]+" id "+position, Toast.LENGTH_LONG).show();
                  switch(position){
                      case 0:
                          setLocal("fr");
                          //recreate();
                          break;
                      case 1:
                          setLocal("ar");
                          //recreate();
                          break;
                      case 2:
                          setLocal("en");
                          //recreate();
                          break;
                      default: //For all other cases, do this
                          setLocal("en");
                          //recreate();
                          break;
                  }
              }
             @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                   // TODO Auto-generated method stub
                         }
        });

and this is my String Array

<string-array name="lang_array">
    <item>french</item>
    <item>arabic</item>
    <item>english</item>
</string-array>

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

How to convert from []byte to int in Go Programming

For encoding/decoding numbers to/from byte sequences, there's the encoding/binary package. There are examples in the documentation: see the Examples section in the table of contents.

These encoding functions operate on io.Writer interfaces. The net.TCPConn type implements io.Writer, so you can write/read directly to network connections.

If you've got a Go program on either side of the connection, you may want to look at using encoding/gob. See the article "Gobs of data" for a walkthrough of using gob (skip to the bottom to see a self-contained example).

How to terminate a process in vbscript

Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.

How to make image hover in css?

Exact solution to your problem

You can change the image on hover by using content:url("YOUR-IMAGE-PATH");

For image hover use below line in your css:

img:hover

and to change the image on hover using the below config inside img:hover:

img:hover{
content:url("https://www.planwallpaper.com/static/images/9-credit-1.jpg");
}

Concat scripts in order with Gulp

Try stream-series. It works like merge-stream/event-stream.merge() except that instead of interleaving, it appends to the end. It doesn't require you to specify the object mode like streamqueue, so your code comes out cleaner.

var series = require('stream-series');

gulp.task('minifyInOrder', function() {
    return series(gulp.src('vendor/*'),gulp.src('extra'),gulp.src('house/*'))
        .pipe(concat('a.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dest'))
});

Exit Shell Script Based on Process Exit Code

If you want to work with $?, you'll need to check it after each command, since $? is updated after each command exits. This means that if you execute a pipeline, you'll only get the exit code of the last process in the pipeline.

Another approach is to do this:

set -e
set -o pipefail

If you put this at the top of the shell script, it looks like Bash will take care of this for you. As a previous poster noted, "set -e" will cause Bash to exit with an error on any simple command. "set -o pipefail" will cause Bash to exit with an error on any command in a pipeline as well.

See here or here for a little more discussion on this problem. Here is the Bash manual section on the set builtin.

Plotting categorical data with pandas and matplotlib

To plot multiple categorical features as bar charts on the same plot, I would suggest:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {
        "colour": ["red", "blue", "green", "red", "red", "yellow", "blue"],
        "direction": ["up", "up", "down", "left", "right", "down", "down"],
    }
)

categorical_features = ["colour", "direction"]
fig, ax = plt.subplots(1, len(categorical_features))
for i, categorical_feature in enumerate(df[categorical_features]):
    df[categorical_feature].value_counts().plot("bar", ax=ax[i]).set_title(categorical_feature)
fig.show()

enter image description here

How to import image (.svg, .png ) in a React Component

Simple way is using location.origin
it will return your domain
ex
http://localhost:8000
https://yourdomain.com

then concat with some string...
Enjoy...

<img src={ location.origin+"/images/robot.svg"} alt="robot"/>

More images ?

var images =[
"img1.jpg",
"img2.png",
"img3.jpg",
]

images.map( (image,index) => (

  <img key={index} 
       src={ location.origin+"/images/"+image} 
       alt="robot"
  />
) )

Lookup City and State by Zip Google Geocode Api

couple of months back, I had the same requirement for one of my projects. I searched a bit for it and found out the following solution. This is not the only solution but I found it to one of the simpler one.

Use the webservice at http://www.webservicex.net/uszip.asmx.
Specifically GetInfoByZIP() method.

You will be able to query by any zipcode (ex: 40220) and you will have a response back as the following...

<?xml version="1.0" encoding="UTF-8"?>
 <NewDataSet>
  <Table>
   <CITY>Louisville</CITY> 
   <STATE>KY</STATE> 
   <ZIP>40220</ZIP> 
   <AREA_CODE>502</AREA_CODE> 
   <TIME_ZONE>E</TIME_ZONE> 
  </Table> 
</NewDataSet>

Hope this helps...

Is there a limit on an Excel worksheet's name length?

Renaming a worksheet manually in Excel, you hit a limit of 31 chars, so I'd suggest that that's a hard limit.

How to print the full NumPy array, without truncation?

Suppose you have a numpy array

 arr = numpy.arange(10000).reshape(250,40)

If you want to print the full array in a one-off way (without toggling np.set_printoptions), but want something simpler (less code) than the context manager, just do

for row in arr:
     print row 

Java - What does "\n" mean?

\n is an escape character for strings that is replaced with the new line object. Writing \n in a string that prints out will print out a new line instead of the \n

Java Escape Characters

when do you need .ascx files and how would you use them?

When you are building a basic asp.net website using webcontrols is a good idea when you want to be able to use your controls at more then one location in your website. Separating code from the layout ascx files will be holding the controls that are used to display the layout, the cs files that belong to the ascx files will be holding the code that fills those controls.

For some basic understanding of usercontrols you can try this website

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

Request Monitoring in Chrome

Update

Chrome changed how to inspect requests and suggests now to use the Catapult Netlog Viewer with the logs exported from chrome://net-export/

chrome://net-export/

More Info

Old Chrome Versions

You also may use this link in Chrome for more detailed information than the inspector did it.

chrome://net-internals/#events

This shows the log of all requests of the browser while open

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

Convert string into integer in bash script - "Leading Zero" number error

In Short: In order to deal with "Leading Zero" numbers (any 0 digit that comes before the first non-zero) in bash - Use bc An arbitrary precision calculator language

Example:

a="000001"
b=$(echo $a | bc)
echo $b

Output: 1

From Bash manual:

"bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming lan- guage. A standard math library is available by command line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)"

c# search string in txt file

I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:

                foreach (var line in File.ReadLines(pathToFile))
                {
                    if (line.Contains("CustomerEN") && current == null)
                    {
                        current = new List<string>();
                        current.Add(line);
                    }
                    else if (line.Contains("CustomerEN") && current != null)
                    {
                        current.Add(line);
                    }
                }
                string s = String.Join(",", current);
                MessageBox.Show(s);

How do I set the timeout for a JAX-WS webservice client?

Here is my working solution :

// --------------------------
// SOAP Message creation
// --------------------------
SOAPMessage sm = MessageFactory.newInstance().createMessage();
sm.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
sm.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");

SOAPPart sp = sm.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
se.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
se.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

SOAPBody sb = sm.getSOAPBody();
// 
// Add all input fields here ...
// 

SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
// -----------------------------------
// URL creation with TimeOut connexion
// -----------------------------------
URL endpoint = new URL(null,
                      "http://myDomain/myWebService.php",
                    new URLStreamHandler() { // Anonymous (inline) class
                    @Override
                    protected URLConnection openConnection(URL url) throws IOException {
                    URL clone_url = new URL(url.toString());
                    HttpURLConnection clone_urlconnection = (HttpURLConnection) clone_url.openConnection();
                    // TimeOut settings
                    clone_urlconnection.setConnectTimeout(10000);
                    clone_urlconnection.setReadTimeout(10000);
                    return(clone_urlconnection);
                    }
                });


try {
    // -----------------
    // Send SOAP message
    // -----------------
    SOAPMessage retour = connection.call(sm, endpoint);
}
catch(Exception e) {
    if ((e instanceof com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl) && (e.getCause()!=null) && (e.getCause().getCause()!=null) && (e.getCause().getCause().getCause()!=null)) {
        System.err.println("[" + e + "] Error sending SOAP message. Initial error cause = " + e.getCause().getCause().getCause());
    }
    else {
        System.err.println("[" + e + "] Error sending SOAP message.");

    }
}

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

How do I prevent Eclipse from hanging on startup?

Check that the Workspace Launcher hasn't opened on your TV or some other second monitor. It happened to me. The symptoms look the same as the problem described.

html "data-" attribute as javascript parameter

The easiest way to get data-* attributes is with element.getAttribute():

onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"

DEMO: http://jsfiddle.net/pm6cH/


Although I would suggest just passing this to fun(), and getting the 3 attributes inside the fun function:

onclick="fun(this);"

And then:

function fun(obj) {
    var one = obj.getAttribute('data-uid'),
        two = obj.getAttribute('data-name'),
        three = obj.getAttribute('data-value');
}

DEMO: http://jsfiddle.net/pm6cH/1/


The new way to access them by property is with dataset, but that isn't supported by all browsers. You'd get them like the following:

this.dataset.uid
// and
this.dataset.name
// and
this.dataset.value

DEMO: http://jsfiddle.net/pm6cH/2/


Also note that in your HTML, there shouldn't be a comma here:

data-name="bbb",

References:

Adding rows dynamically with jQuery

Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.

$('.js-addNew').on('click', function(e) {
   e.preventDefault();
   var $rows   = $('.person'),
       $last   = $rows.filter(':last'),
       $newRow = $last.clone().insertAfter($last);

   $last.find($('.js-addNew')).remove(); // remove old button
   $newRow.hide().find('input').val('');
   $newRow.slideDown(500);
});

How to fix homebrew permissions?

If you don't have the latest Homebrew: I "fixed" this in the past by forcing Homebrew to run as root, which could only be done by changing the ownership of the Homebrew executables to root. At some point, they removed this feature.

And I know they'll give lots of warnings saying it shouldn't run as root, but c'mon, it doesn't work properly otherwise.

Cannot find JavaScriptSerializer in .Net 4.0

using System.Web.Script.Serialization; 

is in assembly : System.Web.Extensions (System.Web.Extensions.dll)

Single-threaded apartment - cannot instantiate ActiveX control

If you used [STAThread] to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!

Private void YourFunc(..)
{
    if (this.InvokeRequired)
    {
        Invoke(new MethodInvoker(delegate()
        {
           // Call your method YourFunc(..);
        }));
    }
    else
    {
        ///
    }

How to prevent Google Colab from disconnecting?

create a python code in your pc with pynput

from pynput.mouse import Button, Controller
import time

mouse = Controller()

while True:
    mouse.click(Button.left, 1)
    time.sleep(30)

Run this code in your Desktop, Then point mouse arrow over (colabs left panel - file section) directory structure on any directory this code will keep clicking on directory on every 30 seconds so it will expand and shrink every 30 seconds so your session will not get expired Important - you have to run this code in your pc

How to dynamically set bootstrap-datepicker's date value?

Simple way like this (one line)

$('#startDateText').val(startDate).datepicker("update");

How to split a string and assign it to variables

Since go is flexible an you can create your own python style split ...

package main

import (
    "fmt"
    "strings"
    "errors"
)

type PyString string

func main() {
    var py PyString
    py = "127.0.0.1:5432"
    ip, port , err := py.Split(":")       // Python Style
    fmt.Println(ip, port, err)
}

func (py PyString) Split(str string) ( string, string , error ) {
    s := strings.Split(string(py), str)
    if len(s) < 2 {
        return "" , "", errors.New("Minimum match not found")
    }
    return s[0] , s[1] , nil
}

NavigationBar bar, tint, and title text color in iOS 8

Swift 4

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.barTintColor = UIColor.orange
    navigationController?.navigationBar.tintColor = UIColor.white
    navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}

What is the use of the @ symbol in PHP?

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Note:-

1) The @-operator works only on expressions.

2) A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

Warning:-

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

How do I get the position selected in a RecyclerView?

No need to have your ViewHolder implementing View.OnClickListener. You can get directly the clicked position by setting a click listener in the method onCreateViewHolder of RecyclerView.Adapter here is a sample of code :

public class ItemListAdapterRecycler extends RecyclerView.Adapter<ItemViewHolder>
{

    private final List<Item> items;

    public ItemListAdapterRecycler(List<Item> items)
    {
        this.items = items;
    }

    @Override
    public ItemViewHolder onCreateViewHolder(final ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);

        view.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                int currentPosition = getClickedPosition(view);
                Log.d("DEBUG", "" + currentPosition);
            }
        });

        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder itemViewHolder, int position)
    {
        ...
    }

    @Override
    public int getItemCount()
    {
        return items.size();
    }

    private int getClickedPosition(View clickedView)
    {
        RecyclerView recyclerView = (RecyclerView) clickedView.getParent();
        ItemViewHolder currentViewHolder = (ItemViewHolder) recyclerView.getChildViewHolder(clickedView);
        return currentViewHolder.getAdapterPosition();
    }

}

How to truncate text in Angular2?

Just tried @Timothy Perez answer and added a line

if (value.length < limit)
   return `${value.substr(0, limit)}`;

to

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {

   if (value.length < limit)
   return `${value.substr(0, limit)}`;

   if (completeWords) {
     limit = value.substr(0, limit).lastIndexOf(' ');
   }
   return `${value.substr(0, limit)}${ellipsis}`;
}
}

Java: How to check if object is null?

It's probably slightly more efficient to catch a NullPointerException. The above methods mean that the runtime is checking for null pointers twice.

Are table names in MySQL case sensitive?

  1. Locate the file at /etc/mysql/my.cnf

  2. Edit the file by adding the following lines:

     [mysqld]
    
     lower_case_table_names=1
    
  3. sudo /etc/init.d/mysql restart

  4. Run mysqladmin -u root -p variables | grep table to check that lower_case_table_names is 1 now

You might need to recreate these tables to make it work.

Most common C# bitwise operations on enums

For the best performance and zero garbage, use this:

using System;
using T = MyNamespace.MyFlags;

namespace MyNamespace
{
    [Flags]
    public enum MyFlags
    {
        None = 0,
        Flag1 = 1,
        Flag2 = 2
    }

    static class MyFlagsEx
    {
        public static bool Has(this T type, T value)
        {
            return (type & value) == value;
        }

        public static bool Is(this T type, T value)
        {
            return type == value;
        }

        public static T Add(this T type, T value)
        {
            return type | value;
        }

        public static T Remove(this T type, T value)
        {
            return type & ~value;
        }
    }
}

How can I initialize an ArrayList with all zeroes in Java?

The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).

To initialize an list with 60 zeros you do:

List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));

If you want to create a list with 60 different objects, you could use the Stream API with a Supplier as follows:

List<Person> persons = Stream.generate(Person::new)
                             .limit(60)
                             .collect(Collectors.toList());

android lollipop toolbar: how to hide/show the toolbar while scrolling?

There are actually quite a number of ways to hide/show the toolbar while you are scrolling the content. One of the ways is to do it via the Android Design Support Library or more specifically the Coordinator layout aka. super-powered frame layout.

Basically all you need to do is to have the following structure in your layout file and you should be able to achieve the result that you want.

<CoordinatorLayout>
   <AppBarLayout>
   </AppBarLayout>
   <NestedScrollView>
   </NestedScrollView>
</CoordinatorLayout>

I have actually made a video to explain how it can be done in a step by step manner. Feel free to check it out and let me know if it helps. Thanks! :)

https://youtu.be/mEGEVeZK7Nw

How to define a relative path in java

I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.

private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className  + ".html";
ExtentReports report;
ExtentTest test;

@BeforeMethod
    //  initialise report variables
    report = new ExtentReports(outputFolder + outputFile);
    test = report.startTest(className);
    // more setup code

@Test
    // test method code with log statements

@AfterMethod
    // takeScreenShot returns the relative path and filename for the image
    String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
    String imagePath = test.addScreenCapture(imgFilename);
    test.log(LogStatus.FAIL, "Added image to report", imagePath);

This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".

This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.

Chris

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);

Convert file: Uri to File in Android

After searching for a long time this is what worked for me:

File file = new File(getPath(uri));


public String getPath(Uri uri) 
    {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) return null;
        int column_index =             cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String s=cursor.getString(column_index);
        cursor.close();
        return s;
    }

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

Require Screen sizes for splash :

LDPI: Portrait: 200 X 320px
MDPI: Portrait: 320 X 480px
HDPI: Portrait: 480 X 800px
XHDPI: Portrait: 720 X 1280px
XXHDPI: Portrait: 960 X 1600px
XXXHDPI: Portrait: 1440 x 2560px

Require icon Sizes for App :

http://iconhandbook.co.uk/reference/chart/android/

Laravel Eloquent get results grouped by days

Here is how I do it. A short example, but made my query much more manageable

$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now->subMonth())
                        ->groupBy(DB::raw('Date(created_at)'))
                        ->orderBy('created_at', 'DESC')->get();

Embed YouTube Video with No Ads

Whether ads are shown on a video is up to the content owner of that video. It's not something that the embedder can control.

If you had permission from the content owners of the videos to upload copies in your own account, and then ensured that your account was set up with monetization turned off, then that would prevent ads from showing during playback. It's up to you to work out that arrangement/permission with the original videos' owners, of course.

(It's also worth pointing out that if your goal is to help non-profits raise money, then allowing them to monetize their video playbacks is in line with that goal...)

Pdf.js: rendering a pdf file using a base64 file source instead of url

Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS

_x000D_
_x000D_
        Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
        convertDataURIToBinary: function(dataURI) {_x000D_
          var BASE64_MARKER = ';base64,',_x000D_
            base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
            base64 = dataURI.substring(base64Index),_x000D_
            raw = window.atob(base64),_x000D_
            rawLength = raw.length,_x000D_
            array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
          for (var i = 0; i < rawLength; i++) {_x000D_
            array[i] = raw.charCodeAt(i);_x000D_
          }_x000D_
          return array;_x000D_
        },
_x000D_
_x000D_
_x000D_

ip address validation in python using regex

The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:

[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Example:

your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Output:

>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>

Quickest way to clear all sheet contents VBA

You can use the .Clear method:

Sheets("Zeros").UsedRange.Clear

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

what does mysql_real_escape_string() really do?

The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.

Open directory dialog

I know this is an old question, but a simple way to do this is use the FileDialog option provided by WPF and using System.IO.Path.GetDirectory(filename).

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

ES6 offers the Set data structure which is basically an array that doesn't accept duplicates. With the Set data structure, there's a very easy way to find duplicates in an array (using only one loop).

Here's my code

function findDuplicate(arr) {
var set = new Set();
var duplicates = new Set();
  for (let i = 0; i< arr.length; i++) {
     var size = set.size;
     set.add(arr[i]);
     if (set.size === size) {
         duplicates.add(arr[i]);
     }
  }
 return duplicates;
}

Testing Spring's @RequestBody using Spring MockMVC

I have encountered a similar problem with a more recent version of Spring. I tried to use a new ObjectMapper().writeValueAsString(...) but it would not work in my case.

I actually had a String in a JSON format, but I feel like it is literally transforming the toString() method of every field into JSON. In my case, a date LocalDate field would end up as:

"date":{"year":2021,"month":"JANUARY","monthValue":1,"dayOfMonth":1,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"FRIDAY","leapYear":false,"dayOfYear":1,"era":"CE"}

which is not the best date format to send in a request ...

In the end, the simplest solution in my case is to use the Spring ObjectMapper. Its behaviour is better since it uses Jackson to build your JSON with complex types.

@Autowired
private ObjectMapper objectMapper;

and I simply used it in mytest:

mockMvc.perform(post("/api/")
                .content(objectMapper.writeValueAsString(...))
                .contentType(MediaType.APPLICATION_JSON)
);

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

mysql> CREATE USER 'name'@'%' IDENTIFIED BY 'passWord'; Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON . TO 'name'@'%'; Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)

mysql>

  1. Make sure you have your name and % the right way round
  2. Makes sure you have added your port 3306 to any firewall you may be running (although this will give a different error message)

hope this helps someone...

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

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

UPD 19.03.2019 Here is a version for browser on GitHub.

Calculate mean across dimension in a 2D array

If you do this a lot, NumPy is the way to go.

If for some reason you can't use NumPy:

>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]

How to uninstall a package installed with pip install --user

The answer is Not possible yet. You have to remove it manually.

How to load local html file into UIWebView

Here's Swift 3:

    if let htmlFile = Bundle.main.path(forResource: "aa", ofType: "html"){
        do{
            let htmlString = try NSString(contentsOfFile: htmlFile, encoding:String.Encoding.utf8.rawValue )
            messageWebView.loadHTMLString(htmlString as String, baseURL: nil)
        }
        catch _ {
        }
    }

Using subprocess to run Python script on Windows

Yes subprocess.Popen(cmd, ..., shell=True) works like a charm. On Windows the .py file extension is recognized, so Python is invoked to process it (on *NIX just the usual shebang). The path environment controls whether things are seen. So the first arg to Popen is just the name of the script.

subprocess.Popen(['myscript.py', 'arg1', ...], ..., shell=True)

How does the Python's range function work?

When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:

for eachItem in someList:
    doSomething(eachItem)

... which, conveniently enough, is syntactically valid Python code.

The Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).

So range(5) returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).

A call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9

A call to range(2,12,3) would return: 2, 5, 8, 11

Notice that I said, a couple times, that Python's range() function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break" out of the loop early (after finding some particular item in which you were interested, for example).

Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.

The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration"). This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."

Other constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.

For most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators. You can just use it and be happy.

If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python. In such cases you could re-think your design and use while loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.

Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).

[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, "lazy evaluation" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].

Activate tabpage of TabControl

There are two properties in a TabControl control that manages which tab page is selected.

SelectedIndex which offer the possibility to select it by index (an integer starting from 0 to the number of tabs you have minus one).

SelectedTab which offer the possibility to selected the tab object itself to select.

Setting either of these property will change the currently displayed tab.

Alternatively you can also use the Select method. It comes in three flavour, one where you pass the index of the tab, another the TabPage object itself and the last one a string representing the tab's name.

Writing List of Strings to Excel CSV File in Python

The csv.writer writerow method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).

csvwriter.writerow(row)

Write the row parameter to the writer’s file object, formatted according to the current dialect.

Do either:

import csv
RESULTS = [
    ['apple','cherry','orange','pineapple','strawberry']
]
with open('output.csv','wb') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writerows(RESULTS)

or:

import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','wb') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writerow(RESULT)

Visual Studio Community 2015 expiration date

There isn't an expiration date for the community edition.

The usage section from the from the Visual Studio website clearly states:

For individuals

Any individual developer can use Visual Studio Community to create their own free or paid apps.

For organizations

An unlimited number of users within an organization can use Visual Studio Community for the following scenarios: in a classroom learning environment, for academic research, or for contributing to open source projects.

For all other usage scenarios: In non-enterprise organizations, up to five users can use Visual Studio Community. In enterprise organizations (meaning those with >250 PCs or >$1 Million US Dollars in annual revenue), no use is permitted beyond the open source, academic research, and classroom learning environment scenarios described above.

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

Foreign Key to multiple tables

Yet another option is to have, in Ticket, one column specifying the owning entity type (User or Group), second column with referenced User or Group id and NOT to use Foreign Keys but instead rely on a Trigger to enforce referential integrity.

Two advantages I see here over Nathan's excellent model (above):

  • More immediate clarity and simplicity.
  • Simpler queries to write.

Usage of MySQL's "IF EXISTS"

I found the example RichardTheKiwi quite informative.

Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...

-- what I might write in MSSQL

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
    SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
    INSERT INTO TABLE(FieldValue) VALUES('')
    SELECT SCOPE_IDENTITY() AS TableID
END

-- rewritten for MySQL

IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
    SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
    INSERT INTO Table (FieldValue) VALUES('');
    SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;

How to crop a CvMat in OpenCV?

To create a copy of the crop we want, we can do the following,

// Read img
cv::Mat img = cv::imread("imgFileName");
cv::Mat croppedImg;

// This line picks out the rectangle from the image
// and copies to a new Mat
img(cv::Rect(xMin,yMin,xMax-xMin,yMax-yMin)).copyTo(croppedImg);

// Display diff
cv::imshow( "Original Image",  img );
cv::imshow( "Cropped Image",  croppedImg);
cv::waitKey();

"Could not find a part of the path" error message

Probably unrelated, but consider using Path.Combine instead of destination_dir + dir.Substring(...). From the look of it, your .Substring() will leave a backlash at the beginning, but the helper classes like Path are there for a reason.

Does my application "contain encryption"?

@hisnameisjimmy is correct: You will notice (at least as of today, Dec 1st 2016) when you go to submit your app for review and reach the Export Compliance walkthrough, you'll notice the menu now states that HTTPS is an exempt version of encryption (if you use it for every call):

enter image description here

enter image description here

SVN remains in conflict?

I use the following command in order to remove conflict using command line

svn revert "location of conflict folder" -R
svn cleanup
svn update

for reverting current directory

svn revert . -R

Datatables warning(table id = 'example'): cannot reinitialise data table

You can also destroy the old datatable by using the following code before creating the new datatable:

$("#example").dataTable().fnDestroy();

How to change legend title in ggplot

I noticed there are two ways to change/specify legend.title for ggboxplot():

library(ggpubr)

bxp.defaultLegend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                               color = "dose", palette = "jco")

# Solution 1, setup legend.title directly in ggboxplot()
bxp.legend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                 color = "dose", palette = "jco", legend.title="Dose (mg)")

# Solution 2: Change legend title and appearnace in ggboxplot() using labs() and theme() option:
plot1 <-  bxp.defaultLegend + labs(color = "Dose (mg)") +
  theme(legend.title = element_text(color = "blue", size = 10), legend.text = element_text(color = "red"))

ggarrange(list(bxp.legend, bxp.defaultLegend, plot1), nrow = 1, ncol = 3,  common.legend = TRUE)

The code is modified based on the example from GitHub.

asynchronous vs non-blocking

The blocking models require the initiating application to block when the I/O has started. This means that it isn't possible to overlap processing and I/O at the same time. The synchronous non-blocking model allows overlap of processing and I/O, but it requires that the application check the status of the I/O on a recurring basis. This leaves asynchronous non-blocking I/O, which permits overlap of processing and I/O, including notification of I/O completion.

How to convert a Java String to an ASCII byte array?

Convert string to ascii values.

   String test = "ABCD";

   for ( int i = 0; i < test.length(); ++i ) {
   char c = test.charAt( i );
   int j = (int) c;
   System.out.println(j);
   }

Why use getters and setters/accessors?

It can be useful for lazy-loading. Say the object in question is stored in a database, and you don't want to go get it unless you need it. If the object is retrieved by a getter, then the internal object can be null until somebody asks for it, then you can go get it on the first call to the getter.

I had a base page class in a project that was handed to me that was loading some data from a couple different web service calls, but the data in those web service calls wasn't always used in all child pages. Web services, for all of the benefits, pioneer new definitions of "slow", so you don't want to make a web service call if you don't have to.

I moved from public fields to getters, and now the getters check the cache, and if it's not there call the web service. So with a little wrapping, a lot of web service calls were prevented.

So the getter saves me from trying to figure out, on each child page, what I will need. If I need it, I call the getter, and it goes to find it for me if I don't already have it.

    protected YourType _yourName = null;
    public YourType YourName{
      get
      {
        if (_yourName == null)
        {
          _yourName = new YourType();
          return _yourName;
        }
      }
    }

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

Cocoa: What's the difference between the frame and the bounds?

Bounds - x:0, y:0, width: 20, height: 40 is a static
Frame - x:60, y:20, width: 45, height: 45 is a dynamic based on inner bounds.

One more illustration to show a difference between frame and bounds. At this example:

  • View B is a subview of View A
  • View B was moved to x:60, y: 20
  • View B was rotated 45 degrees

enter image description here

How do you test running time of VBA code?

We've used a solution based on timeGetTime in winmm.dll for millisecond accuracy for many years. See http://www.aboutvb.de/kom/artikel/komstopwatch.htm

The article is in German, but the code in the download (a VBA class wrapping the dll function call) is simple enough to use and understand without being able to read the article.

Rebuild all indexes in a Database

Try the following script:

Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO

Also

I prefer(After a long search) to use the following script, it contains @fillfactor determines how much percentage of the space on each leaf-level page is filled with data.

DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80 
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO

for more info, check the following link:

https://blog.sqlauthority.com/2009/01/30/sql-server-2008-2005-rebuild-every-index-of-all-tables-of-database-rebuild-index-with-fillfactor/

and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:

SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc

For more information, Check the following link:

http://www.schneider-electric.com/en/faqs/FA234246/

How do I multiply each element in a list by a number?

Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.

using for loop

lst = [5, 20 ,15]
product = []
for i in lst:
    product.append(i*5)
print product

using list comprehension, this is also same as using for-loop but more 'pythonic'

lst = [5, 20 ,15]

prod = [i * 5 for i in lst]
print prod

How can I make an "are you sure" prompt in a Windows batchfile?

If you want to the batch program to exit back to the prompt and not close the prompt (A.K.A cmd.exe) you can use "exit /b".

This may help.

set /p _sure="Are you sure?"
::The underscore is used to ensure that "sure" is not an enviroment
::varible
if /I NOT "_sure"=="y" (
::the /I makes it so you can
exit /b
) else (
::Any other modifications...
)

Or if you don't want to use as many lines...

Set /p _sure="Are you sure?"
if /I NOT "_sure"=="y" exit /b
::Any other modifications and commands.

Hope this helps...

How to pass arguments to entrypoint in docker-compose.yml

Whatever is specified in the command in docker-compose.yml should get appended to the entrypoint defined in the Dockerfile, provided entrypoint is defined in exec form in the Dockerfile.

If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.

How do I disable a href link in JavaScript?

Try this when you dont want user to redirect on click

<a href="javascript: void(0)">I am a useless link</a>

How to remove html special chars?

<?php
function strip_only($str, $tags, $stripContent = false) {
    $content = '';
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false
                 ? explode('>', str_replace('<', '', $tags))
                 : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) {
        if ($stripContent)
             $content = '(.+</'.$tag.'[^>]*>|)';
         $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
    }
    return $str;
}

$str = '<font color="red">red</font> text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?> 

AngularJS For Loop with Numbers & Ranges

I whipped this up and saw it might be useful for some. (Yes, CoffeeScript. Sue me.)

Directive

app.directive 'times', ->
  link: (scope, element, attrs) ->
    repeater = element.html()
    scope.$watch attrs.times, (value) ->
      element.html ''
      return unless value?
      element.html Array(value + 1).join(repeater)

To use:

HTML

<div times="customer.conversations_count">
  <i class="icon-picture></i>
</div>

Can this get any simpler?

I'm wary about filters because Angular likes to re-evaluate them for no good reason all the time, and it's a huge bottleneck if you have thousands of them like I do.

This directive will even watch for changes in your model, and update the element accordingly.

How to represent multiple conditions in a shell if statement?

you can chain more than 2 conditions too :

if [ \( "$1" = '--usage' \) -o \( "$1" = '' \) -o \( "$1" = '--help' \) ]
then
   printf "\033[2J";printf "\033[0;0H"
   cat << EOF_PRINT_USAGE

   $0 - Purpose: upsert qto http json data to postgres db

   USAGE EXAMPLE:

   $0 -a foo -a bar



EOF_PRINT_USAGE
   exit 1
fi

How to build an android library with Android Studio and gradle?

Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

How to stop creating .DS_Store on Mac?

NOTE: "Asepsis is no longer under active development and supported under OS X 10.11 (El Capitan) and later."


Here's a comprehensive review of your options. Asepsis (the second solution mentioned) seems to be what you're looking for, it re-routes .DS_Store creation to a unified cache instead of being located on every folder.