Programs & Examples On #Compositing

Convert RGBA PNG to RGB with PIL

import numpy as np
import PIL

def convert_image(image_file):
    image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
    original_width, original_height = image.size

    np_image = np.array(image)
    new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3)) 
    # create 3D array

    for each_channel in range(3):
        new_image[:,:,each_channel] = np_image[:,:,each_channel]  
        # only copy first 3 channels.

    # flushing
    np_image = []
    return new_image

How to clear the canvas for redrawing

Use clearRect method by passing x,y co-ordinates and height and width of canvas. ClearRect will clear whole canvas as :

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);

c# Image resizing to different size while preserving aspect ratio

public static void resizeImage_n_save(Stream sourcePath, string targetPath, int requiredSize)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            double ratio = 0;

            var newWidth = 0;
            var newHeight = 0;
            double w = Convert.ToInt32(image.Width);
            double h = Convert.ToInt32(image.Height);
            if (w > h)
            {
                ratio = h / w * 100;
                newWidth = requiredSize;
                newHeight = Convert.ToInt32(requiredSize * ratio / 100);
            }
            else
            {
                ratio = w / h * 100;
                newHeight = requiredSize;
                newWidth = Convert.ToInt32(requiredSize * ratio / 100);
            }

            //   var newWidth = (int)(image.Width * scaleFactor);
            // var newHeight = (int)(image.Height * scaleFactor);
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);

            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);

            //var img = FixedSize(image, requiredSize, requiredSize);
            //img.Save(targetPath, image.RawFormat);

        }
    }

How do I position one image on top of another in HTML?

This is a barebones look at what I've done to float one image over another.

_x000D_
_x000D_
img {_x000D_
  position: absolute;_x000D_
  top: 25px;_x000D_
  left: 25px;_x000D_
}_x000D_
.imgA1 {_x000D_
  z-index: 1;_x000D_
}_x000D_
.imgB1 {_x000D_
  z-index: 3;_x000D_
}
_x000D_
<img class="imgA1" src="https://placehold.it/200/333333">_x000D_
<img class="imgB1" src="https://placehold.it/100">
_x000D_
_x000D_
_x000D_

Source

How to check if a string contains text from an array of substrings in JavaScript?

Using underscore.js or lodash.js, you can do the following on an array of strings:

var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];

var filters = ['Bill', 'Sarah'];

contacts = _.filter(contacts, function(contact) {
    return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});

// ['John']

And on a single string:

var contact = 'Billy';
var filters = ['Bill', 'Sarah'];

_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });

// true

Google Maps API warning: NoApiKeys

Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.

BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.

<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>

Get the key here: GoogleApiKey Generation site

How to get domain root url in Laravel 4?

In Laravel 5.1 and later you can use

request()->getHost();

or

request()->getHttpHost();

(the second one will add port if it's not standard one)

how to delete the content of text file without deleting itself

One of the best companion for java is Apache Projects and please do refer to it. For file related operation you can refer to the Commons IO project.

The Below one line code will help us to make the file empty.

FileUtils.write(new File("/your/file/path"), "")

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

Installing tensorflow with anaconda in windows

  • Install Anaconda for Python 3.5 - Can install from here for 64 bit windows

  • Then install TensorFlow from here

(I tried previously with Anaconda for Python 3.6 but failed even after creating Conda env for Python3.5)

Additionally if you want to run a Jupyter Notebook and use TensorFlow in it. Use following steps.

Change to TensorFlow env:

C: > activate tensorflow
(tensorflow) C: > pip install jupyter notebook

Once installed, you can launch Jupyter Notebook and test

(tensorflow) C: > jupyter notebook

Change a Git remote HEAD to point to something besides master

See: http://www.kernel.org/pub/software/scm/git/docs/git-symbolic-ref.html

This sets the default branch in the git repository. You can run this in bare or mirrored repositories.

Usage:

$ git symbolic-ref HEAD refs/heads/<branch name>

Download large file in python with requests

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

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

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

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

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

How do you do a limit query in JPQL or HQL?

My observation is that even you have limit in the HQL (hibernate 3.x), it will be either causing parsing error or just ignored. (if you have order by + desc/asc before limit, it will be ignored, if you don't have desc/asc before limit, it will cause parsing error)

How to find column names for all tables in all databases in SQL Server

Try this:

select 
    o.name,c.name 
    from sys.columns            c
        inner join sys.objects  o on c.object_id=o.object_id
    order by o.name,c.column_id

With resulting column names this would be:

select 
     o.name as [Table], c.name as [Column]
     from sys.columns            c
         inner join sys.objects  o on c.object_id=o.object_id
     --where c.name = 'column you want to find'
     order by o.name,c.name

Or for more detail:

SELECT
    s.name as ColumnName
        ,sh.name+'.'+o.name AS ObjectName
        ,o.type_desc AS ObjectType
        ,CASE
             WHEN t.name IN ('char','varchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length) END+')'
             WHEN t.name IN ('nvarchar','nchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length/2) END+')'
            WHEN t.name IN ('numeric') THEN t.name+'('+CONVERT(varchar(10),s.precision)+','+CONVERT(varchar(10),s.scale)+')'
             ELSE t.name
         END AS DataType

        ,CASE
             WHEN s.is_nullable=1 THEN 'NULL'
            ELSE 'NOT NULL'
        END AS Nullable
        ,CASE
             WHEN ic.column_id IS NULL THEN ''
             ELSE ' identity('+ISNULL(CONVERT(varchar(10),ic.seed_value),'')+','+ISNULL(CONVERT(varchar(10),ic.increment_value),'')+')='+ISNULL(CONVERT(varchar(10),ic.last_value),'null')
         END
        +CASE
             WHEN sc.column_id IS NULL THEN ''
             ELSE ' computed('+ISNULL(sc.definition,'')+')'
         END
        +CASE
             WHEN cc.object_id IS NULL THEN ''
             ELSE ' check('+ISNULL(cc.definition,'')+')'
         END
            AS MiscInfo
    FROM sys.columns                           s
        INNER JOIN sys.types                   t ON s.system_type_id=t.user_type_id and t.is_user_defined=0
        INNER JOIN sys.objects                 o ON s.object_id=o.object_id
        INNER JOIN sys.schemas                sh on o.schema_id=sh.schema_id
        LEFT OUTER JOIN sys.identity_columns  ic ON s.object_id=ic.object_id AND s.column_id=ic.column_id
        LEFT OUTER JOIN sys.computed_columns  sc ON s.object_id=sc.object_id AND s.column_id=sc.column_id
        LEFT OUTER JOIN sys.check_constraints cc ON s.object_id=cc.parent_object_id AND s.column_id=cc.parent_column_id
    ORDER BY sh.name+'.'+o.name,s.column_id

EDIT
Here is a basic example to get all columns in all databases:

DECLARE @SQL varchar(max)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name,c.name,c.column_id
from '+d.name+'.sys.columns            c
    inner join '+d.name+'.sys.objects  o on c.object_id=o.object_id
    INNER JOIN '+d.name+'.sys.schemas  sh on o.schema_id=sh.schema_id
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

EDIT SQL Server 2000 version

DECLARE @SQL varchar(8000)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name,c.name,c.colid
from '+d.name+'..syscolumns            c
    inner join sysobjects  o on c.id=o.id
    INNER JOIN sysusers  sh on o.uid=sh.uid
'
FROM master.dbo.sysdatabases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

EDIT
Based on some comments, here is a version using sp_MSforeachdb:

sp_MSforeachdb 'select 
    ''?'' AS DatabaseName, o.name AS TableName,c.name AS ColumnName
    from sys.columns            c
        inner join ?.sys.objects  o on c.object_id=o.object_id
    --WHERE ''?'' NOT IN (''master'',''msdb'',''tempdb'',''model'')
    order by o.name,c.column_id'

Moving Git repository content to another repository preserving history

As per @Dan-Cohn answer Mirror-push is your friend here. This is my go to for migrating repos:

Mirroring a repository

1.Open Git Bash.

2.Create a bare clone of the repository.

$ git clone --bare https://github.com/exampleuser/old-repository.git

3.Mirror-push to the new repository.

$ cd old-repository.git
$ git push --mirror https://github.com/exampleuser/new-repository.git

4.Remove the temporary local repository you created in step 1.

$ cd ..
$ rm -rf old-repository.git

Reference and Credit: https://help.github.com/en/articles/duplicating-a-repository

How do I get the current date in Cocoa

You can also use:


CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02.0f", currentDate.hour, currentDate.minute, currentDate.second];
CFRelease(currentDate); // Don't forget this! VERY important

I think this has the following advantages:

  1. No direct memory allocation.
  2. Seconds is a double instead of an integer.
  3. No message calls.
  4. Faster.

Checkout subdirectories in Git?

There is no real way to do that in git. And if you won’t be making changes that affect both trees at once as a single work unit, there is no good reason to use a single repository for both. I thought I would miss this Subversion feature, but I found that creating repositories has so little administrative mental overhead (simply due to the fact that repositories are stored right next to their working copy, rather than requiring me to explicitly pick some place outside of the working copy) that I got used to just making lots of small single-purpose repositories.

If you insist (or really need it), though, you could make a git repository with just mytheme and myplugins directories and symlink those from within the WordPress install.


MDCore wrote:

making a commit to, e.g., mytheme will increment the revision number for myplugin

Note that this is not a concern for git, if you do decide to put both directories in a single repository, because git does away entirely with the concept of monotonically increasing revision numbers of any form.

The sole criterion for what things to put together in a single repository in git is whether it constitutes a single unit, ie. in your case whether there are changes where it does not make sense to look at the edits in each directory in isolation. If you have changes where you need to edit files in both directories at once and the edits belong together, they should be one repository. If not, then don’t glom them together.

Git really really wants you to use separate repositories for separate entities.

submodules

Submodules do not address the desire to keep both directories in one repository, because they would actually enforce having a separate repository for each directory, which are then brought together in another repository using submodules. Worse, since the directories inside the WordPress install are not direct subdirectories of the same directory and are also part of a hierarchy with many other files, using the per-directory repositories as submodules in a unified repository would offer no benefit whatsoever, because the unified repository would not reflect any use case/need.

Node.js: How to read a stream into a buffer?

I suggest loganfsmyths method, using an array to hold the data.

var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
  var buf = Buffer.concat(bufs);
}

IN my current working example, i am working with GRIDfs and npm's Jimp.

   var bucket = new GridFSBucket(getDBReference(), { bucketName: 'images' } );
    var dwnldStream = bucket.openDownloadStream(info[0]._id);// original size
  dwnldStream.on('data', function(chunk) {
       data.push(chunk);
    });
  dwnldStream.on('end', function() {
    var buff =Buffer.concat(data);
    console.log("buffer: ", buff);
       jimp.read(buff)
.then(image => {
         console.log("read the image!");
         IMAGE_SIZES.forEach( (size)=>{
         resize(image,size);
         });
});

I did some other research

with a string method but that did not work, per haps because i was reading from an image file, but the array method did work.

const DISCLAIMER = "DONT DO THIS";
var data = "";
stdout.on('data', function(d){ 
           bufs+=d; 
         });
stdout.on('end', function(){
          var buf = Buffer.from(bufs);
          //// do work with the buffer here

          });

When i did the string method i got this error from npm jimp

buffer:  <Buffer 00 00 00 00 00>
{ Error: Could not find MIME for Buffer <null>

basically i think the type coersion from binary to string didnt work so well.

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

How to read multiple text files into a single RDD?

You can use a single textFile call to read multiple files. Scala:

sc.textFile(','.join(files)) 

Which passwordchar shows a black dot (•) in a winforms textbox?

Below are some different ways to achieve this. Pick the one suits you

  1. In fonts like 'Tahoma' and 'Times new Roman' this common password character '?' which is called 'Black circle' has a unicode value 0x25CF. Set the PasswordChar property with either the value 0x25CF or copy paste the actual character itself.

  2. If you want to display the Black Circle by default then enable visual styles which should replace the default password character from '*' to '?' by default irrespective of the font.

  3. Another alternative is to use 'Wingdings 2' font on the TextBox and set the password character to 0x97. This should work even if the application is not unicoded. Refer to charMap.exe to get better idea on different fonts and characters supported.

Insert json file into mongodb

Below command worked for me

mongoimport --db test --collection docs --file example2.json

when i removed the extra newline character before Email attribute in each of the documents.

example2.json

{"FirstName": "Bruce", "LastName": "Wayne", "Email": "[email protected]"}
{"FirstName": "Lucius", "LastName": "Fox", "Email": "[email protected]"}
{"FirstName": "Dick", "LastName": "Grayson", "Email": "[email protected]"}

How can I tell if a VARCHAR variable contains a substring?

    IF CHARINDEX('TextToSearch',@TextWhereISearch, 0) > 0 => TEXT EXISTS

    IF PATINDEX('TextToSearch', @TextWhereISearch) > 0 => TEXT EXISTS

    Additionally we can also use LIKE but I usually don't use LIKE.

How to connect android wifi to adhoc wifi?

If you have a Microsoft Virtual WiFi Miniport Adapter as one of the available network adapters, you may do the following:

  • Run Windows Command Processor (cmd) as Administrator
  • Type: netsh wlan set hostednetwork mode=allow ssid=NAME key=PASSWORD
  • Then: netsh wlan start hostednetwork
  • Open "Control Panel\Network and Internet\Network Connections"
  • Right-click on your active network adapter (the one that you use to connect on the internet) and then click Properties
  • Then open Sharing tab
  • Check "Allow other network users to connect..." and select your WiFi Miniport Adapter
  • Once finished, type: netsh wlan stop hostednetwork

That's it!

Source: How to connect android phone to an ad-hoc network without softwares.

Strange Jackson exception being thrown when serializing Hibernate object

Similar to other answers, the problem for me was declaring a many-to-one column to do lazy fetching. Switching to eager fetching fixed the problem. Before:

@ManyToOne(targetEntity = StatusCode.class, fetch = FetchType.LAZY)

After:

@ManyToOne(targetEntity = StatusCode.class, fetch = FetchType.EAGER)

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

How to get the bluetooth devices as a list?

In this code you just need to call this in your button click.

private void list_paired_Devices() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        ArrayList<String> devices = new ArrayList<>();
        for (BluetoothDevice bt : pairedDevices) {
            devices.add(bt.getName() + "\n" + bt.getAddress());
        }
        ArrayAdapter arrayAdapter = new ArrayAdapter(bluetooth.this, android.R.layout.simple_list_item_1, devices);
        emp.setAdapter(arrayAdapter);
    }

Check if selected dropdown value is empty using jQuery

Try this it will work --

if($('#EventStartTimeMin').val() === " ") {

    alert("Please enter start time!");

}

Undefined index error PHP

This is happening because your PHP code is getting executed before the form gets posted.

To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables

       if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
        {
             //process PHP Code
        }
        else
        {
             //do nothing
         }

How to read a file byte by byte in Python and how to print a bytelist as a binary?

Late to the party, but this may help anyone looking for a quick solution:

you can use bin(ord('b')).replace('b', '')bin() it gives you the binary representation with a 'b' after the last bit, you have to remove it. Also ord() gives you the ASCII number to the char or 8-bit/1 Byte coded character.

Cheers

Delete/Reset all entries in Core Data?

you can also find all the entity names, and delete them by name. Its a longer version but works well, that way you dont have to work with persistence store

 - (void)clearCoreData
{
NSError *error;
NSEntityDescription *des = [NSEntityDescription entityForName:@"Any_Entity_Name" inManagedObjectContext:_managedObjectContext];
NSManagedObjectModel *model = [des managedObjectModel];
NSArray *entityNames = [[model entities] valueForKey:@"name"];

for (NSString *entityName in entityNames){

    NSFetchRequest *deleteAll = [NSFetchRequest fetchRequestWithEntityName:entityName];
    NSArray *matches = [self.database.managedObjectContext executeFetchRequest:deleteAll error:&error];

}
    if (matches.count > 0){
        for (id obj in matches){

            [_managedObjectContext deleteObject:obj];
        }
       [self.database.managedObjectContext save:&error];
    }
}

for "Any_Entity_Name" just give any one of your entity's name, we only need to figure out the entity description your entities are within. ValueForKey@"name" will return all the entity names. Finally, dont forget to save.

Run cron job only if it isn't already running

You can also do it as a one-liner directly in your crontab:

* * * * * [ `ps -ef|grep -v grep|grep <command>` -eq 0 ] && <command>

print spaces with String.format()

You need to specify the minimum width of the field.

String.format("%" + numberOfSpaces + "s", ""); 

Why do you want to generate a String of spaces of a certain length.

If you want a column of this length with values then you can do:

String.format("%" + numberOfSpaces + "s", "Hello"); 

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

send checkbox value in PHP form

if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
    //checked
}

UTF-8 byte[] to String

I use this way

String strIn = new String(_bytes, 0, numBytes);

Selecting Values from Oracle Table Variable / Array?

In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.

So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:

CREATE OR REPLACE TYPE array is table of number;
/

Then you can use it as in these two examples within PL/SQL:

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    for i in (select level from dual connect by level < 10) loop
  5      p.extend;
  6      p(p.count) := i.level;
  7    end loop;
  8    for x in (select column_value from table(cast(p as array))) loop
  9       dbms_output.put_line(x.column_value);
 10    end loop;
 11* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    select level bulk collect into p from dual connect by level < 10;
  5    for x in (select column_value from table(cast(p as array))) loop
  6       dbms_output.put_line(x.column_value);
  7    end loop;
  8* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

Additional example based on comments

Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.

CREATE OR REPLACE PACKAGE p_cache AS
  FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/

CREATE OR REPLACE PACKAGE BODY p_cache AS

  cache_array  array;

  FUNCTION get_p_cursor RETURN sys_refcursor IS
    pCursor  sys_refcursor;
  BEGIN
    OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
    RETURN pCursor;
  END get_p_cursor;

  -- Package initialization runs once in each session that references the package
  BEGIN
    SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
  END p_cache;
/

How do I execute a string containing Python code in Python?

Remember that from version 3 exec is a function!
so always use exec(mystring) instead of exec mystring.

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

In TorpedoQuery it look like this

Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);

Different color for each bar in a bar chart; ChartJS

You can generate easily with livegap charts
Select Mulicolors from Bar menu


(source: livegap.com)

** chart library used is chartnew.js modified version of chart.js library
with chartnew.js code will be something like this

var barChartData = {
        labels: ["001", "002", "003", "004", "005", "006", "007"],
        datasets: [
            {
                label: "My First dataset",
                fillColor: ["rgba(0,10,220,0.5)","rgba(220,0,10,0.5)","rgba(220,0,0,0.5)","rgba(120,250,120,0.5)" ],
                strokeColor: "rgba(220,220,220,0.8)", 
                highlightFill: "rgba(220,220,220,0.75)",
                highlightStroke: "rgba(220,220,220,1)",
                data: [20, 59, 80, 81, 56, 55, 40]
            }
        ]
    };

Beginner Python Practice?

Try this site full of Python Practice Problems. It leans towards problems that has already been solved so that you'll have reference solutions.

Go to particular revision

To go to a particular version/commit run following commands. HASH-CODE you can get from git log --oneline -n 10

git reset --hard HASH-CODE

Note - After reset to particular version/commit you can run git pull --rebase, if you want to bring back all the commits which are discarded.

How to change ProgressBar's progress indicator color in Android

You guys are really giving me a headache. What you can do is make your layer-list drawable via xml first (meaning a background as the first layer, a drawable that represents secondary progress as the second layer, and another drawable that represents the primary progress as the last layer), then change the color on the code by doing the following:

public void setPrimaryProgressColor(int colorInstance) {
      if (progressBar.getProgressDrawable() instanceof LayerDrawable) {
        Log.d(mLogTag, "Drawable is a layer drawable");
        LayerDrawable layered = (LayerDrawable) progressBar.getProgressDrawable();
        Drawable circleDrawableExample = layered.getDrawable(<whichever is your index of android.R.id.progress>);
        circleDrawableExample.setColorFilter(colorInstance, PorterDuff.Mode.SRC_IN);
        progressBar.setProgressDrawable(layered);
    } else {
        Log.d(mLogTag, "Fallback in case it's not a LayerDrawable");
        progressBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
    }
}

This method will give you the best flexibility of having the measurement of your original drawable declared on the xml, WITH NO MODIFICATION ON ITS STRUCTURE AFTERWARDS, especially if you need to have the xml file screen folder specific, then just modifying ONLY THE COLOR via the code. No re-instantiating a new ShapeDrawable from scratch whatsoever.

INSERT IF NOT EXISTS ELSE UPDATE?

Have a look at http://sqlite.org/lang_conflict.html.

You want something like:

insert or replace into Book (ID, Name, TypeID, Level, Seen) values
((select ID from Book where Name = "SearchName"), "SearchName", ...);

Note that any field not in the insert list will be set to NULL if the row already exists in the table. This is why there's a subselect for the ID column: In the replacement case the statement would set it to NULL and then a fresh ID would be allocated.

This approach can also be used if you want to leave particular field values alone if the row in the replacement case but set the field to NULL in the insert case.

For example, assuming you want to leave Seen alone:

insert or replace into Book (ID, Name, TypeID, Level, Seen) values (
   (select ID from Book where Name = "SearchName"),
   "SearchName",
    5,
    6,
    (select Seen from Book where Name = "SearchName"));

passing form data to another HTML page

If you have no option to use server-side programming, such as PHP, you could use the query string, or GET parameters.

In the form, add a method="GET" attribute:

<form action="display.html" method="GET">
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>

When they submit this form, the user will be directed to an address which includes the serialNumber value as a parameter. Something like:

http://www.example.com/display.html?serialNumber=XYZ

You should then be able to parse the query string - which will contain the serialNumber parameter value - from JavaScript, using the window.location.search value:

// from display.html
document.getElementById("write").innerHTML = window.location.search; // you will have to parse
                                                                     // the query string to extract the
                                                                     // parameter you need

See also JavaScript query string.


The alternative is to store the values in cookies when the form is submit and read them out of the cookies again once the display.html page loads.

See also How to use JavaScript to fill a form on another page.

Django: Redirect to previous page after login

Django's built-in authentication works the way you want.

Their login pages include a next query string which is the page to return to after login.

Look at http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required

JavaScript or jQuery browser back button click detector

Found this to work well cross browser and mobile back_button_override.js .

(Added a timer for safari 5.0)

// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () { 
    if (typeof history.pushState === "function") { 
        history.pushState("back", null, null);          
        window.onpopstate = function () { 
            history.pushState('back', null, null);              
            if(count == 1){window.location = 'your url';}
         }; 
     }
 }  
setTimeout(function(){count = 1;},200);

Display all items in array using jquery

Original from Sept. 13, 2015:
Quick and easy.

$.each(yourArray, function(index, value){
    $('.element').html( $('.element').html() + '<span>' + value +'</span>')
});

Update Sept 9, 2019: No jQuery is needed to iterate the array.

yourArray.forEach((value) => {
    $(".element").html(`${$(".element").html()}<span>${value}</span>`);
});

/* --- Or without jQuery at all --- */

yourArray.forEach((value) => {
    document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});

grep output to show only matching file

grep -l 

(That's a lowercase L)

How can I get href links from HTML using Python?

This answer is similar to others with requests and BeautifulSoup, but using list comprehension.

Because find_all() is the most popular method in the Beautiful Soup search API, you can use soup("a") as a shortcut of soup.findAll("a") and using list comprehension:

import requests
from bs4 import BeautifulSoup

URL = "http://www.yourwebsite.com"
page = requests.get(URL)
soup = BeautifulSoup(page.content, features='lxml')
# Find links
all_links = [link.get("href") for link in soup("a")]
# Only external links
ext_links = [link.get("href") for link in soup("a") if "http" in link.get("href")]

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#calling-a-tag-is-like-calling-find-all

Python: convert string to byte array

s = "ABCD"
from array import array
a = array("B", s)

If you want hex:

print map(hex, a)

MongoDB "root" user

I noticed a lot of these answers, use this command:

use admin

which switches to the admin database. At least in Mongo v4.0.6, creating a user in the context of the admin database will create a user with "_id" : "admin.administrator":

> use admin
> db.getUsers()
[ ]
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' }  ] })
> db.getUsers()
[
    {
        "_id" : "admin.administrator",
        "user" : "administrator",
        "db" : "admin",
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]

I emphasize "admin.administrator", for I have a Mongoid (mongodb ruby adapter) application with a different database than admin and I use the URI to reference the database in my mongoid.yml configuration:

development:
  clients:
    default:
      uri: <%= ENV['MONGODB_URI'] %>
      options:
        connect_timeout: 15
        retry_writes: false

This references the following environment variable:

export MONGODB_URI='mongodb://administrator:[email protected]/mysite_development?retryWrites=true&w=majority'

Notice the database is mysite_development, not admin. When I try to run the application, I get an error "User administrator (mechanism: scram256) is not authorized to access mysite_development".

So I return to the Mongo shell delete the user, switch to the specified database and recreate the user:

$ mongo
> db.dropUser('administrator')
> db.getUsers()
[]
> use mysite_development
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' }  ] })
> db.getUsers()
[
    {
        "_id" : "mysite_development.administrator",
        "user" : "administrator",
        "db" : "mysite_development",
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]

Notice that the _id and db changed to reference the specific database my application depends on:

"_id" : "mysite_development.administrator",
"db" : "mysite_development",

After making this change, the error went away and I was able to connect to MongoDB fine inside my application.

Extra Notes:

In my example above, I deleted the user and recreated the user in the right database context. Had you already created the user in the right database context but given it the wrong roles, you could assign a mongodb built-in role to the user:

db.grantRolesToUser('administrator', [{ role: 'root', db: 'admin' }])

There is also a db.updateUser command, albiet typically used to update the user password.

How to center an element horizontally and vertically

This is a related problem that people might come to this page when searching: When I want to centre a div for a (100px square) "waiting.." animated gif I use :

  .centreDiv {
        position: absolute;
        top: calc(50vh - 50px);
        top: -moz-calc(50vh - 50px);
        top: -webkit-calc(50vh - 50px);
        left: calc(50vw - 50px);
        left: -moz-calc(50vw - 50px);
        left: -webkit-calc(50vw - 50px);
        z-index: 1000; /*whatever is required*/
    }

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

Resetting remote to a certain commit

Do one thing, get the commit's SHA no. such as 87c9808 and then,

  1. move yourself ,that is your head to the specified commit (by doing git reset --hard 89cef43//mention your number here )
  2. Next do some changes in a random file , so that the git will ask you to commit that locally and then remotely Thus, what you need to do now is. after applying change git commit -a -m "trial commit"
  3. Now push the following commit (if this has been committed locally) by git push origin master
  4. Now what git will ask from you is that

error: failed to push some refs to 'https://github.com/YOURREPOSITORY/AndroidExperiments.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again.**

  1. Thus now what you can do is

git push --force origin master

  1. And thus, i hope it works :)

Prevent WebView from displaying "web page not available"

Check out the discussion at Android WebView onReceivedError(). It's quite long, but the consensus seems to be that a) you can't stop the "web page not available" page appearing, but b) you could always load an empty page after you get an onReceivedError

How to access my localhost from another PC in LAN?

after your pc connects to other pc use these 4 step:
4 steps:
1- Edit this file: httpd.conf
for that click on wamp server and select Apache and select httpd.conf
2- Find this text: Deny from all
in the below tag:

  <Directory "c:/wamp/www"><!-- maybe other url-->

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
    Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost
</Directory>

3- Change to: Deny from none
like this:

<Directory "c:/wamp/www">

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
    Deny from none
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

4- Restart Apache
Don't forget restart Apache or all servises!!!

Visual Studio Community 2015 expiration date

I also get same issue after I repair vs2015, even I click check license online, still fail. Correct action is: 1. Sign out 2. Check License Status, then it will pop-up login window, after login then it able to successfully get the license info.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

This isn't C, but it's certainly does work. All the other methods I see here work by casing everything into parts of a hexagon, and approximating "angles" from that. By instead starting with a different equation using cosines, and solving for h s and v, you get a lot nicer relationship between hsv and rgb, and tweening becomes smoother (at the cost of it being way slower).

Assume everything is floating point. If r g and b go from 0 to 1, h goes from 0 to 2pi, v goes from 0 to 4/3, and s goes from 0 to 2/3.

The following code is written in Lua. It's easily translatable into anything else.

local hsv do
    hsv         ={}
    local atan2 =math.atan2
    local cos   =math.cos
    local sin   =math.sin

    function hsv.fromrgb(r,b,g)
        local c=r+g+b
        if c<1e-4 then
            return 0,2/3,0
        else
            local p=2*(b*b+g*g+r*r-g*r-b*g-b*r)^0.5
            local h=atan2(b-g,(2*r-b-g)/3^0.5)
            local s=p/(c+p)
            local v=(c+p)/3
            return h,s,v
        end
    end

    function hsv.torgb(h,s,v)
        local r=v*(1+s*(cos(h)-1))
        local g=v*(1+s*(cos(h-2.09439)-1))
        local b=v*(1+s*(cos(h+2.09439)-1))
        return r,g,b
    end

    function hsv.tween(h0,s0,v0,h1,s1,v1,t)
        local dh=(h1-h0+3.14159)%6.28318-3.14159
        local h=h0+t*dh
        local s=s0+t*(s1-s0)
        local v=v0+t*(v1-v0)
        return h,s,v
    end
end

jQuery: Adding two attributes via the .attr(); method

the proper way is:

.attr({target:'nw', title:'Opens in a new window'})

Passing parameters in rails redirect_to

redirect_to new_user_path(:id => 1, :contact_id => 3, :name => 'suleman')

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

See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0); rather than just 0,0

Or better still with the C++ interface:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

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

Intro: There are the (probably) best solutions. But you have to know it and remember it and sometimes you have to hope that your Python version isn't too old or whatever the issue could be.

Then there are the most 'hacky' solutions. They are great and short but sometimes are hard to understand, to read and to remember.

There is, though, an alternative which is to to try to reinvent the wheel. - Why reinventing the wheel? - Generally because it's a really good way to learn (and sometimes just because the already-existing tool doesn't do exactly what you would like and/or the way you would like it) and the easiest way if you don't know or don't remember the perfect tool for your problem.

So, I propose to reinvent the wheel of the Counter class from the collections module (partially at least):

class MyDict(dict):
    def __add__(self, oth):
        r = self.copy()

        try:
            for key, val in oth.items():
                if key in r:
                    r[key] += val  # You can custom it here
                else:
                    r[key] = val
        except AttributeError:  # In case oth isn't a dict
            return NotImplemented  # The convention when a case isn't handled

        return r

a = MyDict({'a':1, 'b':2, 'c':3})
b = MyDict({'b':3, 'c':4, 'd':5})

print(a+b)  # Output {'a':1, 'b': 5, 'c': 7, 'd': 5}

There would probably others way to implement that and there are already tools to do that but it's always nice to visualize how things would basically works.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

Given URL is not allowed by the Application configuration

Go to https://developers.facebook.com/apps and open the app you have created. open setting tab and add platform and insert site url where you want to share facebook button .Its done.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

If you are on MAMP

Check your port number as well generally it is

Host localhost

Port 8889

User root

Password root

Socket /Applications/MAMP/tmp/mysql/mysql.sock

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

5 Jan 2021: link update thanks to @Sadap's comment.

Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.

For example, you can see that _WIN32 is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).

Anyway, I found the tables quite informative and thought I'd share here.

Deleting row from datatable in C#

There several different ways to do it. But You can use the following approach:

List<DataRow> RowsToDelete = new List<DataRow>();

for (int i = 0; i < drr.Length; i++) 
{     
   if(condition to delete the row) 
   {  
       RowsToDelete.Add(drr[i]);     
   } 
}

foreach(var dr in RowsToDelete) 
{     
   drr.Rows.Remove(dr); 
} 

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

Check if checkbox is NOT checked on click - jQuery

The Answer already posted .But We can use the jquery in this way also

demo

$(function(){
    $('#check1').click(function() {
        if($('#check1').attr('checked'))
            alert('checked');
        else
            alert('unchecked');
    });

    $('#check2').click(function() {
        if(!$('#check2').attr('checked'))
            alert('unchecked');
        else
            alert('checked');
    });
});

Change Input to Upper Case

Javascript has a toUpperCase() method. http://www.w3schools.com/jsref/jsref_toUpperCase.asp

So wherever you think best to put it in your code, you would have to do something like

$(".keywords").val().toUpperCase()

Create a basic matrix in C (input by user !)

How about the following?

First ask the user for the number of rows and columns, store that in say, nrows and ncols (i.e. scanf("%d", &nrows);) and then allocate memory for a 2D array of size nrows x ncols. Thus you can have a matrix of a size specified by the user, and not fixed at some dimension you've hardcoded!

Then store the elements with for(i = 0;i < nrows; ++i) ... and display the elements in the same way except you throw in newlines after every row, i.e.

for(i = 0; i < nrows; ++i)
{
   for(j = 0; j < ncols ; ++j) 
   {
      printf("%d\t",mat[i][j]);
   }
printf("\n");
}

Selecting empty text input using jQuery

Since creating an JQuery object for every comparison is not efficient, just use:

$.expr[":"].blank = function(element) {
    return element.value == "";
};

Then you can do:

$(":input:blank")

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

set pythonpath before import statements

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

How to print the array?

It looks like you have a typo on your array, it should read:

int my_array[3][3] = {...

You don't have the _ or the {.

Also my_array[3][3] is an invalid location. Since computers begin counting at 0, you are accessing position 4. (Arrays are weird like that).

If you want just the last element:

printf("%d\n", my_array[2][2]);

If you want the entire array:

for(int i = 0; i < my_array.length; i++) {
  for(int j = 0; j < my_array[i].length; j++)
    printf("%d ", my_array[i][j]);
  printf("\n");
}

How do I test a single file using Jest?

For nestjs users, the simple alternative is to use,

npm test -t <name of the spec file to run>

Nestjs comes preconfigured with the regex of the test files to search for incase of jest A simple example is -

npm test -t app-util.spec.ts

(that is my spec file name)

The complete path need not be given since jest searches for spec files based on the confuguration which is available by default incase of nestjs

"jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

Import regular CSS file in SCSS file?

It is now possible using:

@import 'CSS:directory/filename.css';

how to select first N rows from a table in T-SQL?

You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad

SET ROWCOUNT 10
SELECT * FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate

SET ROWCOUNT 0

In Android, how do I set margins in dp programmatically?

Working utils function using DP for those interested:

public static void setMargins(Context context, View view, int left, int top, int right, int bottom) {
    int marginLeft = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, left, context.getResources().getDisplayMetrics());
    int marginTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, top, context.getResources().getDisplayMetrics());
    int marginRight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, right, context.getResources().getDisplayMetrics());
    int marginBottom = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, bottom, context.getResources().getDisplayMetrics());

    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        p.setMargins(marginLeft, marginTop, marginRight, marginBottom);
        view.requestLayout();
    }
}

How do you get assembler output from C/C++ source in gcc?

I don't see this possibility among answers, probably because the question is from 2008, but in 2018 you can use Matt Goldbolt's online website https://godbolt.org

You can also locally git clone and run his project https://github.com/mattgodbolt/compiler-explorer

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

I had the same issue.

Make sure that In SQL Server configuration --> SQL Server Services --> SQL Server Agent is enable

This solved my problem

Get escaped URL parameter

There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:

    /*
    *   @param      string      parameter to return the value of.
    *   @return     string      value of chosen parameter, if found.
    */
    function get_param(return_this)
    {
        return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.

        var url = window.location.href;                                   // Get the URL.
        var parameters = url.substring(url.indexOf("?") + 1).split("&");  // Split by "param=value".
        var params = [];                                                  // Array to store individual values.

        for(var i = 0; i < parameters.length; i++)
            if(parameters[i].search(return_this + "=") != -1)
                return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");

        return "Parameter not found";
    }

console.log(get_param("parameterName"));

Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.

Content-Disposition:What are the differences between "inline" and "attachment"?

If it is inline, the browser should attempt to render it within the browser window. If it cannot, it will resort to an external program, prompting the user.

With attachment, it will immediately go to the user, and not try to load it in the browser, whether it can or not.

adding css class to multiple elements

You need to qualify the a part of the selector too:

.button input, .button a {
    //css stuff here
}

Basically, when you use the comma to create a group of selectors, each individual selector is completely independent. There is no relationship between them.

Your original selector therefore matched "all elements of type 'input' that are descendants of an element with the class name 'button', and all elements of type 'a'".

Get values from label using jQuery

Try this:

var label = $('#currentMonth').text()

How to iterate over a string in C?

An optimized approach:

for (char character = *string; character != '\0'; character = *++string)
{
    putchar(character); // Do something with character.
}

Most C strings are null-terminated, meaning that as soon as the character becomes a '\0' the loop should stop. The *++string is moving the pointer one byte, then dereferencing it, and the loop repeats.

The reason why this is more efficient than strlen() is because strlen already loops through the string to find the length, so you would effectively be looping twice (one more time than needed) with strlen().

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

Inner text shadow with CSS

Here's a little trick I discovered using the :before and :after pseudo-elements:

.depth {
    color: black;
    position: relative;
}
.depth:before, .depth:after {
    content: attr(title);
    color: rgba(255,255,255,.1);
    position: absolute;
}
.depth:before { top: 1px; left: 1px }
.depth:after  { top: 2px; left: 2px }

The title attribute needs to be the same as the content. Demo: http://dabblet.com/gist/1609945

Mipmap drawables for icons

There are two distinct uses of mipmaps:

  1. For launcher icons when building density specific APKs. Some developers build separate APKs for every density, to keep the APK size down. However some launchers (shipped with some devices, or available on the Play Store) use larger icon sizes than the standard 48dp. Launchers use getDrawableForDensity and scale down if needed, rather than up, so the icons are high quality. For example on an hdpi tablet the launcher might load the xhdpi icon. By placing your launcher icon in the mipmap-xhdpi directory, it will not be stripped the way a drawable-xhdpi directory is when building an APK for hdpi devices. If you're building a single APK for all devices, then this doesn't really matter as the launcher can access the drawable resources for the desired density.

  2. The actual mipmap API from 4.3. I haven't used this and am not familiar with it. It's not used by the Android Open Source Project launchers and I'm not aware of any other launcher using.

How to cancel a local git commit

The first thing you should do is to determine whether you want to keep the local changes before you delete the commit message.

Use git log to show current commit messages, then find the commit_id before the commit that you want to delete, not the commit you want to delete.

If you want to keep the locally changed files, and just delete commit message:

git reset --soft commit_id

If you want to delete all locally changed files and the commit message:

git reset --hard commit_id

That's the difference of soft and hard

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

BIRT, the Eclipse Business Intelligence and Reporting Tool is open source.

BIRT is an open source Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports. BIRT provides core reporting features such as report layout, data access and scripting.

gem install: Failed to build gem native extension (can't find header files)

sudo apt-get install ruby-dev

This command solved the problem for me!

How to get JavaScript variable value in PHP

These are two different languages, that run at different time - you cannot interact with them like that.

PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.

Copying data from one SQLite database to another

I needed to move data from a sql server compact database to sqlite, so using sql server 2008 you can right click on the table and select 'Script Table To' and then 'Data to Inserts'. Copy the insert statements remove the 'GO' statements and it executed successfully when applied to the sqlite database using the 'DB Browser for Sqlite' app.

Deny direct access to all .php files except index.php

URL rewriting could be used to map a URL to .php files. The following rules can identify whether a .php request was made directly or it was re-written. It forbids the request in the first case:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^.+?\ [^?]+\.php[?\ ]
RewriteRule \.php$ - [F]
RewriteRule test index.php

These rules will forbid all requests that end with .php. However, URLs such as / (which fires index.php), /test (which rewrites to index.php) and /test?f=index.php (which contains index.php in querystring) are still allowed.

THE_REQUEST contains the full HTTP request line sent by the browser to the server (e.g., GET /index.php?foo=bar HTTP/1.1)

SyntaxError: Use of const in strict mode?

I had a similar issue recently and ended up in this Q&A. This is not the solution the OP was looking for but may help others with a similar issue.

I'm using PM2 to run a project and in a given staging server I had a really old version of Node, NPM and PM2. I updated everything, however, I kept keeping the same error:

SyntaxError: Use of const in strict mode.

I tried to stop and start the application several times. Also tried to update everything again. Nothing worked. Until I noticed a warning when I ran pm2 start:

>>>> In-memory PM2 is out-of-date, do:
>>>> $ pm2 update
In memory PM2 version: 0.15.10
Local PM2 version: 3.2.9

Gotcha! After running pm2 update, I finally was able to get the application running as expected. No "const in strict mode" errors anymore.

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

In addition to the steps you have already taken, you will need to set the recovery mode to simple before you can shrink the log.

THIS IS NOT A RECOMMENDED PRACTICE for production systems... You will lose your ability to recover to a point in time from previous backups/log files.

See example B on this DBCC SHRINKFILE (Transact-SQL) msdn page for an example, and explanation.

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

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

UPD 19.03.2019 Here is a version for browser on GitHub.

Setting up a JavaScript variable from Spring model by using Thymeleaf

MAKE sure you have thymleaf on page already

//Use this in java
@Controller
@RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
 model.addAttribute("showTextFromJavaController","dummy text");
 return "showingTymleafTextInJavaScript";
}


//thymleaf page  javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>

How do I copy to the clipboard in JavaScript?

To copy a selected text ('Text To Copy') to your clipboard, create a Bookmarklet (browser bookmark that executes JavaScript) and execute it (click on it). It will create a temporary textarea.

Code from GitHub:

https://gist.github.com/stefanmaric/2abf96c740191cda3bc7a8b0fc905a7d

(function (text) {
  var node = document.createElement('textarea');
  var selection = document.getSelection();

  node.textContent = text;
  document.body.appendChild(node);

  selection.removeAllRanges();
  node.select();
  document.execCommand('copy');

  selection.removeAllRanges();
  document.body.removeChild(node);
})('Text To Copy');

How to load a xib file in a UIView

You could try:

UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];

How do I query using fields inside the new PostgreSQL JSON datatype?

With Postgres 9.3+, just use the -> operator. For example,

SELECT data->'images'->'thumbnail'->'url' AS thumb FROM instagram;

see http://clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json/ for some nice examples and a tutorial.

Adding two Java 8 streams, or an extra element to a stream

Just do:

Stream.of(stream1, stream2, Stream.of(element)).flatMap(identity());

where identity() is a static import of Function.identity().

Concatenating multiple streams into one stream is the same as flattening a stream.

However, unfortunately, for some reason there is no flatten() method on Stream, so you have to use flatMap() with the identity function.

Min/Max-value validators in asp.net mvc

A complete example of how this could be done. To avoid having to write client-side validation scripts, the existing ValidationType = "range" has been used.

public class MinValueAttribute : ValidationAttribute, IClientValidatable
{
    private readonly double _minValue;

    public MinValueAttribute(double minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;  
    }

    public MinValueAttribute(int minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;
    }

    public override bool IsValid(object value)
    {
        return Convert.ToDouble(value) >= _minValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = ErrorMessage;
        rule.ValidationParameters.Add("min", _minValue);
        rule.ValidationParameters.Add("max", Double.MaxValue);
        rule.ValidationType = "range";
        yield return rule;
    }

}

write a shell script to ssh to a remote machine and execute commands

There is are multiple ways to execute the commands or script in the multiple remote Linux machines. One simple & easiest way is via pssh (parallel ssh program)

pssh: is a program for executing ssh in parallel on a number of hosts. It provides features such as sending input to all of the processes, passing a password to ssh, saving the output to files, and timing out.

Example & Usage:

Connect to host1 and host2, and print "hello, world" from each:

 pssh -i -H "host1 host2" echo "hello, world"

Run commands via a script on multiple servers:

pssh -h hosts.txt -P -I<./commands.sh

Usage & run a command without checking or saving host keys:

pssh -h hostname_ip.txt -x '-q -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes' -i  'uptime; hostname -f'

If the file hosts.txt has a large number of entries, say 100, then the parallelism option may also be set to 100 to ensure that the commands are run concurrently:

pssh -i -h hosts.txt -p 100 -t 0 sleep 10000

Options:
-I: Read input and sends to each ssh process.
-P: Tells pssh to display output as it arrives.
-h: Reads the host's file.
-H : [user@]host[:port] for single-host.
-i: Display standard output and standard error as each host completes
-x args: Passes extra SSH command-line arguments
-o option: Can be used to give options in the format used in the configuration file.(/etc/ssh/ssh_config) (~/.ssh/config)
-p parallelism: Use the given number as the maximum number of concurrent connections
-q Quiet mode: Causes most warning and diagnostic messages to be suppressed.
-t: Make connections time out after the given number of seconds. 0 means pssh will not timeout any connections

When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.

Disable the StrictHostKeyChecking to handle the RSA authentication prompt.
-o StrictHostKeyChecking=no

Source: man pssh

increase legend font size ggplot2

You can also specify the font size relative to the base_size included in themes such as theme_bw() (where base_size is 11) using the rel() function.

For example:

ggplot(mtcars, aes(disp, mpg, col=as.factor(cyl))) +
  geom_point() +
  theme_bw() +
  theme(legend.text=element_text(size=rel(0.5)))

How to concatenate text from multiple rows into a single text string in SQL server?

MySQL complete Example:

We have Users which can have many Data's and we want to have an output, where we can see all users Datas in a list:

Result:

___________________________
| id   |  rowList         |
|-------------------------|
| 0    | 6, 9             |
| 1    | 1,2,3,4,5,7,8,1  |
|_________________________|

Table Setup:

CREATE TABLE `Data` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;


INSERT INTO `Data` (`id`, `user_id`) VALUES
(1, 1),
(2, 1),
(3, 1),
(4, 1),
(5, 1),
(6, 0),
(7, 1),
(8, 1),
(9, 0),
(10, 1);


CREATE TABLE `User` (
  `id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `User` (`id`) VALUES
(0),
(1);

Query:

SELECT User.id, GROUP_CONCAT(Data.id ORDER BY Data.id) AS rowList FROM User LEFT JOIN Data ON User.id = Data.user_id GROUP BY User.id

Failed to load resource under Chrome

I was getting this error, only in Chrome (last version 24.0.1312.57 m), and only if the image was larger than the html img. I was using a php script to output the image like this:

header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
echo base64_decode($data);

I resolved it adding 1 to the lenght of the image:

header('Content-Length: '.strlen($data) + 1);
header("Content-type: image/{$ext}");
echo base64_decode($data);

Appears that Chrome dont expect the correct number of bytes.

Tested with sucess in Chrome and IE 9. Hope this help.

HTML tag <a> want to add both href and onclick working

To achieve this use following html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Here is working example.

How to parse JSON without JSON.NET library?

I use this...but have never done any metro app development, so I don't know of any restrictions on libraries available to you. (note, you'll need to mark your classes as with DataContract and DataMember attributes)

public static class JSONSerializer<TType> where TType : class
{
    /// <summary>
    /// Serializes an object to JSON
    /// </summary>
    public static string Serialize(TType instance)
    {
        var serializer = new DataContractJsonSerializer(typeof(TType));
        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, instance);
            return Encoding.Default.GetString(stream.ToArray());
        }
    }

    /// <summary>
    /// DeSerializes an object from JSON
    /// </summary>
    public static TType DeSerialize(string json)
    {
        using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
        {
            var serializer = new DataContractJsonSerializer(typeof(TType));
            return serializer.ReadObject(stream) as TType;
        }
    }
}

So, if you had a class like this...

[DataContract]
public class MusicInfo
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Artist { get; set; }

    [DataMember]
    public string Genre { get; set; }

    [DataMember]
    public string Album { get; set; }

    [DataMember]
    public string AlbumImage { get; set; }

    [DataMember]
    public string Link { get; set; }

}

Then you would use it like this...

var musicInfo = new MusicInfo
{
     Name = "Prince Charming",
     Artist = "Metallica",
     Genre = "Rock and Metal",
     Album = "Reload",
     AlbumImage = "http://up203.siz.co.il/up2/u2zzzw4mjayz.png",
     Link = "http://f2h.co.il/7779182246886"
};

// This will produce a JSON String
var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);

// This will produce a copy of the instance you created earlier
var deserialized = JSONSerializer<MusicInfo>.DeSerialize(serialized);

Can't specify the 'async' modifier on the 'Main' method of a console app

I'll add an important feature that all of the other answers have overlooked: cancellation.

One of the big things in TPL is cancellation support, and console apps have a method of cancellation built in (CTRL+C). It's very simple to bind them together. This is how I structure all of my async console apps:

static void Main(string[] args)
{
    CancellationTokenSource cts = new CancellationTokenSource();
    
    System.Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = true;
        cts.Cancel();
    };

    MainAsync(args, cts.Token).GetAwaiter.GetResult();
}

static async Task MainAsync(string[] args, CancellationToken token)
{
    ...
}

Converting an int or String to a char array on Arduino

None of that stuff worked. Here's a much simpler way .. the label str is the pointer to what IS an array...

String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string

str = str + '\r' + '\n'; // Add the required carriage return, optional line feed

byte str_len = str.length();

// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...

byte arrayPointer = 0;

while (str_len)
{
    // I was outputting the digits to the TX buffer

    if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
    {
        UDR0 = str[arrayPointer];
        --str_len;
        ++arrayPointer;
    }
}

To show a new Form on click of a button in C#

private void ButtonClick(object sender, System.EventArgs e)
{
    MyForm form = new MyForm();
    form.Show(); // or form.ShowDialog(this);
}

pandas: find percentile stats of a given column

You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)

my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

I encountered the same problem even I set "UseDefaultCredentials" to false. Later I found that the root cause is that I turned on "2-step Verification" in my account. After I turned it off, the problem is gone.

How to get values and keys from HashMap?

It will work with hash.get("key"); Where key is your key for getting the value from Map

Appending output of a Batch file To log file

Use log4j in your java program instead. Then you can output to multiple media, create rolling logs, etc. and include timestamps, class names and line numbers.

how to make jni.h be found?

Installing the OpenJDK Development Kit (JDK) should fix your problem.

sudo apt-get install openjdk-X-jdk

This should make you able to compile without problems.

How do operator.itemgetter() and sort() work?

a = []
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
print a

[['Nick', 30, 'Doctor'], ['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Mark', 66, 'Retired']]

def _cmp(a,b):     

    if a[1]<b[1]:
        return -1
    elif a[1]>b[1]:
        return 1
    else:
        return 0

sorted(a,cmp=_cmp)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]

def _key(list_ele):

    return list_ele[1]

sorted(a,key=_key)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
>>> 

jQuery - simple input validation - "empty" and "not empty"

JQuery's :empty selector selects all elements on the page that are empty in the sense that they have no child elements, including text nodes, not all inputs that have no text in them.

Jquery: How to check if an input element has not been filled in.

Here's the code stolen from the above thread:

$('#apply-form input').blur(function()          //whenever you click off an input element
{                   
    if( !$(this).val() ) {                      //if it is blank. 
         alert('empty');    
    }
});

This works because an empty string in JavaScript is a 'falsy value', which basically means if you try to use it as a boolean value it will always evaluate to false. If you want, you can change the conditional to $(this).val() === '' for added clarity. :D

git switch branch without discarding local changes

You can use :

  1. git stash to save your work
  2. git checkout <your-branch>
  3. git stash apply or git stash pop to load your last work

Git stash extremely useful when you want temporarily save undone or messy work, while you want to doing something on another branch.

git -stash documentation

Swipe ListView item From right to left show delete button

see there link was very nice and simple. its working fine... u don't want any library its working fine. click here

OnTouchListener gestureListener = new View.OnTouchListener() {
    private int padding = 0;
    private int initialx = 0;
    private int currentx = 0;
    private  ViewHolder viewHolder;

    public boolean onTouch(View v, MotionEvent event) {
        if ( event.getAction() == MotionEvent.ACTION_DOWN) {
            padding = 0;
            initialx = (int) event.getX();
            currentx = (int) event.getX();
            viewHolder = ((ViewHolder) v.getTag());
        }
        if ( event.getAction() == MotionEvent.ACTION_MOVE) {
            currentx = (int) event.getX();
            padding = currentx - initialx;
        }       
        if ( event.getAction() == MotionEvent.ACTION_UP || 
                     event.getAction() == MotionEvent.ACTION_CANCEL) {
            padding = 0;
            initialx = 0;
            currentx = 0;
        }
        if(viewHolder != null) {
            if(padding == 0) {
                v.setBackgroundColor(0xFF000000 );  
                if(viewHolder.running)
                    v.setBackgroundColor(0xFF058805);
            }
            if(padding > 75) {
                viewHolder.running = true;
                v.setBackgroundColor(0xFF00FF00 );  
                viewHolder.icon.setImageResource(R.drawable.clock_running);
            }
            if(padding < -75) {
                viewHolder.running = false;
                v.setBackgroundColor(0xFFFF0000 );  
            }

            v.setPadding(padding, 0,0, 0);
        }

        return true;
    }
};

Passing a callback function to another class

You could use only delegate which is best for callback functions:

public class ServerRequest
{
    public delegate void CallBackFunction(string input);

    public void DoRequest(string request, CallBackFunction callback)
    {
        // do stuff....
        callback(request);
    }
}

and consume this like below:

public class Class1
    {
        private void btn_click(object sender, EventArgs e)
        {
            ServerRequest sr = new ServerRequest();
            var callback = new ServerRequest.CallBackFunction(CallbackFunc);
            sr.DoRequest("myrequest",callback);
        }

        void CallbackFunc(string something)
        {

        }


    }

Manually Set Value for FormBuilder Control

@Filoche's Angular 2 updated solution. Using FormControl

(<Control>this.form.controls['dept']).updateValue(selected.id)

import { FormControl } from '@angular/forms';

(<FormControl>this.form.controls['dept']).setValue(selected.id));

Alternatively you can use @AngularUniversity's solution which uses patchValue

How to convert date to timestamp?

It should have been in this standard date format YYYY-MM-DD, to use below equation. You may have time along with example: 2020-04-24 16:51:56 or 2020-04-24T16:51:56+05:30. It will work fine but date format should like this YYYY-MM-DD only.

var myDate = "2020-04-24";
var timestamp = +new Date(myDate)

What is the purpose of Node.js module.exports and how do you use it?

let test = function() {
    return "Hello world"
};
exports.test = test;

Python assigning multiple variables to same value? list behavior

If you're coming to Python from a language in the C/Java/etc. family, it may help you to stop thinking about a as a "variable", and start thinking of it as a "name".

a, b, and c aren't different variables with equal values; they're different names for the same identical value. Variables have types, identities, addresses, and all kinds of stuff like that.

Names don't have any of that. Values do, of course, and you can have lots of names for the same value.

If you give Notorious B.I.G. a hot dog,* Biggie Smalls and Chris Wallace have a hot dog. If you change the first element of a to 1, the first elements of b and c are 1.

If you want to know if two names are naming the same object, use the is operator:

>>> a=b=c=[0,3,5]
>>> a is b
True

You then ask:

what is different from this?

d=e=f=3
e=4
print('f:',f)
print('e:',e)

Here, you're rebinding the name e to the value 4. That doesn't affect the names d and f in any way.

In your previous version, you were assigning to a[0], not to a. So, from the point of view of a[0], you're rebinding a[0], but from the point of view of a, you're changing it in-place.

You can use the id function, which gives you some unique number representing the identity of an object, to see exactly which object is which even when is can't help:

>>> a=b=c=[0,3,5]
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261120
>>> id(b[0])
4297261120

>>> a[0] = 1
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261216
>>> id(b[0])
4297261216

Notice that a[0] has changed from 4297261120 to 4297261216—it's now a name for a different value. And b[0] is also now a name for that same new value. That's because a and b are still naming the same object.


Under the covers, a[0]=1 is actually calling a method on the list object. (It's equivalent to a.__setitem__(0, 1).) So, it's not really rebinding anything at all. It's like calling my_object.set_something(1). Sure, likely the object is rebinding an instance attribute in order to implement this method, but that's not what's important; what's important is that you're not assigning anything, you're just mutating the object. And it's the same with a[0]=1.


user570826 asked:

What if we have, a = b = c = 10

That's exactly the same situation as a = b = c = [1, 2, 3]: you have three names for the same value.

But in this case, the value is an int, and ints are immutable. In either case, you can rebind a to a different value (e.g., a = "Now I'm a string!"), but the won't affect the original value, which b and c will still be names for. The difference is that with a list, you can change the value [1, 2, 3] into [1, 2, 3, 4] by doing, e.g., a.append(4); since that's actually changing the value that b and c are names for, b will now b [1, 2, 3, 4]. There's no way to change the value 10 into anything else. 10 is 10 forever, just like Claudia the vampire is 5 forever (at least until she's replaced by Kirsten Dunst).


* Warning: Do not give Notorious B.I.G. a hot dog. Gangsta rap zombies should never be fed after midnight.

Parse JSON String into List<string>

I use this JSON Helper class in my projects. I found it on the net a year ago but lost the source URL. So I am pasting it directly from my project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
/// <summary>
/// JSON Serialization and Deserialization Assistant Class
/// </summary>
public class JsonHelper
{
    /// <summary>
    /// JSON Serialization
    /// </summary>
    public static string JsonSerializer<T> (T t)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, t);
        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        return jsonString;
    }
    /// <summary>
    /// JSON Deserialization
    /// </summary>
    public static T JsonDeserialize<T> (string jsonString)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }
}

You can use it like this: Create the classes as Craig W. suggested.

And then deserialize like this

RootObject root = JSONHelper.JsonDeserialize<RootObject>(json);

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

How to correctly use the ASP.NET FileUpload control

I have noticed that when intellisence doesn't work for an object there is usually an error somewhere in the class above line you are working on.

The other option is that you didn't instantiated the FileUpload object as an instance variable. make sure the code:

FileUpload fileUpload = new FileUpload();

is not inside a function in your code behind.

How do I divide so I get a decimal value?

int a = 3;
int b = 2;
float c = ((float)a)/b

Outlets cannot be connected to repeating content iOS

There are two types of table views cells provided to you through the storyboard, they are Dynamic Prototypes and Static Cells

enter image description here

1. Dynamic Prototypes

From the name, this type of cell is generated dynamically. They are controlled through your code, not the storyboard. With help of table view's delegate and data source, you can specify the number of cells, heights of cells, prototype of cells programmatically.

When you drag a cell to your table view, you are declaring a prototype of cells. You can then create any amount of cells base on this prototype and add them to the table view through cellForRow method, programmatically. The advantage of this is that you only need to define 1 prototype instead of creating each and every cell with all views added to them by yourself (See static cell).

So in this case, you cannot connect UI elements on cell prototype to your view controller. You will have only one view controller object initiated, but you may have many cell objects initiated and added to your table view. It doesn't make sense to connect cell prototype to view controller because you cannot control multiple cells with one view controller connection. And you will get an error if you do so.

enter image description here

To fix this problem, you need to connect your prototype label to a UITableViewCell object. A UITableViewCell is also a prototype of cells and you can initiate as many cell objects as you want, each of them is then connected to a view that is generated from your storyboard table cell prototype.

enter image description here

Finally, in your cellForRow method, create the custom cell from the UITableViewCell class, and do fun stuff with the label

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier") as! YourCell

    cell.label.text = "it works!"

    return cell
}

2. Static Cells

On the other hand, static cells are indeed configured though storyboard. You have to drag UI elements to each and every cell to create them. You will be controlling cell numbers, heights, etc from the storyboard. In this case, you will see a table view that is exactly the same from your phone compared with what you created from the storyboard. Static cells are more often used for setting page, which the cells do not change a lot.

To control UI elements for a static cell, you will indeed need to connect them directly to your view controller, and set them up.

enter image description here

What is the significance of load factor in HashMap?

What is load factor ?

The amount of capacity which is to be exhausted for the HashMap to increase its capacity ?

Why load factor ?

Load factor is by default 0.75 of the initial capacity (16) therefore 25% of the buckets will be free before there is an increase in the capacity & this makes many new buckets with new hashcodes pointing to them to exist just after the increase in the number of buckets.

Now why should you keep many free buckets & what is the impact of keeping free buckets on the performance ?

If you set the loading factor to say 1.0 then something very interesting might happen.

Say you are adding an object x to your hashmap whose hashCode is 888 & in your hashmap the bucket representing the hashcode is free , so the object x gets added to the bucket, but now again say if you are adding another object y whose hashCode is also 888 then your object y will get added for sure BUT at the end of the bucket (because the buckets are nothing but linkedList implementation storing key,value & next) now this has a performance impact ! Since your object y is no longer present in the head of the bucket if you perform a lookup the time taken is not going to be O(1) this time it depends on how many items are there in the same bucket. This is called hash collision by the way & this even happens when your loading factor is less than 1.

Correlation between performance , hash collision & loading factor ?

Lower load factor = more free buckets = less chances of collision = high performance = high space requirement.

Correct me if i am wrong somewhere.

How to use wget in php?

wget

wget is a linux command, not a PHP command, so to run this you woud need to use exec, which is a PHP command for executing shell commands.

exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");

This can be useful if you are downloading a large file - and would like to monitor the progress, however when working with pages in which you are just interested in the content, there are simple functions for doing just that.

The exec function is enabled by default, but may be disabled in some situations. The configuration options for this reside in your php.ini, to enable, remove exec from the disabled_functions config string.

alternative

Using file_get_contents we can retrieve the contents of the specified URL/URI. When you just need to read the file into a variable, this would be the perfect function to use as a replacement for curl - follow the URI syntax when building your URL.

// standard url
$content = file_get_contents("http://www.example.com/file.xml");

// or with basic auth
$content = file_get_contents("http://user:[email protected]/file.xml");

As noted by Sean the Bean - you may also need to change allow_url_fopen to true in your php.ini to allow the use of a URL in this method, however, this should be true by default.

If you want to then store that file locally, there is a function file_put_contents to write that into a file, combined with the previous, this could emulate a file download:

file_put_contents("local_file.xml", $content);

Angular 2: How to write a for loop, not a foreach loop

Depending on the length of the wanted loop, maybe even a more "template-driven" solution:

<ul>
  <li *ngFor="let index of [0,1,2,3,4,5]">
    {{ index }}
  </li>
</ul>

Why is Tkinter Entry's get function returning nothing?

you need to put a textvariable in it, so you can use set() and get() method :

var=StringVar()
x= Entry (root,textvariable=var)

Center/Set Zoom of Map to cover all visible Markers?

The size of array must be greater than zero. ?therwise you will have unexpected results.

function zoomeExtends(){
  var bounds = new google.maps.LatLngBounds();
  if (markers.length>0) { 
      for (var i = 0; i < markers.length; i++) {
         bounds.extend(markers[i].getPosition());
        }    
        myMap.fitBounds(bounds);
    }
}

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I just thought I'd share that I found the answer to my own question.

Writing out my problem made it even more clear to me, and I further investigated into where I thought my problem lay: the ssh key

Turns out I was right. The issue wasn't with the key itself, but rather that I had not added it to my local Mac's list of known ssh keys. So even though my Heroku account had the correct key uploaded, my Mac could not authenticate with it because it could not find that key on my computer. The solution?

ssh-add ~/.ssh/id_rsa
#and, to confirm it's been added to the known list of keys
ssh-add -l

I would like to give credit to https://help.github.com/articles/error-permission-denied-publickey for being a good reference.

FileNotFoundError: [Errno 2] No such file or directory

Use the exact path.

import csv


with open('C:\\path\\address.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

SCRIPT5: Access is denied in IE9 on xmlhttprequest

  $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This code will work https sites too

Ball to Ball Collision - Detection and Handling

A good way of reducing the number of collision checks is to split the screen into different sections. You then only compare each ball to the balls in the same section.

Getting Hour and Minute in PHP

Try this:

$hourMin = date('H:i');

This will be 24-hour time with an hour that is always two digits. For all options, see the PHP docs for date().

How do I use a custom Serializer with Jackson?

As mentioned, @JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:

public void serialize(Item value, JsonGenerator jgen,
    SerializerProvider provider) throws IOException,
    JsonProcessingException {
  jgen.writeNumber(id);
}

Yet another possibility is to implement JsonSerializable, in which case no registration is needed.

As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend org.codehaus.jackson.map.ser.SerializerBase as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).

How to embed a PDF?

Here is the code you can use for every browser:

<embed src="pdfFiles/interfaces.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">

Tested on firefox and chrome

What is the MySQL VARCHAR max size?

Before Mysql version 5.0.3 Varchar datatype can store 255 character, but from 5.0.3 it can be store 65,535 characters.

BUT it has a limitation of maximum row size of 65,535 bytes. It means including all columns it must not be more than 65,535 bytes.

In your case it may possible that when you are trying to set more than 10000 it is exceeding more than 65,535 and mysql will gives the error.

For more information: https://dev.mysql.com/doc/refman/5.0/en/column-count-limit.html

blog with example: http://goo.gl/Hli6G3

Is generator.next() visible in Python 3?

If your code must run under Python2 and Python3, use the 2to3 six library like this:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

Vertically centering a div inside another div

Vertical Align Anything with just 3 lines of CSS

HTML

<div class="parent-of-element">

    <div class="element">
        <p>Hello</p>
    </div>

</div>

Simplest

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

CSS

.parent-of-element {
   position: relative;
   height: 500px;
   /* or height: 73.61% */
   /* or height: 35vh */
   /* or height: ANY HEIGHT */
}

.element {
  position: absolute;
  top: 50%;

  -webkit-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
          transform: translateY(-50%);
}

According to shouldiprefix this are the only prefixes you need

You can also use % as the value for the 'height' property of .parent-of-element, as long as parent of element has height or some content that expands its vertical size.

PHP - Check if the page run on Mobile or Desktop browser

You can do it manually if you want.

Reference: http://php.net/manual/en/function.get-browser.php

preg_match('/windows|win32/i', $_SERVER['HTTP_USER_AGENT'])

preg_match('/iPhone|iPod|iPad/', $_SERVER['HTTP_USER_AGENT'])

You can even make it a script

$device = 'Blackberry'

preg_match("/$device/", $_SERVER['HTTP_USER_AGENT'])

Here is somewhat of a small list

                        '/windows nt 6.2/i'     =>  'Windows 8',
                        '/windows nt 6.1/i'     =>  'Windows 7',
                        '/windows nt 6.0/i'     =>  'Windows Vista',
                        '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                        '/windows nt 5.1/i'     =>  'Windows XP',
                        '/windows xp/i'         =>  'Windows XP',
                        '/windows nt 5.0/i'     =>  'Windows 2000',
                        '/windows me/i'         =>  'Windows ME',
                        '/win98/i'              =>  'Windows 98',
                        '/win95/i'              =>  'Windows 95',
                        '/win16/i'              =>  'Windows 3.11',
                        '/macintosh|mac os x/i' =>  'Mac OS X',
                        '/mac_powerpc/i'        =>  'Mac OS 9',
                        '/linux/i'              =>  'Linux',
                        '/ubuntu/i'             =>  'Ubuntu',
                        '/iphone/i'             =>  'iPhone',
                        '/ipod/i'               =>  'iPod',
                        '/ipad/i'               =>  'iPad',
                        '/android/i'            =>  'Android',
                        '/blackberry/i'         =>  'BlackBerry',
                        '/webos/i'              =>  'Mobile'

Browsers

                        '/msie/i'       =>  'Internet Explorer',
                        '/firefox/i'    =>  'Firefox',
                        '/safari/i'     =>  'Safari',
                        '/chrome/i'     =>  'Chrome',
                        '/opera/i'      =>  'Opera',
                        '/netscape/i'   =>  'Netscape',
                        '/maxthon/i'    =>  'Maxthon',
                        '/konqueror/i'  =>  'Konqueror',
                        '/mobile/i'     =>  'Handheld Browser'

Use custom build output folder when using create-react-app

You can't change the build output folder name with the current configuration options.

Moreover, you shouldn't. This is a part of the philosophy behind create-react-app: they say Convention over Configuration.

If you really need to rename your folder, I see two options:

  1. Right after the build process finishes, write a command that copies the build folder content to another folder you want. For example you can try the copyfiles npm package, or anything similar.

  2. You could try to eject create-react-app and tweak the configuration.

    If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

    Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

    However, it is important to note that this is a one-way operation. Once you eject, you can’t go back! You loose all future updates.

Therefore, I'd recommend you to not use a custom folder naming, if possible. Try to stick with the default naming. If not an option, try #1. If it still doesn't work for your specific use-case and you're really out of options - explore #2. Good luck!

How to do parallel programming in Python?

You can use the multiprocessing module. For this case I might use a processing pool:

from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(solve1, [A])    # evaluate "solve1(A)" asynchronously
result2 = pool.apply_async(solve2, [B])    # evaluate "solve2(B)" asynchronously
answer1 = result1.get(timeout=10)
answer2 = result2.get(timeout=10)

This will spawn processes that can do generic work for you. Since we did not pass processes, it will spawn one process for each CPU core on your machine. Each CPU core can execute one process simultaneously.

If you want to map a list to a single function you would do this:

args = [A, B]
results = pool.map(solve1, args)

Don't use threads because the GIL locks any operations on python objects.

C# delete a folder and all files and folders within that folder

Try This:

foreach (string files in Directory.GetFiles(SourcePath))
{
   FileInfo fileInfo = new FileInfo(files);
   fileInfo.Delete(); //delete the files first. 
}
Directory.Delete(SourcePath);// delete the directory as it is empty now.

What is the worst programming language you ever worked with?

I'm surprised no one has mentioned Sybase PowerBuilder

  • Confusing syntax
  • Confusing object model
  • Lack of native regular expression support
  • Difficult to use IDE (esp the tool palette)

AVD Manager - Cannot Create Android Virtual Device

You need to open up your SDK Manager and make sure everything is installed, especially System Image. After that will be alright!

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

you should also check if you are connecting via proxy. If there is a proxy set it up using File > Settings > Appearance and Behavior > System settings > HTTP Proxy

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Maintaining the final state at end of a CSS3 animation

Use animation-fill-mode: forwards;

animation-fill-mode: forwards;

The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).

Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.

Working example

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position :relative;_x000D_
  -webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
  animation: bubble 3s forwards;_x000D_
  /* animation-name: bubble; _x000D_
  animation-duration: 3s;_x000D_
  animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble  {_x000D_
  0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble  {_x000D_
   0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Java random numbers using a seed

That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.

No String-argument constructor/factory method to deserialize from String value ('')

Had this when I accidentally was calling

mapper.convertValue(...)

instead of

mapper.readValue(...)

So, just make sure you call correct method, since argument are same and IDE can find many things

How to change XAMPP apache server port?

if don't work above port id then change it.like 8082,8080 Restart xammp,Start apache server,Check it.It's now working.

TypeError: $(...).on is not a function

If you are using old version of jQuery(< 1.7) then you can use "bind" instead of "on". This will only work in case you are using old version, since as of jQuery 3.0, "bind" has been deprecated.

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

I was getting the same error and could not figure it out. I have a functional component exported and then imported into my App component. I set up my functional component in arrow function format, and was getting the error. I put a "return" statement inside the curly braquets, "return ()" and put all my JSX inside the parens. Hopefully this is useful to someone and not redundant. It seems stackoverflow will auto format this into a single line, however, in my editor, VSCode, it's over multiple lines. Maybe not a big deal, but want to be concise.

import React from 'react';

const Layout = (props) => {
    return (
        <>
            <div>toolbar, sidedrawer, backdrop</div>
            <main>
                {props.children}
            </main>
        </>
    );
};

export default Layout;

Center Plot title in ggplot2

The ggeasy package has a function called easy_center_title() to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5)) and it's so much easier to remember.

ggplot(data = dat, aes(time, total_bill, fill = time)) + 
  geom_bar(colour = "black", fill = "#DD8888", width = .8, stat = "identity") + 
  guides(fill = FALSE) +
  xlab("Time of day") +
  ylab("Total bill") +
  ggtitle("Average bill for 2 people") +
  ggeasy::easy_center_title()

enter image description here

Note that as of writing this answer you will need to install the development version of ggeasy from GitHub to use easy_center_title(). You can do so by running remotes::install_github("jonocarroll/ggeasy").

How do I count the number of rows and columns in a file using bash?

Little twist to kirill_igum's answer, and you can easily count the number of columns of any certain row you want, which was why I've come to this question, even though the question is asking for the whole file. (Though if your file has same columns in each line this also still works of course):

head -2 file |tail -1 |tr '\t' '\n' |wc -l

Gives the number of columns of row 2. Replace 2 with 55 for example to get it for row 55.

-bash-4.2$ cat file
1       2       3
1       2       3       4
1       2
1       2       3       4       5

-bash-4.2$ head -1 file |tail -1 |tr '\t' '\n' |wc -l
3
-bash-4.2$ head -4 file |tail -1 |tr '\t' '\n' |wc -l
5

Code above works if your file is separated by tabs, as we define it to "tr". If your file has another separator, say commas, you can still count your "columns" using the same trick by simply changing the separator character "t" to ",":

-bash-4.2$ cat csvfile
1,2,3,4
1,2
1,2,3,4,5
-bash-4.2$ head -2 csvfile |tail -1 |tr '\,' '\n' |wc -l
2

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Array Length in Java

if you mean by "logical size", the index of array, then simply int arrayLength = arr.length-1; since the the array index starts with "0", so the logical or "array index" will always be less than the actual size by "one".

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

you can use the download attribute on an a tag ...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

Generating all permutations of a given string

Recursive Python solution

def permute(input_str):
    _permute("", input_str)

def _permute(prefix, str_to_permute):
    if str_to_permute == '':
        print(prefix)

    else:
        for i in range(len(str_to_permute)): 
            _permute(prefix+str_to_permute[i], str_to_permute[0:i] + str_to_permute[i+1:])

if __name__ == '__main__':
    permute('foobar')

Convert all first letter to upper case, rest lower for each word

In addition to first answer, remember to change string selectionstart index to the end of the word or you will get reverse order of letters in the string.

s.SelectionStart=s.Length;

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

Print the address or pointer for value in C

I have been in this position, especially with new hardware. I suggest you write a little hex dump routine of your own. You will be able to see the data, and the addresses they are at, shown all together. It's good practice and a confidence builder.

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

Simple C example of doing an HTTP POST and consuming the response

A message has a header part and a message body separated by a blank line. The blank line is ALWAYS needed even if there is no message body. The header starts with a command and has additional lines of key value pairs separated by a colon and a space. If there is a message body, it can be anything you want it to be.

Lines in the header and the blank line at the end of the header must end with a carraige return and linefeed pair (see HTTP header line break style) so that's why those lines have \r\n at the end.

A URL has the form of http://host:port/path?query_string

There are two main ways of submitting a request to a website:

  • GET: The query string is optional but, if specified, must be reasonably short. Because of this the header could just be the GET command and nothing else. A sample message could be:

    GET /path?query_string HTTP/1.0\r\n
    \r\n
    
  • POST: What would normally be in the query string is in the body of the message instead. Because of this the header needs to include the Content-Type: and Content-Length: attributes as well as the POST command. A sample message could be:

    POST /path HTTP/1.0\r\n
    Content-Type: text/plain\r\n
    Content-Length: 12\r\n
    \r\n
    query_string
    

So, to answer your question: if the URL you are interested in POSTing to is http://api.somesite.com/apikey=ARG1&command=ARG2 then there is no body or query string and, consequently, no reason to POST because there is nothing to put in the body of the message and so nothing to put in the Content-Type: and Content-Length:

I guess you could POST if you really wanted to. In that case your message would look like:

POST /apikey=ARG1&command=ARG2 HTTP/1.0\r\n
\r\n

So to send the message the C program needs to:

  • create a socket
  • lookup the IP address
  • open the socket
  • send the request
  • wait for the response
  • close the socket

The send and receive calls won't necessarily send/receive ALL the data you give them - they will return the number of bytes actually sent/received. It is up to you to call them in a loop and send/receive the remainder of the message.

What I did not do in this sample is any sort of real error checking - when something fails I just exit the program. Let me know if it works for you:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    /* first what are we going to send and where are we going to send it? */
    int portno =        80;
    char *host =        "api.somesite.com";
    char *message_fmt = "POST /apikey=%s&command=%s HTTP/1.0\r\n\r\n";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total;
    char message[1024],response[4096];

    if (argc < 3) { puts("Parameters: <apikey> <command>"); exit(0); }

    /* fill in the parameters */
    sprintf(message,message_fmt,argv[1],argv[2]);
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    return 0;
}

Like the other answer pointed out, 4096 bytes is not a very big response. I picked that number at random assuming that the response to your request would be short. If it can be big you have two choices:

  • read the Content-Length: header from the response and then dynamically allocate enough memory to hold the whole response.
  • write the response to a file as the pieces arrive

Additional information to answer the question asked in the comments:

What if you want to POST data in the body of the message? Then you do need to include the Content-Type: and Content-Length: headers. The Content-Length: is the actual length of everything after the blank line that separates the header from the body.

Here is a sample that takes the following command line arguments:

  • host
  • port
  • command (GET or POST)
  • path (not including the query data)
  • query data (put into the query string for GET and into the body for POST)
  • list of headers (Content-Length: is automatic if using POST)

So, for the original question you would run:

a.out api.somesite.com 80 GET "/apikey=ARG1&command=ARG2"

And for the question asked in the comments you would run:

a.out api.somesite.com 80 POST / "name=ARG1&value=ARG2" "Content-Type: application/x-www-form-urlencoded"

Here is the code:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    int i;

    /* first where are we going to send it? */
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total, message_size;
    char *message, response[4096];

    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }

    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(argv[4]);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
        message_size+=strlen("%s %s HTTP/1.0\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(argv[4]);                         /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }

    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/",                 /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"");                 /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/");                /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            strlen(argv[4])>0?argv[4]:"/");                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }

    /* What are we going to send? */
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    free(message);
    return 0;
}

Javascript string/integer comparisons

Always remember when we compare two strings. the comparison happens on chacracter basis. so '2' > '12' is true because the comparison will happen as '2' > '1' and in alphabetical way '2' is always greater than '1' as unicode. SO it will comeout true. I hope this helps.

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

How to change PHP version used by composer

If anyone is still having trouble, remember you can run composer with any php version that you have installed e.g. $ php7.3 -f /usr/local/bin/composer update

Use which composer command to help locate the composer executable.

How to load a model from an HDF5 file in Keras?

load_weights only sets the weights of your network. You still need to define its architecture before calling load_weights:

def create_model():
   model = Sequential()
   model.add(Dense(64, input_dim=14, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5)) 
   model.add(Dense(64, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5))
   model.add(Dense(2, init='uniform'))
   model.add(Activation('softmax'))
   return model

def train():
   model = create_model()
   sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
   model.compile(loss='binary_crossentropy', optimizer=sgd)

   checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
   model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])

def load_trained_model(weights_path):
   model = create_model()
   model.load_weights(weights_path)

Django - Did you forget to register or load this tag?

{% load static %}

Please add this template tag on top of the HTML or base HTML file

What is String pool in Java?

Let's start with a quote from the virtual machine spec:

Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.

This may not occur - This is a hint, that there's something special about String objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:

1: a := "one" 
   --> if(pool[hash("one")] == null)  // true
           pool[hash("one") --> "one"]
       return pool[hash("one")]

2: b := "one" 
  --> if(pool[hash("one")] == null)   // false, "one" already in pool
        pool[hash("one") --> "one"]
      return pool[hash("one")] 

So in this case, variables a and b hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true.

This is not the case if we use the constructor:

1: a := "one"
2: b := new String("one")

Again, "one" is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false

So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).

As programmers we don't have to care much about the String pool, as long as we keep in mind:

  • (a == b) && (a.equals(b)) may be true or false (always use equals to compare Strings)
  • Don't use reflection to change the backing char[] of a String (as you don't know who is actualling using that String)

How to make this Header/Content/Footer layout using CSS?

Using flexbox, this is easy to achieve.

Set the wrapper containing your 3 compartments to display: flex; and give it a height of 100% or 100vh. The height of the wrapper will fill the entire height, and the display: flex; will cause all children of this wrapper which has the appropriate flex-properties (for example flex:1;) to be controlled with the flexbox-magic.

Example markup:

<div class="wrapper">
    <header>I'm a 30px tall header</header>
    <main>I'm the main-content filling the void!</main>
    <footer>I'm a 30px tall footer</footer>
</div>

And CSS to accompany it:

.wrapper {
    height: 100vh;
    display: flex;

    /* Direction of the items, can be row or column */
    flex-direction: column;
}

header,
footer {
    height: 30px;
}

main {
    flex: 1;
}

Here's that code live on Codepen: http://codepen.io/enjikaka/pen/zxdYjX/left

You can see more flexbox-magic here: http://philipwalton.github.io/solved-by-flexbox/

Or find a well made documentation here: http://css-tricks.com/snippets/css/a-guide-to-flexbox/

--[Old answer below]--

Here you go: http://jsfiddle.net/pKvxN/

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Layout</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  header {
    height: 30px;
    background: green;
  }
  footer {
    height: 30px;
    background: red;
  }
</style>
</head>
<body>
  <header>
    <h1>I am a header</h1>
  </header>
  <article>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a ligula dolor.
    </p>
  </article>
  <footer>
    <h4>I am a footer</h4>
  </footer>
</body>
</html>

That works on all modern browsers (FF4+, Chrome, Safari, IE8 and IE9+)

Changing the JFrame title

newTitle is a local variable where you create the fields. So when that functions ends, the variable newTitle, does not exist anymore. (The JTextField that was referenced by newTitle does still exist however.)

Thus, increase the scope of the variable, so that you can access it another method.

public SomeFrame extends JFrame {
   JTextField myTitle;//can be used anywhere in this class

   creationOfTheFields()
   {
   //other code
      myTitle = new JTextField("spam");  
      myTitle.setBounds(80, 40, 225, 20);
      options.add(myTitle);
   //blabla other code
   }

   private void New_Name()  
   {  
      this.setTitle(myTitle.getText());  
   } 
}

Spring Boot Program cannot find main class

I had the same problem. Try this :

Right Click the project -> Maven -> Update Project

Then Re-run the project. Hope it work for you too.

How is OAuth 2 different from OAuth 1?

I see great answers up here but what I miss were some diagrams and since I had to work with Spring Framework I came across their explanation.

I find the following diagrams very useful. They illustrate the difference in communication between parties with OAuth2 and OAuth1.


OAuth 2

enter image description here


OAuth 1

enter image description here

How to call a method after a delay in Android

You can make it much cleaner by using the newly introduced lambda expressions:

new Handler().postDelayed(() -> {/*your code here*/}, time);

Passing additional variables from command line to make

it seems

command args overwrite environment variable

Makefile

send:
    echo $(MESSAGE1) $(MESSAGE2)

Run example

$ MESSAGE1=YES MESSAGE2=NG  make send MESSAGE2=OK
echo YES OK
YES OK

Does PHP have threading?

I know this is a way old question, but you could look at http://phpthreadlib.sourceforge.net/

Bi-directional communication, support for Win32, and no extensions required.

mysql error 1364 Field doesn't have a default values

In phpmyadmin, perform the following:

select @@GLOBAL.sql_mode

In my case, I get the following:

ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES ,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Copy this result and remove STRICT_TRANS_TABLES. Then perform the following:

set GLOBAL sql_mode='ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

How can I set the default value for an HTML <select> element?

Set selected="selected" for the option you want to be the default.

<option selected="selected">
3
</option>

Adding a directory to PATH in Ubuntu

The file .bashrc is read when you start an interactive shell. This is the file that you should update. E.g:

export PATH=$PATH:/opt/ActiveTcl-8.5/bin

Restart the shell for the changes to take effect or source it, i.e.:

source .bashrc

Difference between require, include, require_once and include_once?

Just use require and include.

Because think how to work with include_once or require_once. That is looking for log data which save included or required PHP files. So that is slower than include and require.

if (!defined(php)) {
    include 'php';
    define(php, 1);
}

Just using like this...

How to search for a string in an arraylist

Loop through your list and do a contains or startswith.

ArrayList<String> resList = new ArrayList<String>();
String searchString = "bea";

for (String curVal : list){
  if (curVal.contains(searchString)){
    resList.add(curVal);
  }
}

You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

How to run .jar file by double click on Windows 7 64-bit?

Your problem might also be inside your Java code setting, I mean, if your program somehow could not realize the main class/main file (entry point), it will not launch the the program/.jar (specially application built on IDE's). To solve that on an IDE :

  • Right Click the project > Properties > Run > Browse Main Class > OK.
  • Clean and Rebuild

Try running it now. Hope it helps

How to open a URL in a new Tab using JavaScript or jQuery?

You can easily create a new tab; do like the following:

function newTab() {
     var form = document.createElement("form");
     form.method = "GET";
     form.action = "http://www.example.com";
     form.target = "_blank";
     document.body.appendChild(form);
     form.submit();
}

Large Numbers in Java

Checkout BigDecimal and BigInteger.

Loop through childNodes

Couldn't resist to add another method, using childElementCount. It returns the number of child element nodes from a given parent, so you can loop over it.

for(var i=0, len = parent.childElementCount ; i < len; ++i){
    ... do something with parent.children[i]
    }

Passing data to components in vue.js

A global JS variable (object) can be used to pass data between components. Example: Passing data from Ammlogin.vue to Options.vue. In Ammlogin.vue rspData is set to the response from the server. In Options.vue the response from the server is made available via rspData.

index.html:

<script>
    var rspData; // global - transfer data between components
</script>

Ammlogin.vue:

....    
export default {
data: function() {return vueData}, 
methods: {
    login: function(event){
        event.preventDefault(); // otherwise the page is submitted...
        vueData.errortxt = "";
        axios.post('http://vueamm...../actions.php', { action: this.$data.action, user: this.$data.user, password: this.$data.password})
            .then(function (response) {
                vueData.user = '';
                vueData.password = '';
                // activate v-link via JS click...
                // JSON.parse is not needed because it is already an object
                if (response.data.result === "ok") {
                    rspData = response.data; // set global rspData
                    document.getElementById("loginid").click();
                } else {
                    vueData.errortxt = "Felaktig avändare eller lösenord!"
                }
            })
            .catch(function (error) {
                // Wu oh! Something went wrong
                vueData.errortxt = error.message;
            });
    },
....

Options.vue:

<template>
<main-layout>
  <p>Alternativ</p>
  <p>Resultat: {{rspData.result}}</p>
  <p>Meddelande: {{rspData.data}}</p>
  <v-link href='/'>Logga ut</v-link>
</main-layout>
</template>
<script>
 import MainLayout from '../layouts/Main.vue'
 import VLink from '../components/VLink.vue'
 var optData = { rspData: rspData}; // rspData is global
 export default {
   data: function() {return optData},
   components: {
     MainLayout,
     VLink
   }
 }
</script>

SQL Server tables: what is the difference between @, # and ##?

CREATE TABLE #t

Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.

CREATE TABLE ##t

Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

You can do it using the "collapse" directive: http://jsfiddle.net/iscrow/Es4L3/ (check the two "Note" in the HTML).

        <!-- Note: set the initial collapsed state and change it when clicking -->
        <a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
        </a>
        <a class="brand" href="#">Title</a>
           <!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
           <div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
              <ul class="nav">

That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.


Release 0.14 added a uib- prefix to components:

https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes

Change: collapse to uib-collapse.

How to start nginx via different port(other than 80)

Follow this: Open your config file

vi /etc/nginx/conf.d/default.conf

Change port number on which you are listening;

listen       81;
server_name  localhost;

Add a rule to iptables

 vi /etc/sysconfig/iptables 
-A INPUT -m state --state NEW -m tcp -p tcp --dport 81 -j ACCEPT

Restart IPtables

 service iptables restart;

Restart the nginx server

service nginx restart

Access yr nginx server files on port 81

How Should I Set Default Python Version In Windows?

Use SET command in Windows CMD to temporarily set the default python for the current session.

SET PATH=C:\Program Files\Python 3.5

Abstract class in Java

From oracle documentation

Abstract Methods and Classes:

An abstract class is a class that is declared abstract—it may or may not include abstract methods

Abstract classes cannot be instantiated, but they can be subclassed

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must be declared abstract, as in:

public abstract class GraphicObject {
   // declare fields
   // declare nonabstract methods
   abstract void draw();
}

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

Since abstract classes and interfaces are related, have a look at below SE questions:

What is the difference between an interface and abstract class?

How should I have explained the difference between an Interface and an Abstract class?

Compile error: package javax.servlet does not exist

Copy the file "servlet-api.jar" from location YOUR_INSTILLATION_PATH\tomcat\lib\servlet-api.jar and Paste the file into your Java Directory YOUR_INSTILLATION_PATH\Java\jdk1.8.0_121\jre\lib\ext

this will work (tested).

DateTime format to SQL format using C#

I think the problem was the two single quotes missing.

This is the sql I run to the MSSMS:

WHERE checktime >= '2019-01-24 15:01:36.000' AND checktime <= '2019-01-25 16:01:36.000'

As you can see there are two single quotes, so your codes must be:

string sqlFormattedDate = "'" + myDateTime.Date.ToString("yyyy-MM-dd") + " " + myDateTime.TimeOfDay.ToString("HH:mm:ss") + "'";

Use single quotes for every string in MSSQL or even in MySQL. I hope this helps.