Programs & Examples On #Type constraints

Constraints can be associated with a type parameter of a generic. Constraints declare items that must be supported by any concrete type passed to that parameter in a construction of the generic type.

What does "where T : class, new()" mean?

where (C# Reference)

The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless--or default-- constructor

So it should be, T must be a class, and have an accessible parameterless--or default constructor.

MySQL check if a table exists without throwing an exception

I don't know the PDO syntax for it, but this seems pretty straight-forward:

$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;

Understanding INADDR_ANY for socket programming

To bind socket with localhost, before you invoke the bind function, sin_addr.s_addr field of the sockaddr_in structure should be set properly. The proper value can be obtained either by

my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1")

or by

my_sockaddress.sin_addr.s_addr=htonl(INADDR_LOOPBACK);

HTML if image is not found

simple way to handle this, just add an background image.

What is the difference between NULL, '\0' and 0?

A byte with a value of 0x00 is, on the ASCII table, the special character called NUL or NULL. In C, since you shouldn't embed control characters in your source code, this is represented in C strings with an escaped 0, i.e., \0.

But a true NULL is not a value. It is the absence of a value. For a pointer, it means the pointer has nothing to point to. In a database, it means there is no value in a field (which is not the same thing as saying the field is blank, 0, or filled with spaces).

The actual value a given system or database file format uses to represent a NULL isn't necessarily 0x00.

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

HTML/CSS Approach

If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper <div> and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:

JS Fiddle

HTML

<div id="wrapper">
  <div id="fixed">
    [Fixed Content]
  </div><!-- /fixed -->
  <div id="scroller">
    [Scrolling Content]
  </div><!-- /scroller -->
</div><!-- /wrapper -->

CSS

#wrapper { position: relative; }
#fixed { position: fixed; top: 0; right: 0; }
#scroller { height: 100px; overflow: auto; }

JS

//Compensate for the scrollbar (otherwise #fixed will be positioned over it).
$(function() {
  //Determine the difference in widths between
  //the wrapper and the scroller. This value is
  //the width of the scroll bar (if any).
  var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;

  //Set the right offset
  $('#fixed').css('right', offset + 'px');?
});

Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

Get Time from Getdate()

Did you try to make a cast from date to time?

select cast(getdate() as time)

Reviewing the question, I saw the 'AM/PM' at end. So, my answer for this question is:

select format(getdate(), 'hh:mm:ss tt')

Run on Microsoft SQL Server 2012 and Later.

How to hide a div with jQuery?

$('#myDiv').hide(); hide function is used to edit content and show function is used to show again.

For more please click on this link.

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.

If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.

EDIT

I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.

It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc() call, etc.) so those warnings would not be very useful due to the false positive frequency.

How (and why) to use display: table-cell (CSS)

How (and why) to use display: table-cell (CSS)

I just wanted to mention, since I don't think any of the other answers did directly, that the answer to "why" is: there is no good reason, and you should probably never do this.

In my over a decade of experience in web development, I can't think of a single time I would have been better served to have a bunch of <div>s with display styles than to just have table elements.

The only hypothetical I could come up with is if you have tabular data stored in some sort of non-HTML-table format (eg. a CSV file). In a very specific version of this case it might be easier to just add <div> tags around everything and then add descendent-based styles, instead of adding actual table tags.

But that's an extremely contrived example, and in all real cases I know of simply using table tags would be better.

Multiple selector chaining in jQuery?

If we want to apply the same functionality and features to more than one selectors then we use multiple selector options. I think we can say this feature is used like reusability. write a jquery function and just add multiple selectors in which we want the same features.

Kindly take a look in below example:

_x000D_
_x000D_
$( "div, span, .paragraph, #paraId" ).css( {"font-family": "tahoma", "background": "red"} );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>Div element</div>_x000D_
<p class="paragraph">Paragraph with class selector</p>_x000D_
<p id="paraId">Paragraph with id selector</p>_x000D_
<span>Span element</span>
_x000D_
_x000D_
_x000D_

I hope it will help you. Namaste

Drawing a line/path on Google Maps

It is really easy with Google Maps Android API v2

Just copy the example from Developer documentation

(of course you have to init your map first)

GoogleMap map;
 // ... get a map.
 // Add a thin red line from London to New York.
 Polyline line = map.addPolyline(new PolylineOptions()
     .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
     .width(5)
     .color(Color.RED));

Return sql rows where field contains ONLY non-alphanumeric characters

SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.

As it happens, you are close. Just need leading+trailing wildcards and move the NOT

 WHERE whatever NOT LIKE '%[a-z0-9]%'

How to assign an action for UIImageView object in Swift

I suggest to place invisible(opacity = 0) button on your imageview and then handle interaction on button.

How to post a file from a form with Axios

Add the file to a formData object, and set the Content-Type header to multipart/form-data.

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Setting up Vim for Python

Put the following in your .vimrc

autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
autocmd BufRead *.py set nocindent
autocmd BufWritePre *.py normal m`:%s/\s\+$//e ``
filetype plugin indent on

See also the detailed instructions

I personally use JetBrain's PyCharm with the IdeaVIM plugin when doing anything complex, for simple editing the additions to .vimrc seem sufficient.

Using Jasmine to spy on a function without an object

TypeScript users:

I know the OP asked about javascript, but for any TypeScript users who come across this who want to spy on an imported function, here's what you can do.

In the test file, convert the import of the function from this:

import {foo} from '../foo_functions';

x = foo(y);

To this:

import * as FooFunctions from '../foo_functions';

x = FooFunctions.foo(y);

Then you can spy on FooFunctions.foo :)

spyOn(FooFunctions, 'foo').and.callFake(...);
// ...
expect(FooFunctions.foo).toHaveBeenCalled();

How to exclude property from Json Serialization

Sorry I decided to write another answer since none of the other answers are copy-pasteable enough.

If you don't want to decorate properties with some attributes, or if you have no access to the class, or if you want to decide what to serialize during runtime, etc. etc. here's how you do it in Newtonsoft.Json

//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
    private readonly HashSet<string> ignoreProps;
    public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
    {
        this.ignoreProps = new HashSet<string>(propNamesToIgnore);
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        if (this.ignoreProps.Contains(property.PropertyName))
        {
            property.ShouldSerialize = _ => false;
        }
        return property;
    }
}

Usage

JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
        { ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) };);

Note: make sure you cache the ContractResolver object if you decide to use this answer, otherwise performance may suffer.

I've published the code here in case anyone wants to add anything

https://github.com/jitbit/JsonIgnoreProps

Perl - Multiple condition if statement without duplicating code?

Simple:

if ( $name eq 'tom' && $password eq '123!'
    || $name eq 'frank' && $password eq '321!'
) {

(use the high-precedence && and || in expressions, reserving and and or for flow control, to avoid common precedence errors)

Better:

my %password = (
    'tom' => '123!',
    'frank' => '321!',
);

if ( exists $password{$name} && $password eq $password{$name} ) {

Laravel view not found exception

Use this on your cmd then run your project.

php artisan config:cache php artisan route:cache php artisan controller:cache php artisan optimize:clear

Android Get Application's 'Home' Data Directory

To get the path of file in application package;

ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();

Get escaped URL parameter

You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.

I've created a tiny module that can parse the query string into an object. Use it like this:

// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå

How does HttpContext.Current.User.Identity.Name know which usernames exist?

How does [HttpContext.Current.User] know which usernames exist or do not exist?

Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).

Up until this point, the application has no idea who you are.

Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie. This calls FormsAuthentication.Decrypt (This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand, turning the cookie into a user and stuffing it into Context.User (Reference Source).

How eliminate the tab space in the column in SQL Server 2008

Use the Below Code for that

UPDATE Table1 SET Column1 = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column1, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))`

Hexadecimal to Integer in Java

you can use this method : https://stackoverflow.com/a/31804061/3343174 it's converting perfectly any hexadecimal number (presented as a string) to a decimal number

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

How to build minified and uncompressed bundle with webpack?

In my opinion it's a lot easier just to use the UglifyJS tool directly:

  1. npm install --save-dev uglify-js
  2. Use webpack as normal, e.g. building a ./dst/bundle.js file.
  3. Add a build command to your package.json:

    "scripts": {
        "build": "webpack && uglifyjs ./dst/bundle.js -c -m -o ./dst/bundle.min.js --source-map ./dst/bundle.min.js.map"
    }
    
  4. Whenever you want to build a your bundle as well as uglified code and sourcemaps, run the npm run build command.

No need to install uglify-js globally, just install it locally for the project.

How to compare files from two different branches?

You can do this: git diff branch1:path/to/file branch2:path/to/file

If you have difftool configured, then you can also: git difftool branch1:path/to/file branch2:path/to/file

Related question: How do I view git diff output with visual diff program

How do I import an SQL file using the command line in MySQL?

A common use of mysqldump is for making a backup of an entire database:

shell> mysqldump db_name > backup-file.sql

You can load the dump file back into the server like this:

UNIX

shell> mysql db_name < backup-file.sql

The same in Windows command prompt:

mysql -p -u [user] [database] < backup-file.sql

PowerShell

C:\> cmd.exe /c "mysql -u root -p db_name < backup-file.sql"

MySQL command line

mysql> use db_name;
mysql> source backup-file.sql;

Instagram: Share photo from webpage

The short answer is: No. The only way to post images is through the mobile app.

From the Instagram API documentation: http://instagram.com/developer/endpoints/media/

At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:

  • Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
  • We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.

All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.

How to view/delete local storage in Firefox?

To inspect your localStorage items you may type console.log(localStorage); in your javascript console (firebug for example or in new FF versions the shipped js console).

You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:

localStorage.clear();

What is the difference between compileSdkVersion and targetSdkVersion?

The CompileSdkVersion is the version of the SDK platform your app works with for compilation, etc DURING the development process (you should always use the latest) This is shipped with the API version you are using

enter image description here

You will see this in your build.gradle file:

enter image description here

targetSdkVersion: contains the info your app ships with AFTER the development process to the app store that allows it to TARGET the SPECIFIED version of the Android platform. Depending on the functionality of your app, it can target API versions lower than the current.For instance, you can target API 18 even if the current version is 23.

Take a good look at this official Google page.

how to cancel/abort ajax request in axios

Typically you want to cancel the previous ajax request and ignore it's coming response, only when a new ajax request of that instance is started, for this purpose, do the following:

Example: getting some comments from API:

// declare an ajax request's cancelToken (globally)
let ajaxRequest = null; 

function getComments() {

    // cancel  previous ajax if exists
    if (ajaxRequest ) {
        ajaxRequest.cancel(); 
    }

    // creates a new token for upcomming ajax (overwrite the previous one)
    ajaxRequest = axios.CancelToken.source();  

    return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
        console.log(response.data)
    }).catch(function(err) {
        if (axios.isCancel(err)) {
           console.log('Previous request canceled, new request is send', err.message);
        } else {
               // handle error
        }
    });
}

How to return data from promise

I also don't like using a function to handle a property which has been resolved again and again in every controller and service. Seem I'm not alone :D

Don't tried to get result with a promise as a variable, of course no way. But I found and use a solution below to access to the result as a property.

Firstly, write result to a property of your service:

app.factory('your_factory',function(){
    var theParentIdResult = null;
    var factoryReturn = {  
        theParentId: theParentIdResult,
        addSiteParentId : addSiteParentId
    };
    return factoryReturn;
    function addSiteParentId(nodeId) {   
         var theParentId = 'a';
         var parentId = relationsManagerResource.GetParentId(nodeId)
             .then(function(response){                               
                 factoryReturn.theParentIdResult = response.data;
                 console.log(theParentId);  // #1
             });                    
    }        
})

Now, we just need to ensure that method addSiteParentId always be resolved before we accessed to property theParentId. We can achieve this by using some ways.

  • Use resolve in router method:

    resolve: {
        parentId: function (your_factory) {
             your_factory.addSiteParentId();
        }
    }
    

then in controller and other services used in your router, just call your_factory.theParentId to get your property. Referce here for more information: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

  • Use run method of app to resolve your service.

    app.run(function (your_factory) { your_factory.addSiteParentId(); })
    
  • Inject it in the first controller or services of the controller. In the controller we can call all required init services. Then all remain controllers as children of main controller can be accessed to this property normally as you want.

Chose your ways depend on your context depend on scope of your variable and reading frequency of your variable.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

This happened to me today because I had added a library directory while still in x86 mode, and accidently removed the inherited directories, making them hardcoded instead. Then after switching to x64, my VC++ Directories still read:

"...;$(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);"

instead of the _x64.

How to create an array containing 1...N

There is small function, it allow to use construction like [1, 2].range(3, 4) -> [1, 2, 3, 4] also it works with negative params. Enjoy.

Array.prototype.range = function(from, to)
{
   var range = (!to)? from : Math.abs(to - from) + 1, increase = from < to;
   var tmp = Array.apply(this, {"length": range}).map(function()
      {
         return (increase)?from++ : from--;
      }, Number);

   return this.concat(tmp);
};

OR, AND Operator

Logical OR is ||, logical AND is &&. If you need the negation NOT, prefix your expression with !.

Example:

X = (A && B) || C || !D;

Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).

If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.

Android Get Current timestamp?

You can get Current timestamp in Android by trying below code

time.setText(String.valueOf(System.currentTimeMillis()));

and timeStamp to time format

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(time.getText().toString())));
time.setText(dateString);

Set size of HTML page and browser window

You could try:

<html>
    <head>
        <style>
            #main {
                width: 500; /*Set to whatever*/
                height: 500;/*Set to whatever*/
            }
        </style>
    </head>
    <body id="main">
    </body>
</html>

Check empty string in Swift?

Here is how I check if string is blank. By 'blank' I mean a string that is either empty or contains only space/newline characters.

struct MyString {
  static func blank(text: String) -> Bool {
    let trimmed = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    return trimmed.isEmpty
  }
}

How to use:

MyString.blank(" ") // true

"rm -rf" equivalent for Windows?

Here is what you need to do...

Create a batch file with the following line

RMDIR /S %1

Save your batch file as Remove.bat and put it in C:\windows

Create the following registry key

HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)

Launch regedit and update the default value HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)\default with the following value

"c:\windows\REMOVE.bat" "%1"

Thats it! Now you can right click any directory and use the RMDIR function

What is the correct way to read a serial port using .NET framework?

    using System;
    using System.IO.Ports;
    using System.Threading;

    namespace SerialReadTest
    {
        class SerialRead
        {
            static void Main(string[] args)
            {
        Console.WriteLine("Serial read init");
        SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
        port.Open();
        while(true){
          Console.WriteLine(port.ReadLine());
        }

    }
}
}

Replace HTML page with contents retrieved via AJAX

Can't you just try to replace the body content with the document.body handler?

if your page is this:

<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>

Just use the document.body to replace the body.

This works for me. All the content of the BODY tag is replaced by the innerHTML you specify. If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.

An example with javascript scripting inside it:

<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>

This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.

Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.

How do you create a UIImage View Programmatically - Swift

In Swift 4.2 and Xcode 10.1

//Create image view simply like this.
let imgView = UIImageView()
imgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
imgView.image = UIImage(named: "yourimagename")//Assign image to ImageView
imgView.imgViewCorners()
view.addSubview(imgView)//Add image to our view

//Add image view properties like this(This is one of the way to add properties).  
extension UIImageView {
    //If you want only round corners
    func imgViewCorners() {
        layer.cornerRadius = 10
        layer.borderWidth = 1.0
        layer.masksToBounds = true
    }
}

How to delete columns in a CSV file?

Using a dict to grab headings then looping through gets you what you need cleanly.

import csv
ct = 0
cols_i_want = {'cost' : -1, 'date' : -1}
with open("file1.csv","rb") as source:
    rdr = csv.reader( source )
    with open("result","wb") as result:
        wtr = csv.writer( result )
        for row in rdr:
            if ct == 0:
              cc = 0
              for col in row:
                for ciw in cols_i_want: 
                  if col == ciw:
                    cols_i_want[ciw] = cc
                cc += 1
            wtr.writerow( (row[cols_i_want['cost']], row[cols_i_want['date']]) )
            ct += 1

How to POST form data with Spring RestTemplate?

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

Hence let's create an HTTP entity and send the headers and parameter in body.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-

How to use bitmask?

Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.

An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:

RRRR RGGG GGGB BBBB

You could then use bit masking to retrieve the colour components as follows:

  const unsigned short redMask   = 0xF800;
  const unsigned short greenMask = 0x07E0;
  const unsigned short blueMask  = 0x001F;

  unsigned short lightGray = 0x7BEF;

  unsigned short redComponent   = (lightGray & redMask) >> 11;
  unsigned short greenComponent = (lightGray & greenMask) >> 5;
  unsigned short blueComponent =  (lightGray & blueMask);

Bypass invalid SSL certificate errors when calling web services in .Net

The approach I used when faced with this problem was to add the signer of the temporary certificate to the trusted authorities list on the computer in question.

I normally do testing with certificates created with CACERT, and adding them to my trusted authorities list worked swimmingly.

Doing it this way means you don't have to add any custom code to your application and it properly simulates what will happen when your application is deployed. As such, I think this is a superior solution to turning off the check programmatically.

How to convert std::string to lower case?

Here's a macro technique if you want something simple:

#define STRTOLOWER(x) std::transform (x.begin(), x.end(), x.begin(), ::tolower)
#define STRTOUPPER(x) std::transform (x.begin(), x.end(), x.begin(), ::toupper)
#define STRTOUCFIRST(x) std::transform (x.begin(), x.begin()+1, x.begin(),  ::toupper); std::transform (x.begin()+1, x.end(),   x.begin()+1,::tolower)

However, note that @AndreasSpindler's comment on this answer still is an important consideration, however, if you're working on something that isn't just ASCII characters.

How to align texts inside of an input?

The accepted answer here is correct but I'd like to add a little info. If you are using a library / framework like bootstrap there may be built in classes for this. For example bootstrap uses the text-right class. Use it like this:

<input type="text" class="text-right"/> 
<input type="number" class="text-right"/>

As a note this works on other input types as well, like numeric as shown above.

If you aren't using a nice framework like bootstrap then you can make your own version of this helper class. Similar to other answers but we are not going to add it directly to the input class so it won't apply to every single input on your site or page, this might not be desired behavior. So this would create a nice easy css class to align things right without needing inline styling or affecting every single input box.

.text-right{
    text-align: right;
}

Now you can use this class exactly the same as the inputs above with class="text-right". I know it isn't saving that many key strokes but it makes your code cleaner.

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

PHP refresh window? equivalent to F5 page reload?

with php you can use two redirections. It works same as refresh in some issues.

you can use a page redirect.php and post your last url to it by GET method (for example). then in redirect.php you can change header to location you`ve sent to it by GET method.

like this: your page:

<?php
header("location:redirec.php?ref=".$your_url);
?>

redirect.php:

<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>

that worked for me good.

Number of occurrences of a character in a string

Your string example looks like the query string part of a GET. If so, note that HttpContext has some help for you

int numberOfArgs = HttpContext.Current.QueryString.Count;

For more of what you can do with QueryString, see NameValueCollection

Java Swing - how to show a panel on top of another panel?

There's another layout manager that may be of interest here: Overlay Layout Here's a simple tutorial: OverlayLayout: for layout management of components that lie on top of one another. Overlay Layout allows you to position panels on top of one another, and set a layout inside each panel. You are also able to set size and position of each panel separately.

(The reason I'm answering this question from years ago is because I have stumbled upon the same problem, and I have seen very few mentions of the Overlay Layout on StackOverflow, while it seems to be pretty well documented. Hopefully this may help someone else who keeps searching for it.)

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Hash Map in Python

Python Counter is also a good option in this case:

from collections import Counter

counter = Counter(["Sachin Tendulkar", "Sachin Tendulkar", "other things"])

print(counter)

This returns a dict with the count of each element in the list:

Counter({'Sachin Tendulkar': 2, 'other things': 1})

Remove specific characters from a string in Javascript

Regexp solution:

ref = ref.replace(/^F0/, "");

plain solution:

if (ref.substr(0, 2) == "F0")
     ref = ref.substr(2);

How do I plot list of tuples in Python?

You could also use zip

import matplotlib.pyplot as plt

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
     (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
     (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x, y = zip(*l)

plt.plot(x, y)

No resource identifier found for attribute '...' in package 'com.app....'

I was facing the same problem and solved it using the below steps:

Add this in your app's build.gradle

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

Use namespace:

xmlns:app="http://schemas.android.com/apk/res-auto"

Then use:

app:srcCompat="@drawable/your_vector_drawable_here"

How to do what head, tail, more, less, sed do in Powershell?

Get-Content (alias: gc) is your usual option for reading a text file. You can then filter further:

gc log.txt | select -first 10 # head
gc -TotalCount 10 log.txt     # also head
gc log.txt | select -last 10  # tail
gc -Tail 10 log.txt           # also tail (since PSv3), also much faster than above option
gc log.txt | more             # or less if you have it installed
gc log.txt | %{ $_ -replace '\d+', '($0)' }         # sed

This works well enough for small files, larger ones (more than a few MiB) are probably a bit slow.

The PowerShell Community Extensions include some cmdlets for specialised file stuff (e.g. Get-FileTail).

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

I guess if you change the id_no, some of the foreign keys would not reference anything, thus the constraint violation. You could add initialy deffered to the foreign keys, so the constraints are checked when the changes are commited

error: package javax.servlet does not exist

I needed to import javaee-api as well.

  <dependency>
     <groupId>javax</groupId>
     <artifactId>javaee-api</artifactId>
     <version>7.0</version>
  </dependency>

Unless I got following error:

package javax.servlet.http does not exist
javax.servlet.annotation does not exist
javax.servlet.http does not exist
...

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

For several weeks I was also annoyed by this "bug":

net :: ERR_HTTP2_PROTOCOL_ERROR 200

In my case, it occurred on images generated by PHP.

It was at header() level, and on this one in particular:

header ('Content-Length:'. Filesize($cache_file));

It did obviously not return the exact size, so I deleted it and everything works fine now.

So Chrome checks the accuracy of the data transmitted via the headers, and if it does not correspond, it fails.

EDIT

I found why content-length via filesize was being miscalculated: the GZIP compression is active on the PHP files, so excluding the file in question will fix the problem. Put this code in the .htaccess:

SetEnvIfNoCase Request_URI ^ / thumb.php no-gzip -vary

It works and we keep the header Content-length.

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

What does the line "#!/bin/sh" mean in a UNIX shell script?

If the file that this script lives in is executable, the hash-bang (#!) tells the operating system what interpreter to use to run the script. In this case it's /bin/sh, for example.

There's a Wikipedia article about it for more information.

How to store arbitrary data for some HTML tags

One possibility might be:

  • Create a new div to hold all the extended/arbitrary data
  • Do something to ensure that this div is invisible (e.g. CSS plus a class attribute of the div)
  • Put the extended/arbitrary data within [X]HTML tags (e.g. as text within cells of a table, or anything else you might like) within this invisible div

Where does this come from: -*- coding: utf-8 -*-

This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.

It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

You cannot play a video inside a view. It has to be played fullscreen.

Best Practices for mapping one object to another

Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.

Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.

Save PL/pgSQL output from PostgreSQL to a CSV file

CSV Export Unification

This information isn't really well represented. As this is the second time I've needed to derive this, I'll put this here to remind myself if nothing else.

Really the best way to do this (get CSV out of postgres) is to use the COPY ... TO STDOUT command. Though you don't want to do it the way shown in the answers here. The correct way to use the command is:

COPY (select id, name from groups) TO STDOUT WITH CSV HEADER

Remember just one command!

It's great for use over ssh:

$ ssh psqlserver.example.com 'psql -d mydb "COPY (select id, name from groups) TO STDOUT WITH CSV HEADER"' > groups.csv

It's great for use inside docker over ssh:

$ ssh pgserver.example.com 'docker exec -tu postgres postgres psql -d mydb -c "COPY groups TO STDOUT WITH CSV HEADER"' > groups.csv

It's even great on the local machine:

$ psql -d mydb -c 'COPY groups TO STDOUT WITH CSV HEADER' > groups.csv

Or inside docker on the local machine?:

docker exec -tu postgres postgres psql -d mydb -c 'COPY groups TO STDOUT WITH CSV HEADER' > groups.csv

Or on a kubernetes cluster, in docker, over HTTPS??:

kubectl exec -t postgres-2592991581-ws2td 'psql -d mydb -c "COPY groups TO STDOUT WITH CSV HEADER"' > groups.csv

So versatile, much commas!

Do you even?

Yes I did, here are my notes:

The COPYses

Using /copy effectively executes file operations on whatever system the psql command is running on, as the user who is executing it1. If you connect to a remote server, it's simple to copy data files on the system executing psql to/from the remote server.

COPY executes file operations on the server as the backend process user account (default postgres), file paths and permissions are checked and applied accordingly. If using TO STDOUT then file permissions checks are bypassed.

Both of these options require subsequent file movement if psql is not executing on the system where you want the resultant CSV to ultimately reside. This is the most likely case, in my experience, when you mostly work with remote servers.

It is more complex to configure something like a TCP/IP tunnel over ssh to a remote system for simple CSV output, but for other output formats (binary) it may be better to /copy over a tunneled connection, executing a local psql. In a similar vein, for large imports, moving the source file to the server and using COPY is probably the highest-performance option.

PSQL Parameters

With psql parameters you can format the output like CSV but there are downsides like having to remember to disable the pager and not getting headers:

$ psql -P pager=off -d mydb -t -A -F',' -c 'select * from groups;'
2,Technician,Test 2,,,t,,0,,                                                                                                                                                                   
3,Truck,1,2017-10-02,,t,,0,,                                                                                                                                                                   
4,Truck,2,2017-10-02,,t,,0,,

Other Tools

No, I just want to get CSV out of my server without compiling and/or installing a tool.

How do I jump out of a foreach loop in C#?

Use the 'break' statement. I find it humorous that the answer to your question is literally in your question! By the way, a simple Google search could have given you the answer.

How to Change color of Button in Android when Clicked?

you can try this code to solve your problem

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android

how to create virtual host on XAMPP

Step 1) C:\WINDOWS\system32\drivers\etc\ Open the "hosts" file :

127.0.0.1       localhost
127.0.0.1       test.com
127.0.0.1       example.com

Step 2) xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/test/
    ServerName www.test.com
</VirtualHost>
<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/example/
    ServerName www.example.com
</VirtualHost>

Step 3) C:\xampp\apache\conf\httpd.conf. Scroll down to the Supplemental configuration section at the end, and locate the following section (around line 500), Remove the # from the beginning of the second line so the section now looks like this:

#Virtual hosts
Include conf/extra/httpd-vhosts.conf

Step 4) Restart XAMPP and now run in your browser :

www.example.com or www.test.com

How do I use Spring Boot to serve static content located in Dropbox folder?

@Mark Schäfer

Never too late, but add a slash (/) after static:

spring.resources.static-locations=file:/opt/x/y/z/static/

So http://<host>/index.html is now reachable.

How to get value at a specific index of array In JavaScript?

You can use [];

var indexValue = Index[1];

Android Closing Activity Programmatically

you can use finishAffinity(); to close all the activity..

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

Execution failed app:processDebugResources Android Studio

Had the same problem. I changed the file build.gradle inside the app folder from this: compileSdkVersion 23 buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "com.vastsoftware.family.farmingarea"
    minSdkVersion 11
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"

to this:

compileSdkVersion 23 buildToolsVersion "21.0.2"

defaultConfig {
    applicationId "com.vastsoftware.family.farmingarea"
    minSdkVersion 11
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"

and worked perfectly! hope it works for you too!

How to get current page URL in MVC 3

You could use the Request.RawUrl, Request.Url.OriginalString, Request.Url.ToString() or Request.Url.AbsoluteUri.

Convert interface{} to int

You need to do type assertion for converting your interface{} to int value.

iAreaId := val.(int)
iAreaId, ok := val.(int)

More information is available.

How to print out the method name and line number and conditionally disable NSLog?

My answer to this question might help, looks like it's similar to the one Diederik cooked up. You may also want to replace the call to NSLog() with a static instance of your own custom logging class, that way you can add a priority flag for debug/warning/error messages, send messages to a file or database as well as the console, or pretty much whatever else you can think of.

#define DEBUG_MODE

#ifdef DEBUG_MODE
    #define DebugLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, 
              [[NSString stringWithUTF8String:__FILE__] lastPathComponent], 
              __LINE__, 
              [NSString stringWithFormat:(s), 
              ##__VA_ARGS__] )
#else
    #define DebugLog( s, ... ) 
#endif

What MIME type should I use for CSV?

Strange behavior with MS Excel: If i export to "text based, comma-separated format (csv)" this is the mime-type I get after uploading on my webserver:

[name] => data.csv
[type] => application/vnd.ms-excel

So Microsoft seems to be doing own things again, regardless of existing standards: https://en.wikipedia.org/wiki/Comma-separated_values

package R does not exist

Just to make this simple:

import your.app.package.R;

Of course, replacing your.app.package with your app package.

In all the classes which use R resource references, remove any other import with .R, i.e. import android.R;

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

I ran into this same issue. Someone had logged onto my computer and used their TFS credentials. I'm running VS2012, Windows 7, and the network admins have Credential Manager disabled.

Run this command from a command window with the same user your running visual studio as.

rundll32.exe keymgr.dll,KRShowKeyMgr

You'll see a popup with all your stored credentials. Remove the one for your TFS server.

Note: You will need to restart visual studio because it caches the tfs credentials.

How to adjust gutter in Bootstrap 3 grid system?

To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.

To learn more about the grid and the columns / gutter widths, please also read:

In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px. When setting @grid-columns:3; and setting @grid-gutter-width:15px; in variables.less you will get:

15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px

How to disable copy/paste from/to EditText

Similar to GnrlKnowledge, you can clear the Clipboard

http://developer.android.com/reference/android/text/ClipboardManager.html

If you want, preserve the text in the Clipboard, and on onDestroy, you can set it again.

C# password TextBox in a ASP.net website

I think this is what you are looking for

 <asp:TextBox ID="txbPass" runat="server" TextMode="Password"></asp:TextBox>

Is there a date format to display the day of the week in java?

I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:

new SimpleDateFormat("u").format(new Date());

returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.

Getting DOM element value using pure JavaScript

There is no difference if we look on effect - value will be the same. However there is something more...

Solution 3:

_x000D_
_x000D_
function doSomething() {_x000D_
  console.log( theId.value );_x000D_
}
_x000D_
<input id="theId" value="test" onclick="doSomething()" />
_x000D_
_x000D_
_x000D_

if DOM element has id then you can use it in js directly

Adding custom radio buttons in android

Below code is example of custom radio button. follow below steps..

  1. Xml file.

     <FrameLayout
         android:layout_width="0dp"
         android:layout_height="match_parent"
         android:layout_weight="0.5">
    
         <TextView
             android:id="@+id/text_gender"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="left|center_vertical"
             android:gravity="center"
             android:text="@string/gender"
             android:textColor="#263238"
             android:textSize="15sp"
             android:textStyle="normal"
    
             />
    
         <TextView
             android:id="@+id/text_male"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="center"
             android:layout_marginLeft="10dp"
             android:gravity="center"
             android:text="@string/male"
             android:textColor="#263238"
             android:textSize="15sp"
             android:textStyle="normal"/>
    
         <RadioButton
             android:id="@+id/radio_Male"
             android:layout_width="28dp"
             android:layout_height="28dp"
             android:layout_gravity="right|center_vertical"
             android:layout_marginRight="4dp"
             android:button="@drawable/custom_radio_button"
             android:checked="true"
             android:text=""
             android:onClick="onButtonClicked"
             android:textSize="15sp"
             android:textStyle="normal"
    
             />
     </FrameLayout>
    
     <FrameLayout
         android:layout_width="0dp"
         android:layout_height="match_parent"
         android:layout_weight="0.6">
    
         <RadioButton
             android:id="@+id/radio_Female"
             android:layout_width="28dp"
             android:layout_height="28dp"
             android:layout_gravity="right|center_vertical"
             android:layout_marginLeft="10dp"
             android:layout_marginRight="0dp"
             android:button="@drawable/custom_female_button"
             android:text=""
             android:onClick="onButtonClicked"
             android:textSize="15sp"
             android:textStyle="normal"/>
    
         <TextView
             android:id="@+id/text_female"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="left|center_vertical"
             android:gravity="center"
             android:text="@string/female"
             android:textColor="#263238"
             android:textSize="15sp"
             android:textStyle="normal"/>
    
         <RadioButton
             android:id="@+id/radio_Other"
             android:layout_width="28dp"
             android:layout_height="28dp"
             android:layout_gravity="center_horizontal|bottom"
             android:layout_marginRight="10dp"
             android:button="@drawable/custom_other_button"
             android:text=""
             android:onClick="onButtonClicked"
             android:textSize="15sp"
             android:textStyle="normal"/>
    
         <TextView
             android:id="@+id/text_other"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="right|center_vertical"
             android:layout_marginRight="34dp"
             android:gravity="center"
             android:text="@string/other"
             android:textColor="#263238"
             android:textSize="15sp"
             android:textStyle="normal"/>
     </FrameLayout>
    

2.add the custom xml for the radio buttons

2.1.other drawable

custom_other_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@drawable/select_radio_other" />
    <item android:state_checked="false" android:drawable="@drawable/default_radio" />

</selector>

2.2.female drawable

custom_female_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@drawable/select_radio_female" />
    <item android:state_checked="false" android:drawable="@drawable/default_radio" />

</selector>

2.3. male drawable

custom_radio_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@drawable/select_radio_male" />
    <item android:state_checked="false" android:drawable="@drawable/default_radio" />
</selector>
  1. Output: this is the output screen

Android and setting width and height programmatically in dp units

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

Javascript - Replace html using innerHTML

You should chain the replace() together instead of assigning the result and replacing again.

var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
                        .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                        .replace(/.bbbbbb/g,'/world\">Helloworld</a>');

See DEMO.

Using Java with Nvidia GPUs (CUDA)

First of all, you should be aware of the fact that CUDA will not automagically make computations faster. On the one hand, because GPU programming is an art, and it can be very, very challenging to get it right. On the other hand, because GPUs are well-suited only for certain kinds of computations.

This may sound confusing, because you can basically compute anything on the GPU. The key point is, of course, whether you will achieve a good speedup or not. The most important classification here is whether a problem is task parallel or data parallel. The first one refers, roughly speaking, to problems where several threads are working on their own tasks, more or less independently. The second one refers to problems where many threads are all doing the same - but on different parts of the data.

The latter is the kind of problem that GPUs are good at: They have many cores, and all the cores do the same, but operate on different parts of the input data.

You mentioned that you have "simple math but with huge amount of data". Although this may sound like a perfectly data-parallel problem and thus like it was well-suited for a GPU, there is another aspect to consider: GPUs are ridiculously fast in terms of theoretical computational power (FLOPS, Floating Point Operations Per Second). But they are often throttled down by the memory bandwidth.

This leads to another classification of problems. Namely whether problems are memory bound or compute bound.

The first one refers to problems where the number of instructions that are done for each data element is low. For example, consider a parallel vector addition: You'll have to read two data elements, then perform a single addition, and then write the sum into the result vector. You will not see a speedup when doing this on the GPU, because the single addition does not compensate for the efforts of reading/writing the memory.

The second term, "compute bound", refers to problems where the number of instructions is high compared to the number of memory reads/writes. For example, consider a matrix multiplication: The number of instructions will be O(n^3) when n is the size of the matrix. In this case, one can expect that the GPU will outperform a CPU at a certain matrix size. Another example could be when many complex trigonometric computations (sine/cosine etc) are performed on "few" data elements.

As a rule of thumb: You can assume that reading/writing one data element from the "main" GPU memory has a latency of about 500 instructions....

Therefore, another key point for the performance of GPUs is data locality: If you have to read or write data (and in most cases, you will have to ;-)), then you should make sure that the data is kept as close as possible to the GPU cores. GPUs thus have certain memory areas (referred to as "local memory" or "shared memory") that usually is only a few KB in size, but particularly efficient for data that is about to be involved in a computation.

So to emphasize this again: GPU programming is an art, that is only remotely related to parallel programming on the CPU. Things like Threads in Java, with all the concurrency infrastructure like ThreadPoolExecutors, ForkJoinPools etc. might give the impression that you just have to split your work somehow and distribute it among several processors. On the GPU, you may encounter challenges on a much lower level: Occupancy, register pressure, shared memory pressure, memory coalescing ... just to name a few.

However, when you have a data-parallel, compute-bound problem to solve, the GPU is the way to go.


A general remark: Your specifically asked for CUDA. But I'd strongly recommend you to also have a look at OpenCL. It has several advantages. First of all, it's an vendor-independent, open industry standard, and there are implementations of OpenCL by AMD, Apple, Intel and NVIDIA. Additionally, there is a much broader support for OpenCL in the Java world. The only case where I'd rather settle for CUDA is when you want to use the CUDA runtime libraries, like CUFFT for FFT or CUBLAS for BLAS (Matrix/Vector operations). Although there are approaches for providing similar libraries for OpenCL, they can not directly be used from Java side, unless you create your own JNI bindings for these libraries.


You might also find it interesting to hear that in October 2012, the OpenJDK HotSpot group started the project "Sumatra": http://openjdk.java.net/projects/sumatra/ . The goal of this project is to provide GPU support directly in the JVM, with support from the JIT. The current status and first results can be seen in their mailing list at http://mail.openjdk.java.net/mailman/listinfo/sumatra-dev


However, a while ago, I collected some resources related to "Java on the GPU" in general. I'll summarize these again here, in no particular order.

(Disclaimer: I'm the author of http://jcuda.org/ and http://jocl.org/ )

(Byte)code translation and OpenCL code generation:

https://github.com/aparapi/aparapi : An open-source library that is created and actively maintained by AMD. In a special "Kernel" class, one can override a specific method which should be executed in parallel. The byte code of this method is loaded at runtime using an own bytecode reader. The code is translated into OpenCL code, which is then compiled using the OpenCL compiler. The result can then be executed on the OpenCL device, which may be a GPU or a CPU. If the compilation into OpenCL is not possible (or no OpenCL is available), the code will still be executed in parallel, using a Thread Pool.

https://github.com/pcpratts/rootbeer1 : An open-source library for converting parts of Java into CUDA programs. It offers dedicated interfaces that may be implemented to indicate that a certain class should be executed on the GPU. In contrast to Aparapi, it tries to automatically serialize the "relevant" data (that is, the complete relevant part of the object graph!) into a representation that is suitable for the GPU.

https://code.google.com/archive/p/java-gpu/ : A library for translating annotated Java code (with some limitations) into CUDA code, which is then compiled into a library that executes the code on the GPU. The Library was developed in the context of a PhD thesis, which contains profound background information about the translation process.

https://github.com/ochafik/ScalaCL : Scala bindings for OpenCL. Allows special Scala collections to be processed in parallel with OpenCL. The functions that are called on the elements of the collections can be usual Scala functions (with some limitations) which are then translated into OpenCL kernels.

Language extensions

http://www.ateji.com/px/index.html : A language extension for Java that allows parallel constructs (e.g. parallel for loops, OpenMP style) which are then executed on the GPU with OpenCL. Unfortunately, this very promising project is no longer maintained.

http://www.habanero.rice.edu/Publications.html (JCUDA) : A library that can translate special Java Code (called JCUDA code) into Java- and CUDA-C code, which can then be compiled and executed on the GPU. However, the library does not seem to be publicly available.

https://www2.informatik.uni-erlangen.de/EN/research/JavaOpenMP/index.html : Java language extension for for OpenMP constructs, with a CUDA backend

Java OpenCL/CUDA binding libraries

https://github.com/ochafik/JavaCL : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings

http://jogamp.org/jocl/www/ : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings

http://www.lwjgl.org/ : Java bindings for OpenCL: Auto-generated low-level bindings and object-oriented convenience classes

http://jocl.org/ : Java bindings for OpenCL: Low-level bindings that are a 1:1 mapping of the original OpenCL API

http://jcuda.org/ : Java bindings for CUDA: Low-level bindings that are a 1:1 mapping of the original CUDA API

Miscellaneous

http://sourceforge.net/projects/jopencl/ : Java bindings for OpenCL. Seem to be no longer maintained since 2010

http://www.hoopoe-cloud.com/ : Java bindings for CUDA. Seem to be no longer maintained


Find the nth occurrence of substring in a string

How about:

c = os.getcwd().split('\\')
print '\\'.join(c[0:-2])

How to fix "Incorrect string value" errors?

I would not suggest Richies answer, because you are screwing up the data inside the database. You would not fix your problem but try to "hide" it and not being able to perform essential database operations with the crapped data.

If you encounter this error either the data you are sending is not UTF-8 encoded, or your connection is not UTF-8. First, verify, that the data source (a file, ...) really is UTF-8.

Then, check your database connection, you should do this after connecting:

SET NAMES 'utf8';
SET CHARACTER SET utf8;

Next, verify that the tables where the data is stored have the utf8 character set:

SELECT
  `tables`.`TABLE_NAME`,
  `collations`.`character_set_name`
FROM
  `information_schema`.`TABLES` AS `tables`,
  `information_schema`.`COLLATION_CHARACTER_SET_APPLICABILITY` AS `collations`
WHERE
  `tables`.`table_schema` = DATABASE()
  AND `collations`.`collation_name` = `tables`.`table_collation`
;

Last, check your database settings:

mysql> show variables like '%colla%';
mysql> show variables like '%charac%';

If source, transport and destination are UTF-8, your problem is gone;)

How to find encoding of a file via script on Linux?

In Cygwin, this looks like it works for me:

find -type f -name "<FILENAME_GLOB>" | while read <VAR>; do (file -i "$<VAR>"); done

Example:

find -type f -name "*.txt" | while read file; do (file -i "$file"); done

You could pipe that to awk and create an iconv command to convert everything to utf8, from any source encoding supported by iconv.

Example:

find -type f -name "*.txt" | while read file; do (file -i "$file"); done | awk -F[:=] '{print "iconv -f "$3" -t utf8 \""$1"\" > \""$1"_utf8\""}' | bash

Download large file in python with requests

Your chunk size could be too large, have you tried dropping that - maybe 1024 bytes at a time? (also, you could use with to tidy up the syntax)

def DownloadFile(url):
    local_filename = url.split('/')[-1]
    r = requests.get(url)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
    return 

Incidentally, how are you deducing that the response has been loaded into memory?

It sounds as if python isn't flushing the data to file, from other SO questions you could try f.flush() and os.fsync() to force the file write and free memory;

    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                f.flush()
                os.fsync(f.fileno())

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I was in the same boat. Installed Eclipse, realized need CDT.

sudo apt-get install eclipse eclipse-cdt g++

This just adds the CDT package on top of existing installation - no un-installation etc. required.

Find the version of an installed npm package

npm info YOUR_PACKAGE version

e.g.

npm info grunt version
0.4.5

Get the time difference between two datetimes

When you call diff, moment.js calculates the difference in milliseconds. If the milliseconds is passed to duration, it is used to calculate duration which is correct. However. when you pass the same milliseconds to the moment(), it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT). That is why you get 1969 as the year together with wrong hour.

duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")

So, I think this is how you should do it since moment.js does not offer format function for duration. Or you can write a simple wrapper to make it easier/prettier.

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

Unsigned values in C

Having unsigned in variable declaration is more useful for the programmers themselves - don't treat the variables as negative. As you've noticed, both -1 and 4294967295 have exact same bit representation for a 4 byte integer. It's all about how you want to treat or see them.

The statement unsigned int a = -1; is converting -1 in two's complement and assigning the bit representation in a. The printf() specifier x, d and u are showing how the bit representation stored in variable a looks like in different format.

Regex pattern to match at least 1 number and 1 character in a string

The accepted answers is not worked as it is not allow to enter special characters.

Its worked perfect for me.

^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$

  • one digit must
  • one character must (lower or upper)
  • every other things optional

Thank you.

Why can't I define a default constructor for a struct in .NET?

Here's my solution to the no default constructor dilemma. I know this is a late solution, but I think it's worth noting this is a solution.

public struct Point2D {
    public static Point2D NULL = new Point2D(-1,-1);
    private int[] Data;

    public int X {
        get {
            return this.Data[ 0 ];
        }
        set {
            try {
                this.Data[ 0 ] = value;
            } catch( Exception ) {
                this.Data = new int[ 2 ];
            } finally {
                this.Data[ 0 ] = value;
            }
        }
    }

    public int Z {
        get {
            return this.Data[ 1 ];
        }
        set {
            try {
                this.Data[ 1 ] = value;
            } catch( Exception ) {
                this.Data = new int[ 2 ];
            } finally {
                this.Data[ 1 ] = value;
            }
        }
    }

    public Point2D( int x , int z ) {
        this.Data = new int[ 2 ] { x , z };
    }

    public static Point2D operator +( Point2D A , Point2D B ) {
        return new Point2D( A.X + B.X , A.Z + B.Z );
    }

    public static Point2D operator -( Point2D A , Point2D B ) {
        return new Point2D( A.X - B.X , A.Z - B.Z );
    }

    public static Point2D operator *( Point2D A , int B ) {
        return new Point2D( B * A.X , B * A.Z );
    }

    public static Point2D operator *( int A , Point2D B ) {
        return new Point2D( A * B.Z , A * B.Z );
    }

    public override string ToString() {
        return string.Format( "({0},{1})" , this.X , this.Z );
    }
}

ignoring the fact I have a static struct called null, (Note: This is for all positive quadrant only), using get;set; in C#, you can have a try/catch/finally, for dealing with the errors where a particular data type is not initialized by the default constructor Point2D(). I guess this is elusive as a solution to some people on this answer. Thats mostly why i'm adding mine. Using the getter and setter functionality in C# will allow you to bypass this default constructor non-sense and put a try catch around what you dont have initialized. For me this works fine, for someone else you might want to add some if statements. So, In the case where you would want a Numerator/Denominator setup, this code might help. I'd just like to reiterate that this solution does not look nice, probably works even worse from an efficiency standpoint, but, for someone coming from an older version of C#, using array data types gives you this functionality. If you just want something that works, try this:

public struct Rational {
    private long[] Data;

    public long Numerator {
        get {
            try {
                return this.Data[ 0 ];
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                return this.Data[ 0 ];
            }
        }
        set {
            try {
                this.Data[ 0 ] = value;
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                this.Data[ 0 ] = value;
            }
        }
    }

    public long Denominator {
        get {
            try {
                return this.Data[ 1 ];
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                return this.Data[ 1 ];
            }
        }
        set {
            try {
                this.Data[ 1 ] = value;
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                this.Data[ 1 ] = value;
            }
        }
    }

    public Rational( long num , long denom ) {
        this.Data = new long[ 2 ] { num , denom };
        /* Todo: Find GCD etc. */
    }

    public Rational( long num ) {
        this.Data = new long[ 2 ] { num , 1 };
        this.Numerator = num;
        this.Denominator = 1;
    }
}

How to output a multiline string in Bash?

Inspired by the insightful answers on this page, I created a mixed approach, which I consider the simplest and more flexible one. What do you think?

First, I define the usage in a variable, which allows me to reuse it in different contexts. The format is very simple, almost WYSIWYG, without the need to add any control characters. This seems reasonably portable to me (I ran it on MacOS and Ubuntu)

__usage="
Usage: $(basename $0) [OPTIONS]

Options:
  -l, --level <n>              Something something something level
  -n, --nnnnn <levels>         Something something something n
  -h, --help                   Something something something help
  -v, --version                Something something something version
"

Then I can simply use it as

echo "$__usage"

or even better, when parsing parameters, I can just echo it there in a one-liner:

levelN=${2:?"--level: n is required!""${__usage}"}

How to load a UIView using a nib file created with Interface Builder

For Swift user with designable option:

  1. Create a custom UIView subclass and a xib files, that we will name after our own class name: in our case MemeView. Inside the Meme View class remember to define it as designable with the @IBDesignable attribute before the class declaration
  2. Rember to set the File’s Owner in the xib with our custom UIView subclass in Indetity Inspector panel

    enter image description here

  3. In the xib file now we can build our interface, make constraints, create outlets, actions etc. enter image description here

  4. We need to implement few methods to our custom class to open the xib once initialized

    class XibbedView: UIView {

    weak var nibView: UIView!
    
    override convenience init(frame: CGRect) {
        let nibName = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
        self.init(nibName: nibName)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let nibName = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
        let nib = loadNib(nibName)
        nib.frame = bounds
        nib.translatesAutoresizingMaskIntoConstraints = false
        addSubview(nib)
        nibView = nib
        setUpConstraints()
    }
    
    init(nibName: String) {
        super.init(frame: CGRectZero)
        let nibName = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
        let nib = loadNib(nibName)
        nib.frame = bounds
        nib.translatesAutoresizingMaskIntoConstraints = false
        addSubview(nib)
        nibView = nib
        setUpConstraints()
    }
    
    func setUpConstraints() {
        ["V","H"].forEach { (quote) -> () in
            let format = String(format:"\(quote):|[nibView]|")
            addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: [], metrics: nil, views: ["nibView" : nibView]))
        }
    }
    
    func loadNib(name: String) -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: name, bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
    
        return view
    }
    

    }

  5. In our custom class we can also define some inspecatable properties to have full control over them from interface builder

    @IBDesignable class MemeView: XibbedView {

    @IBInspectable var memeImage: UIImage = UIImage() {
        didSet {
            imageView.image = memeImage
        }
    }
    @IBInspectable var textColor: UIColor = UIColor.whiteColor() {
        didSet {
            label.textColor = textColor
        }
    }
    @IBInspectable var text: String = "" {
        didSet {
            label.text = text
        }
    }
    @IBInspectable var roundedCorners: Bool = false {
        didSet {
            if roundedCorners {
                layer.cornerRadius = 20.0
                clipsToBounds = true
            }
            else {
                layer.cornerRadius = 0.0
                clipsToBounds = false
            }
        }
    }
    
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var imageView: UIImageView!
    

}

Few examples:
enter image description here enter image description here

If we need to add more information the view while is displayed inside a storyboard or another xib, to do that we can implement prepareForInterfaceBuilder(), this method will be executed only while opening the file in interface builder. If you did everything I wrote but nothing is working, the is a way to debug a sigle view by adding breakpoints in its implementation. enter image description here
Here is the views hierarchy. View hiearchy

Hope this helps a full sample can be downloaded here

Set title background color

Take a peek in platforms/android-2.1/data/res/layout/screen.xml of the SDK. It seems to define a title there. You can frequently examine layouts like this and borrow the style="?android:attr/windowTitleStyle" styles which you can then use and override in your own TextViews.

You may be able to even select the title for direct tweaking by doing:

TextView title = (TextView)findViewById(android.R.id.title);

Package doesn't exist error in intelliJ

I had the same problem and it was fixed for me by changing the "Maven home directory" in Settings from "Bundled" to my locally installed maven. Perhaps this triggered some kind of refresh somewhere since I had not changed this setting for months without any issue.

Inverse dictionary lookup in Python

Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:

key = next(key for key, value in dd.items() if value == 'value')

where dd is the dict. Will raise StopIteration if no match is found, so you might want to catch that and return a more appropriate exception like ValueError or KeyError.

Difference between dangling pointer and memory leak

A dangling pointer is one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect. For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated.

A memory leak is when you dynamically allocate memory from the heap but never free it, possibly because you lost all references to it.

They are related in that they are both situations relating to mismanaged pointers, especially regarding dynamically allocated memory. In one situation (dangling pointer) you have likely freed the memory but tried to reference it afterwards; in the other (memory leak), you have forgotten to free the memory entirely!

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

Well a fix for you could be to put it on the UpdatedDate field and have a trigger that updates the AddedDate field with the UpdatedDate value only if AddedDate is null.

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

Another solution would be to implement a download handler or download handler middleware. (see scrapy docs for more information on downloader middleware) The following is an example class using selenium with headless phantomjs webdriver:

1) Define class within the middlewares.py script.

from selenium import webdriver
from scrapy.http import HtmlResponse

class JsDownload(object):

    @check_spider_middleware
    def process_request(self, request, spider):
        driver = webdriver.PhantomJS(executable_path='D:\phantomjs.exe')
        driver.get(request.url)
        return HtmlResponse(request.url, encoding='utf-8', body=driver.page_source.encode('utf-8'))

2) Add JsDownload() class to variable DOWNLOADER_MIDDLEWARE within settings.py:

DOWNLOADER_MIDDLEWARES = {'MyProj.middleware.MiddleWareModule.MiddleWareClass': 500}

3) Integrate the HTMLResponse within your_spider.py. Decoding the response body will get you the desired output.

class Spider(CrawlSpider):
    # define unique name of spider
    name = "spider"

    start_urls = ["https://www.url.de"] 

    def parse(self, response):
        # initialize items
        item = CrawlerItem()

        # store data as items
        item["js_enabled"] = response.body.decode("utf-8") 

Optional Addon:
I wanted the ability to tell different spiders which middleware to use so I implemented this wrapper:

def check_spider_middleware(method):
@functools.wraps(method)
def wrapper(self, request, spider):
    msg = '%%s %s middleware step' % (self.__class__.__name__,)
    if self.__class__ in spider.middleware:
        spider.log(msg % 'executing', level=log.DEBUG)
        return method(self, request, spider)
    else:
        spider.log(msg % 'skipping', level=log.DEBUG)
        return None

return wrapper

for wrapper to work all spiders must have at minimum:

middleware = set([])

to include a middleware:

middleware = set([MyProj.middleware.ModuleName.ClassName])

Advantage:
The main advantage to implementing it this way rather than in the spider is that you only end up making one request. In A T's solution for example: The download handler processes the request and then hands off the response to the spider. The spider then makes a brand new request in it's parse_page function -- That's two requests for the same content.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

If you're triggering your code from Jenkins, enabling the option "Start Xvfb before the build, and shut it down after" might help. It helped me.

What is the scope of variables in JavaScript?

run the code. hope this will give an idea about scoping

Name = 'global data';
document.Name = 'current document data';
(function(window,document){
var Name = 'local data';
var myObj = {
    Name: 'object data',
    f: function(){
        alert(this.Name);
    }
};

myObj.newFun = function(){
    alert(this.Name);
}

function testFun(){
    alert("Window Scope : " + window.Name + 
          "\nLocal Scope : " + Name + 
          "\nObject Scope : " + this.Name + 
          "\nCurrent document Scope : " + document.Name
         );
}


testFun.call(myObj);
})(window,document);

Find nearest value in numpy array

I think the most pythonic way would be:

 num = 65 # Input number
 array = n.random.random((10))*100 # Given array 
 nearest_idx = n.where(abs(array-num)==abs(array-num).min())[0] # If you want the index of the element of array (array) nearest to the the given number (num)
 nearest_val = array[abs(array-num)==abs(array-num).min()] # If you directly want the element of array (array) nearest to the given number (num)

This is the basic code. You can use it as a function if you want

What are the First and Second Level caches in (N)Hibernate?

There's a pretty good explanation of first level caching on the Streamline Logic blog.

Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.

How to add screenshot to READMEs in github repository?

JUNE 3, 2020 : WORKING ANSWER-

  1. Upload your image to postimage.org
  2. Copy Github-Markdown-Url after uploading Image
  3. Insert in your ReadMe

for loop in Python

Here are some example to iterate over integer range and string:

#(initial,final but not included,gap)
for i in range(1,10,2): 
  print(i); 
1,3,5,7,9

# (initial, final but not included)  
# note: 4 not included
for i in range (1,4): 
   print(i);
1,2,3 

#note: 5 not included
for i in range (5):
  print (i);
0,1,2,3,4 

# you can also iterate over strings
myList = ["ml","ai","dl"];  

for i in myList:
  print(i);
output:  ml,ai,dl

Get the last element of a std::string

In C++11 and beyond, you can use the back member function:

char ch = myStr.back();

In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin:

char ch = *myStr.rbegin();

In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

Hope this helps!

How to remove not null constraint in sql server using query

Remove column constraint: not null to null

ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;

How to set a bitmap from resource

Assuming you are calling this in an Activity class

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).

Can't execute jar- file: "no main manifest attribute"

Alternatively, you can use maven-assembly-plugin, as shown in the below example:

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <archive>
        <manifest>
          <addClasspath>true</addClasspath>
          <mainClass>com.package.MainClass</mainClass>
        </manifest>
      </archive>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
  </plugin> 

In this example all the dependency jars as specified in section will be automatically included in your single jar. Note that jar-with-dependencies should be literally put as, not to be replaced with the jar file names you want to include.

SQLite - getting number of rows in a database

In SQL, NULL = NULL is false, you usually have to use IS NULL:

SELECT CASE WHEN MAX(id) IS NULL THEN 0 ELSE (MAX(id) + 1) END FROM words

But, if you want the number of rows, you should just use count(id) since your solution will give 10 if your rows are (0,1,3,5,9) where it should give 5.

If you can guarantee you will always ids from 0 to N, max(id)+1 may be faster depending on the index implementation (it may be faster to traverse the right side of a balanced tree rather than traversing the whole tree, counting.

But that's very implementation-specific and I would advise against relying on it, not least because it locks your performance to a specific DBMS.

How to make an HTTP request + basic auth in Swift

my solution works as follows:

import UIKit


class LoginViewController: UIViewController, NSURLConnectionDataDelegate {

  @IBOutlet var usernameTextField: UITextField
  @IBOutlet var passwordTextField: UITextField

  @IBAction func login(sender: AnyObject) {
    var url = NSURL(string: "YOUR_URL")
    var request = NSURLRequest(URL: url)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

  }

  func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {

    if challenge.previousFailureCount > 1 {

    } else {
        let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
        challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)

    }

}

  func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
    let status = (response as NSHTTPURLResponse).statusCode
    println("status code is \(status)")
    // 200? Yeah authentication was successful
  }


  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }  
}

You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.

Explanation: In function login you create your request with NSURL, NSURLRequest and NSURLConnection. Essential here is the delegate which references to this class (self). For receiving the delegates calls you need to

  • Add the protocol NSURLConnectionDataDelegate to the class
  • Implement the protocols' function "connection:willSendRequestForAuthenticationChallenge" This is used for adding the credentials to the request
  • Implement the protocols' function "connection:didReceiveResponse" This will check the http response status code

PHP: How to remove specific element from an array?

If you are using a plain array here (which seems like the case), you should be using this code instead:

if (($key = array_search('strawberry', $array)) !== false) {
    array_splice($array, $key, 1);
}

unset($array[$key]) only removes the element but does not reorder the plain array.

Supposingly we have an array and use array_splice:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
array_splice($array, 2, 1);
json_encode($array); 
// yields the array ['apple', 'orange', 'blueberry', 'kiwi']

Compared to unset:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[2]);
json_encode($array);
// yields an object {"0": "apple", "1": "orange", "3": "blueberry", "4": "kiwi"}

Notice how unset($array[$key]) does not reorder the array.

DateTimePicker time picker in 24 hour but displaying in 12hr?

With seconds!

$('.Timestamp').datetimepicker({
    format: 'DD/MM/YYYY HH:mm:ss'
});

To skip future dates:

$(function () {
    var date = new Date();
    var currentMonth = date.getMonth();
    var currentDate = date.getDate();
    var currentYear = date.getFullYear();
    $('#datetimepicker,#datetimepicker1').datetimepicker({
        pickTime: false,
        format: "DD-MM-YYYY",  
        maxDate: new Date(currentYear, currentMonth, currentDate + 1)
    });
});

How to push a single file in a subdirectory to Github (not master)

git status #then file which you need to push git add example.FileExtension

git commit "message is example"

git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)

Select rows having 2 columns equal value

select t.* from table t
    join (
        select C2, C3, C4
        from table
        group by C2, C3, C4
        having count(*) > 1
    ) t2
    using (C2, C3, C4);

jQuery AJAX form data serialize using PHP

_x000D_
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
    var form=$("#myForm");_x000D_
    $("#smt").click(function(){_x000D_
        $.ajax({_x000D_
            type:"POST",_x000D_
            url:form.attr("action"),_x000D_
            data:form.serialize(),_x000D_
            success: function(response){_x000D_
                console.log(response);  _x000D_
            }_x000D_
        });_x000D_
    });_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

This is perfect code , there is no problem.. You have to check that in php script.

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

How to list the files in current directory?

There is nothing wrong with your code. It should list all of the files and directories directly contained by the nominated directory.

The problem is most likely one of the following:

  • The "." directory is not what you expect it to be. The "." pathname actually means the "current directory" or "working directory" for the JVM. You can verify what directory "." actually is by printing out dir.getCanonicalPath().

  • You are misunderstanding what dir.listFiles() returns. It doesn't return all objects in the tree beneath dir. It only returns objects (files, directories, symlinks, etc) that are directly in dir.

The ".classpath" file suggests that you are looking at an Eclipse project directory, and Eclipse projects are normally configured with the Java files in a subdirectory such as "./src". I wouldn't expect to see any Java source code in the "." directory.


Can anyone explain to me why src isn't the current folder?"

Assuming that you are launching an application in Eclipse, then the current folder defaults to the project directory. You can change the default current directory via one of the panels in the Launcher configuration wizard.

Pandas: drop a level from a multi-level column index?

I have struggled with this problem since I don’t know why my droplevel() function does not work. Work through several and learn that ‘a’ in your table is columns name and ‘b’, ‘c’ are index. Do like this will help

df.columns.name = None
df.reset_index() #make index become label

retrieve links from web page using python and BeautifulSoup

I found the answer by @Blairg23 working , after the following correction (covering the scenario where it failed to work correctly):

for link in BeautifulSoup(response.content, 'html.parser', parse_only=SoupStrainer('a')):
    if link.has_attr('href'):
        if file_type in link['href']:
            full_path =urlparse.urljoin(url , link['href']) #module urlparse need to be imported
            wget.download(full_path)

For Python 3:

urllib.parse.urljoin has to be used in order to obtain the full URL instead.

Why does Date.parse give incorrect results?

During recent experience writing a JS interpreter I wrestled plenty with the inner workings of ECMA/JS dates. So, I figure I'll throw in my 2 cents here. Hopefully sharing this stuff will help others with any questions about the differences among browsers in how they handle dates.

The Input Side

All implementations store their date values internally as 64-bit numbers that represent the number of milliseconds (ms) since 1970-01-01 UTC (GMT is the same thing as UTC). This date is the ECMAScript epoch that is also used by other languages such as Java and POSIX systems such as UNIX. Dates occurring after the epoch are positive numbers and dates prior are negative.

The following code is interpreted as the same date in all current browsers, but with the local timezone offset:

Date.parse('1/1/1970'); // 1 January, 1970

In my timezone (EST, which is -05:00), the result is 18000000 because that's how many ms are in 5 hours (it's only 4 hours during daylight savings months). The value will be different in different time zones. This behaviour is specified in ECMA-262 so all browsers do it the same way.

While there is some variance in the input string formats that the major browsers will parse as dates, they essentially interpret them the same as far as time zones and daylight saving is concerned even though parsing is largely implementation dependent.

However, the ISO 8601 format is different. It's one of only two formats outlined in ECMAScript 2015 (ed 6) specifically that must be parsed the same way by all implementations (the other is the format specified for Date.prototype.toString).

But, even for ISO 8601 format strings, some implementations get it wrong. Here is a comparison output of Chrome and Firefox when this answer was originally written for 1/1/1970 (the epoch) on my machine using ISO 8601 format strings that should be parsed to exactly the same value in all implementations:

Date.parse('1970-01-01T00:00:00Z');       // Chrome: 0         FF: 0
Date.parse('1970-01-01T00:00:00-0500');   // Chrome: 18000000  FF: 18000000
Date.parse('1970-01-01T00:00:00');        // Chrome: 0         FF: 18000000
  • In the first case, the "Z" specifier indicates that the input is in UTC time so is not offset from the epoch and the result is 0
  • In the second case, the "-0500" specifier indicates that the input is in GMT-05:00 and both browsers interpret the input as being in the -05:00 timezone. That means that the UTC value is offset from the epoch, which means adding 18000000ms to the date's internal time value.
  • The third case, where there is no specifier, should be treated as local for the host system. FF correctly treats the input as local time while Chrome treats it as UTC, so producing different time values. For me this creates a 5 hour difference in the stored value, which is problematic. Other systems with different offsets will get different results.

This difference has been fixed as of 2020, but other quirks exist between browsers when parsing ISO 8601 format strings.

But it gets worse. A quirk of ECMA-262 is that the ISO 8601 date–only format (YYYY-MM-DD) is required to be parsed as UTC, whereas ISO 8601 requires it to be parsed as local. Here is the output from FF with the long and short ISO date formats with no time zone specifier.

Date.parse('1970-01-01T00:00:00');       // 18000000
Date.parse('1970-01-01');                // 0

So the first is parsed as local because it's ISO 8601 date and time with no timezone, and the second is parsed as UTC because it's ISO 8601 date only.

So, to answer the original question directly, "YYYY-MM-DD" is required by ECMA-262 to be interpreted as UTC, while the other is interpreted as local. That's why:

This doesn't produce equivalent results:

console.log(new Date(Date.parse("Jul 8, 2005")).toString()); // Local
console.log(new Date(Date.parse("2005-07-08")).toString());  // UTC

This does:

console.log(new Date(Date.parse("Jul 8, 2005")).toString());
console.log(new Date(Date.parse("2005-07-08T00:00:00")).toString());

The bottom line is this for parsing date strings. The ONLY ISO 8601 string that you can safely parse across browsers is the long form with an offset (either ±HH:mm or "Z"). If you do that you can safely go back and forth between local and UTC time.

This works across browsers (after IE9):

console.log(new Date(Date.parse("2005-07-08T00:00:00Z")).toString());

Most current browsers do treat the other input formats equally, including the frequently used '1/1/1970' (M/D/YYYY) and '1/1/1970 00:00:00 AM' (M/D/YYYY hh:mm:ss ap) formats. All of the following formats (except the last) are treated as local time input in all browsers. The output of this code is the same in all browsers in my timezone. The last one is treated as -05:00 regardless of the host timezone because the offset is set in the timestamp:

console.log(Date.parse("1/1/1970"));
console.log(Date.parse("1/1/1970 12:00:00 AM"));
console.log(Date.parse("Thu Jan 01 1970"));
console.log(Date.parse("Thu Jan 01 1970 00:00:00"));
console.log(Date.parse("Thu Jan 01 1970 00:00:00 GMT-0500"));

However, since parsing of even the formats specified in ECMA-262 is not consistent, it is recommended to never rely on the built–in parser and to always manually parse strings, say using a library and provide the format to the parser.

E.g. in moment.js you might write:

let m = moment('1/1/1970', 'M/D/YYYY'); 

The Output Side

On the output side, all browsers translate time zones the same way but they handle the string formats differently. Here are the toString functions and what they output. Notice the toUTCString and toISOString functions output 5:00 AM on my machine. Also, the timezone name may be an abbreviation and may be different in different implementations.

Converts from UTC to Local time before printing

 - toString
 - toDateString
 - toTimeString
 - toLocaleString
 - toLocaleDateString
 - toLocaleTimeString

Prints the stored UTC time directly

 - toUTCString
 - toISOString 

In Chrome
toString            Thu Jan 01 1970 00:00:00 GMT-05:00 (Eastern Standard Time)
toDateString        Thu Jan 01 1970
toTimeString        00:00:00 GMT-05:00 (Eastern Standard Time)
toLocaleString      1/1/1970 12:00:00 AM
toLocaleDateString  1/1/1970
toLocaleTimeString  00:00:00 AM

toUTCString         Thu, 01 Jan 1970 05:00:00 GMT
toISOString         1970-01-01T05:00:00.000Z

In Firefox
toString            Thu Jan 01 1970 00:00:00 GMT-05:00 (Eastern Standard Time)
toDateString        Thu Jan 01 1970
toTimeString        00:00:00 GMT-0500 (Eastern Standard Time)
toLocaleString      Thursday, January 01, 1970 12:00:00 AM
toLocaleDateString  Thursday, January 01, 1970
toLocaleTimeString  12:00:00 AM

toUTCString         Thu, 01 Jan 1970 05:00:00 GMT
toISOString         1970-01-01T05:00:00.000Z

I normally don't use the ISO format for string input. The only time that using that format is beneficial to me is when dates need to be sorted as strings. The ISO format is sortable as-is while the others are not. If you have to have cross-browser compatibility, either specify the timezone or use a compatible string format.

The code new Date('12/4/2013').toString() goes through the following internal pseudo-transformation:

  "12/4/2013" -> toUCT -> [storage] -> toLocal -> print "12/4/2013"

I hope this answer was helpful.

Turning error reporting off php

Read up on the configuration settings (e.g., display_errors, display_startup_errors, log_errors) and update your php.ini or .htaccess or .user.ini file, whichever is appropriate.

It works.

What's the difference between struct and class in .NET?

  1. Events declared in a class have their += and -= access automatically locked via a lock(this) to make them thread safe (static events are locked on the typeof the class). Events declared in a struct do not have their += and -= access automatically locked. A lock(this) for a struct would not work since you can only lock on a reference type expression.

  2. Creating a struct instance cannot cause a garbage collection (unless the constructor directly or indirectly creates a reference type instance) whereas creating a reference type instance can cause garbage collection.

  3. A struct always has a built-in public default constructor.

    class DefaultConstructor
    {
        static void Eg()
        {
            Direct     yes = new   Direct(); // Always compiles OK
            InDirect maybe = new InDirect(); // Compiles if constructor exists and is accessible
            //...
        }
    }
    

    This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.

    class NonInstantiable
    {
        private NonInstantiable() // OK
        {
        }
    }
    
    struct Direct
    {
        private Direct() // Compile-time error
        {
        }
    }
    
  4. A struct cannot have a destructor. A destructor is just an override of object.Finalize in disguise, and structs, being value types, are not subject to garbage collection.

    struct Direct
    {
        ~Direct() {} // Compile-time error
    }
    class InDirect
    {
        ~InDirect() {} // Compiles OK
    }
    
    And the CIL for ~Indirect() looks like this:
    
    .method family hidebysig virtual instance void
            Finalize() cil managed
    {
      // ...
    } // end of method Indirect::Finalize
    
  5. A struct is implicitly sealed, a class isn't.
    A struct can't be abstract, a class can.
    A struct can't call : base() in its constructor whereas a class with no explicit base class can.
    A struct can't extend another class, a class can.
    A struct can't declare protected members (for example, fields, nested types) a class can.
    A struct can't declare abstract function members, an abstract class can.
    A struct can't declare virtual function members, a class can.
    A struct can't declare sealed function members, a class can.
    A struct can't declare override function members, a class can.
    The one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString().

SQL Query - Using Order By in UNION

SELECT field1
FROM ( SELECT field1 FROM table1
       UNION
       SELECT field1 FROM table2
     ) AS TBL
ORDER BY TBL.field1

(use ALIAS)

How to save an HTML5 Canvas as an image on a server?

Send canvas image to PHP:

var photo = canvas.toDataURL('image/jpeg');                
$.ajax({
  method: 'POST',
  url: 'photo_upload.php',
  data: {
    photo: photo
  }
});

Here's PHP script:
photo_upload.php

<?php

    $data = $_POST['photo'];
    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);

    mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");

    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
    die;
?>

Can RDP clients launch remote applications and not desktops

This is called "seamless" mode. rdesktop, the RDP client for Unix, is capable of this. From the manpage:

   -A     Enable SeamlessRDP. In this mode, rdesktop creates a X11 window for each window on the server
          side.  This  mode  requires  the  SeamlessRDP  server side component, which is available from
          http://www.cendio.com/seamlessrdp/.  When using this option, you  should  specify  a  startup
          shell which launches the desired application through SeamlessRDP.

See mentioned Cendio website for more information.

How to sort an array of objects with jquery or javascript

the sort method contains an optional argument to pass a custom compare function.

Assuming you wanted an array of arrays:

var arr = [[3, "Mike", 20],[5, "Alex", 15]];

function compareName(a, b)
{

  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
}
arr.sort(compareName);

Otherwise if you wanted an array of objects, you could do:

function compareName(a, b)
{

  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
}

C++ passing an array pointer as a function argument

int *a[], when used as a function parameter (but not in normal declarations), is a pointer to a pointer, not a pointer to an array (in normal declarations, it is an array of pointers). A pointer to an array looks like this:

int (*aptr)[N]

Where N is a particular positive integer (not a variable).

If you make your function a template, you can do it and you don't even need to pass the size of the array (because it is automatically deduced):

template<size_t SZ>
void generateArray(int (*aptr)[SZ])
{
    for (size_t i=0; i<SZ; ++i)
        (*aptr)[i] = rand() % 9;
}

int main()
{    
    int a[5];    
    generateArray(&a);
}

You could also take a reference:

template<size_t SZ>
void generateArray(int (&arr)[SZ])
{
    for (size_t i=0; i<SZ; ++i)
        arr[i] = rand() % 9;
}

int main()
{    
    int a[5];    
    generateArray(a);
}

Maven with Eclipse Juno

This is what I was getting when tried to install m2e from Eclipse Market place. I am using Eclipse Juno.

Cannot complete the install because one or more required items could not be found. Software being installed: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Cannot satisfy dependency: From: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) To: org.eclipse.m2e.core [1.5.0.20140606-0033]

However, the below links is perfect, it works for me.

http://marketplace.eclipse.org/content/maven-integration-eclipse-wtp-juno-0

Regards, Bilal

What is the difference between sed and awk?

Both tools are meant to work with text and there are tasks both tools can be used for.

For me the rule to separate them is: Use sed to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.

Also you should not forget about grep. Use grep if you only want to search/extract something in a text (file)

How to revert multiple git commits?

Clean way which I found useful

git revert --no-commit HEAD~3..

This command reverts last 3 commits with only one commit.

Also doesn't rewrite history.

The .. helps create a range. Meaning HEAD~3.. is the same as HEAD~3..HEAD

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__func__ is documented in the C++0x standard at section 8.4.1. In this case it's a predefined function local variable of the form:

static const char __func__[] = "function-name ";

where "function name" is implementation specfic. This means that whenever you declare a function, the compiler will add this variable implicitly to your function. The same is true of __FUNCTION__ and __PRETTY_FUNCTION__. Despite their uppercasing, they aren't macros. Although __func__ is an addition to C++0x

g++ -std=c++98 ....

will still compile code using __func__.

__PRETTY_FUNCTION__ and __FUNCTION__ are documented here http://gcc.gnu.org/onlinedocs/gcc-4.5.1/gcc/Function-Names.html#Function-Names. __FUNCTION__ is just another name for __func__. __PRETTY_FUNCTION__ is the same as __func__ in C but in C++ it contains the type signature as well.

How do I check for null values in JavaScript?

In JavaScript, no string is equal to null.

Maybe you expected pass == null to be true when pass is an empty string because you're aware that the loose equality operator == performs certain kinds of type coercion.

For example, this expression is true:

'' == 0

In contrast, the strict equality operator === says that this is false:

'' === 0

Given that '' and 0 are loosely equal, you might reasonably conjecture that '' and null are loosely equal. However, they are not.

This expression is false:

'' == null

The result of comparing any string to null is false. Therefore, pass == null and all your other tests are always false, and the user never gets the alert.

To fix your code, compare each value to the empty string:

pass === ''

If you're certain that pass is a string, pass == '' will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.

If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.

How to implement an STL-style iterator and avoid common pitfalls?

I was trying to solve the problem of being able to iterate over several different text arrays all of which are stored within a memory resident database that is a large struct.

The following was worked out using Visual Studio 2017 Community Edition on an MFC test application. I am including this as an example as this posting was one of several that I ran across that provided some help yet were still insufficient for my needs.

The struct containing the memory resident data looked something like the following. I have removed most of the elements for the sake of brevity and have also not included the Preprocessor defines used (the SDK in use is for C as well as C++ and is old).

What I was interested in doing is having iterators for the various WCHAR two dimensional arrays which contained text strings for mnemonics.

typedef struct  tagUNINTRAM {
    // stuff deleted ...
    WCHAR   ParaTransMnemo[MAX_TRANSM_NO][PARA_TRANSMNEMO_LEN]; /* prog #20 */
    WCHAR   ParaLeadThru[MAX_LEAD_NO][PARA_LEADTHRU_LEN];   /* prog #21 */
    WCHAR   ParaReportName[MAX_REPO_NO][PARA_REPORTNAME_LEN];   /* prog #22 */
    WCHAR   ParaSpeMnemo[MAX_SPEM_NO][PARA_SPEMNEMO_LEN];   /* prog #23 */
    WCHAR   ParaPCIF[MAX_PCIF_SIZE];            /* prog #39 */
    WCHAR   ParaAdjMnemo[MAX_ADJM_NO][PARA_ADJMNEMO_LEN];   /* prog #46 */
    WCHAR   ParaPrtModi[MAX_PRTMODI_NO][PARA_PRTMODI_LEN];  /* prog #47 */
    WCHAR   ParaMajorDEPT[MAX_MDEPT_NO][PARA_MAJORDEPT_LEN];    /* prog #48 */
    //  ... stuff deleted
} UNINIRAM;

The current approach is to use a template to define a proxy class for each of the arrays and then to have a single iterator class that can be used to iterate over a particular array by using a proxy object representing the array.

A copy of the memory resident data is stored in an object that handles reading and writing the memory resident data from/to disk. This class, CFilePara contains the templated proxy class (MnemonicIteratorDimSize and the sub class from which is it is derived, MnemonicIteratorDimSizeBase) and the iterator class, MnemonicIterator.

The created proxy object is attached to an iterator object which accesses the necessary information through an interface described by a base class from which all of the proxy classes are derived. The result is to have a single type of iterator class which can be used with several different proxy classes because the different proxy classes all expose the same interface, the interface of the proxy base class.

The first thing was to create a set of identifiers which would be provided to a class factory to generate the specific proxy object for that type of mnemonic. These identifiers are used as part of the user interface to identify the particular provisioning data the user is interested in seeing and possibly modifying.

const static DWORD_PTR dwId_TransactionMnemonic = 1;
const static DWORD_PTR dwId_ReportMnemonic = 2;
const static DWORD_PTR dwId_SpecialMnemonic = 3;
const static DWORD_PTR dwId_LeadThroughMnemonic = 4;

The Proxy Class

The templated proxy class and its base class are as follows. I needed to accommodate several different kinds of wchar_t text string arrays. The two dimensional arrays had different numbers of mnemonics, depending on the type (purpose) of the mnemonic and the different types of mnemonics were of different maximum lengths, varying between five text characters and twenty text characters. Templates for the derived proxy class was a natural fit with the template requiring the maximum number of characters in each mnemonic. After the proxy object is created, we then use the SetRange() method to specify the actual mnemonic array and its range.

// proxy object which represents a particular subsection of the
// memory resident database each of which is an array of wchar_t
// text arrays though the number of array elements may vary.
class MnemonicIteratorDimSizeBase
{
    DWORD_PTR  m_Type;

public:
    MnemonicIteratorDimSizeBase(DWORD_PTR x) { }
    virtual ~MnemonicIteratorDimSizeBase() { }

    virtual wchar_t *begin() = 0;
    virtual wchar_t *end() = 0;
    virtual wchar_t *get(int i) = 0;
    virtual int ItemSize() = 0;
    virtual int ItemCount() = 0;

    virtual DWORD_PTR ItemType() { return m_Type; }
};

template <size_t sDimSize>
class MnemonicIteratorDimSize : public MnemonicIteratorDimSizeBase
{
    wchar_t    (*m_begin)[sDimSize];
    wchar_t    (*m_end)[sDimSize];

public:
    MnemonicIteratorDimSize(DWORD_PTR x) : MnemonicIteratorDimSizeBase(x), m_begin(0), m_end(0) { }
    virtual ~MnemonicIteratorDimSize() { }

    virtual wchar_t *begin() { return m_begin[0]; }
    virtual wchar_t *end() { return m_end[0]; }
    virtual wchar_t *get(int i) { return m_begin[i]; }

    virtual int ItemSize() { return sDimSize; }
    virtual int ItemCount() { return m_end - m_begin; }

    void SetRange(wchar_t (*begin)[sDimSize], wchar_t (*end)[sDimSize]) {
        m_begin = begin; m_end = end;
    }

};

The Iterator Class

The iterator class itself is as follows. This class provides just basic forward iterator functionality which is all that is needed at this time. However I expect that this will change or be extended when I need something additional from it.

class MnemonicIterator
{
private:
    MnemonicIteratorDimSizeBase   *m_p;  // we do not own this pointer. we just use it to access current item.
    int      m_index;                    // zero based index of item.
    wchar_t  *m_item;                    // value to be returned.

public:
    MnemonicIterator(MnemonicIteratorDimSizeBase *p) : m_p(p) { }
    ~MnemonicIterator() { }

    // a ranged for needs begin() and end() to determine the range.
    // the range is up to but not including what end() returns.
    MnemonicIterator & begin() { m_item = m_p->get(m_index = 0); return *this; }                 // begining of range of values for ranged for. first item
    MnemonicIterator & end() { m_item = m_p->get(m_index = m_p->ItemCount()); return *this; }    // end of range of values for ranged for. item after last item.
    MnemonicIterator & operator ++ () { m_item = m_p->get(++m_index); return *this; }            // prefix increment, ++p
    MnemonicIterator & operator ++ (int i) { m_item = m_p->get(m_index++); return *this; }       // postfix increment, p++
    bool operator != (MnemonicIterator &p) { return **this != *p; }                              // minimum logical operator is not equal to
    wchar_t * operator *() const { return m_item; }                                              // dereference iterator to get what is pointed to
};

The proxy object factory determines which object to created based on the mnemonic identifier. The proxy object is created and the pointer returned is the standard base class type so as to have a uniform interface regardless of which of the different mnemonic sections are being accessed. The SetRange() method is used to specify to the proxy object the specific array elements the proxy represents and the range of the array elements.

CFilePara::MnemonicIteratorDimSizeBase * CFilePara::MakeIterator(DWORD_PTR x)
{
    CFilePara::MnemonicIteratorDimSizeBase  *mi = nullptr;

    switch (x) {
    case dwId_TransactionMnemonic:
        {
            CFilePara::MnemonicIteratorDimSize<PARA_TRANSMNEMO_LEN> *mk = new CFilePara::MnemonicIteratorDimSize<PARA_TRANSMNEMO_LEN>(x);
            mk->SetRange(&m_Para.ParaTransMnemo[0], &m_Para.ParaTransMnemo[MAX_TRANSM_NO]);
            mi = mk;
        }
        break;
    case dwId_ReportMnemonic:
        {
            CFilePara::MnemonicIteratorDimSize<PARA_REPORTNAME_LEN> *mk = new CFilePara::MnemonicIteratorDimSize<PARA_REPORTNAME_LEN>(x);
            mk->SetRange(&m_Para.ParaReportName[0], &m_Para.ParaReportName[MAX_REPO_NO]);
            mi = mk;
        }
        break;
    case dwId_SpecialMnemonic:
        {
            CFilePara::MnemonicIteratorDimSize<PARA_SPEMNEMO_LEN> *mk = new CFilePara::MnemonicIteratorDimSize<PARA_SPEMNEMO_LEN>(x);
            mk->SetRange(&m_Para.ParaSpeMnemo[0], &m_Para.ParaSpeMnemo[MAX_SPEM_NO]);
            mi = mk;
        }
        break;
    case dwId_LeadThroughMnemonic:
        {
            CFilePara::MnemonicIteratorDimSize<PARA_LEADTHRU_LEN> *mk = new CFilePara::MnemonicIteratorDimSize<PARA_LEADTHRU_LEN>(x);
            mk->SetRange(&m_Para.ParaLeadThru[0], &m_Para.ParaLeadThru[MAX_LEAD_NO]);
            mi = mk;
        }
        break;
    }

    return mi;
}

Using the Proxy Class and Iterator

The proxy class and its iterator are used as shown in the following loop to fill in a CListCtrl object with a list of mnemonics. I am using std::unique_ptr so that when the proxy class i not longer needed and the std::unique_ptr goes out of scope, the memory will be cleaned up.

What this source code does is to create a proxy object for the array within the struct which corresponds to the specified mnemonic identifier. It then creates an iterator for that object, uses a ranged for to fill in the CListCtrl control and then cleans up. These are all raw wchar_t text strings which may be exactly the number of array elements so we copy the string into a temporary buffer in order to ensure that the text is zero terminated.

    std::unique_ptr<CFilePara::MnemonicIteratorDimSizeBase> pObj(pFile->MakeIterator(m_IteratorType));
    CFilePara::MnemonicIterator pIter(pObj.get());  // provide the raw pointer to the iterator who doesn't own it.

    int i = 0;    // CListCtrl index for zero based position to insert mnemonic.
    for (auto x : pIter)
    {
        WCHAR szText[32] = { 0 };     // Temporary buffer.

        wcsncpy_s(szText, 32, x, pObj->ItemSize());
        m_mnemonicList.InsertItem(i, szText);  i++;
    }

Change the bullet color of list

Example JS Fiddle

Bullets take the color property of the list:

.listStyle {
    color: red;
}

Note if you want your list text to be a different colour, you have to wrap it in say, a p, for example:

.listStyle p {
    color: black;
}

Example HTML:

<ul class="listStyle">
    <li>
        <p><strong>View :</strong> blah blah.</p>
    </li>
    <li>
        <p><strong>View :</strong> blah blah.</p>
    </li>
</ul>

Laravel 4: how to run a raw SQL?

Actually, Laravel 4 does have a table rename function in Illuminate/Database/Schema/Builder.php, it's just undocumented at the moment: Schema::rename($from, $to);.

How to read one single line of csv data in Python?

To print a range of line, in this case from line 4 to 7

import csv

with open('california_housing_test.csv') as csv_file:
    data = csv.reader(csv_file)
    for row in list(data)[4:7]:
        print(row)

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

If you want to change in AppServiceProvider then you need to define the length of email field in migration. just replace the first line of code to the second line.

create_users_table

$table->string('email')->unique();
$table->string('email', 50)->unique();

create_password_resets_table

$table->string('email')->index();
$table->string('email', 50)->index();

After successfully changes you can run the migration.
Note: first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migration table.

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.

Declare variable in SQLite and use it

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

I've used the below approach for large projects and works like a charm.

/* Create in-memory temp table for variables */
BEGIN;

PRAGMA temp_store = 2;
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);

/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');

/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';

/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...

DROP TABLE _Variables;
END;

How to pick element inside iframe using document.getElementById

(this is to add to the chosen answer)

Make sure the iframe is loaded before you

contentWindow.document

Otherwise, your getElementById will be null.

PS: Can't comment, still low reputation to comment, but this is a follow-up on the chosen answer as I've spent some good debugging time trying to figure out I should force the iframe load before selecting the inner-iframe element.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

How to create an empty array in PHP with predefined size?

PHP provides two types of array.

  • normal array
  • SplFixedArray

normal array : This array is dynamic.

SplFixedArray : this is a standard php library which provides the ability to create array of fix size.

How to use continue in jQuery each() loop?

return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".

How to get first 5 characters from string

You can get your result by simply use substr():

Syntax substr(string,start,length)

Example

<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>

Output :

 Hello

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

I was able to trigger an SDK download like this:

  1. Close Android Studio
  2. Open android studio, but be ready
  3. Once you see "loading project", click cancel. (this will only appear for seconds on a fast machine)
  4. The SDK download window appeared!

How do you give iframe 100% height

The problem with iframes not getting 100% height is not because they're unwieldy. The problem is that for them to get 100% height they need their parents to have 100% height. If one of the iframe's parents is not 100% tall the iframe won't be able to go beyond that parent's height.

So the best possible solution would be:

html, body, iframe { height: 100%; }

…given the iframe is directly under body. If the iframe has a parent between itself and the body, the iframe will still get the height of its parent. One must explicitly set the height of every parent to 100% as well (if that's what one wants).

Tested in:

Chrome 30, Firefox 24, Safari 6.0.5, Opera 16, IE 7, 8, 9 and 10

PS: I don't mean to be picky but the solution marked as correct doesn't work on Firefox 24 at the time of this writing, but worked on Chrome 30. Haven't tested on other browsers though. I came across the error on Firefox because the page I was testing had very little content... It could be it's my meager markup or the CSS reset altering the output, but if I experienced this error I guess the accepted answer doesn't work in every situation.

Update 2021

@Zeni suggested this in 2015:

iframe { height: 100vh }

...and indeed it does the trick!

Careful with positioning as it can potentially break the effect. Test thoroughly, you might not need positioning depending of what you're trying to achieve.

What is the "right" way to iterate through an array in Ruby?

Using the same method for iterating through both arrays and hashes makes sense, for example to process nested hash-and-array structures often resulting from parsers, from reading JSON files etc..

One clever way that has not yet been mentioned is how it's done in the Ruby Facets library of standard library extensions. From here:

class Array

  # Iterate over index and value. The intention of this
  # method is to provide polymorphism with Hash.
  #
  def each_pair #:yield:
    each_with_index {|e, i| yield(i,e) }
  end

end

There is already Hash#each_pair, an alias of Hash#each. So after this patch, we also have Array#each_pair and can use it interchangeably to iterate through both Hashes and Arrays. This fixes the OP's observed insanity that Array#each_with_index has the block arguments reversed compared to Hash#each. Example usage:

my_array = ['Hello', 'World', '!']
my_array.each_pair { |key, value| pp "#{key}, #{value}" }

# result: 
"0, Hello"
"1, World"
"2, !"

my_hash = { '0' => 'Hello', '1' => 'World', '2' => '!' }
my_hash.each_pair { |key, value| pp "#{key}, #{value}" }

# result: 
"0, Hello"
"1, World"
"2, !"

illegal character in path

The string is surrounded by double quotes. Yes, that's not a valid character in a path.

You should probably tackle it at the source, but you can strip them out with:

        path = path.Replace("\"", "");

Why doesn't RecyclerView have onItemClickListener()?

As far as I understand MLProgrammer-CiM answer, simply it's possible to just do this:

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    private ImageView image;
    private TextView title;
    private TextView price;

    public MyViewHolder(View itemView) {
        super(itemView);
        image = (ImageView)itemView.findViewById(R.id.horizontal_list_image);
        title = (TextView)itemView.findViewById(R.id.horizontal_list_title);
        price = (TextView)itemView.findViewById(R.id.horizontal_list_price);
        image.setOnClickListener(this);
        title.setOnClickListener(this);
        price.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        Toast.makeText(context, "Item click nr: "+getLayoutPosition(), Toast.LENGTH_SHORT).show();
    }
}

MySQL config file location - redhat linux server

On RH systems, MySQL configuration file is located under /etc/my.cnf by default.

Equivalent of Clean & build in Android Studio?

reed these links

http://tools.android.com/tech-docs/new-build-system/version-compatibility https://developer.android.com/studio/releases/gradle-plugin.html

in android studio version 2+, use this in gradle config

android{
..

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
        incremental = false;
}
...

}

after 3 days of search and test :(, this solve "rebuild for any run"

Calculating the distance between 2 points

If you are using System.Windows.Point data type to represent a point, you can use

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distance = Point.Subtract(p2, p1).Length;

Update 2017-01-08:

  • Add reference to Microsoft documentation
  • Result of Point.Subtract is System.Windows.Vector and it has also property LengthSquared to save one sqrt calculation if you just need to compare distance.
  • Adding reference to WindowsBase assembly may be needed in your project
  • You can also use operators

Example with LengthSquared and operators

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distanceSquared = (p2 - p1).LengthSquared;

Laravel-5 how to populate select box from database with id value and name value

Laravel >= 5.3 method lists() is deprecated use pluck()

$items = Items::pluck('name', 'id');

{!! Form::select('items', $items, null, ['class' => 'some_css_class']) !!}

This will give you a select box with same select options as id numbers in DB

for example if you have this in your DB table:

id name
1  item1
2  item2
3  item3
4  item4

in select box it will be like this

<select>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>

I found out that pluck now returns a collection, and you need to add ->toArray() at the end of pluck...so like this: pluck('name', 'id')->toArray();

Setting Action Bar title and subtitle

Try This:

In strings.xml add your title and subtitle...

ActionBar ab = getActionBar();
ab.setTitle(getResources().getString(R.string.myTitle));
ab.setSubtitle(getResources().getString(R.string.mySubTitle));

How to delete a selected DataGridViewRow and update a connected database table?

To delete multiple rows in datagrid, c#

parts of my code:

private void btnDelete_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in datagrid1.SelectedRows)
        {
            //get key
            int rowId = Convert.ToInt32(row.Cells[0].Value);

            //avoid updating the last empty row in datagrid
            if (rowId > 0)
            {
                //delete 
                aController.Delete(rowId);

                //refresh datagrid
                datagrid1.Rows.RemoveAt(row.Index); 
            }  
        }
    }




 public void Delete(int rowId)
        {
            var toBeDeleted = db.table1.First(c => c.Id == rowId);
            db.table1.DeleteObject(toBeDeleted);
            db.SaveChanges();

        }

Javascript button to insert a big black dot (•) into a html textarea

Just access the element and append it to the value.

<input
     type="button" 
     onclick="document.getElementById('myTextArea').value += '•'" 
     value="Add •">

See a live demo.

For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.

Also it needs to be a UTF8 character.

Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Removing Conda environment

My environment name is: test

conda remove -n test --all

What determines the monitor my app runs on?

So I agree there are some apps that you can configured to open on one screen by maximizing or right clicking and moving/sizing screen, then close and reopen. However, there are others that will only open on the main screen.

What I've done to resolve: set the monitor you prefer stubborn apps to open on, as monitor 1 and the your other monitor as 2, then change your monitor 2 to be the primary - so your desktop settings and start bar remain. Hope this helps.

How to replace a set of tokens in a Java String?

The most efficient way would be using a matcher to continually find the expressions and replace them, then append the text to a string builder:

Pattern pattern = Pattern.compile("\\[(.+?)\\]");
Matcher matcher = pattern.matcher(text);
HashMap<String,String> replacements = new HashMap<String,String>();
//populate the replacements map ...
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
    String replacement = replacements.get(matcher.group(1));
    builder.append(text.substring(i, matcher.start()));
    if (replacement == null)
        builder.append(matcher.group(0));
    else
        builder.append(replacement);
    i = matcher.end();
}
builder.append(text.substring(i, text.length()));
return builder.toString();

Scala best way of turning a Collection into a Map-by-key?

You can construct a Map with a variable number of tuples. So use the map method on the collection to convert it into a collection of tuples and then use the : _* trick to convert the result into a variable argument.

scala> val list = List("this", "maps", "string", "to", "length") map {s => (s, s.length)}
list: List[(java.lang.String, Int)] = List((this,4), (maps,4), (string,6), (to,2), (length,6))

scala> val list = List("this", "is", "a", "bunch", "of", "strings")
list: List[java.lang.String] = List(this, is, a, bunch, of, strings)

scala> val string2Length = Map(list map {s => (s, s.length)} : _*)
string2Length: scala.collection.immutable.Map[java.lang.String,Int] = Map(strings -> 7, of -> 2, bunch -> 5, a -> 1, is -> 2, this -> 4)

How to study design patterns?

I recommend HeadFirst DesignPattern. Reading the book is not enough, after assimilating the concepts you need to findout the answers for lot of questions arise in your mind and try to findout the real life applications where in these patterns can be used. I am doing the same and started asking questions even those questions look silly.

How to find the serial port number on Mac OS X?

Found the port esp32 was connected to by -

ls /dev/*

You would get a long list and you can find the port you need

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon destroys the session as stated above so you should use this when logging someone out. I think a good use of Session.Clear would be for a shopping basket on an ecommerce website. That way the basket gets cleared without logging out the user.

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

I used this code to produce your desired output. Is this what you were after?

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

  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

How to convert date format to DD-MM-YYYY in C#

First convert your string into DateTime variable:

DateTime date = DateTime.Parse(your variable);

Then convert this variable back to string in correct format:

String dateInString = date.ToString("dd-MM-yyyy");

How to Query Database Name in Oracle SQL Developer?

You can use the following command to know just the name of the database without the extra columns shown.

select name  from v$database;

If you need any other information about the db then first know which are the columns names available using

describe v$database;

and select the columns that you want to see;

The CSRF token is invalid. Please try to resubmit the form

I faced a similar issue. After ensuring the token field was actually rendered (see accepted answer) I checked my cookies. There were 2(!) cookies for the domain in my Chrome browser, apparently because I was running the application on the same domain as another app, but with a different port (i.e. mydomain.com set the original cookie while the buggy app was running on mydomain.com:123) Now apparently Chrome sent the wrong cookie so the CSRF protection was unable to link the token to the correct session.

Fix: clear all the cookies for the domain in question, make sure you don't run multiple applications on the same domain with differing ports.

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

Another possible cause of the “Workspace in use or cannot be created, chose a different one” issue is that the real path to your workspace may have changed.

In my case, the real location of the workspace had changed, but I had used a symlink to make it look like it was in the same location. I saw errors in logs indicating that eclipse was looking at the previous "real" location, as opposed to following the symlink, and this was causing the errors.

In my case, I just moved the workspace back to its old location.

CSS: How to remove pseudo elements (after, before,...)?

had a same problem few minutes ago and just content:none; did not do work but adding content:none !important; and display:none !important; worked for me

Checking cin input stream produces an integer

There is a function in c called isdigit(). That will suit you just fine. Example:

int var1 = 'h';
int var2 = '2';

if( isdigit(var1) )
{
   printf("var1 = |%c| is a digit\n", var1 );
}
else
{
   printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
  printf("var2 = |%c| is a digit\n", var2 );
}
else
{
   printf("var2 = |%c| is not a digit\n", var2 );
}

From here

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

Python print statement “Syntax Error: invalid syntax”

Use print("use this bracket -sample text")

In Python 3 print "Hello world" gives invalid syntax error.

To display string content in Python3 have to use this ("Hello world") brackets.

Adding days to $Date in PHP

You can also use the following format

strtotime("-3 days", time());
strtotime("+1 day", strtotime($date));

You can stack changes this way:

strtotime("+1 day", strtotime("+1 year", strtotime($date)));

Note the difference between this approach and the one in other answers: instead of concatenating the values +1 day and <timestamp>, you can just pass in the timestamp as the second parameter of strtotime.

How to list files in an android directory?

I just discovered that:

new File("/sdcard/").listFiles() returns null if you do not have:

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

set in your AndroidManifest.xml file.

String or binary data would be truncated. The statement has been terminated

When you define varchar etc without a length, the default is 1.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

So, if you expect 400 bytes in the @trackingItems1 column from stock, use nvarchar(400).

Otherwise, you are trying to fit >1 character into nvarchar(1) = fail

As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better

ALTER FUNCTION [dbo].[testing1](@price int)
RETURNS
AS
   SELECT ta.item, ta.warehouse, ta.price 
   FROM   stock ta
   WHERE  ta.price >= @price;

Of course, you could just use a normal SELECT statement..

How do I wait for an asynchronously dispatched block to finish?

Here's a nifty trick that doesn't use a semaphore:

dispatch_queue_t serialQ = dispatch_queue_create("serialQ", DISPATCH_QUEUE_SERIAL);
dispatch_async(serialQ, ^
{
    [object doSomething];
});
dispatch_sync(serialQ, ^{ });

What you do is wait using dispatch_sync with an empty block to Synchronously wait on a serial dispatch queue until the A-Synchronous block has completed.

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

How to render an ASP.NET MVC view as a string?

I found a new solution that renders a view to string without having to mess with the Response stream of the current HttpContext (which doesn't allow you to change the response's ContentType or other headers).

Basically, all you do is create a fake HttpContext for the view to render itself:

/// <summary>Renders a view to string.</summary>
public static string RenderViewToString(this Controller controller,
                                        string viewName, object viewData) {
    //Create memory writer
    var sb = new StringBuilder();
    var memWriter = new StringWriter(sb);

    //Create fake http context to render the view
    var fakeResponse = new HttpResponse(memWriter);
    var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
    var fakeControllerContext = new ControllerContext(
        new HttpContextWrapper(fakeContext),
        controller.ControllerContext.RouteData,
        controller.ControllerContext.Controller);

    var oldContext = HttpContext.Current;
    HttpContext.Current = fakeContext;

    //Use HtmlHelper to render partial view to fake context
    var html = new HtmlHelper(new ViewContext(fakeControllerContext,
        new FakeView(), new ViewDataDictionary(), new TempDataDictionary()),
        new ViewPage());
    html.RenderPartial(viewName, viewData);

    //Restore context
    HttpContext.Current = oldContext;    

    //Flush memory and return output
    memWriter.Flush();
    return sb.ToString();
}

/// <summary>Fake IView implementation used to instantiate an HtmlHelper.</summary>
public class FakeView : IView {
    #region IView Members

    public void Render(ViewContext viewContext, System.IO.TextWriter writer) {
        throw new NotImplementedException();
    }

    #endregion
}

This works on ASP.NET MVC 1.0, together with ContentResult, JsonResult, etc. (changing Headers on the original HttpResponse doesn't throw the "Server cannot set content type after HTTP headers have been sent" exception).

Update: in ASP.NET MVC 2.0 RC, the code changes a bit because we have to pass in the StringWriter used to write the view into the ViewContext:

//...

//Use HtmlHelper to render partial view to fake context
var html = new HtmlHelper(
    new ViewContext(fakeControllerContext, new FakeView(),
        new ViewDataDictionary(), new TempDataDictionary(), memWriter),
    new ViewPage());
html.RenderPartial(viewName, viewData);

//...

How do I make a batch file terminate upon encountering an error?

No matter how I tried, the errorlevel always stays 0 even when msbuild failed. So I built my workaround:

Build Project and save log to Build.log

SET Build_Opt=/flp:summary;logfile=Build.log;append=true

msbuild "myproj.csproj" /t:rebuild /p:Configuration=release /fl %Build_Opt%

search for "0 Error" string in build log, set the result to var

FOR /F "tokens=* USEBACKQ" %%F IN (`find /c /i "0 Error" Build.log`) DO (
    SET var=%%F
)
echo %var%

get the last character, which indicates how many lines contains the search string

set result=%var:~-1%

echo "%result%"

if string not found, then error > 0, build failed

if "%result%"=="0" ( echo "build failed" )

That solution was inspired by Mechaflash's post at How to set commands output as a variable in a batch file

and https://ss64.com/nt/syntax-substring.html

Fixed digits after decimal with f-strings

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'