Programs & Examples On #Fractals

Fractals are interesting mathematical objects with a special behaviour in a complex-plane [Re, Im], depending on their initial position ( location ). Visualised in popular media, typically as shapes with infinite dimensionality that exhibit a sort of self-similarity. Well-known fractal sets include the named Mandelbrot set, Julia sets, and Phoenix sets. Tree-like fractal drawings are also common.

How to program a fractal?

You should indeed start with the Mandelbrot set, and understand what it really is.

The idea behind it is relatively simple. You start with a function of complex variable

f(z) = z2 + C

where z is a complex variable and C is a complex constant. Now you iterate it starting from z = 0, i.e. you compute z1 = f(0), z2 = f(z1), z3 = f(z2) and so on. The set of those constants C for which the sequence z1, z2, z3, ... is bounded, i.e. it does not go to infinity, is the Mandelbrot set (the black set in the figure on the Wikipedia page).

In practice, to draw the Mandelbrot set you should:

  • Choose a rectangle in the complex plane (say, from point -2-2i to point 2+2i).
  • Cover the rectangle with a suitable rectangular grid of points (say, 400x400 points), which will be mapped to pixels on your monitor.
  • For each point/pixel, let C be that point, compute, say, 20 terms of the corresponding iterated sequence z1, z2, z3, ... and check whether it "goes to infinity". In practice you can check, while iterating, if the absolute value of one of the 20 terms is greater than 2 (if one of the terms does, the subsequent terms are guaranteed to be unbounded). If some z_k does, the sequence "goes to infinity"; otherwise, you can consider it as bounded.
  • If the sequence corresponding to a certain point C is bounded, draw the corresponding pixel on the picture in black (for it belongs to the Mandelbrot set). Otherwise, draw it in another color. If you want to have fun and produce pretty plots, draw it in different colors depending on the magnitude of abs(20th term).

The astounding fact about fractals is how we can obtain a tremendously complex set (in particular, the frontier of the Mandelbrot set) from easy and apparently innocuous requirements.

Enjoy!

Null vs. False vs. 0 in PHP

I think bad developers find all different uses of null/0/false in there code.

For example, one of the most common mistakes developers make is to return error code in the form of data with a function.

// On error GetChar returns -1
int GetChar()

This is an example of a sugar interface. This is exsplained in the book "Debuging the software development proccess" and also in another book "writing correct code".

The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot.

Instead, the best way is not to mix error code with your data. So the following function.

char GetChar()

now becomes

// On success return 1
// on failure return 0
bool GetChar(int &char)

This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code.

So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine.

How to unblock with mysqladmin flush hosts

You should put it into command line in windows.

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

For network login use the following command:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

How do you list volumes in docker containers?

You can get information about which volumes were specifically baked into the container by inspecting the container and looking in the JSON output and comparing a couple of the fields. When you run docker inspect myContainer, the Volumes and VolumesRW fields give you information about ALL of the volumes mounted inside a container, including volumes mounted in both the Dockerfile with the VOLUME directive, and on the command line with the docker run -v command. However, you can isolate which volumes were mounted in the container using the docker run -v command by checking for the HostConfig.Binds field in the docker inspect JSON output. To clarify, this HostConfig.Binds field tells you which volumes were mounted specifically in your docker run command with the -v option. So if you cross-reference this field with the Volumes field, you will be able to determine which volumes were baked into the container using VOLUME directives in the Dockerfile.

A grep could accomplish this like:

$ docker inspect myContainer | grep -C2 Binds
...
"HostConfig": {
    "Binds": [
        "/var/docker/docker-registry/config:/registry"
    ],

And...

$ docker inspect myContainer | grep -C3 -e "Volumes\":"
...
"Volumes": {
    "/data": "/var/lib/docker...",
    "/config": "/var/lib/docker...",
    "/registry": "/var/docker/docker-registry/config"

And in my example, you can see I've mounted /var/docker/docker-registry/config into the container as /registry using the -v option in my docker run command, and I've mounted the /data and /config volumes using the VOLUME directive in my Dockerfile. The container does not need to be running to get this information, but it needs to have been run at least one time in order to populate the HostConfig JSON output of your docker inspect command.

How to save a plot as image on the disk?

For the first question, I find dev.print to be the best when working interactively. First, you set up your plot visually and when you are happy with what you see, you can ask R to save the current plot to disk

dev.print(pdf, file="filename.pdf");

You can replace pdf with other formats such as png.

This will copy the image exactly as you see it on screen. The problem with dev.copy is that the image is often different and doesn't remember the window size and aspect ratio - it forces the plot to be square by default.

For the second question, (as others have already answered), you must direct the output to disk before you execute your plotting commands

pdf('filename.pdf')
plot( yourdata )
points (some_more_data)
dev.off() # to complete the writing process and return output to your monitor

SQL Column definition : default value and not null redundant?

My SQL teacher said that if you specify both a DEFAULT value and NOT NULLor NULL, DEFAULT should always be expressed before NOT NULL or NULL.

Like this:

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL

How do you use global variables or constant values in Ruby?

I think it's local to the file you declared offset. Consider every file to be a method itself.

Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);?

Easiest way to convert month name to month number in JS ? (Jan = 01)

Another way;

alert( "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf("Jun") / 3 + 1 );

How to detect internet speed in JavaScript?

It's better to use images for testing the speed. But if you have to deal with zip files, the below code works.

var fileURL = "your/url/here/testfile.zip";

var request = new XMLHttpRequest();
var avoidCache = "?avoidcache=" + (new Date()).getTime();;
request.open('GET', fileURL + avoidCache, true);
request.responseType = "application/zip";
var startTime = (new Date()).getTime();
var endTime = startTime;
request.onreadystatechange = function () {
    if (request.readyState == 2)
    {
        //ready state 2 is when the request is sent
        startTime = (new Date().getTime());
    }
    if (request.readyState == 4)
    {
        endTime = (new Date()).getTime();
        var downloadSize = request.responseText.length;
        var time = (endTime - startTime) / 1000;
        var sizeInBits = downloadSize * 8;
        var speed = ((sizeInBits / time) / (1024 * 1024)).toFixed(2);
        console.log(downloadSize, time, speed);
    }
}

request.send();

This will not work very well with files < 10MB. You will have to run aggregated results on multiple download attempts.

How to set the component size with GridLayout? Is there a better way?

For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.

Media Queries: How to target desktop, tablet, and mobile?

$xs : "extra-small";
$s  : "small";
$m  : "medium";
$l  : "large";
$xl : "extra-large";

@mixin respond($breakpoint) {
  @if($breakpoint == $xs)  {
    @media only screen and (min-width: 320px) and (max-width: 479px) { @content; }
  }
  @if($breakpoint == $s)  {
    @media only screen and (min-width: 480px) and (max-width: 767px) { @content; }
  }
  @if($breakpoint == $m)  {
    @media only screen and (min-width: 768px) and (max-width: 991px) { @content; }
  }
  @if($breakpoint == $l)  {
    @media only screen and (min-width: 992px) and (max-width: 1199px) { @content; }
  }
  @if($breakpoint == $xl)  {
    @media only screen and (min-width: 1200px) { @content; }
  }
}

you can also add one more for for sceen smaller then 320px like Galaxy fold

Laravel 5 – Clear Cache in Shared Hosting Server

Basically I want to clear the views cache.

There is now a command in Laravel 5.1 for that

php artisan view:clear

Error: vector does not name a type

You need to either qualify vector with its namespace (which is std), or import the namespace at the top of your CPP file:

using namespace std;

Getting path of captured image in Android using camera intent

try this

String[] projection = { MediaStore.Images.Media.DATA };
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(mCapturedImageURI, projection,
                    null, null, null);
            int column_index_data = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            image_path = cursor.getString(column_index_data);
            Log.e("path of image from CAMERA......******************.........",
                    image_path + "");

for capturing image:

    String fileName = "temp.jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    mCapturedImageURI = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
    values.clear();

Batch files: How to read a file?

Under NT-style cmd.exe, you can loop through the lines of a text file with

FOR /F %i IN (file.txt) DO @echo %i

Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)

Adding default parameter value with type hint in Python

Your second way is correct.

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

{'opts': <class 'dict'>}

It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

I strongly advise against using mutable keyword arguments. More information here.

Detect when an image fails to load in Javascript

/**
 * Tests image load.
 * @param {String} url
 * @returns {Promise}
 */
function testImageUrl(url) {
  return new Promise(function(resolve, reject) {
    var image = new Image();
    image.addEventListener('load', resolve);
    image.addEventListener('error', reject);
    image.src = url;
  });
}

return testImageUrl(imageUrl).then(function imageLoaded(e) {
  return imageUrl;
})
.catch(function imageFailed(e) {
  return defaultImageUrl;
});

Required attribute HTML5

I just ran into this issue with Safari 5 and it has been an issue with Opera 10 for some time, but I never spent time to fix it. Now I need to fix it and saw your post but no solution yet on how to cancel the form. After much searching I finally found something:

http://www.w3.org/TR/html5/forms.html#attr-fs-formnovalidate

<input type=submit formnovalidate name=cancel value="Cancel">

Works on Safari 5 and Opera 10.

Set value of textarea in jQuery

Using $("textarea#ExampleMessage").html('whatever you want to put here'); can be a good way, because .val() can have problems when you are using data from database.

For example:

A database field named as description has the following value asjkdfklasdjf sjklñadf. In this case using .val() to assign value to textarea can be a tedious job.

What is a good practice to check if an environmental variable exists or not?

There is a case for either solution, depending on what you want to do conditional on the existence of the environment variable.

Case 1

When you want to take different actions purely based on the existence of the environment variable, without caring for its value, the first solution is the best practice. It succinctly describes what you test for: is 'FOO' in the list of environment variables.

if 'KITTEN_ALLERGY' in os.environ:
    buy_puppy()
else:
    buy_kitten()

Case 2

When you want to set a default value if the value is not defined in the environment variables the second solution is actually useful, though not in the form you wrote it:

server = os.getenv('MY_CAT_STREAMS', 'youtube.com')

or perhaps

server = os.environ.get('MY_CAT_STREAMS', 'youtube.com')

Note that if you have several options for your application you might want to look into ChainMap, which allows to merge multiple dicts based on keys. There is an example of this in the ChainMap documentation:

[...]
combined = ChainMap(command_line_args, os.environ, defaults)

Android EditText view Floating Hint in Material Design

Yes, as of May 29, 2015 this functionality is now provided in the Android Design Support Library

This library includes support for

  • Floating labels
  • Floating action button
  • Snackbar
  • Navigation drawer
  • and more

Basic HTML - how to set relative path to current folder?

Just dot is working. The doctype makes a difference however as sometimes the ./ is fine as well.

<a href=".">Link to this folder</a>

Append String in Swift

In the accepted answer PREMKUMAR there are a couple of errors in his Complete code in Swift answer. First print should read (appendString) and Second print should read (appendString1). Also, updated println deprecated in Swift 2.0

His

let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
println("APPEND STRING1:\(appendString1)")
println("APPEND STRING2:\(appendString2)")

Corrected

let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING:\(appendString)")
print("APPEND STRING1:\(appendString1)")

How to sort an array of objects in Java?

Update for Java 8 constructs

Assuming a Book class with a name field getter, you can use Arrays.sort method by passing an additional Comparator specified using Java 8 constructs - Comparator default method & method references.

Arrays.sort(bookArray, Comparator.comparing(Book::getName));

Also, it's possible to compare on multiple fields using thenComparing methods.

Arrays.sort(bookArray, Comparator.comparing(Book::getName)
      .thenComparing(Book::getAuthor))
      .thenComparingInt(Book::getId));

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

Remove all spaces from a string in SQL Server

Just a tip, in case you are having trouble with the replace function, you might have the datatype set to nchar (in which case it is a fixed length and it will not work).

Case insensitive string compare in LINQ-to-SQL

I used System.Data.Linq.SqlClient.SqlMethods.Like(row.Name, "test") in my query.

This performs a case-insensitive comparison.

Enable vertical scrolling on textarea

Maybe a fixed height and overflow-y: scroll;

PHP salt and hash SHA256 for login password

array hash_algos(void)

echo hash('sha384', 'Message to be hashed'.'salt');

Here is a link to reference http://php.net/manual/en/function.hash.php

react hooks useEffect() cleanup for only componentWillUnmount?

instead of creating too many complicated functions and methods what I do is I create an event listener and automatically have mount and unmount done for me without having to worry about doing it manually. Here is an example.

//componentDidMount
useEffect( () => {

    window.addEventListener("load",  pageLoad);

    //component will unmount
    return () => {
       
        window.removeEventListener("load", pageLoad);
    }

 });

now that this part is done I just run anything I want from the pageLoad function like this.

const pageLoad = () =>{
console.log(I was mounted and unmounted automatically :D)}

Create a hexadecimal colour based on a string with JavaScript

All you really need is a good hash function. On node, I just use

const crypto = require('crypto');
function strToColor(str) {
    return '#' + crypto.createHash('md5').update(str).digest('hex').substr(0, 6);
}

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

I prefer this simple XML hack which makes columns clickable in SSMS on a cell-by-cell basis. With this method, you can view your data quickly in SSMS’s tabular view and click on particular cells to see the full value when they are interesting. This is identical to the OP’s technique except that it avoids the XML errors.

SELECT
     e.EventID
    ,CAST(REPLACE(REPLACE(e.Details, '&', '&amp;'), '<', '&lt;') AS XML) Details
FROM Events e
WHERE 1=1
AND e.EventID BETWEEN 13920 AND 13930
;

Disabling Minimize & Maximize On WinForm?

public Form1()
{
InitializeComponent();
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
}

Sizing elements to percentage of screen width/height

There is many way to do this.

1. Using MediaQuery : Its return fullscreen of your device including appbar,toolbar

 Container(
        width: MediaQuery.of(context).size.width * 0.50,
        height: MediaQuery.of(context).size.height*0.50, 
        color: Colors.blueAccent[400],
 )

enter image description here


2. Using Expanded : You can set width/height in ratio

 Container(
        height: MediaQuery.of(context).size.height * 0.50,
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 70,
              child: Container(
                color: Colors.lightBlue[400],
              ),
            ),
            Expanded(
              flex: 30,
              child: Container(
                color: Colors.deepPurple[800],
              ),
            )
          ],
        ),
    )

enter image description here



3. Others Like Flexible and AspectRatio and FractionallySizedBox

jQuery: Get height of hidden element in jQuery

I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.

flexibox example enter image description here

I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.

Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.

$('[selector]').onVisibleChanged(function(e, isVisible)
{
    var realWidth = $('[selector]').width();
    var realHeight = $('[selector]').height();

    // render or adjust something
});

For more information, Please visit at my project GitHub.

https://github.com/Soul-Master/visible.event.js

demo: http://jsbin.com/ETiGIre/7

Testing if a checkbox is checked with jQuery

Try this

$('input:checkbox:checked').click(function(){
    var val=(this).val(); // it will get value from checked checkbox;
})

Here flag is true if checked otherwise false

var flag=$('#ans').attr('checked');

Again this will make cheked

$('#ans').attr('checked',true);

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

How to add Android Support Repository to Android Studio?

You are probably hit by this bug which prevents the Android Gradle Plugin from automatically adding the "Android Support Repository" to the list of Gradle repositories. The work-around, as mentioned in the bug report, is to explicitly add the m2repository directory as a local Maven directory in the top-level build.gradle file as follows:

allprojects {
    repositories {
        // Work around https://code.google.com/p/android/issues/detail?id=69270.
        def androidHome = System.getenv("ANDROID_HOME")
        maven {
            url "$androidHome/extras/android/m2repository/"
        }
    }
}

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

Now you should be able to use the new proxy integration type for Lambda to automatically get the full request in standard shape, rather than configure mappings.

see: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-set-up-lambda-proxy-integration-on-proxy-resource

How do I calculate r-squared using Python and Numpy?

R-squared is a statistic that only applies to linear regression.

Essentially, it measures how much variation in your data can be explained by the linear regression.

So, you calculate the "Total Sum of Squares", which is the total squared deviation of each of your outcome variables from their mean. . .

formula1

where y_bar is the mean of the y's.

Then, you calculate the "regression sum of squares", which is how much your FITTED values differ from the mean

formula2

and find the ratio of those two.

Now, all you would have to do for a polynomial fit is plug in the y_hat's from that model, but it's not accurate to call that r-squared.

Here is a link I found that speaks to it a little.

How to check String in response body with mockMvc

One possible approach is to simply include gson dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

and parse the value to make your verifications:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private HelloService helloService;

    @Before
    public void before() {
        Mockito.when(helloService.message()).thenReturn("hello world!");
    }

    @Test
    public void testMessage() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/"))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_VALUE))
                .andReturn();

        String responseBody = mvcResult.getResponse().getContentAsString();
        ResponseDto responseDto
                = new Gson().fromJson(responseBody, ResponseDto.class);
        Assertions.assertThat(responseDto.message).isEqualTo("hello world!");
    }
}

MySQL: Set user variable from result of query

Use this way so that result will not be displayed while running stored procedure.

The query:

SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;

ImportError: No module named PytQt5

this can be solved under MacOS X by installing pyqt with brew

brew install pyqt

OR is not supported with CASE Statement in SQL Server

That format requires you to use either:

CASE ebv.db_no 
  WHEN 22978 THEN 'WECS 9500' 
  WHEN 23218 THEN 'WECS 9500'  
  WHEN 23219 THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

Otherwise, use:

CASE  
  WHEN ebv.db_no IN (22978, 23218, 23219) THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

How to convert date into this 'yyyy-MM-dd' format in angular 2

The date can be converted in typescript to this format 'yyyy-MM-dd' by using Datepipe

import { DatePipe } from '@angular/common'
...
constructor(public datepipe: DatePipe){}
...
myFunction(){
 this.date=new Date();
 let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
}

and just add Datepipe in 'providers' array of app.module.ts. Like this:

import { DatePipe } from '@angular/common'
...
providers: [DatePipe]

Block direct access to a file over http but allow php script access

That is how I prevented direct access from URL to my ini files. Paste the following code in .htaccess file on root. (no need to create extra folder)

<Files ~ "\.ini$">
  Order allow,deny
  Deny from all
</Files>

my settings.ini file is on the root, and without this code is accessible www.mydomain.com/settings.ini

Passing Arrays to Function in C++

I just wanna add this, when you access the position of the array like

arg[n]

is the same as

*(arg + n) than means an offset of n starting from de arg address.

so arg[0] will be *arg

Find all storage devices attached to a Linux machine

You can always do fdisk -l which seems to work pretty well, even on strange setups such as EC2 xvda devices.

Here is a dump for a m1.large instance:

root@ip-10-126-247-82:~# fdisk -l

Disk /dev/xvda1: 10.7 GB, 10737418240 bytes
255 heads, 63 sectors/track, 1305 cylinders, total 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/xvda1 doesn't contain a valid partition table

Disk /dev/xvda2: 365.0 GB, 365041287168 bytes
255 heads, 63 sectors/track, 44380 cylinders, total 712971264 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/xvda2 doesn't contain a valid partition table

Disk /dev/xvda3: 939 MB, 939524096 bytes
255 heads, 63 sectors/track, 114 cylinders, total 1835008 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/xvda3 doesn't contain a valid partition table

While mount says:

root@ip-10-126-247-82:~# mount
/dev/xvda1 on / type ext4 (rw)
proc on /proc type proc (rw,noexec,nosuid,nodev)
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
fusectl on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
udev on /dev type devtmpfs (rw,mode=0755)
devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)
none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)
none on /run/shm type tmpfs (rw,nosuid,nodev)
/dev/xvda2 on /mnt type ext3 (rw)

And /proc/partitions says:

root@ip-10-126-247-82:~# cat /proc/partitions
major minor  #blocks  name

 202        1   10485760 xvda1
 202        2  356485632 xvda2
 202        3     917504 xvda3

Side Note

How fdisk -l works is something I would love to know myself.

Objective-C: Reading a file line by line

Mac OS X is Unix, Objective-C is C superset, so you can just use old-school fopen and fgets from <stdio.h>. It's guaranteed to work.

[NSString stringWithUTF8String:buf] will convert C string to NSString. There are also methods for creating strings in other encodings and creating without copying.

Using std::max_element on a vector<double>

min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

Calling a function of a module by using its name (a string)

locals()["myfunction"]()

or

globals()["myfunction"]()

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

Cannot instantiate the type List<Product>

List can be instantiated by any class implementing the interface.By this way,Java provides us polymorphic behaviour.See the example below:

List<String> list = new ArrayList<String>();

Instead of instantiating an ArrayList directly,I am using a List to refer to ArrayList object so that we are using only the List interface methods and do not care about its actual implementation.

Examples of classes implementing List are ArrayList,LinkedList,Vector.You probably want to create a List depending upon your requirements.

Example:- a LinkedList is more useful when you hve to do a number of inertion or deletions .Arraylist is more performance intensive as it is backed by a fixed size array and array contents have to be changed by moving or regrowing the array.

Again,using a List we can simply change our object instantiation without changing any code further in your programs.

Suppose we are using ArrayList<String> value = new ArrayList<String>();

we may use a specific method of ArrrayList and out code will not be robust

By using List<String> value = new ArrayList<String>();

we are making sure we are using only List interface methods..and if we want to change it to a LinkedList we simply have to change the code :

List<String> value = new ArrayList<String>(); 

------ your code uses List interface methods.....

value = new LinkedList<String>(); 

-----your code still uses List interface methods and we do not have to change anything---- and we dont have to change anything in our code further

By the way a LinkedList also works a Deque which obviously also you cannot instantiate as it is also an interface

Append lines to a file using a StreamWriter

Use this instead:

new StreamWriter("c:\\file.txt", true);

With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.

C# 4 and above offers the following syntax, which some find more readable:

new StreamWriter("c:\\file.txt", append: true);

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

This worked for me on Mac

sudo chown -R $(whoami) $(brew --prefix)/*

NodeJS / Express: what is "app.use"?

app.use
is created by express(nodejs middleware framework )
app.use is use to execute any specific query at intilization process
server.js(node)
var app = require('express');
app.use(bodyparser.json())
so the basically app.use function called every time when server up

What does ON [PRIMARY] mean?

To add a very important note on what Mark S. has mentioned in his post. In the specific SQL Script that has been mentioned in the question you can NEVER mention two different file groups for storing your data rows and the index data structure.

The reason why is due to the fact that the index being created in this case is a clustered Index on your primary key column. The clustered index data and the data rows of your table can NEVER be on different file groups.

So in case you have two file groups on your database e.g. PRIMARY and SECONDARY then below mentioned script will store your row data and clustered index data both on PRIMARY file group itself even though I've mentioned a different file group ([SECONDARY]) for the table data. More interestingly the script runs successfully as well (when I was expecting it to give an error as I had given two different file groups :P). SQL Server does the trick behind the scene silently and smartly.

CREATE TABLE [dbo].[be_Categories](
    [CategoryID] [uniqueidentifier] ROWGUIDCOL  NOT NULL CONSTRAINT [DF_be_Categories_CategoryID]  DEFAULT (newid()),
    [CategoryName] [nvarchar](50) NULL,
    [Description] [nvarchar](200) NULL,
    [ParentID] [uniqueidentifier] NULL,
 CONSTRAINT [PK_be_Categories] PRIMARY KEY CLUSTERED 
(
    [CategoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [SECONDARY]
GO

NOTE: Your index can reside on a different file group ONLY if the index being created is non-clustered in nature.

The below script which creates a non-clustered index will get created on [SECONDARY] file group instead when the table data already resides on [PRIMARY] file group:

CREATE NONCLUSTERED INDEX [IX_Categories] ON [dbo].[be_Categories]
(
    [CategoryName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Secondary]
GO

You can get more information on how storing non-clustered indexes on a different file group can help your queries perform better. Here is one such link.

Batch file to split .csv file

If splitting very large files, the solution I found is an adaptation from this, with PowerShell "embedded" in a batch file. This works fast, as opposed to many other things I tried (I wouldn't know about other options posted here).

The way to use mysplit.bat below is

mysplit.bat <mysize> 'myfile'

Note: The script was intended to use the first argument as the split size. It is currently hardcoded at 100Mb. It should not be difficult to fix this.

Note 2: The filname should be enclosed in single quotes. Other alternatives for quoting apparently do not work.

Note 3: It splits the file at given number of bytes, not at given number of lines. For me this was good enough. Some lines of code could be probably added to complete each chunk read, up to the next CR/LF. This will split in full lines (not with a constant number of them), with no sacrifice in processing time.

Script mysplit.bat:

@REM Using https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file
@REM and https://stackoverflow.com/questions/1001776/how-can-i-split-a-text-file-using-powershell
@PowerShell  ^
    $upperBound = 100MB;  ^
    $rootName = %2;  ^
    $from = $rootName;  ^
    $fromFile = [io.file]::OpenRead($from);  ^
    $buff = new-object byte[] $upperBound;  ^
    $count = $idx = 0;  ^
    try {  ^
        do {  ^
            'Reading ' + $upperBound;  ^
            $count = $fromFile.Read($buff, 0, $buff.Length);  ^
            if ($count -gt 0) {  ^
                $to = '{0}.{1}' -f ($rootName, $idx);  ^
                $toFile = [io.file]::OpenWrite($to);  ^
                try {  ^
                    'Writing ' + $count + ' to ' + $to;  ^
                    $tofile.Write($buff, 0, $count);  ^
                } finally {  ^
                    $tofile.Close();  ^
                }  ^
            }  ^
            $idx ++;  ^
        } while ($count -gt 0);  ^
    }  ^
    finally {  ^
        $fromFile.Close();  ^
    }  ^
%End PowerShell%

How to return value from function which has Observable subscription inside?

For example this is my html template:

<select class="custom-select d-block w-100" id="genre" name="genre"
                  [(ngModel)]="film.genre"
                  #genreInput="ngModel"
                  required>
            <option value="">Choose...</option>
            <option *ngFor="let genre of genres;" [value]="genre.value">{{genre.name}}</option>
          </select>

This is the field that binded with template from my Component:

  // Genres of films like action or drama that will populate dropdown list.
  genres: Genre[];

I fetch genres of films from server dynamically. In order do communicate with server I have created FilmService

This is the method which communicate server:

 fetchGenres(): Observable<Genre[]> {
    return this.client.get(WebUtils.RESOURCE_HOST_API + 'film' + '/genre') as Observable<Genre[]>;
  }

Why this method returns Observable<Genre[]> not something like Genre[]?

JavaScript is async and it does not wait for a method to return value after an expensive process. With expensive I mean a process that take a time to return value. Like fetching data from server. So you have to return reference of Observable and subscribe it.

For example in my Component :

ngOnInit() {
    this.filmService.fetchGenres().subscribe(
      val => this.genres = val
    );
  }

Table variable error: Must declare the scalar variable "@temp"

Either use an Allias in the table like T and use T.ID, or use just the column name.

declare @TEMP table (ID int, Name varchar(max))
insert into @temp SELECT ID, Name FROM Table

SELECT * FROM @TEMP 
WHERE ID  = 1 

How to center a "position: absolute" element

Your images are not centered because your list items are not centered; only their text is centered. You can achieve the positioning you want by either centering the entire list or centering the images within the list.

A revised version of your code can be found at the bottom. In my revision I center both the list and the images within it.

The truth is you cannot center an element that has a position set to absolute.

But this behavior can be imitated!

Note: These instructions will work with any DOM block element, not just img.

  1. Surround your image with a div or other tag (in your case a li).

    <div class="absolute-div">
      <img alt="my-image" src="#">
    </div>
    

    Note: The names given to these elements are not special.

  2. Alter your css or scss to give the div absolute positioning and your image centered.

    .absolute-div {
      position: absolute;
    
      width: 100%; 
      // Range to be centered over. 
    
      // If this element's parent is the body then 100% = the window's width
    
      // Note: You can apply additional top/bottom and left/right attributes
      // i.e. - top: 200px; left: 200px;
    
      // Test for desired positioning.
    }
    
    .absolute-div img {
      width: 500px;
      // Note: Setting a width is crucial for margin: auto to work.
    
      margin: 0 auto;
    }
    

And there you have it! Your img should be centered!

Your code:

Try this out:

_x000D_
_x000D_
body_x000D_
{_x000D_
  text-align : center;_x000D_
}_x000D_
_x000D_
#slideshow_x000D_
{_x000D_
  list-style : none;_x000D_
  width      : 800px;_x000D_
  // alter to taste_x000D_
_x000D_
  margin     : 50px auto 0;_x000D_
}_x000D_
_x000D_
#slideshow li_x000D_
{_x000D_
  position : absolute;_x000D_
}_x000D_
_x000D_
#slideshow img_x000D_
{_x000D_
  border  : 1px solid #CCC;_x000D_
  padding : 4px;_x000D_
  height  : 500px;_x000D_
  width   : auto;_x000D_
  // This sets the width relative to your set height._x000D_
_x000D_
  // Setting a width is required for the margin auto attribute below. _x000D_
_x000D_
  margin  : 0 auto;_x000D_
}
_x000D_
<ul id="slideshow">_x000D_
    <li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 1" /></li>_x000D_
    <li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 2" /></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

I hope this was helpful. Good luck!

Specifying width and height as percentages without skewing photo proportions in HTML

width="50%" and height="50%" sets the width and height attributes to half of the parent element's width and height if I'm not mistaken. Also setting just width or height should set the width or height to the percentage of the parent element, if you're using percents.

SQL Server 2000: How to exit a stored procedure?

Unless you specify a severity of 20 or higher, raiserror will not stop execution. See the MSDN documentation.

The normal workaround is to include a return after every raiserror:

if @whoops = 1
    begin
    raiserror('Whoops!', 18, 1)
    return -1
    end

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

You have to bind your event handlers to correct context (this):

onChange={this.setAuthorState.bind(this)}

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this:

Dim ws As Worksheet

Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

Alternately:

With Sheets("SheetName")
    Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so:

ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

or

With Sheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Angular2 - Radio Button Binding

My manual workaround, which involves manually updating model.options when a new radio button is selected:

template: `
  <label *ngFor="let item of radioItems">
    <input type="radio" name="options" (click)="model.options = item" 
     [checked]="item === model.options">
    {{item}}
  </label>`

class App {
  radioItems = 'one two three'.split(' ');
  model      = { options: 'two' };
}

This Plunker demonstrates the above, as well as how to use a button to change the selected radio button -- i.e., to prove that the data binding is two-way:

<button (click)="model.options = 'one'">set one</button>

Application Crashes With "Internal Error In The .NET Runtime"

In my case the problem was a C++/CLI library in which there was a call to the NtQuerySystemInformation; for some kind of reason sometimes (and under mysterious circumstances), when it was called the CLR heap got corrupted and the application crashed.

I've resolved the problem using a "custom heap" created with HeapCreate and allocating there the buffers used by that function.

Finding all the subsets of a set

Here is a working code which I wrote some time ago

// Return all subsets of a given set
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<string>
#include<sstream>
#include<cstring>
#include<climits>
#include<cmath>
#include<iterator>
#include<set>
#include<map>
#include<stack>
#include<queue>
using namespace std;


typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector< vector<int> > vvi;
typedef vector<string> vs;

vvi get_subsets(vi v, int size)
{
    if(size==0) return vvi(1);
    vvi subsets = get_subsets(v,size-1);

    vvi more_subsets(subsets);

    for(typeof(more_subsets.begin()) it = more_subsets.begin(); it !=more_subsets.end(); it++)
    {
        (*it).push_back(v[size-1]);
    }

    subsets.insert(subsets.end(), (more_subsets).begin(), (more_subsets).end());
    return subsets;
}

int main()
{
    int ar[] = {1,2,3};
    vi v(ar , ar+int(sizeof(ar)/sizeof(ar[0])));
    vvi subsets = get_subsets(v,int((v).size()));


    for(typeof(subsets.begin()) it = subsets.begin(); it !=subsets.end(); it++)
    {
        printf("{ ");

        for(typeof((*it).begin()) it2 = (*it).begin(); it2 !=(*it).end(); it2++)
        {
            printf("%d,",*it2 );
        }
        printf(" }\n");
    }
    printf("Total subsets = %d\n",int((subsets).size()) );
}

How to insert default values in SQL table?

Best practice it to list your columns so you're independent of table changes (new column or column order etc)

insert into table1 (field1, field3)  values (5,10)

However, if you don't want to do this, use the DEFAULT keyword

insert into table1 values (5, DEFAULT, 10, DEFAULT)

Keyboard shortcuts with jQuery

After studying some jQuery at Codeacademy I found a solution to bind a key with the animate property. The whole idea was to animate without scrolling to jump from one section to another. The example from Codeacademy was to move Mario through the DOM but I applied this for my website sections (CSS with 100% height). Here is a part of the code:

$(document).keydown(function(key) {
    switch(parseInt(key.which, 10)) {
        case 39:
            $('section').animate({top: "-=100%"}, 2000);
            break;
        case 37:
            $('section').animate({top: "+=100%"}, 2000);
            break;
        default:
            break;
    }
});

I think you could use this for any letter and property.

Source: http://www.codecademy.com/forum_questions/50e85b2714bd580ab300527e

What are named pipes?

Inter-process communication (mostly) for Windows Applications. Similar to using sockets to communicate between applications in Unix.

MSDN

Getting URL hash location, and using it in jQuery

I'm using this to address the security implications noted in @CMS's answer.

// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});

What's the difference between "super()" and "super(props)" in React when using es6 classes?

Here we won't get this in the constructor so it will return undefined, but we will be able to fetch this outside the constructor function

class MyComponent extends React.Component {
  constructor() {
    console.log(this); // Reference Error i.e return undefined
  }

  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

If we are using super(), then we can fetch the "this" variable inside the constructor as well

class MyComponent extends React.Component {
  constructor() {
    super();
    console.log(this); // this logged to console
  }

  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

So when we are using super(); we will be able to fetch this but this.props will be undefined in the constructor. But other than constructor, this.props will not return undefined.

If we use super(props), then we can use this.props value inside the constructor as well

Sophie Alpert's Answer

If you want to use this.props in the constructor, you need to pass props to super. Otherwise, it doesn’t matter because React sets .props on the instance from the outside immediately after calling the constructor.

C++ sorting and keeping track of indexes

There are many ways. A rather simple solution is to use a 2D vector.

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
 vector<vector<double>> val_and_id;
 val_and_id.resize(5);
 for (int i = 0; i < 5; i++) {
   val_and_id[i].resize(2); // one to store value, the other for index.
 }
 // Store value in dimension 1, and index in the other:
 // say values are 5,4,7,1,3.
 val_and_id[0][0] = 5.0;
 val_and_id[1][0] = 4.0;
 val_and_id[2][0] = 7.0;
 val_and_id[3][0] = 1.0;
 val_and_id[4][0] = 3.0;

 val_and_id[0][1] = 0.0;
 val_and_id[1][1] = 1.0;
 val_and_id[2][1] = 2.0;
 val_and_id[3][1] = 3.0;
 val_and_id[4][1] = 4.0;

 sort(val_and_id.begin(), val_and_id.end());
 // display them:
 cout << "Index \t" << "Value \n";
 for (int i = 0; i < 5; i++) {
  cout << val_and_id[i][1] << "\t" << val_and_id[i][0] << "\n";
 }
 return 0;
}

Here is the output:

   Index   Value
   3       1
   4       3
   1       4
   0       5
   2       7

Storing a Key Value Array into a compact JSON string

For use key/value pair in json use an object and don't use array

Find name/value in array is hard but in object is easy

Ex:

_x000D_
_x000D_
var exObj = {_x000D_
  "mainData": {_x000D_
    "slide0001.html": "Looking Ahead",_x000D_
    "slide0008.html": "Forecast",_x000D_
    "slide0021.html": "Summary",_x000D_
    // another THOUSANDS KEY VALUE PAIRS_x000D_
    // ..._x000D_
  },_x000D_
  "otherdata" : { "one": "1", "two": "2", "three": "3" }_x000D_
};_x000D_
var mainData = exObj.mainData;_x000D_
// for use:_x000D_
Object.keys(mainData).forEach(function(n,i){_x000D_
  var v = mainData[n];_x000D_
  console.log('name' + i + ': ' + n + ', value' + i + ': ' + v);_x000D_
});_x000D_
_x000D_
// and string length is minimum_x000D_
console.log(JSON.stringify(exObj));_x000D_
console.log(JSON.stringify(exObj).length);
_x000D_
_x000D_
_x000D_

Notepad++ Multi editing

You can add/edit content on multiple lines by using control button. This is multi edit feature in Notepad++, we need to enable it from settings. Press and hold control, select places where you want to enter text, release control and start typing, this will update the text at all the places selected previously.

enter image description here

Ref: http://notepad-plus-plus.org/features/multi-editing.html

Most efficient way to create a zero filled JavaScript array?

The fastest way to do that is with forEach =)

(we keep backward compatibility for IE < 9)

var fillArray = Array.prototype.forEach
    ? function(arr, n) {
         arr.forEach(function(_, index) { arr[index] = n; });
         return arr;
      }
    : function(arr, n) {
         var len = arr.length;
         arr.length = 0;
         while(len--) arr.push(n);
         return arr;
      };

// test
fillArray([1,2,3], 'X'); // => ['X', 'X', 'X']

Is it possible to have placeholders in strings.xml for runtime values?

Was looking for the same and finally found the following very simple solution. Best: it works out of the box.
1. alter your string ressource:

<string name="welcome_messages">Hello, <xliff:g name="name">%s</xliff:g>! You have 
<xliff:g name="count">%d</xliff:g> new messages.</string>

2. use string substitution:

c.getString(R.string.welcome_messages,name,count);

where c is the Context, name is a string variable and count your int variable

You'll need to include

<resources xmlns:xliff="http://schemas.android.com/apk/res-auto">

in your res/strings.xml. Works for me. :)

Convert javascript array to string

You can use .toString() to join an array with a comma.

var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c

Or, set the separator with array.join('; '); // result: a; b; c.

How to find Port number of IP address?

Port numbers are defined by convention. HTTP servers generally listen on port 80, ssh servers listen on 22. But there are no requirements that they do.

Is there a unique Android device ID?

Normally, I use device unique id for my apps. But sometime I use IMEI. Both are unique numbers.

to get IMEI (international mobile equipment identifier)

public String getIMEI(Activity activity) {
    TelephonyManager telephonyManager = (TelephonyManager) activity
            .getSystemService(Context.TELEPHONY_SERVICE);
    return telephonyManager.getDeviceId();
}

to get device unique id

public String getDeviceUniqueID(Activity activity){
    String device_unique_id = Secure.getString(activity.getContentResolver(),
            Secure.ANDROID_ID);
    return device_unique_id;
}

disabling spring security in spring boot app

just add

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

How can I insert new line/carriage returns into an element.textContent?

The following code works well (On FireFox, IE and Chrome) :

var display_out = "This is line 1" + "<br>" + "This is line 2";

document.getElementById("demo").innerHTML = display_out;

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Go to Control Panel -> Programs -> Programs and features

    Step 1 - Programs and features

  2. Go to Windows Features and disable Internet Explorer 11

    Step 2 - Windows Features

    Step 3 - Uncheck Internet Explorer 11

  3. Then click on Display installed updates

    Step 4 - Display installed updates

  4. Search for Internet explorer

  5. Right-click on Internet Explorer 11 -> Uninstall

    Step 5 - Uninstall Internet Explorer 11

  6. Do the same with Internet Explorer 10

  7. Restart your computer
  8. Install Internet Explorer 10 here (old broken link)

I think it will be okay.

How to send password using sftp batch file

PSFTP -b path/file_name.sftp user@IP_server -hostkey 1e:52:b1... -pw password

the file content is:

lcd "path_file for send"

cd path_destination

mput file_name_to_send

quit

to have the hostkey run:

psftp  user@IP_SERVER

How to improve Netbeans performance?

We can use the following JVM option to make NetBeans load/run bit faster.

JVM Option: -J-Xverify:none

  • this option tells JVM not to verify byte-code during class loading and avoids preloading unnecessary classes.

How to set:

Edit the file C:\Program Files\NetBeans <version>\etc\netbeans.conf (check your NetBeans installation folder if you installed it in another location)

  • Find the line that says

    netbeans_default_options="..."

  • Add the option -J-Xverify:none to the list of options.

  • Restart NetBeans.

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

PHP String to Float

If you need to handle values that cannot be converted separately, you can use this method:

try {
    $valueToUse = trim($stringThatMightBeNumeric) + 0;
} catch (\Throwable $th) {
    // bail here if you need to
}

allowing only alphabets in text box using java script

From kosare comments, i have create an demo http://jsbin.com/aTUMeMAV/2/

HTML

      <form name="f" onsubmit="return onlyAlphabets()">
         <input type="text" name="nm">
         <div id="notification"></div>
         <input type="submit">
      </form>

javascript

  function onlyAlphabets() {

  var regex = /^[a-zA-Z]*$/;
  if (regex.test(document.f.nm.value)) {

      //document.getElementById("notification").innerHTML = "Watching.. Everything is Alphabet now";
      return true;
  } else {
      document.getElementById("notification").innerHTML = "Alphabets Only";
      return false;
  }


}

How to use fetch in typescript

Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.

That being said, the following works...

 fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then((res: Actor) => {
          // res is now an Actor
      });

I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...

callBack: (response: any) => void

But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...

fetch(`http://swapi.co/api/people/1/`)
  .then(res => res.json())
  .then(res => {
      if (callback) {
        callback(res);    // Client receives the response as desired type.  
      }
  });

So that a client can call it with a callback like...

(response: IApigeeResponse) => {
    // Process response as an IApigeeResponse
}

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

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

For some basic understanding of usercontrols you can try this website

moment.js, how to get day of week number

I think this would work

moment().weekday(); //if today is thursday it will return 4

jQuery `.is(":visible")` not working in Chrome

I added next style on the parent and .is(":visible") worked.

display: inline-block;

Access to the requested object is only available from the local network phpmyadmin

If you see below error message, when try into phpyAdmin:

New XAMPP security concept:
Access to the requested directory is only available from the local network.
This setting can be configured in the file "httpd-xampp.conf".

You can do next (for XAMPP, deployed on the UNIX-system): You can try change configuration for <Directory "/opt/lampp/phpmyadmin">

# vi /opt/lampp/etc/extra/httpd-xampp.conf

and change security settings to

#LoadModule perl_module        modules/mod_perl.so

<Directory "/opt/lampp/phpmyadmin">
    AllowOverride AuthConfig Limit
    Order allow,deny
    Allow from all
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

First - comment pl module, second - change config for node Directory. After it, you should restart httpd daemon

# /opt/lampp/xampp restart

Now you can access http://[server_ip]/phpmyadmin/

Removing carriage return and new-line from the end of a string in c#

I use lots of erasing level

String donen = "lots of stupid whitespaces and new lines and others..."

//Remove multilines
donen = Regex.Replace(donen, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
//remove multi whitespaces
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
donen = regex.Replace(donen, " ");
//remove tabs
char tab = '\u0009';
donen = donen.Replace(tab.ToString(), "");
//remove endoffile newlines
donen = donen.TrimEnd('\r', '\n');
//to be sure erase new lines again from another perspective
donen.Replace(Environment.NewLine, "");

and now we have a clean one row

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

Bluetooth pairing without user confirmation

Yes it is possible in theory as defined by the specification. However there is no practical implementation as yet that would allow this.

Refer: NFC Forum Connection Handover Technical Specification http://www.nfc-forum.org/specs/spec_list/

Quoting from the specification regarding the security - "The Handover Protocol requires transmission of network access data and credentials (the carrier configuration data) to allow one device to connect to a wireless network provided by another device. Because of the close proximity needed for communication between NFC Devices and Tags, eavesdropping of carrier configuration data is difficult, but not impossible, without recognition by the legitimate owner of the devices. Transmission of carrier configuration data to devices that can be brought to close proximity is deemed legitimate within the scope of this specification."

Android Open External Storage directory(sdcard) for storing file

Complementing rijul gupta answer:

String strSDCardPath = System.getenv("SECONDARY_STORAGE");

    if ((strSDCardPath == null) || (strSDCardPath.length() == 0)) {
        strSDCardPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
    }

    //If may get a full path that is not the right one, even if we don't have the SD Card there. 
    //We just need the "/mnt/extSdCard/" i.e and check if it's writable
    if(strSDCardPath != null) {
        if (strSDCardPath.contains(":")) {
            strSDCardPath = strSDCardPath.substring(0, strSDCardPath.indexOf(":"));
        }
        File externalFilePath = new File(strSDCardPath);

        if (externalFilePath.exists() && externalFilePath.canWrite()){
            //do what you need here
        }
    }

"unable to locate adb" using Android Studio

Got it to work go to the local.properties file under your build.gradle files to find out the PATH to your SDK, from the SDK location go into the platform-tools folder and look and see if you have adb.exe. If not go to http://adbshell.com/downloads and download ADB KITS. Copy the zip folder's contents into the platform-tools folder and re-make your project.

I didn't need to update the PATH in the Extended Controls Settings section on the emulator, I left Use detected ADB location settings on. Hope this makes this faster for you !

How to find MySQL process list and to kill those processes?

select GROUP_CONCAT(stat SEPARATOR ' ') from (select concat('KILL ',id,';') as stat from information_schema.processlist) as stats;

Then copy and paste the result back into the terminal. Something like:

KILL 2871; KILL 2879; KILL 2874; KILL 2872; KILL 2866;

"FATAL: Module not found error" using modprobe

The best thing is to actually use the kernel makefile to install the module:

Here is are snippets to add to your Makefile

around the top add:

PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root

around the end add:

install:
        $(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
           INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install

and then you can issue

    sudo make install

this will put it either in /lib/modules/$(uname -r)/extra/

or /lib/modules/$(uname -r)/misc/

and run depmod appropriately

CSS Pseudo-classes with inline styles

You could try https://hacss.io:

<a href="http://www.google.com" class=":hover{text-decoration:none;}">Google</a>

Demo

Remove a parameter to the URL with JavaScript

function removeParam(parameter)
{
  var url=document.location.href;
  var urlparts= url.split('?');

 if (urlparts.length>=2)
 {
  var urlBase=urlparts.shift(); 
  var queryString=urlparts.join("?"); 

  var prefix = encodeURIComponent(parameter)+'=';
  var pars = queryString.split(/[&;]/g);
  for (var i= pars.length; i-->0;)               
      if (pars[i].lastIndexOf(prefix, 0)!==-1)   
          pars.splice(i, 1);
  url = urlBase+'?'+pars.join('&');
  window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .

}
return url;
}

This will resolve your problem

How to Validate on Max File Size in Laravel?

Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.

I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up

My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:

in resources/lang/en/validaton.php:

'uploaded' => 'The :attribute failed to upload.',

And this is the message displayed when the file is larger than the limit set by PHP.

I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.

However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.

So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.

Here is what works if the file to smaller than the PHP file size limit:

In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:

This is how I set a custom error message and maximum file size:

I have an input field <input type="file" name="upload">. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
  ...
  ...
  public function rules() {
    return [
      'upload' => 'required|file|max:8192',
    ];
  }
  public function messages()
  {
    return [            
      'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
      'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
    ];
  }
}

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

You get that error because you haven't saved your file, save it for example "holamundo.py" then run it Ctrl + B

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

You need to tell it that you are using SSL:

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

In case you miss anything, here is working code:

String  d_email = "[email protected]",
            d_uname = "Name",
            d_password = "urpassword",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Indoors Readable File: " + params[0].getName(),
            m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
    Properties props = new Properties();
    props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);
    try {
        msg.setSubject(m_subject);
        msg.setFrom(new InternetAddress(d_email));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

Transport transport = session.getTransport("smtps");
            transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

How to do a https request with bad certificate?

Generally, The DNS Domain of the URL MUST match the Certificate Subject of the certificate.

In former times this could be either by setting the domain as cn of the certificate or by having the domain set as a Subject Alternative Name.

Support for cn was deprecated for a long time (since 2000 in RFC 2818) and Chrome browser will not even look at the cn anymore so today you need to have the DNS Domain of the URL as a Subject Alternative Name.

RFC 6125 which forbids checking the cn if SAN for DNS Domain is present, but not if SAN for IP Address is present. RFC 6125 also repeats that cn is deprecated which was already said in RFC 2818. And the Certification Authority Browser Forum to be present which in combination with RFC 6125 essentially means that cn will never be checked for DNS Domain name.

Can I install/update WordPress plugins without providing FTP access?

You can add following in wp-config.php

define('METHOD','direct');

Here is a youtube video that explaining how to do it. https://youtu.be/pq4QRp4427c

How to do case insensitive string comparison?

Remember that casing is a locale specific operation. Depending on scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not. This why I use following function in my utils library (note that type checking is not included for performance reason).

function compareStrings (string1, string2, ignoreCase, useLocale) {
    if (ignoreCase) {
        if (useLocale) {
            string1 = string1.toLocaleLowerCase();
            string2 = string2.toLocaleLowerCase();
        }
        else {
            string1 = string1.toLowerCase();
            string2 = string2.toLowerCase();
        }
    }

    return string1 === string2;
}

Javascript: formatting a rounded number to N decimals

Hopefully working code (didn't do much testing):

function toFixed(value, precision) {
    var precision = precision || 0,
        neg = value < 0,
        power = Math.pow(10, precision),
        value = Math.round(value * power),
        integral = String((neg ? Math.ceil : Math.floor)(value / power)),
        fraction = String((neg ? -value : value) % power),
        padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');

    return precision ? integral + '.' +  padding + fraction : integral;
}

Disable firefox same origin policy

about:config -> security.fileuri.strict_origin_policy -> false

How to remove youtube branding after embedding video in web page?

The only way to remove the YouTube branding (while keeping the video clickable) is to place the embed iFrame inside a container that has overflow set to hidden and has a slightly smaller height than the iFrame.

Of course this means the bottom of your video gets chopped off.

Also, you will be most likely breaching YouTube's Terms of Service.

CSS:

.videoWrapper {
  width: 550px;
  height: 250px;
  overflow: hidden;
}

HTML:

<div class="videoWrapper">
  <iframe width="550" height="314" src="https://www.youtube.com/embed/vidid?modestbranding=1&amp;rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>

How to step through Python code to help debug issues?

Python Tutor is an online single-step debugger meant for novices. You can put in code on the edit page then click "Visualize Execution" to start it running.

Among other things, it supports:

However it also doesn't support a lot of things, for example:

  • Reading/writing files - use io.StringIO and io.BytesIO instead: demo
  • Code that is too large, runs too long, or defines too many variables or objects
  • Command-line arguments
  • Lots of standard library modules like argparse, csv, enum, html, os, struct, weakref...

Add a property to a JavaScript object using a variable as the name?

Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:

this.setState({ [`${name}`]: value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[name]));
    });

PS: Please mind the quote character.

how to evenly distribute elements in a div next to each other?

I have managed to do it with the following css combination:

text-align: justify;
text-align-last: justify;
text-justify: inter-word;

How to validate email id in angularJs using ng-pattern

angularjs controller way, just an example to look for one or more email in the body of a message.

sp = $scope.messagebody; // email message body

if (sp != null && sp.match(/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+/)) {   
console.log('Error. You are not allowed to have an email in the message body');
}

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

I don't know that you are going to find a platform-neutral solution.

This is commonly called an "UPSERT".

See some related discussions:

Fastest way to zero out a 2d array in C?

If array is truly an array, then you can "zero it out" with:

memset(array, 0, sizeof array);

But there are two points you should know:

  • this works only if array is really a "two-d array", i.e., was declared T array[M][N]; for some type T.
  • it works only in the scope where array was declared. If you pass it to a function, then the name array decays to a pointer, and sizeof will not give you the size of the array.

Let's do an experiment:

#include <stdio.h>

void f(int (*arr)[5])
{
    printf("f:    sizeof arr:       %zu\n", sizeof arr);
    printf("f:    sizeof arr[0]:    %zu\n", sizeof arr[0]);
    printf("f:    sizeof arr[0][0]: %zu\n", sizeof arr[0][0]);
}

int main(void)
{
    int arr[10][5];
    printf("main: sizeof arr:       %zu\n", sizeof arr);
    printf("main: sizeof arr[0]:    %zu\n", sizeof arr[0]);
    printf("main: sizeof arr[0][0]: %zu\n\n", sizeof arr[0][0]);
    f(arr);
    return 0;
}

On my machine, the above prints:

main: sizeof arr:       200
main: sizeof arr[0]:    20
main: sizeof arr[0][0]: 4

f:    sizeof arr:       8
f:    sizeof arr[0]:    20
f:    sizeof arr[0][0]: 4

Even though arr is an array, it decays to a pointer to its first element when passed to f(), and therefore the sizes printed in f() are "wrong". Also, in f() the size of arr[0] is the size of the array arr[0], which is an "array [5] of int". It is not the size of an int *, because the "decaying" only happens at the first level, and that is why we need to declare f() as taking a pointer to an array of the correct size.

So, as I said, what you were doing originally will work only if the two conditions above are satisfied. If not, you will need to do what others have said:

memset(array, 0, m*n*sizeof array[0][0]);

Finally, memset() and the for loop you posted are not equivalent in the strict sense. There could be (and have been) compilers where "all bits zero" does not equal zero for certain types, such as pointers and floating-point values. I doubt that you need to worry about that though.

creating an array of structs in c++

Some compilers support compound literals as an extention, allowing this construct:

Customer customerRecords[2];
customerRecords[0] = (Customer){25, "Bob Jones"};
customerRecords[1] = (Customer){26, "Jim Smith"};

But it's rather unportable.

Is there a jQuery unfocus method?

I like the following approach as it works for all situations:

$(':focus').blur();

How to tell PowerShell to wait for each command to end before starting the next?

Just use "Wait-process" :

"notepad","calc","wmplayer" | ForEach-Object {Start-Process $_} | Wait-Process ;dir

job is done

What does the fpermissive flag do?

The -fpermissive flag causes the compiler to report some things that are actually errors (but are permitted by some compilers) as warnings, to permit code to compile even if it doesn't conform to the language rules. You really should fix the underlying problem. Post the smallest, compilable code sample that demonstrates the problem.

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Best radio-button implementation for IOS

I've written a controller for handling the logic behind an array of radio buttons. It's open source and on GitHub, check it out!

https://github.com/goosoftware/GSRadioButtonSetController

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

Here are a couple links for reference.

Oracle "(+)" Operator

The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.

select * from emp, dept where emp.dept_id=dept.dept_id(+)

So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!

How to get all values from python enum class?

class enum.Enum is a class that solves all your enumeration needs, so you just need to inherit from it, and add your own fields. Then from then on, all you need to do is to just call it's attributes: name & value:

from enum import Enum

class Letter(Enum):
   A = 1
   B = 2
   C = 3

print({i.name: i.value for i in Letter})
# prints {'A': 1, 'B': 2, 'C': 3}

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

for each project in your solution make sure that

Properties > Config. Properties > General > Platform Toolset

is one for all of them, v100 for visual studio 2010, v110 for visual studio 2012

you also may be working on v100 from visual studio 2012

find . -type f -exec chmod 644 {} ;

A good alternative is this:

find . -type f | xargs chmod -v 644

and for directories:

find . -type d | xargs chmod -v 755

and to be more explicit:

find . -type f | xargs -I{} chmod -v 644 {}

How to convert a Bitmap to Drawable in android?

Try this it converts a Bitmap type image to Drawable

Drawable d = new BitmapDrawable(getResources(), bitmap);

updating Google play services in Emulator

Running the app on a virtual device with system image, 'Google Play API' instead of 'Google API' will solve your issue smoothly..

  • Virtual devices Nexus 5x and Nexus 5 supports 'Google Play API' image.

  • Google Play API comes with Nougat 7.1.1 and O 8.0.

Just follow the below simple steps and make sure your pc is connected to internet.

  1. Create a new virtual device by selecting Create Virtual Device(left-bottom corner) from Android Virtual Devices Manager.

  2. Select the Hardware 'Nexus 5x' or 'Nexus 5'.

  3. Download the system image 'Nougat' with Google Play or 'O' with Google Play. 'O' is the latest Android 8.0 version.

  4. Click on Next and Finish.

  5. Run your app again on the new virtual device and click on the 'Upgrade now ' option that shows along with the warning message.

  6. You will be directed to the Play Store and you can update your Google Play services easily.

See your app runs smoothly!

  • Note: If you plan to use APIs from Google Play services, you must use the Google APIs System Image.

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

If the new data could be an array or a scalar, and you want to prevent the new data to be nested if it was an array, the splat operator is awesome! It returns a scalar for a scalar, and an unpacked list of arguments for an array.

1.9.3-p551 :020 > a = [1, 2]
 => [1, 2] 
1.9.3-p551 :021 > b = [3, 4]
 => [3, 4] 
1.9.3-p551 :022 > c = 5
 => 5 
1.9.3-p551 :023 > a.object_id
 => 6617020 
1.9.3-p551 :024 > a.push *b
 => [1, 2, 3, 4] 
1.9.3-p551 :025 > a.object_id
 => 6617020 
1.9.3-p551 :026 > a.push *c
 => [1, 2, 3, 4, 5] 
1.9.3-p551 :027 > a.object_id
 => 6617020 

java collections - keyset() vs entrySet() in map

Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.

Iterator<String> itr2 = keys.iterator();
    while(itr2.hasNext()){
        String v = itr2.next();
        System.out.println("Key: "+v+" ,value: "+m.get(v));
    }

Create a Cumulative Sum Column in MySQL

Using a correlated query:


  SELECT t.id,
         t.count,
         (SELECT SUM(x.count)
            FROM TABLE x
           WHERE x.id <= t.id) AS cumulative_sum
    FROM TABLE t
ORDER BY t.id

Using MySQL variables:


  SELECT t.id,
         t.count,
         @running_total := @running_total + t.count AS cumulative_sum
    FROM TABLE t
    JOIN (SELECT @running_total := 0) r
ORDER BY t.id

Note:

  • The JOIN (SELECT @running_total := 0) r is a cross join, and allows for variable declaration without requiring a separate SET command.
  • The table alias, r, is required by MySQL for any subquery/derived table/inline view

Caveats:

  • MySQL specific; not portable to other databases
  • The ORDER BY is important; it ensures the order matches the OP and can have larger implications for more complicated variable usage (IE: psuedo ROW_NUMBER/RANK functionality, which MySQL lacks)

CSS: image link, change on hover

You could do the following, without needing CSS...

<a href="ENTER_DESTINATION_URL"><img src="URL_OF_FIRST_IMAGE_SOURCE" onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" /></a>

Example: https://jsfiddle.net/jord8on/k1zsfqyk/

This solution was PERFECT for my needs! I found this solution here.

Disclaimer: Having a solution that is possible without CSS is important to me because I design content on the Jive-x cloud community platform which does not give us access to global CSS.

Pandas read_csv from url

To Import Data through URL in pandas just apply the simple below code it works actually better.

import pandas as pd
train = pd.read_table("https://urlandfile.com/dataset.csv")
train.head()

If you are having issues with a raw data then just put 'r' before URL

import pandas as pd
train = pd.read_table(r"https://urlandfile.com/dataset.csv")
train.head()

How to migrate GIT repository from one server to a new one

follow these instructions If you want to keep all the commits and branches from old to new repo

git clone --bare <old-repo-url>
cd <old-repo-directory>
git push --mirror <new-repo-url>

Generate preview image from Video file?

Two ways come to mind:

  • Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that

  • Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.

Write to CSV file and export it?

Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.

https://github.com/jitbit/CsvExport

It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs file to your project and you're good to go.

(disclaimer: I'm one of the contributors)

Save file/open file dialog box, using Swing & Netbeans GUI editor

I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileChooserEx {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new FileChooserEx().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JButton saveBtn = new JButton("Save");
        JButton openBtn = new JButton("Open");

        saveBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveFile = new JFileChooser();
                saveFile.showSaveDialog(null);
            }
        });

        openBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser openFile = new JFileChooser();
                openFile.showOpenDialog(null);
            }
        });

        frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
        frame.add(saveBtn, BorderLayout.CENTER);
        frame.add(openBtn, BorderLayout.SOUTH);
        frame.setTitle("File Chooser");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

How to create query parameters in Javascript?

If you are using Prototype there is Form.serialize

If you are using jQuery there is Ajax/serialize

I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.

How to call a function within class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...

How to see PL/SQL Stored Function body in Oracle

If is a package then you can get the source for that with:

    select text from all_source where name = 'PADCAMPAIGN' 
    and type = 'PACKAGE BODY'
    order by line;

Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.

Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use

    select text from all_source where name = 'pAdCampaign' 
    and type = 'PACKAGE BODY'
    order by line;

Select a Column in SQL not in Group By

What you are asking, Sir, is as the answer of RedFilter. This answer as well helps in understanding why group by is somehow a simpler version or partition over: SQL Server: Difference between PARTITION BY and GROUP BY since it changes the way the returned value is calculated and therefore you could (somehow) return columns group by can not return.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

I think that the issue is that the file is on your local computer, and IE is denying access because if it let scripts have access to files on the comp that the browser is running on, that would be a HUGE security hole.
If you have access to a server or another comp that you could use as one, maybe you could try putting the files on the that, and then running the scripts as you would from a website.

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

Is it possible to use 'else' in a list comprehension?

Also, would I be right in concluding that a list comprehension is the most efficient way to do this?

Maybe. List comprehensions are not inherently computationally efficient. It is still running in linear time.

From my personal experience: I have significantly reduced computation time when dealing with large data sets by replacing list comprehensions (specifically nested ones) with for-loop/list-appending type structures you have above. In this application I doubt you will notice a difference.

Font Awesome & Unicode

You can also use the FontAwesome icon with the CSS3 pseudo selector as shown below. enter image description here

Ensure to set the font-family to FontAwesome as shown below:

table.dataTable thead th.sorting:after {font-family: FontAwesome;}

To get the above working, you must do the following:

  1. Download the FontAwesome css library here FontAwesome v4.7.0
  2. Extract from the zip file and include into your app root folder, the two folders as shown below: enter image description here
  3. Reference only the css folder in the <head></head> section of your app as shown below: enter image description here

Check if table exists

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

How to create a user in Django?

If you creat user normally, you will not be able to login as password creation method may b different You can use default signup form for that

from django.contrib.auth.forms import UserCreationForm

You can extend that also

from django.contrib.auth.forms import UserCreationForm

class UserForm(UserCreationForm):
    mobile = forms.CharField(max_length=15, min_length=10)
    email = forms.EmailField(required=True)
    class Meta:
        model = User
        fields = ['username', 'password', 'first_name', 'last_name', 'email', 'mobile' ]

Then in view use this class

class UserCreate(CreateView):
    form_class = UserForm
    template_name = 'registration/signup.html'
    success_url = reverse_lazy('list')

    def form_valid(self, form):
        user = form.save()

Parsing JSON giving "unexpected token o" error

Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.

var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);

How to sum a list of integers with java streams?

I suggest 2 more options:

integers.values().stream().mapToInt(Integer::intValue).sum();
integers.values().stream().collect(Collectors.summingInt(Integer::intValue));

The second one uses Collectors.summingInt() collector, there is also a summingLong() collector which you would use with mapToLong.


And a third option: Java 8 introduces a very effective LongAdder accumulator designed to speed-up summarizing in parallel streams and multi-thread environments. Here, here's an example use:

LongAdder a = new LongAdder();
map.values().parallelStream().forEach(a::add);
sum = a.intValue();

How to redirect in a servlet filter?

I'm trying to find a method to redirect my request from filter to login page

Don't

You just invoke

chain.doFilter(request, response);

from filter and the normal flow will go ahead.

I don't know how to redirect from servlet

You can use

response.sendRedirect(url);

to redirect from servlet

Python script header

From the manpage for env (GNU coreutils 6.10):

env - run a program in a modified environment

In theory you could use env to reset the environment (removing many of the existing environment variables) or add additional environment variables in the script header. Practically speaking, the two versions you mentioned are identical. (Though others have mentioned a good point: specifying python through env lets you abstractly specify python without knowing its path.)

How to add constraints programmatically using Swift

the following code works for me in this scenario: an UIImageView forced landscape.

    imagePreview!.isUserInteractionEnabled = true
    imagePreview!.isExclusiveTouch = true
    imagePreview!.contentMode = UIView.ContentMode.scaleAspectFit
    
    // Remove all constraints
    imagePreview!.removeAllConstraints()
    
    // Add the new constraints
    let guide = view.safeAreaLayoutGuide
    imagePreview!.translatesAutoresizingMaskIntoConstraints = false
    imagePreview!.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
    imagePreview!.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
    imagePreview!.heightAnchor.constraint(equalTo: guide.heightAnchor, multiplier: 1.0).isActive = true

where removeAllConstraints is an extension

extension UIView {
    
    func removeAllConstraints() {
        var _superview = self.superview
        
        func removeAllConstraintsFromView(view: UIView) { for c in view.constraints { view.removeConstraint(c) } }
        
        while let superview = _superview {
            for constraint in superview.constraints {
                
                if let first = constraint.firstItem as? UIView, first == self {
                    superview.removeConstraint(constraint)
                }
                
                if let second = constraint.secondItem as? UIView, second == self {
                    superview.removeConstraint(constraint)
                }
            }
            
            _superview = superview.superview
        }
        
        self.removeConstraints(self.constraints)
        self.translatesAutoresizingMaskIntoConstraints = true
    }
}

What does "The APR based Apache Tomcat Native library was not found" mean?

I just went through this and configured it with the following:

Ubuntu 16.04

Tomcat 8.5.9

Apache2.4.25

APR 1.5.2

Tomcat-native 1.2.10

Java 8

These are the steps i used based on the older posts here:

Install package

sudo apt-get update
sudo apt-get install libtcnative-1

Verify these packages are installed

sudo apt-get install make 
sudo apt-get install gcc
sudo apt-get install openssl

Install package

sudo apt-get install libssl-dev

Install and compile Apache APR

cd /opt/tomcat/bin
sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
sudo tar -xzvf apr-1.5.2.tar.gz
cd apr-1.5.2
sudo ./configure
sudo make
sudo make install

verify installation

cd /usr/local/apr/lib/
ls 

you should see the compiled file as

libapr-1.la

Download and install Tomcat Native source package

cd /opt/tomcat/bin
sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
cd tomcat-native-1.2.10-src/native

verify JAVA_HOME

sudo pico ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
source ~/.bashrc
sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
sudo make
sudo make install

Edit the /opt/tomcat/bin/setenv.sh file with following line:

sudo pico /opt/tomcat/bin/setenv.sh
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

restart tomcat

sudo service tomcat restart

Convert a object into JSON in REST service by Spring MVC


The Json conversion should work out-of-the box. In order this to happen you need add some simple configurations:
First add a contentNegotiationManager into your spring config file. It is responsible for negotiating the response type:

<bean id="contentNegotiationManager"
      class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="true" />
    <property name="ignoreAcceptHeader" value="true" />
    <property name="useJaf" value="false" />
     <property name="defaultContentType" value="application/json" />

      <property name="mediaTypes">
         <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
         </map>
      </property>
   </bean>

   <mvc:annotation-driven
      content-negotiation-manager="contentNegotiationManager" />

   <context:annotation-config />

Then add Jackson2 jars (jackson-databind and jackson-core) in the service's class path. Jackson is responsible for the data serialization to JSON. Spring will detect these and initialize the MappingJackson2HttpMessageConverter automatically for you. Having only this configured I have my automatic conversion to JSON working. The described config has an additional benefit of giving you the possibility to serialize to XML if you set accept:application/xml header.

Replace Fragment inside a ViewPager

I followed the answers by @wize and @mdelolmo and I got the solution. Thanks Tons. But, I tuned these solutions a little bit to improve the memory consumption.

Problems I observed:

They save the instance of Fragment which is replaced. In my case, it is a Fragment which holds MapView and I thought its costly. So, I am maintaining the FragmentPagerPositionChanged (POSITION_NONE or POSITION_UNCHANGED) instead of Fragment itself.

Here is my implementation.

  public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {

    private SwitchFragListener mSwitchFragListener;
    private Switch mToggle;
    private int pagerAdapterPosChanged = POSITION_UNCHANGED;
    private static final int TOGGLE_ENABLE_POS = 2;


    public DemoCollectionPagerAdapter(FragmentManager fm, Switch toggle) {
        super(fm);
        mToggle = toggle;

        mSwitchFragListener = new SwitchFragListener();
        mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mSwitchFragListener.onSwitchToNextFragment();
            }
        });
    }

    @Override
    public Fragment getItem(int i) {
        switch (i)
        {
            case TOGGLE_ENABLE_POS:
                if(mToggle.isChecked())
                {
                    return TabReplaceFragment.getInstance();
                }else
                {
                    return DemoTab2Fragment.getInstance(i);
                }

            default:
                return DemoTabFragment.getInstance(i);
        }
    }

    @Override
    public int getCount() {
        return 5;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Tab " + (position + 1);
    }

    @Override
    public int getItemPosition(Object object) {

        //  This check make sures getItem() is called only for the required Fragment
        if (object instanceof TabReplaceFragment
                ||  object instanceof DemoTab2Fragment)
            return pagerAdapterPosChanged;

        return POSITION_UNCHANGED;
    }

    /**
     * Switch fragments Interface implementation
     */
    private final class SwitchFragListener implements
            SwitchFragInterface {

        SwitchFragListener() {}

        public void onSwitchToNextFragment() {

            pagerAdapterPosChanged = POSITION_NONE;
            notifyDataSetChanged();
        }
    }

    /**
     * Interface to switch frags
     */
    private interface SwitchFragInterface{
        void onSwitchToNextFragment();
    }
}

Demo link here.. https://youtu.be/l_62uhKkLyM

For demo purpose, used 2 fragments TabReplaceFragment and DemoTab2Fragment at position two. In all the other cases I'm using DemoTabFragment instances.

Explanation:

I'm passing Switch from Activity to the DemoCollectionPagerAdapter. Based on the state of this switch we will display correct fragment. When the switch check is changed, I'm calling the SwitchFragListener's onSwitchToNextFragment method, where I'm changing the value of pagerAdapterPosChanged variable to POSITION_NONE. Check out more about POSITION_NONE. This will invalidate the getItem and I have logics to instantiate the right fragment over there. Sorry, if the explanation is a bit messy.

Once again big thanks to @wize and @mdelolmo for the original idea.

Hope this is helpful. :)

Let me know if this implementation has any flaws. That will be greatly helpful for my project.

How to link html pages in same or different folders?

For ASP.NET, this worked for me on development and deployment:

<a runat="server" href="~/Subfolder/TargetPage">TargetPage</a>

Using runat="server" and the href="~/" are the keys for going to the root.

How to Count Duplicates in List with LINQ

You can also do Dictionary:

 var list = new List<string> { "a", "b", "a", "c", "a", "b" };
 var result = list.GroupBy(x => x)
            .ToDictionary(y=>y.Key, y=>y.Count())
            .OrderByDescending(z => z.Value);

 foreach (var x in result)
        {
            Console.WriteLine("Value: " + x.Key + " Count: " + x.Value);
        }

Construct a manual legend for a complicated plot

You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.


To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white")) to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL) would set the background to null for the legend, but it did not. Perhaps worth another question.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here


To get rid of the black background in the legend, you need to use the override.aes argument to the guide_legend. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, 
                      guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

Joining two lists together

The two options I use are:

list1.AddRange(list2);

or

list1.Concat(list2);

However I noticed as I used that when using the AddRange method with a recursive function, that calls itself very often I got an SystemOutOfMemoryException because the maximum number of dimensions was reached.

(Message Google Translated)
The array dimensions exceeded the supported range.

Using Concat solved that issue.

How to parse the AndroidManifest.xml file inside an .apk package

it can be helpful

public static int vCodeApk(String path) {
    PackageManager pm = G.context.getPackageManager();
    PackageInfo info = pm.getPackageArchiveInfo(path, 0);
    return info.versionCode;
    //        Toast.makeText(this, "VersionCode : " + info.versionCode + ", VersionName : " + info.versionName, Toast.LENGTH_LONG).show();
}

G is my Application class :

public class G extends Application {

Nginx 403 forbidden for all files

If you still see permission denied after verifying the permissions of the parent folders, it may be SELinux restricting access.

To check if SELinux is running:

# getenforce

To disable SELinux until next reboot:

# setenforce Permissive

Restart Nginx and see if the problem persists. To allow nginx to serve your www directory (make sure you turn SELinux back on before testing this. i.e, setenforce Enforcing)

# chcon -Rt httpd_sys_content_t /path/to/www

See my answer here for more details

How to secure an ASP.NET Web API

Update:

I have added this link to my other answer how to use JWT authentication for ASP.NET Web API here for anyone interested in JWT.


We have managed to apply HMAC authentication to secure Web API, and it worked okay. HMAC authentication uses a secret key for each consumer which both consumer and server both know to hmac hash a message, HMAC256 should be used. Most of the cases, hashed password of the consumer is used as a secret key.

The message normally is built from data in the HTTP request, or even customized data which is added to HTTP header, the message might include:

  1. Timestamp: time that request is sent (UTC or GMT)
  2. HTTP verb: GET, POST, PUT, DELETE.
  3. post data and query string,
  4. URL

Under the hood, HMAC authentication would be:

Consumer sends a HTTP request to web server, after building the signature (output of hmac hash), the template of HTTP request:

User-Agent: {agent}   
Host: {host}   
Timestamp: {timestamp}
Authentication: {username}:{signature}

Example for GET request:

GET /webapi.hmac/api/values

User-Agent: Fiddler    
Host: localhost    
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

The message to hash to get signature:

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n

Example for POST request with query string (signature below is not correct, just an example)

POST /webapi.hmac/api/values?key2=value2

User-Agent: Fiddler    
Host: localhost    
Content-Type: application/x-www-form-urlencoded
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

key1=value1&key3=value3

The message to hash to get signature

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n
key1=value1&key2=value2&key3=value3

Please note that form data and query string should be in order, so the code on the server get query string and form data to build the correct message.

When HTTP request comes to the server, an authentication action filter is implemented to parse the request to get information: HTTP verb, timestamp, uri, form data and query string, then based on these to build signature (use hmac hash) with the secret key (hashed password) on the server.

The secret key is got from the database with the username on the request.

Then server code compares the signature on the request with the signature built; if equal, authentication is passed, otherwise, it failed.

The code to build signature:

private static string ComputeHash(string hashedPassword, string message)
{
    var key = Encoding.UTF8.GetBytes(hashedPassword.ToUpper());
    string hashString;

    using (var hmac = new HMACSHA256(key))
    {
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
        hashString = Convert.ToBase64String(hash);
    }

    return hashString;
}

So, how to prevent replay attack?

Add constraint for the timestamp, something like:

servertime - X minutes|seconds  <= timestamp <= servertime + X minutes|seconds 

(servertime: time of request coming to server)

And, cache the signature of the request in memory (use MemoryCache, should keep in the limit of time). If the next request comes with the same signature with the previous request, it will be rejected.

The demo code is put as here: https://github.com/cuongle/Hmac.WebApi

nullable object must have a value

I got this solution and it is working for me

if (myNewDT.MyDateTime == null)
{
   myNewDT.MyDateTime = DateTime.Now();
}

Counting array elements in Perl

print scalar grep { defined $_ } @a;

Redirect From Action Filter Attribute

I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.

Extend AuthorizeAttribute say CutomAuthorizer override the OnAuthorization and HandleUnauthorizedRequest

Register the CustomAuthorizer in the RegisterGlobalFilters.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

    filters.Add(new CustomAuthorizer());
}

upon identifying the unAuthorized access call HandleUnauthorizedRequestand redirect to the concerned controller action as shown below.


public class CustomAuthorizer : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = IsAuthorized(filterContext); // check authorization
        base.OnAuthorization(filterContext);
        if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
            && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
        {

            HandleUnauthorizedRequest(filterContext);

        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "LogOn" },
                                          { "action", "Unauthorized" }

                                         });

    }
}

C# : Out of Memory exception

I know this is an old question but since none of the answers mentioned the large object heap, this might be of use to others who find this question ...

Any memory allocation in .NET that is over 85,000 bytes comes from the large object heap (LOH) not the normal small object heap. Why does this matter? Because the large object heap is not compacted. Which means that the large object heap gets fragmented and in my experience this inevitably leads to out of memory errors.

In the original question the list has 50,000 items in it. Internally a list uses an array, and assuming 32 bit that requires 50,000 x 4bytes = 200,000 bytes (or double that if 64 bit). So that memory allocation is coming from the large object heap.

So what can you do about it?

If you are using a .net version prior to 4.5.1 then about all you can do about it is to be aware of the problem and try to avoid it. So, in this instance, instead of having a list of vehicles you could have a list of lists of vehicles, provided no list ever had more than about 18,000 elements in it. That can lead to some ugly code, but it is viable work around.

If you are using .net 4.5.1 or later then the behaviour of the garbage collector has changed subtly. If you add the following line where you are about to make large memory allocations:

System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;

it will force the garbage collector to compact the large object heap - next time only.

It might not be the best solution but the following has worked for me:

int tries = 0;
while (tries++ < 2)
{
  try 
  {
    . . some large allocation . .
    return;
  }
  catch (System.OutOfMemoryException)
  {
    System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;
    GC.Collect();
  }
}

of course this only helps if you have the physical (or virtual) memory available.

Javascript require() function giving ReferenceError: require is not defined

Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:

In your BrowserWindow declaration, add the following webPreferences field: i.e, instead of plain mainWindow = new BrowserWindow(), write

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    });

parsing JSONP $http.jsonp() response in angular.js

This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:

var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
    $http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
        $scope.data = data;
    });
});

Then display or manipulate {{ data }} in your Angular template.

Given final block not properly padded

I met this issue due to operation system, simple to different platform about JRE implementation.

new SecureRandom(key.getBytes())

will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);

"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.

How do I add comments to package.json for npm install?

I have a funny hack idea.

Create an npm package name suitably as a comment divider for dependencies and devDependencies block in file package.json, for example x----x----x

{
    "name": "app-name",
    "dependencies": {
        "x----x----x": "this is the first line of a comment",
        "babel-cli": "6.x.x",
        "babel-core": "6.x.x",
        "x----x----x": "this is the second line of a comment",
        "knex": "^0.11.1",
        "mocha": "1.20.1",
        "x----x----x": "*"
    }
}

NOTE: You must add the last comment divider line with a valid version, like * in the block.

JavaScript equivalent of PHP’s die

If you're using nodejs, you can use

process.exit(<code>);

Want to download a Git repository, what do I need (windows machine)?

Install mysysgit. (Same as Greg Hewgill's answer.)

Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)

After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.

This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)

Close Window from ViewModel

You can pass the window to your ViewModel using the CommandParameter. See my Example below.

I've implemented an CloseWindow Method which takes a Windows as parameter and closes it. The window is passed to the ViewModel via CommandParameter. Note that you need to define an x:Name for the window which should be close. In my XAML Window i call this method via Command and pass the window itself as a parameter to the ViewModel using CommandParameter.

Command="{Binding CloseWindowCommand, Mode=OneWay}" 
CommandParameter="{Binding ElementName=TestWindow}"

ViewModel

public RelayCommand<Window> CloseWindowCommand { get; private set; }

public MainViewModel()
{
    this.CloseWindowCommand = new RelayCommand<Window>(this.CloseWindow);
}

private void CloseWindow(Window window)
{
    if (window != null)
    {
       window.Close();
    }
}

View

<Window x:Class="ClientLibTestTool.ErrorView"
        x:Name="TestWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:localization="clr-namespace:ClientLibTestTool.ViewLanguages"
        DataContext="{Binding Main, Source={StaticResource Locator}}"
        Title="{x:Static localization:localization.HeaderErrorView}"
        Height="600" Width="800"
        ResizeMode="NoResize"
        WindowStartupLocation="CenterScreen">
    <Grid> 
        <Button Content="{x:Static localization:localization.ButtonClose}" 
                Height="30" 
                Width="100" 
                Margin="0,0,10,10" 
                IsCancel="True" 
                VerticalAlignment="Bottom" 
                HorizontalAlignment="Right" 
                Command="{Binding CloseWindowCommand, Mode=OneWay}" 
                CommandParameter="{Binding ElementName=TestWindow}"/>
    </Grid>
</Window>

Note that i'm using the MVVM light framework, but the principal applies to every wpf application.

This solution violates of the MVVM pattern, because the view-model shouldn't know anything about the UI Implementation. If you want to strictly follow the MVVM programming paradigm you have to abstract the type of the view with an interface.

MVVM conform solution (Former EDIT2)

the user Crono mentions a valid point in the comment section:

Passing the Window object to the view model breaks the MVVM pattern IMHO, because it forces your vm to know what it's being viewed in.

You can fix this by introducing an interface containing a close method.

Interface:

public interface ICloseable
{
    void Close();
}

Your refactored ViewModel will look like this:

ViewModel

public RelayCommand<ICloseable> CloseWindowCommand { get; private set; }

public MainViewModel()
{
    this.CloseWindowCommand = new RelayCommand<IClosable>(this.CloseWindow);
}

private void CloseWindow(ICloseable window)
{
    if (window != null)
    {
        window.Close();
    }
}

You have to reference and implement the ICloseable interface in your view

View (Code behind)

public partial class MainWindow : Window, ICloseable
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

Answer to the original question: (former EDIT1)

Your Login Button (Added CommandParameter):

<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding ShowLoginCommand}" CommandParameter="{Binding ElementName=LoginWindow}"/>

Your code:

 public RelayCommand<Window> CloseWindowCommand { get; private set; } // the <Window> is important for your solution!

 public MainViewModel() 
 {
     //initialize the CloseWindowCommand. Again, mind the <Window>
     //you don't have to do this in your constructor but it is good practice, thought
     this.CloseWindowCommand = new RelayCommand<Window>(this.CloseWindow);
 }

 public bool CheckLogin(Window loginWindow) //Added loginWindow Parameter
 {
    var user = context.Users.Where(i => i.Username == this.Username).SingleOrDefault();

    if (user == null)
    {
        MessageBox.Show("Unable to Login, incorrect credentials.");
        return false;
    }
    else if (this.Username == user.Username || this.Password.ToString() == user.Password)
    {
        MessageBox.Show("Welcome "+ user.Username + ", you have successfully logged in.");
        this.CloseWindow(loginWindow); //Added call to CloseWindow Method
        return true;
    }
    else
    {
        MessageBox.Show("Unable to Login, incorrect credentials.");
        return false;
    }
 }

 //Added CloseWindow Method
 private void CloseWindow(Window window)
 {
     if (window != null)
     {
         window.Close();
     }
 }

How do I include a Perl module that's in a different directory?

Most likely the reason your push did not work is order of execution.

use is a compile time directive. You push is done at execution time:

push ( @INC,"directory_path/more_path");
use Foo.pm;  # In directory path/more_path

You can use a BEGIN block to get around this problem:

BEGIN {
    push ( @INC,"directory_path/more_path");
}
use Foo.pm;  # In directory path/more_path

IMO, it's clearest, and therefore best to use lib:

use lib "directory_path/more_path";
use Foo.pm;  # In directory path/more_path

See perlmod for information about BEGIN and other special blocks and when they execute.

Edit

For loading code relative to your script/library, I strongly endorse File::FindLib

You can say use File::FindLib 'my/test/libs'; to look for a library directory anywhere above your script in the path.

Say your work is structured like this:

   /home/me/projects/
    |- shared/
    |   |- bin/
    |   `- lib/
    `- ossum-thing/
       `- scripts 
           |- bin/
           `- lib/

Inside a script in ossum-thing/scripts/bin:

use File::FindLib 'lib/';
use File::FindLib 'shared/lib/';

Will find your library directories and add them to your @INC.

It's also useful to create a module that contains all the environment set-up needed to run your suite of tools and just load it in all the executables in your project.

use File::FindLib 'lib/MyEnvironment.pm'

C programming: Dereferencing pointer to incomplete type error

How did you actually define the structure? If

struct {
  char name[32];
  int  size;
  int  start;
  int  popularity;
} stasher_file;

is to be taken as type definition, it's missing a typedef. When written as above, you actually define a variable called stasher_file, whose type is some anonymous struct type.

Try

typedef struct { ... } stasher_file;

(or, as already mentioned by others):

struct stasher_file { ... };

The latter actually matches your use of the type. The first form would require that you remove the struct before variable declarations.

What is the definition of "interface" in object oriented programming

In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.

In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).

As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.

XML Schema How to Restrict Attribute by Enumeration

The numerical value seems to be missing from your price definition. Try the following:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />
  </xs:restriction>
</xs:simpleType>



<xs:element name="price">
        <xs:complexType>
            <xs:extension base="xs:decimal">
              <xs:attribute name="currency" type="curr"/>
            </xs:extension>
        </xs:complexType>
</xs:element>

Why does flexbox stretch my image rather than retaining aspect ratio?

The key attribute is align-self: center:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>Without align-self:</p>_x000D_
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
    <p>With align-self:</p>_x000D_
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Switch tabs using Selenium WebDriver with Java

Since the driver.window_handles is not in order , a better solution is this.

first switch to the first tab using the shortcut Control + X to switch to the 'x' th tab in the browser window .

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "1");
# goes to 1st tab

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "4");
# goes to 4th tab if its exists or goes to last tab.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

if multiple myslq running on same port no enter image description here

Right click on wamp and test port 3306 if its wampmysqld64 its correct else change port no and restart server

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

How do I get a UTC Timestamp in JavaScript?

I want to make clear that new Date().getTime() does in fact return a UTC value, so it is a really helpful way to store and manage dates in a way that is agnostic to localized times.

In other words, don't bother with all the UTC javascript functions. Instead, just use Date.getTime().

More info on the explanation is here: If javascript "(new Date()).getTime()" is run from 2 different Timezones.

Java Multiple Inheritance

As you will already be aware, multiple inheritance of classes in Java is not possible, but it's possible with interfaces. You may also want to consider using the composition design pattern.

I wrote a very comprehensive article on composition a few years ago...

https://codereview.stackexchange.com/questions/14542/multiple-inheritance-and-composition-with-java-and-c-updated

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

First off, if you're starting a new project, go with Entity Framework ("EF") - it now generates much better SQL (more like Linq to SQL does) and is easier to maintain and more powerful than Linq to SQL ("L2S"). As of the release of .NET 4.0, I consider Linq to SQL to be an obsolete technology. MS has been very open about not continuing L2S development further.

1) Performance

This is tricky to answer. For most single-entity operations (CRUD) you will find just about equivalent performance with all three technologies. You do have to know how EF and Linq to SQL work in order to use them to their fullest. For high-volume operations like polling queries, you may want to have EF/L2S "compile" your entity query such that the framework doesn't have to constantly regenerate the SQL, or you can run into scalability issues. (see edits)

For bulk updates where you're updating massive amounts of data, raw SQL or a stored procedure will always perform better than an ORM solution because you don't have to marshal the data over the wire to the ORM to perform updates.

2) Speed of Development

In most scenarios, EF will blow away naked SQL/stored procs when it comes to speed of development. The EF designer can update your model from your database as it changes (upon request), so you don't run into synchronization issues between your object code and your database code. The only time I would not consider using an ORM is when you're doing a reporting/dashboard type application where you aren't doing any updating, or when you're creating an application just to do raw data maintenance operations on a database.

3) Neat/Maintainable code

Hands down, EF beats SQL/sprocs. Because your relationships are modeled, joins in your code are relatively infrequent. The relationships of the entities are almost self-evident to the reader for most queries. Nothing is worse than having to go from tier to tier debugging or through multiple SQL/middle tier in order to understand what's actually happening to your data. EF brings your data model into your code in a very powerful way.

4) Flexibility

Stored procs and raw SQL are more "flexible". You can leverage sprocs and SQL to generate faster queries for the odd specific case, and you can leverage native DB functionality easier than you can with and ORM.

5) Overall

Don't get caught up in the false dichotomy of choosing an ORM vs using stored procedures. You can use both in the same application, and you probably should. Big bulk operations should go in stored procedures or SQL (which can actually be called by the EF), and EF should be used for your CRUD operations and most of your middle-tier's needs. Perhaps you'd choose to use SQL for writing your reports. I guess the moral of the story is the same as it's always been. Use the right tool for the job. But the skinny of it is, EF is very good nowadays (as of .NET 4.0). Spend some real time reading and understanding it in depth and you can create some amazing, high-performance apps with ease.

EDIT: EF 5 simplifies this part a bit with auto-compiled LINQ Queries, but for real high volume stuff, you'll definitely need to test and analyze what fits best for you in the real world.

How to check object is nil or not in swift?

The case of if abc == nil is used when you are declaring a var and want to force unwrap and then check for null. Here you know this can be nil and you can check if != nil use the NSString functions from foundation.

In case of String? you are not aware what is wrapped at runtime and hence you have to use if-let and perform the check.

You were doing following but without "!". Hope this clears it.

From apple docs look at this:

let assumedString: String! = "An implicitly unwrapped optional string."

You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:

if assumedString != nil {
    println(assumedString)
}
// prints "An implicitly unwrapped optional string."

Reverse a string in Python

Thats my way:

def reverse_string(string):
    character_list = []
    for char in string:
        character_list.append(char)
    reversed_string = ""
    for char in reversed(character_list):
        reversed_string += char
    return reversed_string

MySQL JOIN with LIMIT 1 on joined table

What about this?

SELECT c.id, c.title, (SELECT id from products AS p 
                            WHERE c.id = p.category_id 
                            ORDER BY ... 
                            LIMIT 1)
   FROM categories AS c;

XAMPP - Apache could not start - Attempting to start Apache service

start xampp (as administrator), (1) right click C:\xampp\xampp-control.exe, and run as administrator. (2) unistall service module and then install service module. (3) now try start the apache and mysql.

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

How to build a 'release' APK in Android Studio?

AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle

android {

    signingConfigs {

        release {

            storeFile file('android.keystore')
            storePassword "pwd"
            keyAlias "alias"
            keyPassword "pwd"
        }
    }

    buildTypes {

       release {

           signingConfig signingConfigs.release
       }
    }
}

To actually run your application at emulator or device run gradle installDebug or gradle installRelease.

You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872

How do I use method overloading in Python?

Python does not support method overloading like Java or C++. We may overload the methods, but we can only use the latest defined method.

# First sum method.
# Takes two argument and print their sum
def sum(a, b):
    s = a + b
    print(s)

# Second sum method
# Takes three argument and print their sum
def sum(a, b, c):
    s = a + b + c
    print(s)

# Uncommenting the below line shows an error
# sum(4, 5)

# This line will call the second sum method
sum(4, 5, 5)

We need to provide optional arguments or *args in order to provide a different number of arguments on calling.

Courtesy Python | Method Overloading

Dynamically adding HTML form field using jQuery

You can add any type of HTML with methods like append and appendTo (among others):

jQuery manipulation methods

Example:

$('form#someform').append('<input type="text" name="something" id="something" />');

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Verify if cv2.so did compile, should be placed in: /usr/local/lib/python2.7/site-packages Then export that path like this

export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH

Same as in the answer here

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

I had the opposite problem and finally had to create my own bash shell script for the company to migrate the hundred of repos from Github to Gitlab due to a change in the company policy.
The script use the Gitlab API to remotely create a repo, and push the Github repo into it. There is no README.md file yet, but the sh is well documented.
The same thing can be done opposite way I imagine. Hope this could help.
https://github.com/mahmalsami/migrate-github-gitlab/blob/master/migrate.sh

IntelliJ cannot find any declarations

I too faced this issue. I've tried the solutions mentioned here. The issue seems not with the source folder.

For me the issue occurred when I installed a new version of IntelliJ, was using 2019 version moved to 2020 version. The project got opened in the new version but the declarations were missing.

I fixed this by :

 - File>Project Structure.  
 - Under Project Settings go to Modules. Here you should see the different project folders, for me it was not there. 
 - Click the + button on top and click Import Module.
 - Select the root pom.xml and wait for the indexing to complete.

After the indexing is done all the declarations were working.

UTC Date/Time String to Timezone

General purpose normalisation function to format any timestamp from any timezone to other. Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')

/**
 * Convert Datetime from any given olsonzone to other.
 * @return datetime in user specified format
 */

function datetimeconv($datetime, $from, $to)
{
    try {
        if ($from['localeFormat'] != 'Y-m-d H:i:s') {
            $datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
        }
        $datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
        $datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
        return $datetime->format($to['localeFormat']);
    } catch (\Exception $e) {
        return null;
    }
}

Usage:

$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];

$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];

datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"

Is it possible to program Android to act as physical USB keyboard?

I've modified kernel on Nexus 7 to act like standard HID keyboard and mouse, without losing MTP/ADB/other USB functionality.

You can use usb-gadget-test commandline utility to send keystrokes and mouse movements to your PC. I want to create a remote admin app later, which will send key events and receive video from camera.

Kernel patch, binaries and instructions: https://github.com/pelya/android-keyboard-gadget

Edit: I've published a proper app to Google Play, if your Nexus 7 is rooted you can flash kernel right from the app, and send keypresses with it.