Programs & Examples On #Nsmutablearray

NSMutableArray represents a modifiable (mutable) array object for Cocoa and Cocoa Touch. It is Available in OS X v10.0 and later

How do I convert NSMutableArray to NSArray?

Objective-C

Below is way to convert NSMutableArray to NSArray:

//oldArray is having NSMutableArray data-type.
//Using Init with Array method.
NSArray *newArray1 = [[NSArray alloc]initWithArray:oldArray];

//Make copy of array
NSArray *newArray2 = [oldArray copy];

//Make mutablecopy of array
NSArray *newArray3 = [oldArray mutableCopy];

//Directly stored NSMutableArray to NSArray.
NSArray *newArray4 = oldArray;

Swift

In Swift 3.0 there is new data type Array. Declare Array using let keyword then it would become NSArray And if declare using var keyword then it's become NSMutableArray.

Sample code:

let newArray = oldArray as Array

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

Swift version: 5.1

If you have a custom struct or class and want to sort them arbitrarily, you should call sort() using a trailing closure that sorts on a field you specify. Here's an example using an array of custom structs that sorts on a particular property:

    struct User {
        var firstName: String
    }

    var users = [
        User(firstName: "Jemima"),
        User(firstName: "Peter"),
        User(firstName: "David"),
        User(firstName: "Kelly"),
        User(firstName: "Isabella")
    ]

    users.sort {
        $0.firstName < $1.firstName
    }

If you want to return a sorted array rather than sort it in place, use sorted() like this:

    let sortedUsers = users.sorted {
        $0.firstName < $1.firstName
    }

The best way to remove duplicate values from NSMutableArray in Objective-C?

Your NSSet approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet to begin with?

I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:

NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];

If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:

NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
    if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
        [mutableArray removeObjectAtIndex:index];
    }
    index--;
}
[copy release];

'Invalid update: invalid number of rows in section 0

Here is some code from above added with actual action code (point 1 and 2);

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in

        // 1. remove object from your array
        scannedItems.remove(at: indexPath.row)
        // 2. reload the table, otherwise you get an index out of bounds crash
        self.tableView.reloadData()

        completionHandler(true)
    }
    deleteAction.backgroundColor = .systemOrange
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    configuration.performsFirstActionWithFullSwipe = true
    return configuration
}

Get everything after and before certain character in SQL Server

You can try this:

Declare @test varchar(100)='images/test.jpg'
Select REPLACE(RIGHT(@test,charindex('/',reverse(@test))-1),'.jpg','')

Connect to SQL Server database from Node.js

There is a module on npm called mssqlhelper

You can install it to your project by npm i mssqlhelper

Example of connecting and performing a query:

var db = require('./index');

db.config({
    host: '192.168.1.100'
    ,port: 1433
    ,userName: 'sa'
    ,password: '123'
    ,database:'testdb'
});

db.query(
    'select @Param1 Param1,@Param2 Param2'
    ,{
         Param1: { type : 'NVarChar', size: 7,value : 'myvalue' }
         ,Param2: { type : 'Int',value : 321 }
    }
    ,function(res){
        if(res.err)throw new Error('database error:'+res.err.msg);
        var rows = res.tables[0].rows;
        for (var i = 0; i < rows.length; i++) {
            console.log(rows[i].getValue(0),rows[i].getValue('Param2'));
        }
    }
);

You can read more about it here: https://github.com/play175/mssqlhelper

:o)

Get the current year in JavaScript

Take this example, you can place it wherever you want to show it without referring to script in the footer or somewhere else like other answers

<script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>

Copyright note on the footer as an example

Copyright 2010 - <script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Here is my answer to a similar question:

I think (not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so:

var x = this.Handle; 

(See http://ikriv.com/en/prog/info/dotnet/MysteriousHang.html)

How do I get the height of a div's full content with jQuery?

Element.scrollHeight is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow and height to auto, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

get data from mysql database to use in javascript

To do with javascript you could do something like this:

<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>

Then you can use whatever you want in your javascript to put the text var into the textbox.

Which is the default location for keystore/truststore of Java applications?

Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).

javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456

Then load the properties to your environment from your code. This makes your application configurable.

FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);

Get commit list between tags in git

If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:

git log --no-merges --pretty=format:"%s" 'old-tag^'...new-tag > /path/to/changelog.md
  • --no-merges omits the merge commits from the list
  • old-tag^ refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).

VBA - If a cell in column A is not blank the column B equals

If you really want a vba solution you can loop through a range like this:

Sub Check()
    Dim dat As Variant
    Dim rng As Range
    Dim i As Long

    Set rng = Range("A1:A100")
    dat = rng
    For i = LBound(dat, 1) To UBound(dat, 1)
        If dat(i, 1) <> "" Then
            rng(i, 2).Value = "My Text"
        End If
    Next
End Sub

*EDIT*

Instead of using varients you can just loop through the range like this:

Sub Check()
    Dim rng As Range
    Dim i As Long

    'Set the range in column A you want to loop through
    Set rng = Range("A1:A100")
    For Each cell In rng
        'test if cell is empty
        If cell.Value <> "" Then
            'write to adjacent cell
            cell.Offset(0, 1).Value = "My Text"
        End If
    Next
End Sub

EOL conversion in notepad ++

That functionality is already built into Notepad++. From the "Edit" menu, select "EOL Conversion" -> "UNIX/OSX Format".

screenshot of the option for even quicker finding (or different language versions)

You can also set the default EOL in notepad++ via "Settings" -> "Preferences" -> "New Document/Default Directory" then select "Unix/OSX" under the Format box.

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

Visual Studio popup: "the operation could not be completed"

I had to remove a webproject. There was an old referencing DLL file inside, and I had to clean that webproject, and then it worked.

How to compile Tensorflow with SSE4.2 and AVX instructions?

Thanks to all this replies + some trial and errors, I managed to install it on a Mac with clang. So just sharing my solution in case it is useful to someone.

  1. Follow the instructions on Documentation - Installing TensorFlow from Sources

  2. When prompted for

    Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]

then copy-paste this string:

-mavx -mavx2 -mfma -msse4.2

(The default option caused errors, so did some of the other flags. I got no errors with the above flags. BTW I replied n to all the other questions)

After installing, I verify a ~2x to 2.5x speedup when training deep models with respect to another installation based on the default wheels - Installing TensorFlow on macOS

Hope it helps

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

How to change default timezone for Active Record in Rails?

In Ruby on Rails 6.0.1 go to config > locales > application.rb y agrega lo siguiente:

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module CrudRubyOnRails6
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    config.active_record.default_timezone = :local
    config.time_zone = 'Lima'

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end
end

You can see that I am configuring the time zone with 2 lines:

config.active_record.default_timezone =: local
config.time_zone = 'Lima'

I hope it helps those who are working with Ruby on Rails 6.0.1

Call a VBA Function into a Sub Procedure

Here are some of the different ways you can call things in Microsoft Access:

To call a form sub or function from a module

The sub in the form you are calling MUST be public, as in:

Public Sub DoSomething()
  MsgBox "Foo"
End Sub

Call the sub like this:

Call Forms("form1").DoSomething

The form must be open before you make the call.

To call an event procedure, you should call a public procedure within the form, and call the event procedure within this public procedure.

To call a subroutine in a module from a form

Public Sub DoSomethingElse()
  MsgBox "Bar"
End Sub

...just call it directly from your event procedure:

Call DoSomethingElse

To call a subroutine from a form without using an event procedure

If you want, you can actually bind the function to the form control's event without having to create an event procedure under the control. To do this, you first need a public function in the module instead of a sub, like this:

Public Function DoSomethingElse()
  MsgBox "Bar"
End Function

Then, if you have a button on the form, instead of putting [Event Procedure] in the OnClick event of the property window, put this:

=DoSomethingElse()

When you click the button, it will call the public function in the module.

To call a function instead of a procedure

If calling a sub looks like this:

Call MySub(MyParameter)

Then calling a function looks like this:

Result=MyFunction(MyFarameter)

where Result is a variable of type returned by the function.

NOTE: You don't always need the Call keyword. Most of the time, you can just call the sub like this:

MySub(MyParameter)

Error: Specified cast is not valid. (SqlManagerUI)

There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?

Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:\YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf' 

Routing with Multiple Parameters using ASP.NET MVC

You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
                                  api_key=b25b959554ed76058ac220b7b2e0a026

That could be:

routes.MapRoute(
    "ArtistsImages",
    "{ws}/artists/{artist}/{action}/{*apikey}",
    new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
    );

So if someone used the following route:

ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/

It would take them to the same place your example querystring did.

The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.

Html table tr inside td

You cannot put tr inside td. You can see the allowed content from MDN web docs documentation about td. The relevant information is in the permitted content section.

Another way to achieve this is by using colspan and rowspan. Check this fiddle.

HTML:

<table width="100%">
 <tr>
  <td>Name 1</td>
  <td>Name 2</td>
  <td colspan="2">Name 3</td>
  <td>Name 4</td>
 </tr>

 <tr>
  <td rowspan="3">ITEM 1</td>
  <td rowspan="3">ITEM 2</td>
  <td>name1</td>
  <td>price1</td>
  <td rowspan="3">ITEM 4</td>
 </tr>

 <tr>
  <td>name2</td>
  <td>price2</td>
 </tr>
 <tr>
  <td>name3</td>
  <td>price3/td>
 </tr>
</table>

And some CSS:

table {
    border-collapse: collapse       
}

td {
   border: 1px solid #000000
}

How to compile makefile using MinGW?

I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/

It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.

The Makefile looking like:

EXECUTABLE = src/Main.cpp

CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

Is embedding background image data into CSS as Base64 good or bad practice?

Bringing a bit for users of Sublime Text 2, there is a plugin that gives the base64 code we load the images in the ST.

Called Image2base64: https://github.com/tm-minty/sublime-text-2-image2base64

PS: Never save this file generated by the plugin because it would overwrite the file and would destroy.

Reverting single file in SVN to a particular revision

If you just want the old file in your working copy:

svn up -r 147 myfile.py

If you want to rollback, see this "How to return to an older version of our code in subversion?".

How do I format currencies in a Vue component?

I have created a filter. The filter can be used in any page.

Vue.filter('toCurrency', function (value) {
    if (typeof value !== "number") {
        return value;
    }
    var formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 0
    });
    return formatter.format(value);
});

Then I can use this filter like this:

        <td class="text-right">
            {{ invoice.fees | toCurrency }}
        </td>

I used these related answers to help with the implementation of the filter:

Unable to resolve host "<insert URL here>" No address associated with hostname

I had the same issue with the Android 10 emulator and I was able to solve the problem by following the steps below:

  1. Go to Settings ? Network & internet ? Advanced ? Private DNS
  2. Select Private DNS provider hostname
  3. Enter: dns.google
  4. Click Save

With this setup, you URL should work as expected.

How can I pass a class member function as a callback?

A simple solution "workaround" still is to create a class of virtual functions "interface" and inherit it in the caller class. Then pass it as a parameter "could be in the constructor" of the other class that you want to call your caller class back.

DEFINE Interface:

class CallBack 
{
   virtual callMeBack () {};
};

This is the class that you want to call you back:

class AnotherClass ()
{
     public void RegisterMe(CallBack *callback)
     {
         m_callback = callback;
     }

     public void DoSomething ()
     {
        // DO STUFF
        // .....
        // then call
        if (m_callback) m_callback->callMeBack();
     }
     private CallBack *m_callback = NULL;
};

And this is the class that will be called back.

class Caller : public CallBack
{
    void DoSomthing ()
    {
    }

    void callMeBack()
    {
       std::cout << "I got your message" << std::endl;
    }
};

How do I commit only some files?

Some of this seems "incomplete"

Groups of people are NOT going to know if they should use quotes etc..

Add 1 specific file showing the location paths as well

git add JobManager/Controllers/APIs/ProfileApiController.cs

Commit (remember, commit is local only, it is not affecting any other system)

git commit -m "your message"  

Push to remote repo

git push  (this is after the commit and this attempts to Merge INTO the remote location you have instructed it to merge into)

Other answer(s) show the stash etc. which you sometimes will want to do

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

How to find the 'sizeof' (a pointer pointing to an array)?

The answer is, "No."

What C programmers do is store the size of the array somewhere. It can be part of a structure, or the programmer can cheat a bit and malloc() more memory than requested in order to store a length value before the start of the array.

XSLT counting elements with a given value

<xsl:variable name="count" select="count(/Property/long = $parPropId)"/>

Un-tested but I think that should work. I'm assuming the Property nodes are direct children of the root node and therefor taking out your descendant selector for peformance

fatal: early EOF fatal: index-pack failed

This error may occur for memory needs of git. You can add these lines to your global git configuration file, which is .gitconfig in $USER_HOME, in order to fix that problem.

[core] 
packedGitLimit = 512m 
packedGitWindowSize = 512m 
[pack] 
deltaCacheSize = 2047m 
packSizeLimit = 2047m 
windowMemory = 2047m

How do I escape the wildcard/asterisk character in bash?

I'll add a bit to this old thread.

Usually you would use

$ echo "$FOO"

However, I've had problems even with this syntax. Consider the following script.

#!/bin/bash
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"

The * needs to be passed verbatim to curl, but the same problems will arise. The above example won't work (it will expand to filenames in the current directory) and neither will \*. You also can't quote $curl_opts because it will be recognized as a single (invalid) option to curl.

curl: option -s --noproxy * -O: is unknown
curl: try 'curl --help' or 'curl --manual' for more information

Therefore I would recommend the use of the bash variable $GLOBIGNORE to prevent filename expansion altogether if applied to the global pattern, or use the set -f built-in flag.

#!/bin/bash
GLOBIGNORE="*"
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"  ## no filename expansion

Applying to your original example:

me$ FOO="BAR * BAR"

me$ echo $FOO
BAR file1 file2 file3 file4 BAR

me$ set -f
me$ echo $FOO
BAR * BAR

me$ set +f
me$ GLOBIGNORE=*
me$ echo $FOO
BAR * BAR

What is EOF in the C programming language?

You should change your parenthesis to

while((c = getchar()) != EOF)

Because the "=" operator has a lower precedence than the "!=" operator. Then you will get the expected results. Your expression is equal to

while (c = (getchar()!= EOF))

You are getting the two 1's as output, because you are making the comparison "c!=EOF". This will always become one for the character you entered and then the "\n" that follows by hitting return. Except for the last comparison where c really is EOF it will give you a 0.

EDIT about EOF: EOF is typically -1, but this is not guaranteed by the standard. The standard only defines about EOF in section 7.19.1:

EOF which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

It is reasonable to assume that EOF equals -1, but when using EOF you should not test against the specific value, but rather use the macro.

Combating AngularJS executing controller twice

AngularJS docs - ngController
Note that you can also attach controllers to the DOM by declaring it in a route definition via the $route service. A common mistake is to declare the controller again using ng-controller in the template itself. This will cause the controller to be attached and executed twice.

When you use ngRoute with the ng-view directive, the controller gets attached to that dom element by default (or ui-view if you use ui-router). So you will not need to attach it again in the template.

How to write "not in ()" sql query using join

SELECT d1.Short_Code 
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case it was a component.member which was not existing e.g.

[formControl]="personId"

Adding it to the class declaration fixed it

this.personId = new FormControl(...)

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

Getting the location from an IP address

I wrote a bot using an API from ipapi.co, here's how you can get location for an IP address (e.g. 1.2.3.4) in php :

Set header :

$opts = array('http'=>array('method'=>"GET", 'header'=>"User-Agent: mybot.v0.7.1"));
$context = stream_context_create($opts);

Get JSON response

echo file_get_contents('https://ipapi.co/1.2.3.4/json/', false, $context);

of get a specific field (country, timezone etc.)

echo file_get_contents('https://ipapi.co/1.2.3.4/country/', false, $context);

How to set a bitmap from resource

Try this

This is from sdcard

ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);

This is from resources

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

Deleting Objects in JavaScript

Setting a variable to null makes sure to break any references to objects in all browsers including circular references being made between the DOM elements and Javascript scopes. By using delete command we are marking objects to be cleared on the next run of the Garbage collection, but if there are multiple variables referencing the same object, deleting a single variable WILL NOT free the object, it will just remove the linkage between that variable and the object. And on the next run of the Garbage collection, only the variable will be cleaned.

if else statement in AngularJS templates

A possibility for Angular: I had to include an if - statement in the html part, I had to check if all variables of an URL that I produce are defined. I did it the following way and it seems to be a flexible approach. I hope it will be helpful for somebody.

The html part in the template:

    <div  *ngFor="let p of poemsInGrid; let i = index" >
        <a [routerLink]="produceFassungsLink(p[0],p[3])" routerLinkActive="active">
    </div>

And the typescript part:

  produceFassungsLink(titel: string, iri: string) {
      if(titel !== undefined && iri !== undefined) {
         return titel.split('/')[0] + '---' + iri.split('raeber/')[1];
      } else {
         return 'Linkinformation has not arrived yet';
      }
  }

Thanks and best regards,

Jan

How do I convert an NSString value to NSData?

For Swift 3, you will mostly be converting from String to Data.

let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)

Detecting the character encoding of an HTTP POST request

the default encoding of a HTTP POST is ISO-8859-1.

else you have to look at the Content-Type header that will then look like

Content-Type: application/x-www-form-urlencoded ; charset=UTF-8

You can maybe declare your form with

<form enctype="application/x-www-form-urlencoded;charset=UTF-8">

or

<form accept-charset="UTF-8">

to force the encoding.

Some references :

http://www.htmlhelp.com/reference/html40/forms/form.html

http://www.w3schools.com/tags/tag_form.asp

How to properly export an ES6 class in Node 4?

class expression can be used for simplicity.

 // Foo.js
'use strict';

// export default class Foo {}
module.exports = class Foo {}

-

// main.js
'use strict';

const Foo = require('./Foo.js');

let Bar = new class extends Foo {
  constructor() {
    super();
    this.name = 'bar';
  }
}

console.log(Bar.name);

Print a list of space-separated elements in Python 3

Joining elements in a list space separated:

word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
   joined_string = w + joined_string + " "
print(joined_string.rstrim())

Creating a blurring overlay view

This answer is based on Mitja Semolic's excellent earlier answer. I've converted it to swift 3, added an explanation to what's happening in coments, made it an extension of a UIViewController so any VC can call it at will, added an unblurred view to show selective application, and added a completion block so that the calling view controller can do whatever it wants at the completion of the blur.

    import UIKit
//This extension implements a blur to the entire screen, puts up a HUD and then waits and dismisses the view.
    extension UIViewController {
        func blurAndShowHUD(duration: Double, message: String, completion: @escaping () -> Void) { //with completion block
            //1. Create the blur effect & the view it will occupy
            let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
            let blurEffectView = UIVisualEffectView()//(effect: blurEffect)
            blurEffectView.frame = self.view.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        //2. Add the effect view to the main view
            self.view.addSubview(blurEffectView)
        //3. Create the hud and add it to the main view
        let hud = HudView.getHUD(view: self.view, withMessage: message)
        self.view.addSubview(hud)
        //4. Begin applying the blur effect to the effect view
        UIView.animate(withDuration: 0.01, animations: {
            blurEffectView.effect = blurEffect
        })
        //5. Halt the blur effects application to achieve the desired blur radius
        self.view.pauseAnimationsInThisView(delay: 0.004)
        //6. Remove the view (& the HUD) after the completion of the duration
        DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
            blurEffectView.removeFromSuperview()
            hud.removeFromSuperview()
            self.view.resumeAnimationsInThisView()
            completion()
        }
    }
}

extension UIView {
    public func pauseAnimationsInThisView(delay: Double) {
        let time = delay + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, time, 0, 0, 0, { timer in
            let layer = self.layer
            let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil)
            layer.speed = 0.0
            layer.timeOffset = pausedTime
        })
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
    }
    public func resumeAnimationsInThisView() {
        let pausedTime  = layer.timeOffset

        layer.speed = 1.0
        layer.timeOffset = 0.0
        layer.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    }
}

I've confirmed that it works with both iOS 10.3.1 and iOS 11

Order data frame rows according to vector with specific order

If you don't want to use any libraries and you have reoccurrences in your data, you can use which with sapply as well.

new_order <- sapply(target, function(x,df){which(df$name == x)}, df=df)
df        <- df[new_order,]

Android Studio - Auto complete and other features not working

Simpy It was working for me after restarting the Android studio.

How to call a .NET Webservice from Android using KSOAP2?

How does your .NET Webservice look like?

I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)

And everytime I used

    Integer result = (Integer)envelope.getResponse();

to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive exception.

I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.

    [SoapRpcMethod(), WebMethod]
    public Object GetInteger1(int i)
    {
        // android device will throw exception
        return 0;
    }

    [WebMethod]
    public Object GetInteger2(int i)
    {
        // android device will get the value
        return 0;
    }

Then I changed my Android code to:

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString() method, so I use Integer.parseInt(result.toString()) to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.

Here is the full source:

private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";

public int GetInteger2() throws IOException, XmlPullParserException {
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo pi = new PropertyInfo();
    pi.setName("i");
    pi.setValue(123);
    request.addProperty(pi);

    SoapSerializationEnvelope envelope =
        new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);

    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    androidHttpTransport.call(SOAP_ACTION, envelope);

    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
    return Integer.parseInt(result.toString());
}

How can I replace newlines using PowerShell?

A CRLF is two characters, of course, the CR and the LF. However, `n consists of both. For example:

PS C:\> $x = "Hello
>> World"

PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>

I think you're running into problems with the `r. I was able to remove the `r from your example, use only `n, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

Relative imports in Python 3

My boilerplate to make a module with relative imports in a package runnable standalone.

package/module.py

## Standalone boilerplate before relative imports
if __package__ is None:                  
    DIR = Path(__file__).resolve().parent
    sys.path.insert(0, str(DIR.parent))
    __package__ = DIR.name

from . import variable_in__init__py
from . import other_module_in_package
...

Now you can use your module in any fashion:

  1. Run module as usual: python -m package.module
  2. Use it as a module: python -c 'from package import module'
  3. Run it standalone: python package/module.py
  4. or with shebang (#!/bin/env python) just: package/module.py

NB! Using sys.path.append instead of sys.path.insert will give you a hard to trace error if your module has the same name as your package. E.g. my_script/my_script.py

Of course if you have relative imports from higher levels in your package hierarchy, than this is not enough, but for most cases, it's just okay.

WAMP/XAMPP is responding very slow over localhost

The solution that worked for me was to disable the cgi_module. Use one of these methods:

(Method 1) Right click on WAMP > Apache > Apache Modules > uncheck "cgi_module"

(Method 2) Edit httpd.conf and disable the loading of the CGI module by commenting this line:

LoadModule cgi_module modules/mod_cgi.so

Commenting would be just adding a # in front, like this:

#LoadModule cgi_module modules/mod_cgi.so

Restart the Apache service and you should be good to go.

jQuery: How to detect window width on the fly?

Changing a variable doesn't magically execute code within the if-block. Place the common code in a function, then bind the event, and call the function:

$(document).ready(function() {
    // Optimalisation: Store the references outside the event handler:
    var $window = $(window);
    var $pane = $('#pane1');

    function checkWidth() {
        var windowsize = $window.width();
        if (windowsize > 440) {
            //if the window is greater than 440px wide then turn on jScrollPane..
            $pane.jScrollPane({
               scrollbarWidth:15, 
               scrollbarMargin:52
            });
        }
    }
    // Execute on load
    checkWidth();
    // Bind event listener
    $(window).resize(checkWidth);
});

sendKeys() in Selenium web driver

This is a single line command to send the TAB key;

driver.findElement(By.id("Enter_ID")).sendKeys("\t");

Removing duplicate elements from an array in Swift

For arrays where the elements are neither Hashable nor Comparable (e.g. complex objects, dictionaries or structs), this extension provides a generalized way to remove duplicates:

extension Array
{
   func filterDuplicate<T:Hashable>(_ keyValue:(Element)->T) -> [Element]
   {
      var uniqueKeys = Set<T>()
      return filter{uniqueKeys.insert(keyValue($0)).inserted}
   }

   func filterDuplicate<T>(_ keyValue:(Element)->T) -> [Element]
   { 
      return filterDuplicate{"\(keyValue($0))"}
   }
}

// example usage: (for a unique combination of attributes):

peopleArray = peopleArray.filterDuplicate{ ($0.name, $0.age, $0.sex) }

or...

peopleArray = peopleArray.filterDuplicate{ "\(($0.name, $0.age, $0.sex))" }

You don't have to bother with making values Hashable and it allows you to use different combinations of fields for uniqueness.

Note: for a more robust approach, please see the solution proposed by Coeur in the comments below.

stackoverflow.com/a/55684308/1033581

[EDIT] Swift 4 alternative

With Swift 4.2 you can use the Hasher class to build a hash much easier. The above extension could be changed to leverage this :

extension Array
{
    func filterDuplicate(_ keyValue:((AnyHashable...)->AnyHashable,Element)->AnyHashable) -> [Element]
    {
        func makeHash(_ params:AnyHashable ...) -> AnyHashable
        { 
           var hash = Hasher()
           params.forEach{ hash.combine($0) }
           return hash.finalize()
        }  
        var uniqueKeys = Set<AnyHashable>()
        return filter{uniqueKeys.insert(keyValue(makeHash,$0)).inserted}     
    }
}

The calling syntax is a little different because the closure receives an additional parameter containing a function to hash a variable number of values (which must be Hashable individually)

peopleArray = peopleArray.filterDuplicate{ $0($1.name, $1.age, $1.sex) } 

It will also work with a single uniqueness value (using $1 and ignoring $0).

peopleArray = peopleArray.filterDuplicate{ $1.name } 

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

git switch branch without discarding local changes

Use git stash

git stash

It pushes changes to a stack. When you want to pull them back use

git stash apply

You can even pull individual items out. To completely blow away the stash:

git stash clear

What is lexical scope?

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.

This concept is heavily used in closures in JavaScript.

Let's say we have the below code.

var x = 2;
var add = function() {
    var y = 1;
    return x + y;
};

Now, when you call add() --> this will print 3.

So, the add() function is accessing the global variable x which is defined before method function add. This is called due to lexical scoping in JavaScript.

How to copy a char array in C?

You cannot assign arrays, the names are constants that cannot be changed.

You can copy the contents, with:

strcpy(array2, array1);

assuming the source is a valid string and that the destination is large enough, as in your example.

How To Add An "a href" Link To A "div"?

I'd say:

 <a href="#"id="buttonOne">
            <div id="linkedinB">
                <img src="img/linkedinB.png" width="40" height="40">
            </div>
      </div> 

However, it will still be a link. If you want to change your link into a button, you should rename the #buttonone to #buttonone a { your css here }.

Open a selected file (image, pdf, ...) programmatically from my Android Application?

MimeTypeMap.getSingleton().getExtensionFromMimeType(file.getName());

Probably, this is the easiest solution.

https://developer.android.com/reference/android/webkit/MimeTypeMap

https://developer.android.com/reference/java/net/URLConnection.html#guessContentTypeFromName(java.lang.String)

private void openFile(File file) {

    Uri uri = Uri.fromFile(file);

    Intent intent = new Intent(Intent.ACTION_VIEW);

    intent.setDataAndType(uri, MimeTypeMap.getSingleton().getExtensionFromMimeType(file.getName()));


    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(Intent.createChooser(intent, "Open " + file.getName() + " with ..."));
}

hibernate could not get next sequence value

I would also like to add a few notes about a MySQL-to-PostgreSQL migration:

  1. In your DDL, in the object naming prefer the use of '_' (underscore) character for word separation to the camel case convention. The latter works fine in MySQL but brings a lot of issues in PostgreSQL.
  2. The IDENTITY strategy for @GeneratedValue annotation in your model class-identity fields works fine for PostgreSQLDialect in hibernate 3.2 and superior. Also, The AUTO strategy is the typical setting for MySQLDialect.
  3. If you annotate your model classes with @Table and set a literal value to these equal to the table name, make sure you did create the tables to be stored under public schema.

That's as far as I remember now, hope these tips can spare you a few minutes of trial and error fiddling!

Getting Textarea Value with jQuery

try this:

<a id="send-thoughts" href="">Click</a>
<textarea id="message"></textarea>
<!--<textarea id="#message"></textarea>-->

            jQuery("a#send-thoughts").click(function() {
                //var thought = jQuery("textarea#message").val();
                var thought = $("#message").val();
                alert(thought);
            });

Counting number of characters in a file through shell script

I would have thought that it would be better to use stat to find the size of a file, since the filesystem knows it already, rather than causing the whole file to have to be read with awk or wc - especially if it is a multi-GB file or one that may be non-resident in the file-system on an HSM.

stat -c%s file

Yes, I concede it doesn't account for multi-byte characters, but would add that the OP has never clarified whether that is/was an issue.

Get query from java.sql.PreparedStatement

If you only want to log the query, then add 'logger' and 'profileSQL' to the jdbc url:

&logger=com.mysql.jdbc.log.Slf4JLogger&profileSQL=true

Then you will get the SQL statement below:

2016-01-14 10:09:43  INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0
2016-01-14 10:09:43  INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0 message: SET sql_mode='NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES'
2016-01-14 10:09:43  INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0
2016-01-14 10:09:43  INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 2 connection: 19130945 statement: 13 resultset: 17 message: select 1
2016-01-14 10:09:43  INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 13 resultset: 17
2016-01-14 10:09:43  INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 15 resultset: 18 message: select @@session.tx_read_only
2016-01-14 10:09:43  INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 15 resultset: 18
2016-01-14 10:09:43  INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 2 connection: 19130945 statement: 14 resultset: 0 message: update sequence set seq=seq+incr where name='demo' and seq=4602
2016-01-14 10:09:43  INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 14 resultset: 0

The default logger is:

com.mysql.jdbc.log.StandardLogger

Mysql jdbc property list: https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html

Ajax request returns 200 OK, but an error event is fired instead of success

You simply have to remove the dataType: "json" in your AJAX call

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json', //**** REMOVE THIS LINE ****//
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

Compile/run assembler in Linux?

There is also FASM for Linux.

format ELF executable

segment readable executable

start:
mov eax, 4
mov ebx, 1
mov ecx, hello_msg
mov edx, hello_size
int 80h

mov eax, 1
mov ebx, 0
int 80h

segment readable writeable

hello_msg db "Hello World!",10,0
hello_size = $-hello_msg

It comiles with

fasm hello.asm hello

How to completely remove node.js from Windows

I had the same problem with me yesterday and my solution is: 1. uninstall from controlpanel not from your cli 2. download and install the latest or desired version of node from its website 3. if by mistake you tried uninstalling through cli (it will not remove completely most often) then you do not get uninstall option in cpanel in this case install the same version of node and then follow my 1. step

Hope it helps someone.

How can I escape a single quote?

Represent it as a text entity (ASCII 39):

<input type='text' id='abc' value='hel&#39;lo'>

input[type='text'] CSS selector does not apply to default-type text inputs?

The CSS uses only the data in the DOM tree, which has little to do with how the renderer decides what to do with elements with missing attributes.

So either let the CSS reflect the HTML

input:not([type]), input[type="text"]
{
background:red;
}

or make the HTML explicit.

<input name='t1' type='text'/> /* Is Not Red */

If it didn't do that, you'd never be able to distinguish between

element { ...properties... }

and

element[attr] { ...properties... }

because all attributes would always be defined on all elements. (For example, table always has a border attribute, with 0 for a default.)

NotificationCompat.Builder deprecated in Android O

It is mentioned in the documentation that the builder method NotificationCompat.Builder(Context context) has been deprecated. And we have to use the constructor which has the channelId parameter:

NotificationCompat.Builder(Context context, String channelId)

NotificationCompat.Builder Documentation:

This constructor was deprecated in API level 26.0.0-beta1. use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.

Notification.Builder Documentation:

This constructor was deprecated in API level 26. use Notification.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.

If you want to reuse the builder setters, you can create the builder with the channelId, and pass that builder to a helper method and set your preferred settings in that method.

Ways to save enums in database

For a large database, I am reluctant to lose the size and speed advantages of the numeric representation. I often end up with a database table representing the Enum.

You can enforce database consistency by declaring a foreign key -- although in some cases it might be better to not declare that as a foreign key constraint, which imposes a cost on every transaction. You can ensure consistency by periodically doing a check, at times of your choosing, with:

SELECT reftable.* FROM reftable
  LEFT JOIN enumtable ON reftable.enum_ref_id = enumtable.enum_id
WHERE enumtable.enum_id IS NULL;

The other half of this solution is to write some test code that checks that the Java enum and the database enum table have the same contents. That's left as an exercise for the reader.

remove borders around html input

Try this

#generic_search_button
{
    float: left;
    width: 24px; /*new width*/
    height: 24px; /*new width*/
    border: none !important; /* no border and override any inline styles*/
    margin-top: 7px;
    cursor: pointer;
    background-color: White;
    background-image: url(/Images/search.png);
    background-repeat: no-repeat;
    background-position: center center;
}

I think the image size might be wrong

How to show a running progress bar while page is loading

Take a look here,

html file

<div class='progress' id="progress_div">
   <div class='bar' id='bar1'></div>
   <div class='percent' id='percent1'></div>
</div>

<div id="wrapper">
   <div id="content">
     <h1>Display Progress Bar While Page Loads Using jQuery<p>TalkersCode.com</p></h1>
   </div>
</div>

js file

document.onreadystatechange = function(e) {
  if (document.readyState == "interactive") {
    var all = document.getElementsByTagName("*");
    for (var i = 0, max = all.length; i < max; i++) {
      set_ele(all[i]);
    }
  }
}

function check_element(ele) {
  var all = document.getElementsByTagName("*");
  var totalele = all.length;
  var per_inc = 100 / all.length;

  if ($(ele).on()) {
    var prog_width = per_inc + Number(document.getElementById("progress_width").value);
    document.getElementById("progress_width").value = prog_width;
    $("#bar1").animate({
      width: prog_width + "%"
    }, 10, function() {
      if (document.getElementById("bar1").style.width == "100%") {
        $(".progress").fadeOut("slow");
      }
    });
  } else {
    set_ele(ele);
  }
}

function set_ele(set_element) {
  check_element(set_element);
}

it definitely solve your problem for complete tutorial here is the link http://talkerscode.com/webtricks/display-progress-bar-while-page-loads-using-jquery.php

CodeIgniter: 404 Page Not Found on Live Server

I have solved this problem, please just make few changes

1- all controller class name should start with capital letter. i mean first letter of class should be capital . eg we have controler with class name Pages

so it should be Pages not pages

2- save the controller class Pages as Pages.php not pages.php

so first letter must be capital

same for model, model class first letter should be capital and also save model class as Pages_model.php not page_model.php

hope this will solve ur problem

StringUtils.isBlank() vs String.isEmpty()

public static boolean isEmpty(String ptext) {
 return ptext == null || ptext.trim().length() == 0;
}

public static boolean isBlank(String ptext) {
 return ptext == null || ptext.trim().length() == 0;
}

Both have the same code how will isBlank handle white spaces probably you meant isBlankString this has the code for handling whitespaces.

public static boolean isBlankString( String pString ) {
 int strLength;
 if( pString == null || (strLength = pString.length()) == 0)
 return true;
 for(int i=0; i < strLength; i++)
 if(!Character.isWhitespace(pString.charAt(i)))
 return false;
 return false;
}

Capture keyboardinterrupt in Python without try-except

Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signal
import sys
import time
import threading

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()
forever.wait()

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

getPathInfo() gives the extra path information after the URI, used to access your Servlet, where as getRequestURI() gives the complete URI.

I would have thought they would be different, given a Servlet must be configured with its own URI pattern in the first place; I don't think I've ever served a Servlet from root (/).

For example if Servlet 'Foo' is mapped to URI '/foo' then I would have thought the URI:

/foo/path/to/resource

Would result in:

RequestURI = /foo/path/to/resource

and

PathInfo = /path/to/resource

Rails 4: how to use $(document).ready() with turbo-links

$(document).ready(ready)  

$(document).on('turbolinks:load', ready)

How ViewBag in ASP.NET MVC works

public dynamic ViewBag
{
    get
    {
        if (_viewBag == null)
        {
            _viewBag = new DynamicViewData(() => ViewData);
        }

        return _viewBag;
    }
}

Confused about stdin, stdout and stderr?

As a complement of the answers above, here is a sum up about Redirections: Redirections cheatsheet

EDIT: This graphic is not entirely correct.

The first example does not use stdin at all, it's passing "hello" as an argument to the echo command.

The graphic also says 2>&1 has the same effect as &> however

ls Documents ABC > dirlist 2>&1
#does not give the same output as 
ls Documents ABC > dirlist &>

This is because &> requires a file to redirect to, and 2>&1 is simply sending stderr into stdout

How can I get this ASP.NET MVC SelectList to work?

I had the exact same problem. The solution is simple. Just change the "name" parameter passed to the DropDownList helper to something that does not match any of the properties existing in your ViewModel. read more here: http://www.dotnetguy.co.uk/post/2009/06/25/net-mvc-selectlists-selected-value-does-not-get-set-in-the-view

I quote the Dan Watson:

In MVC if the view is strongly typed the selectlist’s selected option will be overridden and the selected option property set on the constructor will never reach the view and the first option in the dropdown will be selected instead (why is still a bit of a mystery).

cheers!

Is it wrong to place the <script> tag after the </body> tag?

Yes. But if you do add the code outside it most likely will not be the end of the world since most browsers will fix it, but it is still a bad practice to get into.

Facebook how to check if user has liked page and show content?

There are some changes required to JavaScript code to handle rendering based on user liking or not liking the page mandated by Facebook moving to Auth2.0 authorization.

Change is fairly simple:-

sessions has to be replaced by authResponse and uid by userID

Moreover given the requirement of the code and some issues faced by people(including me) in general with FB.login, use of FB.getLoginStatus is a better alternative. It saves query to FB in case user is logged in and has authenticated your app.

Refer to Response and Sessions Object section for info on how this might save query to FB server. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

Issues with FB.login and its fixes using FB.getLoginStatus. http://forum.developers.facebook.net/viewtopic.php?id=70634

Here is the code posted above with changes which worked for me.

$(document).ready(function(){
    FB.getLoginStatus(function(response) {
        if (response.status == 'connected') {
            var user_id = response.authResponse.userID;
            var page_id = "40796308305"; //coca cola
            var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid=" + user_id;
            var the_query = FB.Data.query(fql_query);

            the_query.wait(function(rows) {

                if (rows.length == 1 && rows[0].uid == user_id) {
                    $("#container_like").show();

                    //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

                } else {
                    $("#container_notlike").show();
                    //and here you could get the content for a non liker in ajax...
                }
            });
        } else {
            // user is not logged in
        }
    });

});

How to give a Blob uploaded as FormData a file name?

Haven't tested it, but that should alert the blobs data url:

var blob = event.clipboardData.items[0].getAsFile(), 
    form = new FormData(),
    request = new XMLHttpRequest();

var reader = new FileReader();
reader.onload = function(event) {
  alert(event.target.result); // <-- data url
};
reader.readAsDataURL(blob);

Fastest way to add an Item to an Array

Case C) is the fastest. Having this as an extension:

Public Module MyExtensions
    <Extension()> _
    Public Sub Add(Of T)(ByRef arr As T(), item As T)
        Array.Resize(arr, arr.Length + 1)
        arr(arr.Length - 1) = item
    End Sub
End Module

Usage:

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr.Add(newItem)

' --> duration for adding 100.000 items: 1 msec
' --> duration for adding 100.000.000 items: 1168 msec

Where to get this Java.exe file for a SQL Developer installation

You need to install JAVA SDK and give the path upto bin directory which contains the java.exe file.

example - c:/programfiles/java/jdk/bin

How to implement HorizontalScrollView like Gallery?

I implemented something similar with Horizontal Variable ListView The only drawback is, it works only with Android 2.3 and later.

Using this library is as simple as implementing a ListView with a corresponding Adapter. The library also provides an example

How to cherry pick a range of commits and merge into another branch?

I have tested that some days ago, after reading the very clear explanation of Vonc.

My steps

Start

  • Branch dev : A B C D E F G H I J
  • Branch target: A B C D
  • I don't want E nor H

Steps to copy features without the step E and H in the branch dev_feature_wo_E_H

  • git checkout dev
  • git checkout -b dev_feature_wo_E_H
  • git rebase --interactive --rebase-merges --no-ff D where I put drop front of E and H in the rebase editor
  • resolve conflicts, continue and commit

Steps to copy the the branch dev_feature_wo_E_H on target.

  • git checkout target
  • git merge --no-ff --no-commit dev_feature_wo_E_H
  • resolve conflicts, continue and commit

Some remarks

  • I've done that because of too much cherry-pick in the days before
  • git cherry-pick is powerful and simple but

    • it creates duplicates commits
    • and when I want to merge I have to resolve conflicts of the initial commits and duplicates commits, so for one or two cherry-pick, it's OK to "cherry-picking" but for more it's too verbose and the branch will become too complex
  • In my mind the steps I've done are more clear than git rebase --onto

Algorithm to calculate the number of divisors of a given number

The sieve of Atkin is an optimized version of the sieve of Eratosthenes which gives all prime numbers up to a given integer. You should be able to google this for more detail.

Once you have that list, it's a simple matter to divide your number by each prime to see if it's an exact divisor (i.e., remainder is zero).

The basic steps calculating the divisors for a number (n) are [this is pseudocode converted from real code so I hope I haven't introduced errors]:

for z in 1..n:
    prime[z] = false
prime[2] = true;
prime[3] = true;

for x in 1..sqrt(n):
    xx = x * x

    for y in 1..sqrt(n):
        yy = y * y

        z = 4*xx+yy
        if (z <= n) and ((z mod 12 == 1) or (z mod 12 == 5)):
            prime[z] = not prime[z]

        z = z-xx
        if (z <= n) and (z mod 12 == 7):
            prime[z] = not prime[z]

        z = z-yy-yy
        if (z <= n) and (x > y) and (z mod 12 == 11):
            prime[z] = not prime[z]

for z in 5..sqrt(n):
    if prime[z]:
        zz = z*z
        x = zz
        while x <= limit:
            prime[x] = false
            x = x + zz

for z in 2,3,5..n:
    if prime[z]:
        if n modulo z == 0 then print z

convert date string to mysql datetime field

Use DateTime::createFromFormat like this :

$date = DateTime::createFromFormat('m/d/Y H:i:s', $input_string.' 00:00:00');
$mysql_date_string = $date->format('Y-m-d H:i:s');

You can adapt this to any input format, whereas strtotime() will assume you're using the US date format if you use /, even if you're not.

The added 00:00:00 is because createFromFormat will use the current date to fill missing data, ie : it will take the current hour:min:sec and not 00:00:00 if you don't precise it.

Copying PostgreSQL database to another server

Accepted answer is correct, but if you want to avoid entering the password interactively, you can use this:

PGPASSWORD={{export_db_password}} pg_dump --create -h {{export_db_host}} -U {{export_db_user}} {{export_db_name}} | PGPASSWORD={{import_db_password}} psql -h {{import_db_host}} -U {{import_db_user}} {{import_db_name}}

Reload browser window after POST without prompting user to resend POST data

This worked

<button onclick="window.location.href=window.location.href; return false;">Continue</button>

The reason it doesn't work without the return false; is that the button click would trigger a form submit. With an explicit return false on it, it doesn't do the form submit and just does the reload of the same page that was a result of a previous POST to that page.

Phone Number Validation MVC

Try this:

[DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]

How do I suspend painting for a control and its children?

To help with not forgetting to reenable drawing:

public static void SuspendDrawing(Control control, Action action)
{
    SendMessage(control.Handle, WM_SETREDRAW, false, 0);
    action();
    SendMessage(control.Handle, WM_SETREDRAW, true, 0);
    control.Refresh();
}

usage:

SuspendDrawing(myControl, () =>
{
    somemethod();
});

Python list sort in descending order

You can simply do this:

timestamps.sort(reverse=True)

How to open CSV file in R when R says "no such file or directory"?

this work for me, accesing data from root. use double slash to access address.

dataset = read.csv('C:\\Users\\Desktop\\Machine Learning\\Data.csv')

Bulk package updates using Conda

You want conda update --all.

conda search --outdated will show outdated packages, and conda update --all will update them (note that the latter will not update you from Python 2 to Python 3, but the former will show Python as being outdated if you do use Python 2).

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

How to plot multiple functions on the same figure, in Matplotlib?

Perhaps a more pythonic way of doing so.

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

How can I get a web site's favicon?

Sometimes we can't get the favicon image with the purposed solution as some websites use .png or other image extensions. Here is the working solution.

  1. Open your website with a firefox browser.
  2. Right-click on the website and click the "View page info" option from the list.
  3. It will open up a dialog and click on the "Media" tab.
  4. In that tab you will see all the images including favicon.
  5. Select the favicon.ico image or click through the images to see which image is used as favicon. Some websites use .png images as well.
  6. Then click on the "Save As" button and you should be good to go.

thanks!

How to get an input text value in JavaScript

All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value; inside the function function kk().

What I suggest is, you may call that variable from another function fun_inside()

function fun_inside()
{    
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}

It can be useful when you built complex projects.

iOS 7 - Failing to instantiate default view controller

None of the above solved the issue for me. In my case it was not also setting the correct application scene manifest.

I had to change LoginScreen used to be Main

enter image description here

What is the size limit of a post request?

As David pointed out, I would go with KB in most cases.

php_value post_max_size 2K

Note: my form is simple, just a few text boxes, not long text.

(PHP shorthand for KB is K, as outlined here.)

Installing tensorflow with anaconda in windows

1) Update conda

Run the anaconda prompt as administrator

conda update -n base -c defaults conda

2) Create an environment for python new version say, 3.6

conda create --name py36 python=3.6

3) Activate the new environment

conda activate py36

4) Upgrade pip

pip install --upgrade pip

5) Install tensorflow

pip install https://testpypi.python.org/packages/db/d2/876b5eedda1f81d5b5734277a155fa0894d394a7f55efa9946a818ad1190/tensorflow-0.12.1-cp36-cp36m-win_amd64.whl

If it doesn't work

If you have problem with wheel at the environment location, or pywrap_tensorflow problem,

 pip install tensorflow --upgrade --force-reinstall

How do I import .sql files into SQLite 3?

From a sqlite prompt:

sqlite> .read db.sql

Or:

cat db.sql | sqlite3 database.db

Also, your SQL is invalid - you need ; on the end of your statements:

create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);

Spring Boot Java Config Set Session Timeout

server.session.timeout in the application.properties file is now deprecated. The correct setting is:

server.servlet.session.timeout=60s

Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

It can be a mathematical convention in the definition of an interval where square brackets mean "extremal inclusive" and round brackets "extremal exclusive".

Stop node.js program from command line

If you want to stop your server with npm stop or something like this. You can write the code that kill your server process as:

require('child_process').exec(`kill -9 ${pid}`)

Check this link for the detail: https://gist.github.com/dominhhai/aa7f3314ad27e2c50fd5

Why does ++[[]][+[]]+[+[]] return the string "10"?

Perhaps the shortest possible ways to evaluate an expression into "10" without digits are:

+!+[] + [+[]] // "10"

-~[] + [+[]] // "10"

//========== Explanation ==========\\

+!+[] : +[] Converts to 0. !0 converts to true. +true converts to 1. -~[] = -(-1) which is 1

[+[]] : +[] Converts to 0. [0] is an array with a single element 0.

Then JS evaluates the 1 + [0], thus Number + Array expression. Then the ECMA specification works: + operator converts both operands to a string by calling the toString()/valueOf() functions from the base Object prototype. It operates as an additive function if both operands of an expression are numbers only. The trick is that arrays easily convert their elements into a concatenated string representation.

Some examples:

1 + {} //    "1[object Object]"
1 + [] //    "1"
1 + new Date() //    "1Wed Jun 19 2013 12:13:25 GMT+0400 (Caucasus Standard Time)"

There's a nice exception that two Objects addition results in NaN:

[] + []   //    ""
[1] + [2] //    "12"
{} + {}   //    NaN
{a:1} + {b:2}     //    NaN
[1, {}] + [2, {}] //    "1,[object Object]2,[object Object]"

Deleting rows from parent and child tables

Here's a complete example of how it can be done. However you need flashback query privileges on the child table.

Here's the setup.

create table parent_tab
  (parent_id number primary key,
  val varchar2(20));

create table child_tab
    (child_id number primary key,
    parent_id number,
    child_val number,
     constraint child_par_fk foreign key (parent_id) references parent_tab);

insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');

insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);

commit;

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).

delete from child_tab where child_val = 100;

Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab

delete from parent_tab
where parent_id in
  (select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
  minus
  select parent_id from child_tab);

'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

select * from parent_tab;

It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.

Using dig to search for SPF records

I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:

dig @ns1.nameserver1.com domain.com txt

How to click on hidden element in Selenium WebDriver?

First store that element in object, let's say element and then write following code to click on that hidden element:

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

Postman - How to see request with headers and body data with variables substituted

Even though they are separate windows but the request you send from Postman, it's details should be available in network tab of developer tools. Just make sure you are not sending any other http traffic during that time, just for clarity.

SVN Repository on Google Drive or DropBox

Here's one application that works for me. In our case...I wanted the Sales team to use SVN for certain docs (Price sheets and such)...but a bit over there head.

I setup an Auto SVN like this: - Created a REPO in my SVN server. - Checked out repo into a DB folder call AutoSVN. - I run EasySVN on my PC, which auto commits and updates the REPO.

With he 'Auto', there are no log comments, but not critical for these particular docs.

The Sales guys use the DB folder...and simply maintain the file name of those docs that need version control such as price sheets.

How to solve error: "Clock skew detected"?

please try to do

make clean

(instead of make), then

make

again.

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

This code simply worked for me

System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox 54\\firefox.exe");
String Firefoxdriverpath = "C:\\Users\\Hp\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", Firefoxdriverpath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);

Customizing the template within a Directive

Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.

Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.

The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:

    angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
           var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
             return htmlText;
        }
        compile: function(element, attrs)
        {
           //do whatever else is necessary
        }
    }
})

What does \d+ mean in regular expression terms?

\d means 'digit'. + means, '1 or more times'. So \d+ means one or more digit. It will match 12 and 1.

Converting char[] to byte[]

private static byte[] charArrayToByteArray(char[] c_array) {
        byte[] b_array = new byte[c_array.length];
        for(int i= 0; i < c_array.length; i++) {
            b_array[i] = (byte)(0xFF & (int)c_array[i]);
        }
        return b_array;
}

Pass array to ajax request in $.ajax()

info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});

How to convert Java String into byte[]?

I know I'm a little late tothe party but thisworks pretty neat (our professor gave it to us)

public static byte[] asBytes (String s) {                   
           String tmp;
           byte[] b = new byte[s.length() / 2];
           int i;
           for (i = 0; i < s.length() / 2; i++) {
             tmp = s.substring(i * 2, i * 2 + 2);
             b[i] = (byte)(Integer.parseInt(tmp, 16) & 0xff);
           }
           return b;                                            //return bytes
    }

Can I get a patch-compatible output from git-diff?

If you want to use patch you need to remove the a/ b/ prefixes that git uses by default. You can do this with the --no-prefix option (you can also do this with patch's -p option):

git diff --no-prefix [<other git-diff arguments>]

Usually though, it is easier to use straight git diff and then use the output to feed to git apply.

Most of the time I try to avoid using textual patches. Usually one or more of temporary commits combined with rebase, git stash and bundles are easier to manage.

For your use case I think that stash is most appropriate.

# save uncommitted changes
git stash

# do a merge or some other operation
git merge some-branch

# re-apply changes, removing stash if successful
# (you may be asked to resolve conflicts).
git stash pop

Does a finally block always get executed in Java?

No, not always one exception case is// System.exit(0); before the finally block prevents finally to be executed.

  class A {
    public static void main(String args[]){
        DataInputStream cin = new DataInputStream(System.in);
        try{
            int i=Integer.parseInt(cin.readLine());
        }catch(ArithmeticException e){
        }catch(Exception e){
           System.exit(0);//Program terminates before executing finally block
        }finally{
            System.out.println("Won't be executed");
            System.out.println("No error");
        }
    }
}

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

how to count the spaces in a java string?

If you use Java 8, the following should work:

long count = "0 1 2 3 4.".chars().filter(Character::isWhitespace).count();

This will also work in Java 8 using Eclipse Collections:

int count = Strings.asChars("0 1 2 3 4.").count(Character::isWhitespace);

Note: I am a committer for Eclipse Collections.

Get specific ArrayList item

Time to familiarize yourself with the ArrayList API and more:

ArrayList at Java 6 API Documentation

For your immediate question:

mainList.get(3);

Dynamic classname inside ngClass in angular 2

Is basically duplication of the other answers - but I didn't get it completely. maybe someone will finally understand it with this example now.

[ngClass]="['svg-icon', 'recolor-' + recolor, size ? 'size-' + size : '']"

will result for e.g. in

class="svg-icon recolor-red size-m"

How to simulate key presses or a click with JavaScript?

Simulating a mouse click

My guess is that the webpage is listening to mousedown rather than click (which is bad for accessibility because when a user uses the keyboard, only focus and click are fired, not mousedown). So you should simulate mousedown, click, and mouseup (which, by the way, is what the iPhone, iPod Touch, and iPad do on tap events).

To simulate the mouse events, you can use this snippet for browsers that support DOM 2 Events. For a more foolproof simulation, fill in the mouse position using initMouseEvent instead.

// DOM 2 Events
var dispatchMouseEvent = function(target, var_args) {
  var e = document.createEvent("MouseEvents");
  // If you need clientX, clientY, etc., you can call
  // initMouseEvent instead of initEvent
  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
dispatchMouseEvent(element, 'mouseover', true, true);
dispatchMouseEvent(element, 'mousedown', true, true);
dispatchMouseEvent(element, 'click', true, true);
dispatchMouseEvent(element, 'mouseup', true, true);

When you fire a simulated click event, the browser will actually fire the default action (e.g. navigate to the link's href, or submit a form).

In IE, the equivalent snippet is this (unverified since I don't have IE). I don't think you can give the event handler mouse positions.

// IE 5.5+
element.fireEvent("onmouseover");
element.fireEvent("onmousedown");
element.fireEvent("onclick");  // or element.click()
element.fireEvent("onmouseup");

Simulating keydown and keypress

You can simulate keydown and keypress events, but unfortunately in Chrome they only fire the event handlers and don't perform any of the default actions. I think this is because the DOM 3 Events working draft describes this funky order of key events:

  1. keydown (often has default action such as fire click, submit, or textInput events)
  2. keypress (if the key isn't just a modifier key like Shift or Ctrl)
  3. (keydown, keypress) with repeat=true if the user holds down the button
  4. default actions of keydown!!
  5. keyup

This means that you have to (while combing the HTML5 and DOM 3 Events drafts) simulate a large amount of what the browser would otherwise do. I hate it when I have to do that. For example, this is roughly how to simulate a key press on an input or textarea.

// DOM 3 Events
var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
  var e = document.createEvent("KeyboardEvents");
  e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
var dispatchTextEvent = function(target, initTextEvent_args) {
  var e = document.createEvent("TextEvent");
  e.initTextEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
var dispatchSimpleEvent = function(target, type, canBubble, cancelable) {
  var e = document.createEvent("Event");
  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};

var canceled = !dispatchKeyboardEvent(element,
    'keydown', true, true,  // type, bubbles, cancelable
    null,  // window
    'h',  // key
    0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick
    '');  // space-sparated Shift, Control, Alt, etc.
dispatchKeyboardEvent(
    element, 'keypress', true, true, null, 'h', 0, '');
if (!canceled) {
  if (dispatchTextEvent(element, 'textInput', true, true, null, 'h', 0)) {
    element.value += 'h';
    dispatchSimpleEvent(element, 'input', false, false);
    // not supported in Chrome yet
    // if (element.form) element.form.dispatchFormInput();
    dispatchSimpleEvent(element, 'change', false, false);
    // not supported in Chrome yet
    // if (element.form) element.form.dispatchFormChange();
  }
}
dispatchKeyboardEvent(
    element, 'keyup', true, true, null, 'h', 0, '');

I don't think it is possible to simulate key events in IE.

Extracting the last n characters from a string in R

UPDATE: as noted by mdsumner, the original code is already vectorised because substr is. Should have been more careful.

And if you want a vectorised version (based on Andrie's code)

substrRight <- function(x, n){
  sapply(x, function(xx)
         substr(xx, (nchar(xx)-n+1), nchar(xx))
         )
}

> substrRight(c("12345","ABCDE"),2)
12345 ABCDE
 "45"  "DE"

Note that I have changed (nchar(x)-n) to (nchar(x)-n+1) to get n characters.

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

Such inexplicable exceptions are often a result of an unclean xib file. Open the xib in xcode, select File's Owner and click on the "Connection Inspector" (upper right arrow), to see all outlets at once. Look for !s which indicates a missing outlet.

Print out the values of a (Mat) matrix in OpenCV C++

If you are using opencv3, you can print Mat like python numpy style:

Mat xTrainData = (Mat_<float>(5,2) << 1, 1, 1, 1, 2, 2, 2, 2, 2, 2);

cout << "xTrainData (python)  = " << endl << format(xTrainData, Formatter::FMT_PYTHON) << endl << endl;

Output as below, you can see it'e more readable, see here for more information.

enter image description here

But in most case, there is no need to output all the data in Mat, you can output by row range like 0 ~ 2 row:

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    //row: 6, column: 3,unsigned one channel
    Mat image1(6, 3, CV_8UC1, 5);

    // output row: 0 ~ 2
    cout << "image1 row: 0~2 = "<< endl << " "  << image1.rowRange(0, 2) << endl << endl;

    //row: 8, column: 2,unsigned three channel
    Mat image2(8, 2, CV_8UC3, Scalar(1, 2, 3));

    // output row: 0 ~ 2
    cout << "image2 row: 0~2 = "<< endl << " "  << image2.rowRange(0, 2) << endl << endl;

    return 0;
}

Output as below:

enter image description here

Add a linebreak in an HTML text area

In a text area, as in the form input, then just a normal line break will work:

<textarea>
This is a text area
line breaks are automatic
</textarea>

If you're talking about normal text on the page, the <br /> (or just <br> if using plain 'ole HTML4) is a line break.

However, I'd say that you often don't actually want a line break. Usually, your text is seperated into paragraphs:

<p>
  This is some text
</p>
<p>
  This is some more
</p>

Which is much better because it gives a clue as to how your text is structured to machines that read it. Machines that read it include screen readers for the partially sighted or blind, seperating text into paragraphs gives it a chance of being presented correctly to these users.

Best way to convert pdf files to tiff files

Required ghostscript & tiffcp Tested in Ubuntu

import os

def pdf2tiff(source, destination):
    idx = destination.rindex('.')
    destination = destination[:idx]
    args = [
    '-q', '-dNOPAUSE', '-dBATCH',
    '-sDEVICE=tiffg4',
    '-r600', '-sPAPERSIZE=a4',
    '-sOutputFile=' + destination + '__%03d.tiff'
    ]
    gs_cmd = 'gs ' + ' '.join(args) +' '+ source
    os.system(gs_cmd)
    args = [destination + '__*.tiff', destination + '.tiff' ]
    tiffcp_cmd = 'tiffcp  ' + ' '.join(args)
    os.system(tiffcp_cmd)
    args = [destination + '__*.tiff']
    rm_cmd = 'rm  ' + ' '.join(args)
    os.system(rm_cmd)    
pdf2tiff('abc.pdf', 'abc.tiff')

Using a batch to copy from network drive to C: or D: drive

You are copying all files to a single file called TEST_BACKUP_FOLDER

try this:

md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER

MSBUILD : error MSB1008: Only one project can be specified

If you are using Azure DevOps MSBuild task the error may be caused by doubled configuration flag. Please make sure you put $(BuildConfiguration) in specified box instead of MSBuild Arguments one: enter image description here

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

If you use the WEB API with Claims, you can use this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute:  AuthorizationFilterAttribute
{
    public string Company { get; set; }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
        var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();

        string privilegeLevels = string.Join("", claim.Value);        

        if (privilegeLevels.Contains(this.Company)==false)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
        }
    }
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}

How to export html table to excel using javascript

Check https://github.com/linways/table-to-excel. Its a wrapper for exceljs/exceljs to export html tables to xlsx.

_x000D_
_x000D_
TableToExcel.convert(document.getElementById("simpleTable1"));
_x000D_
<script src="https://cdn.jsdelivr.net/gh/linways/[email protected]/dist/tableToExcel.js"></script>_x000D_
<table id="simpleTable1" data-cols-width="70,15,10">_x000D_
<tbody>_x000D_
    <tr>_x000D_
        <td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="middle" data-f-underline="true">_x000D_
            Sample Excel_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial" data-a-v="top">_x000D_
            Italic and horizontal center in Arial_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th data-a-text-rotation="90">Col 1 (number)</th>_x000D_
        <th data-a-text-rotation="vertical">Col 2</th>_x000D_
        <th data-a-wrap="true">Wrapped Text</th>_x000D_
        <th data-a-text-rotation="-45">Col 4 (date)</th>_x000D_
        <th data-a-text-rotation="-90">Col 5</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td rowspan="1" data-t="n">1</td>_x000D_
        <td rowspan="1" data-b-b-s="thick" data-b-l-s="thick" data-b-r-s="thick">_x000D_
            ABC1_x000D_
        </td>_x000D_
        <td rowspan="1" data-f-strike="true">Striked Text</td>_x000D_
        <td data-t="d">05-20-2018</td>_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2210.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td rowspan="2" data-t="n">2</td>_x000D_
        <td rowspan="2" data-fill-color="FFFF0000" data-f-color="FFFFFFFF">_x000D_
            ABC 2_x000D_
        </td>_x000D_
        <td rowspan="2" data-a-indent="3">Merged cell</td>_x000D_
        <td data-t="d">05-21-2018</td>_x000D_
        <td data-t="n" data-b-a-s="dashed" data-num-fmt="$ 0.00">230.00</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="d">05-22-2018</td>_x000D_
_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2493.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-h="right" data-hyperlink="https://google.com">_x000D_
            <b><a href="https://google.com">Hyperlink</a></b>_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>4933.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-rtl="true">_x000D_
            ?????_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>2009.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-a-s="dashed" data-b-a-c="FFFF0000">All borders</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="b">true</td>_x000D_
        <td data-t="b">false</td>_x000D_
        <td data-t="b">1</td>_x000D_
        <td data-t="b">0</td>_x000D_
        <td data-error="#VALUE!">Value Error</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-t-s="thick" data-b-l-s="thick" data-b-b-s="thick" data-b-r-s="thick" data-b-t-c="FF00FF00" data-b-l-c="FF00FF00" data-b-b-c="FF00FF00" data-b-r-c="FF00FF00">_x000D_
            All borders separately_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr data-exclude="true">_x000D_
        <td>Excluded row</td>_x000D_
        <td>Something</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Included Cell</td>_x000D_
        <td data-exclude="true">Excluded Cell</td>_x000D_
        <td>Included Cell</td>_x000D_
    </tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This creates valid xlsx on the client side. Also supports some basic styling. Check https://codepen.io/rohithb/pen/YdjVbb for a working example.

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

How to expand a list to function arguments in Python

Try the following:

foo(*values)

This can be found in the Python docs as Unpacking Argument Lists.

VBA check if file exists

Maybe it caused by Filename variable

File = TextBox1.Value

It should be

Filename = TextBox1.Value

How can I post an array of string to ASP.NET MVC Controller without a form?

Thanks everyone for the answers. Another quick solution will be to use jQuery.param method with traditional parameter set to true to convert JSON object to string:

$.post("/your/url", $.param(yourJsonObject,true));

How to remove specific value from array using jQuery

The second most upvoted answer here is on the closest track possible to a one-liner jQuery method of the intended behavior the OP wants, but they stumbled at the end of their code, and it has a flaw. If your item to be removed isn't actually in the array, the last item will get removed.

A few have noticed this issue, and some have offered ways to loop through to guard against this. I offer the shortest, cleanest method I could find, and I have commented under their answer for the way to fix their code according to this method.

var x = [1, 2, "bye", 3, 4];
var y = [1, 2, 3, 4];
var removeItem = "bye";

// Removing an item that exists in array
x.splice( $.inArray(removeItem,x), $.inArray(removeItem,x) ); // This is the one-liner used

// Removing an item that DOESN'T exist in array
y.splice( $.inArray(removeItem,y), $.inArray(removeItem,y) ); // Same usage, different array

// OUTPUT -- both cases are expected to be [1,2,3,4]
alert(x + '\n' + y);

array x will remove the element "bye" easily, and array y will be untouched.

The use of the argument $.inArray(removeItem,array) as a second argument actually ends up being the length to splice. Since the item was not found, this evaluates to array.splice(-1,-1);, which will just result in nothing being spliced... all without having to write a loop for this.

How to find Oracle Service Name

Check the service name of a database by

sql> show parameter service;

How can I provide multiple conditions for data trigger in WPF?

To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c).

For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.

The logic for dimming is thus:

NOT IsFocused AND (IsDefocused OR NOT Enabled)

To implement this logic, I made a generic IMultiValueConverter named (awkwardly) to match my logic

// 'P' represents a parenthesis
//     !  a &&  ( b ||  !  c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
    // redacted [...] for brevity
    public object Convert(object[] values, ...)
    {
        bool a = System.Convert.ToBoolean(values[0]);
        bool b = System.Convert.ToBoolean(values[1]);
        bool c = System.Convert.ToBoolean(values[2]);

        return !a && (b || !c);
    }
    ...
}

In the XAML I use this in a MultiDataTrigger in a <Style><Style.Triggers> resource

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <!-- when the equation is TRUE ... -->
        <Condition Value="True">
            <Condition.Binding>
                <MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
                    <!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
                    <Binding Path="IsFocus"/>
                    <Binding Path="IsDefocused" />
                    <Binding Path="Enabled" />
                </MultiBinding>
            </Condition.Binding>
        </Condition>
    </MultiDataTrigger.Conditions>
    <MultiDataTrigger.Setters>
        <!-- ... show the 'dim-out' overlay -->
        <Setter Property="Visibility" Value="Visible" />
    </MultiDataTrigger.Setters>
</MultiDataTrigger>

And for completeness sake, my converter is defined in a ResourceDictionary

<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
    <conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>

How to set True as default value for BooleanField on Django?

In DJango 3.0 the default value of a BooleanField in model.py is set like this:

class model_name(models.Model):
example_name = models.BooleanField(default=False)

Binding objects defined in code-behind

One way would be to create an ObservableCollection (System.Collections.ObjectModel) and have your dictionary data in there. Then you should be able to bind the ObservableCollection to your ListBox.

In your XAML you should have something like this:

<ListBox ItemsSource="{Binding Path=Name_of_your_ObservableCollection" />

Ansible date variable

The filter option filters only the first level subkey below ansible_facts

Inversion of Control vs Dependency Injection

IOC (Inversion Of Control): Giving control to the container to get an instance of the object is called Inversion of Control, means instead of you are creating an object using the new operator, let the container do that for you.

DI (Dependency Injection): Way of injecting properties to an object is called Dependency Injection.

We have three types of Dependency Injection:

  1. Constructor Injection
  2. Setter/Getter Injection
  3. Interface Injection

Spring supports only Constructor Injection and Setter/Getter Injection.

When to throw an exception?

I have philosophical problems with the use of exceptions. Basically, you are expecting a specific scenario to occur, but rather than handling it explicitly you are pushing the problem off to be handled "elsewhere." And where that "elsewhere" is can be anyone's guess.

Error - Unable to access the IIS metabase

Open visual studio command prompt and type below command and run

aspnet_regiis -ga machinename\ASPNET

After running the above command Reset the IIS and test the application that resolve your issue.

If above command doesn’t resolve your problem then try to run below command in visual studio command prompt:-

aspnet_regiis -i

Alternatively we can run above command from our windows command prompt also

Go to the Start menu and open Run and enter and click OK

%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe –I

After that Reset the IIS and test the application that resolves your issue

Android ListView with onClick items

listview.setOnItemClickListener(new OnItemClickListener(){

//setting onclick to items in the listview.

@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){

// case 0 is the first item in the listView.

  case 0:
    intent = new Intent(Activity.this,firstActivity.class);
    break;
//case 1 is the second item in the listView.

  case 1:
    intent = new Intent(Activity.this,secondActivity.class);
    break;
 case 2:
    intent = new Intent(Activity.this,thirdActivity.class);
    break;
//add more if you have more items in listView
startActivity(intent);
}

});

MISCONF Redis is configured to save RDB snapshots

I hit this problem while working on a server with AFS disk space because my authentication token had expired, which yielded Permission Denied responses when the redis-server tried to save. I solved this by refreshing my token:

kinit USERNAME_HERE -l 30d && aklog

The page cannot be displayed because an internal server error has occurred on server

In my case, setting httpErrors and the like in Web.config did not help to identify the issue.

Instead I did:

  1. Activate "Failed Request Tracing" for the website with the error.
  2. Configured a trace for HTTP errors 350-999 (just in case), although I suspected 500.
  3. Called the erroneous URL again.
  4. Watched in the log folder ("%SystemDrive%\inetpub\logs\FailedReqLogFiles" in my case).
  5. Opened one of the XML files in Internet Explorer.

I then saw an entry with a detailed exception information. In my case it was

\?\C:\Websites\example.com\www\web.config ( 592) :Cannot add duplicate collection entry of type 'mimeMap' with unique key attribute 'fileExtension' set to '.json'

I now was able to resolve it and fix the error. After that I deactivated "Failed Request Tracing" again.

You need to use a Theme.AppCompat theme (or descendant) with this activity

For me none of the above answers worked even after I had Theme.AppCompat as my base theme for the application. I was using com.android.support:design:24.1.0 So I just changed the version to 24.1.1. After the gradle sync, Its working again and the exception went away. Seems to me the issue was with some older versions of design support libraries.

Just putting this here in case other answers don't work for some people.

How can I determine browser window size on server side C#

Here how I solved it using Cookies:

First of all, inside the website main script:

var browserWindowSize = getCookie("_browserWindowSize");
var newSize = $(window).width() + "," + $(window).height();
var reloadForCookieRefresh = false;

if (browserWindowSize == undefined || browserWindowSize == null || newSize != browserWindowSize) {
    setCookie("_browserWindowSize", newSize, 30);
    reloadForCookieRefresh = true;
}

if (reloadForCookieRefresh)
    window.location.reload();

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

And inside MVC action filter:

public class SetCurrentRequestDataFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // currentRequestService is registered per web request using IoC
        var currentRequestService = iocResolver.Resolve<ICurrentRequestService>();

        if (filterContext.HttpContext.Request.Cookies.AllKeys.Contains("_browserWindowSize"))
        {
            var browserWindowSize = filterContext.HttpContext.Request.Cookies.Get("_browserWindowSize").Value.Split(',');
            currentRequestService.browserWindowWidth = int.Parse(browserWindowSize[0]);
            currentRequestService.browserWindowHeight = int.Parse(browserWindowSize[1]);
        }

    }
}

C#: Assign same value to multiple variables in single statement

Something a little shorter in syntax but taking what the others have already stated.

int num1, num2 = num1 = 1;

How to make VS Code to treat other file extensions as certain language?

The easiest way I've found for a global association is simply to ctrl+k m (or ctrl+shift+p and type "change language mode") with a file of the type you're associating open.

In the first selections will be "Configure File Association for 'x' " (whatever file type - see image attached) Selecting this makes the filetype association permanent

enter image description here

This may have changed (probably did) since the original question and accepted answer (and I don't know when it changed) but it's so much easier than the manual editing steps in the accepted and some of the other answers, and totaly avoids having to muss with IDs that may not be obvious.

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

How to tell if string starts with a number with Python?

Surprising that after such a long time there is still the best answer missing.

The downside of the other answers is using [0] to select the first character, but as noted, this breaks on the empty string.

Using the following circumvents this problem, and, in my opinion, gives the prettiest and most readable syntax of the options we have. It also does not import/bother with regex either):

>>> string = '1abc'
>>> string[:1].isdigit()
True

>>> string = ''
>>> string[:1].isdigit()
False

How do I create dynamic properties in C#?

If you need this for data-binding purposes, you can do this with a custom descriptor model... by implementing ICustomTypeDescriptor, TypeDescriptionProvider and/or TypeCoverter, you can create your own PropertyDescriptor instances at runtime. This is what controls like DataGridView, PropertyGrid etc use to display properties.

To bind to lists, you'd need ITypedList and IList; for basic sorting: IBindingList; for filtering and advanced sorting: IBindingListView; for full "new row" support (DataGridView): ICancelAddNew (phew!).

It is a lot of work though. DataTable (although I hate it) is cheap way of doing the same thing. If you don't need data-binding, just use a hashtable ;-p

Here's a simple example - but you can do a lot more...

Create a remote branch on GitHub

It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.

To retrieve your new branch from github, use the standard git fetch command.

create branch github ui

I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.

process.env.NODE_ENV is undefined

As early as possible in your application, require and configure dotenv.

require('dotenv').config()

Hibernate Group by Criteria Object

GroupBy using in Hibernate

This is the resulting code

public Map getStateCounts(final Collection ids) {
    HibernateSession hibernateSession = new HibernateSession();
    Session session = hibernateSession.getSession();
    Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
            .add(Restrictions.in("id", ids));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("state"));
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);
    List results = criteria.list();
    Map stateMap = new HashMap();
    for (Object[] obj : results) {
        DownloadState downloadState = (DownloadState) obj[0];
        stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
    }
    hibernateSession.closeSession();
    return stateMap;
}

How to force Eclipse to ask for default workspace?

I had the same problem on my eclipse, and calling eclipse -clean did not solve the problem.

In the end I figured out that within the installation folder of eclipse there is a script called eclipse. This script does some setting of environment variables and then calls eclipse.bin. The call for eclipse.bin contained the command line switch

-data ~/.eclipse

When I removed that switch from start-up script, I got the workspace selection as expected. Maybe that helps others to solve their problems.

Testing socket connection in Python

12 years later for anyone having similar problems.

try:
    s.connect((address, '80'))
except:
    alert('failed' + address, 'down')

doesn't work because the port '80' is a string. Your port needs to be int.

try:
    s.connect((address, 80))

This should work. Not sure why even the best answer didnt see this.

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

Where is virtualenvwrapper.sh after pip install?

Have you installed it using sudo? Was the error in my case.

If...Then...Else with multiple statements after Then

This works with multiple statements:

if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6

Or you can split it over multiple lines:

if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

I had the same issue using an older version of Fancybox. Upgrading to v3 will solve your problem OR you can just add:

html, body {
    -webkit-overflow-scrolling : touch !important;
    overflow: auto !important;
    height: 100% !important;
}

Rolling back local and remote git repository by 1 commit

If you want revert last commit listen:

Step 1:

Check your local commits with messages

$ git log

Step 2:

Remove last commit without resetting the changes from local branch (or master)

$ git reset HEAD^

OR if you don't want last commit files and updates listens

$ git reset HEAD^ --hard

Step 3:

We can update the files and codes and again need to push with force it will delete previous commit. It will keep new commit.

$ git push origin branch -f

That's it!

Quickly create large file on a Windows system

Simple answer in Python: If you need to create a large real text file I just used a simple while loop and was able to create a 5 GB file in about 20 seconds. I know it's crude, but it is fast enough.

outfile = open("outfile.log", "a+")

def write(outfile):
    outfile.write("hello world hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello world"+"\n")
    return

i=0
while i < 1000000:
    write(outfile)
    i += 1
outfile.close()

Using setDate in PreparedStatement

The problem you're having is that you're passing incompatible formats from a formatted java.util.Date to construct an instance of java.sql.Date, which don't behave in the same way when using valueOf() since they use different formats.

I also can see that you're aiming to persist hours and minutes, and I think that you'd better change the data type to java.sql.Timestamp, which supports hours and minutes, along with changing your database field to DATETIME or similar (depending on your database vendor).

Anyways, if you want to change from java.util.Date to java.sql.Date, I suggest to use

java.util.Date date = Calendar.getInstance().getTime();
java.sql.Date sqlDate = new java.sql.Date(date.getTime()); 
// ... more code here
prs.setDate(sqlDate);

jquery if div id has children

if ( $('#myfav').children().length > 0 ) {
     // do something
}

This should work. The children() function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.

Can I obtain method parameter name using Java reflection?

Yes.
Code must be compiled with Java 8 compliant compiler with option to store formal parameter names turned on (-parameters option).
Then this code snippet should work:

Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
   System.err.println(m.getName());
   for (Parameter p : m.getParameters()) {
    System.err.println("  " + p.getName());
   }
}

C fopen vs open

opening a file using fopen
before we can read(or write) information from (to) a file on a disk we must open the file. to open the file we have called the function fopen.

1.firstly it searches on the disk the file to be opened.
2.then it loads the file from the disk into a place in memory called buffer.
3.it sets up a character pointer that points to the first character of the buffer.

this the way of behaviour of fopen function
there are some causes while buffering process,it may timedout. so while comparing fopen(high level i/o) to open (low level i/o) system call , and it is a faster more appropriate than fopen.

Converting a string to a date in JavaScript

For ?onverting string to date in js i use http://momentjs.com/

moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd');                    // Sunday
moment().format("MMM Do YY");               // Aug 16th 15
moment().format('YYYY [escaped] YYYY');     // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 16 hours ago
moment().endOf('day').fromNow();          // in 8 hours

Breadth First Vs Depth First

Given this binary tree:

enter image description here

Breadth First Traversal:
Traverse across each level from left to right.

"I'm G, my kids are D and I, my grandkids are B, E, H and K, their grandkids are A, C, F"

- Level 1: G 
- Level 2: D, I 
- Level 3: B, E, H, K 
- Level 4: A, C, F

Order Searched: G, D, I, B, E, H, K, A, C, F

Depth First Traversal:
Traversal is not done ACROSS entire levels at a time. Instead, traversal dives into the DEPTH (from root to leaf) of the tree first. However, it's a bit more complex than simply up and down.

There are three methods:

1) PREORDER: ROOT, LEFT, RIGHT.
You need to think of this as a recursive process:  
Grab the Root. (G)  
Then Check the Left. (It's a tree)  
Grab the Root of the Left. (D)  
Then Check the Left of D. (It's a tree)  
Grab the Root of the Left (B)  
Then Check the Left of B. (A)  
Check the Right of B. (C, and it's a leaf node. Finish B tree. Continue D tree)  
Check the Right of D. (It's a tree)  
Grab the Root. (E)  
Check the Left of E. (Nothing)  
Check the Right of E. (F, Finish D Tree. Move back to G Tree)  
Check the Right of G. (It's a tree)  
Grab the Root of I Tree. (I)  
Check the Left. (H, it's a leaf.)  
Check the Right. (K, it's a leaf. Finish G tree)  
DONE: G, D, B, A, C, E, F, I, H, K  

2) INORDER: LEFT, ROOT, RIGHT
Where the root is "in" or between the left and right child node.  
Check the Left of the G Tree. (It's a D Tree)  
Check the Left of the D Tree. (It's a B Tree)  
Check the Left of the B Tree. (A)  
Check the Root of the B Tree (B)  
Check the Right of the B Tree (C, finished B Tree!)  
Check the Right of the D Tree (It's a E Tree)  
Check the Left of the E Tree. (Nothing)  
Check the Right of the E Tree. (F, it's a leaf. Finish E Tree. Finish D Tree)...  
Onwards until...   
DONE: A, B, C, D, E, F, G, H, I, K  

3) POSTORDER: 
LEFT, RIGHT, ROOT  
DONE: A, C, B, F, E, D, H, K, I, G

Usage (aka, why do we care):
I really enjoyed this simple Quora explanation of the Depth First Traversal methods and how they are commonly used:
"In-Order Traversal will print values [in order for the BST (binary search tree)]"
"Pre-order traversal is used to create a copy of the [binary search tree]."
"Postorder traversal is used to delete the [binary search tree]."
https://www.quora.com/What-is-the-use-of-pre-order-and-post-order-traversal-of-binary-trees-in-computing

SQL Server remove milliseconds from datetime

May be this will help.. SELECT [Datetime] = CAST('20120228' AS smalldatetime)

o/p: 2012-02-28 00:00:00

Delete all lines starting with # or ; in Notepad++

Find:

^[#;].*

Replace with nothing. The ^ indicates the start of a line, the [#;] is a character class to match either # or ;, and .* matches anything else in the line.

In versions of Notepad++ before 6.0, you won't be able to actually remove the lines due to a limitation in its regex engine; the replacement results in blank lines for each line matched. In other words, this:

# foo
; bar
statement;

Will turn into:



statement;

However, the replacement will work in Notepad++ 6.0 if you add \r, \n or \r\n to the end of the pattern, depending on which line ending your file is using, resulting in:

statement;

ReactJS - Get Height of an element

Instead of using document.getElementById(...), a better (up to date) solution is to use the React useRef hook that stores a reference to the component/element, combined with a useEffect hook, which fires at component renders.

import React, {useState, useEffect, useRef} from 'react';

export default App = () => {
  const [height, setHeight] = useState(0);
  const elementRef = useRef(null);

  useEffect(() => {
    setHeight(elementRef.current.clientHeight);
  }, []); //empty dependency array so it only runs once at render

  return (
    <div ref={elementRef}>
      {height}
    </div>
  )
}

How to set width and height dynamically using jQuery

I tried all of the suggestions above and none of them worked for me, they changed the clientWidth and clientHeight not the actual width and height.

The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."

The css approach did the same thing so I had to use the $().attr() methods instead.

_canvas.attr('width', 100);
_canvas.attr('height', 200);

I don't know is this affect me because I was trying to resize a element and it is some how different or not.

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

One approach you could take is the following method:

// Counts how many of a certain character occurs in the given string
public static int CharCountInString(char chr, string str)
{
    return str.Split(chr).Length-1;
}

As per the parameters this method returns the count of a specific character within a specific string.

This method works by splitting the string into an array by the specified character and then returning the length of that array -1.

How to print the full NumPy array, without truncation?

If you are using Jupyter, try the variable inspector extension. You can click each variable to see the entire array.

Changing default encoding of Python?

There is an insightful blog post about it.

See https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/.

I paraphrase its content below.

In python 2 which was not as strongly typed regarding the encoding of strings you could perform operations on differently encoded strings, and succeed. E.g. the following would return True.

u'Toshio' == 'Toshio'

That would hold for every (normal, unprefixed) string that was encoded in sys.getdefaultencoding(), which defaulted to ascii, but not others.

The default encoding was meant to be changed system-wide in site.py, but not somewhere else. The hacks (also presented here) to set it in user modules were just that: hacks, not the solution.

Python 3 did changed the system encoding to default to utf-8 (when LC_CTYPE is unicode-aware), but the fundamental problem was solved with the requirement to explicitly encode "byte"strings whenever they are used with unicode strings.

Check if a JavaScript string is a URL

This function disallows localhost and only allows URLs for web pages (ie, only allows http or https protocol).

It also only allows safe characters as defined here: https://www.urlencoder.io/learn/

function isValidWebUrl(url) {
   let regEx = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
   return regEx.test(url);
}

How to read json file into java with simple JSON library

Use google-simple library.

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Please find the sample code below:

public static void main(String[] args) {
    try {
        JSONParser parser = new JSONParser();
        //Use JSONObject for simple JSON and JSONArray for array of JSON.
        JSONObject data = (JSONObject) parser.parse(
              new FileReader("/resources/config.json"));//path to the JSON file.

        String json = data.toJSONString();
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

Use JSONObject for simple JSON like {"id":"1","name":"ankur"} and JSONArray for array of JSON like [{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}].