Programs & Examples On #Powerdesigner

PowerDesigner is an enterprise modeling tool from SAP.

SQL Server - stop or break execution of a SQL script

I would not use RAISERROR- SQL has IF statements that can be used for this purpose. Do your validation and lookups and set local variables, then use the value of the variables in IF statements to make the inserts conditional.

You wouldn't need to check a variable result of every validation test. You could usually do this with only one flag variable to confirm all conditions passed:

declare @valid bit

set @valid = 1

if -- Condition(s)
begin
  print 'Condition(s) failed.'
  set @valid = 0
end

-- Additional validation with similar structure

-- Final check that validation passed
if @valid = 1
begin
  print 'Validation succeeded.'

  -- Do work
end

Even if your validation is more complex, you should only need a few flag variables to include in your final check(s).

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

The host should be specified in each environment's config file. Eg:

config/environments/development.rb

See this question and this question.

How to remove outliers from a dataset

The boxplot function returns the values used to do the plotting (which is actually then done by bxp():

bstats <- boxplot(count ~ spray, data = InsectSprays, col = "lightgray") 
#need to "waste" this plot
bstats$out <- NULL
bstats$group <- NULL
bxp(bstats)  # this will plot without any outlier points

I purposely did not answer the specific question because I consider it statistical malpractice to remove "outliers". I consider it acceptable practice to not plot them in a boxplot, but removing them just because they exceed some number of standard deviations or some number of inter-quartile widths is a systematic and unscientific mangling of the observational record.

How to implement the ReLU function in Numpy

This is more precise implementation:

def ReLU(x):
    return abs(x) * (x > 0)

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

How do I set the maximum line length in PyCharm?

For PyCharm 4

File >> Settings >> Editor >> Code Style: Right margin (columns)

suggestion: Take a look at other options in that tab, they're very helpful

Can't push to GitHub because of large file which I already deleted

rather than doing complicated stuff, copy your repo (on your computer) to another place. delete the large file. do a couple of push and pull. Then some of your files will be messed up having things like "<<<<<< HEAD". Just copy your backup into the old folder on the disk. Do another add, commit, push!

ImportError: No module named pythoncom

You should be using pip to install packages, since it gives you uninstall capabilities.

Also, look into virtualenv. It works well with pip and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.

How to check the version before installing a package using apt-get?

OK, I found it.

apt-cache policy <package name> will show the version details.

It also shows which version is currently installed and which versions are available to install.

For example, apt-cache policy hylafax+

Short form for Java if statement

To avoid calling .getName() twice I would use

name = city.getName();
if (name == null) name = "N/A";

Remove duplicate rows in MySQL

-- Here is what I used, and it works:
create table temp_table like my_table;
-- t_id is my unique column
insert into temp_table (id) select id from my_table GROUP by t_id;
delete from my_table where id not in (select id from temp_table);
drop table temp_table;

Using Java 8 to convert a list of objects into a string obtained from the toString() method

There is a collector joining in the API. It's a static method in Collectors.

list.stream().map(Object::toString).collect(Collectors.joining(","))

Not perfect because of the necessary call of toString, but works. Different delimiters are possible.

Linking to a specific part of a web page

That is only possible if that site has declared anchors in the page. It is done by giving a tag a name or id attribute, so look for any of those close to where you want to link to.

And then the syntax would be

<a href="page.html#anchor">text</a>

Why is visible="false" not working for a plain html table?

For a similar post a long time ago there seems to be issues with making table visibility hidden.

You have two options, one is to use the display:none attribute.

Or two wrap the table in a div and make the div hidden.

<div id="wrapper" style="visibility:hidden">
    <table>
        <tr>
            <td>
            Content
            </td>
        </tr>
    </table>
</div>

Unable to run Java GUI programs with Ubuntu

This command worked for me.

Sudo dnf install java-1.8.0-openjdk (Fedora)

Sudo apt-get install java-1.8.0-openjdk

Should work for Ubuntu.

disabling spring security in spring boot app

security.ignored is deprecated since Spring Boot 2.

For me simply extend the Annotation of your Application class did the Trick:

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

Toggle visibility property of div

To do it with an effect like with $.fadeIn() and $.fadeOut() you can use transitions

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 1s linear;
}
.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 1s, opacity 1s linear;
}

Conversion from List<T> to array T[]

To go twice as fast by using multiple processor cores HPCsharp nuget package provides:

list.ToArrayPar();

Should image size be defined in the img tag height/width attributes or in CSS?

While it's ok to use inline styles, your purposes may better be served by including an external CSS file on the page. This way you could define a class of image (i.e. 'Thumbnail', 'Photo', 'Large', etc) and assign it a constant size. This will help when you end up with images requiring the same placement across multiple pages.

Like this:

In your header:
<link type="text/css" rel="stylesheet" href="css/style.css" />

Your HTML:
<img class="thumbnail" src="images/academia_vs_business.png" alt="" />

In css/style.css:
img.thumbnail {
   width: 75px;
   height: 75px;
}

If you'd like to use inline styles though, it's probably best to set the width and height using the style attribute for the sake of readability.

Adding external library into Qt Creator project

The proper way to do this is like this:

LIBS += -L/path/to -lpsapi

This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.

In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_ variable, e.g.:

LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi

ICommand MVVM implementation

@Carlo I really like your implementation of this, but I wanted to share my version and how to use it in my ViewModel

First implement ICommand

public class Command : ICommand
{
    public delegate void ICommandOnExecute();
    public delegate bool ICommandOnCanExecute();

    private ICommandOnExecute _execute;
    private ICommandOnCanExecute _canExecute;

    public Command(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod = null)
    {
        _execute = onExecuteMethod;
        _canExecute = onCanExecuteMethod;
    }

    #region ICommand Members

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute?.Invoke() ?? true;
    }

    public void Execute(object parameter)
    {
        _execute?.Invoke();
    }

    #endregion
}

Notice I have removed the parameter from ICommandOnExecute and ICommandOnCanExecute and added a null to the constructor

Then to use in the ViewModel

public Command CommandToRun_WithCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        }, () =>
        {
            // Code to check to see if we can run 
            // Return true or false
        });
    }
}

public Command CommandToRun_NoCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        });
    }
}

I just find this way cleaner as I don't need to assign variables and then instantiate, it all done in one go.

Programmatically add custom event in the iPhone Calendar

Calendar access is being added in iPhone OS 4.0:

Calendar Access
Apps can now create and edit events directly in the Calendar app with Event Kit.
Create recurring events, set up start and end times and assign them to any calendar on the device.

Adding an .env file to React Project

If in case you are getting the values as undefined, then you should consider restarting the node server and recompile again.

Generate PDF from Swagger API documentation

Checkout https://mrin9.github.io/RapiPdf a custom element with plenty of customization and localization feature.

Disclaimer: I am the author of this package

Save bitmap to file function

implementation save bitmap and load bitmap directly. fast and ease on mfc class

void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
{
CImage img;
PBITMAPINFO bmi;
BITMAPINFOHEADER Info;
BITMAPFILEHEADER bFileHeader;
CBitmap bm;     
CFile file2;
file2.Open(destination, CFile::modeRead | CFile::typeBinary);
file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
file2.Read(&Info, sizeof(BITMAPINFOHEADER));    
BYTE ch;
int width = Info.biWidth;
int height = Info.biHeight;
if (height < 0)height = -height;
int size1 = width*height * 3;
int size2 = ((width * 24 + 31) / 32) * 4 * height;
int widthnew = (size2 - size1) / height;
BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
//////////////////////////
HGDIOBJ old;
unsigned char alpha = 0;    
int z = 0;  
z = 0;
int gap = (size2 - size1) / height;
for (int y = 0;y < height;y++)
{
    for (int x = 0;x < width*3;x++)
    {
        file2.Read(&ch, 1);
        buffer[z] = ch;
        z++;
    }
    for (int z1 = 0;z1 <gap;z1++)
    {
        file2.Read(&ch,1);
    }
}
bm.CreateCompatibleBitmap(&memdc, width, height);
bm.SetBitmapBits(size1,buffer);
old = memdc.SelectObject(&bm);   
///////////////////////////  
 //bm.SetBitmapBits(size1, buffer);     
 GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
 memdc.SelectObject(&old);
 bm.DeleteObject();
 GlobalFree(buffer);     
 file2.Close();
 }
 void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
  {     
BITMAP bm;
PBITMAPINFO bmi;
BITMAPINFOHEADER Info;
BITMAPFILEHEADER bFileHeader;
CFile file1;
            CSize size = bit1.GetBitmap(&bm);
 int z = 0;  
 BYTE ch = 0;
 size.cx = bm.bmWidth;
 size.cy = bm.bmHeight;
 int width = size.cx;    
 int size1 = (size.cx)*(size.cy);
 int size2 = size1 * 3;  
 size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;     
 BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);               
 bFileHeader.bfType = 'B' + ('M' << 8); 
 bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
 bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
 bFileHeader.bfReserved1 = 0;
 bFileHeader.bfReserved2 = 0;   
 Info.biSize = sizeof(BITMAPINFOHEADER);
 Info.biPlanes = 1;
 Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
 Info.biCompression = BI_RGB;
 Info.biWidth =bm.bmWidth;
 Info.biHeight =-bm.bmHeight;///reverse pic if negative height
 Info.biSizeImage =size1;
 Info.biClrImportant = 0;
 if (bm.bmBitsPixel <= 8)
 {
     Info.biClrUsed = 1 << bm.bmBitsPixel;
 }else
 Info.biClrUsed = 0;
 Info.biXPelsPerMeter = 0;
 Info.biYPelsPerMeter = 0;
 bit1.GetBitmapBits(size2, buffer);      
 file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
 file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
 file1.Write(&Info, sizeof(BITMAPINFOHEADER));
 unsigned char alpha = 0;    
 for (int y = 0;y<size.cy;y++)
 {
     for (int x = 0;x<size.cx;x++)
     {
         //for reverse picture below
         //z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;          
     z = (((y)*size.cx) + (x)) * 3;
     file1.Write(&buffer[z], 1);
     file1.Write(&buffer[z + 1], 1);
     file1.Write(&buffer[z + 2], 1);
     }               
     for (int z = 0;z < (size1 - size2) / size.cy;z++)
     {
         file1.Write(&alpha, 1);
     }
 }   
 GlobalFree(buffer);     
 file1.Close();  
 file1.m_hFile = NULL;
        }

How to show multiline text in a table cell

style="white-space:pre-wrap; word-wrap:break-word"

This would solve the issue of new line. pre tag would add additional CSS than required.

How do I get the last day of a month?

You can find the last date of any month by this code:

var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month);
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth);

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

How do I dynamically assign properties to an object in TypeScript?

I tend to put any on the other side i.e. var foo:IFoo = <any>{}; So something like this is still typesafe:

interface IFoo{
    bar:string;
    baz:string;
    boo:string;     
}

// How I tend to intialize 
var foo:IFoo = <any>{};

foo.bar = "asdf";
foo.baz = "boo";
foo.boo = "boo";

// the following is an error, 
// so you haven't lost type safety
foo.bar = 123; 

Alternatively you can mark these properties as optional:

interface IFoo{
    bar?:string;
    baz?:string;
    boo?:string;    
}

// Now your simple initialization works
var foo:IFoo = {};

Try it online

How to Parse JSON Array with Gson

[
      {
           id : '1',
           title: 'sample title',
           ....
      },
      {
           id : '2',
           title: 'sample title',
           ....
     },
      ...
 ]

Check Easy code for this output

 Gson gson=new GsonBuilder().create();
                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

How to remove empty lines with or without whitespace in Python

I use this solution to delete empty lines and join everything together as one line:

match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above

PHP Redirect with POST data

$_SESSION is your friend if you don't want to mess with Javascript

Let's say you're trying to pass an email:

On page A:

// Start the session
session_start();

// Set session variables
$_SESSION["email"] = "[email protected]";

header('Location: page_b.php');

And on Page B:

// Start the session
session_start();

// Show me the session!  
echo "<pre>";
print_r($_SESSION);
echo "</pre>";

To destroy the session

unset($_SESSION['email']);
session_destroy();

Entity Framework code first unique column

In Entity Framework 6.1+ you can use this attribute on your model:

[Index(IsUnique=true)]

You can find it in this namespace:

using System.ComponentModel.DataAnnotations.Schema;

If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First:

Column 'x' in table 'dbo.y' is of a type that is invalid for use as a key column in an index.

The reason is because of this:

SQL Server retains the 900-byte limit for the maximum total size of all index key columns."

(from: http://msdn.microsoft.com/en-us/library/ms191241.aspx )

You can solve this by setting a maximum string length on your model:

[StringLength(450)]

Your model will look like this now in EF CF 6.1+:

public class User
{
   public int UserId{get;set;}
   [StringLength(450)]
   [Index(IsUnique=true)]
   public string UserName{get;set;}
}

Update:

if you use Fluent:

  public class UserMap : EntityTypeConfiguration<User>
  {
    public UserMap()
    {
      // ....
      Property(x => x.Name).IsRequired().HasMaxLength(450).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index") { IsUnique = true } }));
    }
  }

and use in your modelBuilder:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  // ...
  modelBuilder.Configurations.Add(new UserMap());
  // ...
}

Update 2

for EntityFrameworkCore see also this topic: https://github.com/aspnet/EntityFrameworkCore/issues/1698

Update 3

for EF6.2 see: https://github.com/aspnet/EntityFramework6/issues/274

Update 4

ASP.NET Core Mvc 2.2 with EF Core:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Unique { get; set; }

Setting the correct PATH for Eclipse

I have resolved this problem by adding or changing variables in environment variables. Go to Win7 -> My Computer - > Properties - > Advanced system settings -> environment Variables

  1. If there is no variable JAVA_HOME, add it with value of variable, with route to folder where your JDK installed, for examle C:\Program Files\Java\jdk-11.0.2
  2. If there is no variable PATH or it have another value, change the value of variable to C:\Program Files\Java\jdk-11.0.2\bin or add variable PATH with this value

Good Luck

Passing vector by reference

You can pass the container by reference in order to modify it in the function. What other answers haven’t addressed is that std::vector does not have a push_front member function. You can use the insert() member function on vector for O(n) insertion:

void do_something(int el, std::vector<int> &arr){
    arr.insert(arr.begin(), el);
}

Or use std::deque instead for amortised O(1) insertion:

void do_something(int el, std::deque<int> &arr){
    arr.push_front(el);
}

Create hyperlink to another sheet

This macro adds a hyperlink to the worksheet with the same name, I also modify the range to be more flexible, just change the first cell in the code. Works like a charm

Sub hyper()
 Dim cl As Range
 Dim nS As String

 Set MyRange = Sheets("Sheet1").Range("B16")
 Set MyRange = Range(MyRange, MyRange.End(xlDown))

 For Each cl In MyRange
  nS = cl.Value
  cl.Hyperlinks.Add Anchor:=cl, Address:="", SubAddress:="'" & nS & "'" & "!B16", TextToDisplay:=nS
 Next
End Sub

Rebasing a Git merge commit

It looks like what you want to do is remove your first merge. You could follow the following procedure:

git checkout master      # Let's make sure we are on master branch
git reset --hard master~ # Let's get back to master before the merge
git pull                 # or git merge remote/master
git merge topic

That would give you what you want.

How to quickly and conveniently create a one element arraylist

Seeing as Guava gets a mention, I thought I would also suggest Eclipse Collections (formerly known as GS Collections).

The following examples all return a List with a single item.

Lists.mutable.of("Just one item");
Lists.mutable.with("Or use with");
Lists.immutable.of("Maybe it must be immutable?");
Lists.immutable.with("And use with if you want");

There are similar methods for other collections.

Simplest way to set image as JPanel background

Simplest way to set image as JPanel background

Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.

See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:

  1. scaled
  2. tiled
  3. actual

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

My solution was rather simple: backup everything from the application, uninstall it, delete everything from the remaining folders (but not the folders so I won't have to grant the same permissions again) then copy back the files from the backup.

AES Encrypt and Decrypt

You can just copy & paste these methods (Swift 4+):

    class func encryptMessage(message: String, encryptionKey: String, iv: String) -> String? {
        if let aes = try? AES(key: encryptionKey, iv: iv),
            let encrypted = try? aes.encrypt(Array<UInt8>(message.utf8)) {
            return encrypted.toHexString()
        }
        return nil
    }

    class func decryptMessage(encryptedMessage: String, encryptionKey: String, iv: String) -> String? {
        if let aes = try? AES(key: encryptionKey, iv: iv),
            let decrypted = try? aes.decrypt(Array<UInt8>(hex: encryptedMessage)) {
            return String(data: Data(bytes: decrypted), encoding: .utf8)
        }
        return nil
    }

Example:

let encryptMessage = encryptMessage(message: "Hello World!", encryptionKey: "mykeymykeymykey1", iv: "myivmyivmyivmyiv")    
// Output of encryptMessage is: 649849a5e700d540f72c4429498bf9f4

let decryptedMessage = decryptMessage(encryptedMessage: encryptMessage, encryptionKey: "mykeymykeymykey1", iv: "myivmyivmyivmyiv")
// Output of decryptedMessage is: Hello World!

Don't forget encryptionKey & iv should be 16 bytes.


How do you test a public/private DSA keypair?

If it returns nothing, then they match:

cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
ssh -i $HOME/.ssh/id_rsa localhost

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How can I get Docker Linux container information from within the container itself?

Unless overridden, the hostname seems to be the short container id in Docker 1.12

root@d2258e6dec11:/project# cat /etc/hostname
d2258e6dec11

Externally

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED                 STATUS                      PORTS               NAMES
d2258e6dec11        300518d26271        "bash"              5 minutes ago       

$ docker -v
Docker version 1.12.0, build 8eab29e, experimental

How do I remove the passphrase for the SSH key without having to create a new key?

On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.

How to call a method daily, at specific time, in C#?

I know this is old but how about this:

Build a timer to fire at startup that calculates time to next run time. At the first call of the runtime, cancel the first timer and start a new daily timer. change daily to hourly or whatever you want the periodicity to be.

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

edit: As lots of people seem to want to do this, I have written up a short guide with a more general use case here https://www.atlascode.com/bootstrap-fixed-width-sidebars/. Hope it helps.

The bootstrap3 grid system supports row nesting which allows you to adjust the root row to allow fixed width side menus.

You need to put in a padding-left on the root row, then have a child row which contains your normal grid layout elements.

Here is how I usually do this http://jsfiddle.net/u9gjjebj/

html

<div class="container">
    <div class="row">
        <div class="col-fixed-240">Fixed 240px</div>
        <div class="col-fixed-160">Fixed 160px</div>
        <div class="col-md-12 col-offset-400">
            <div class="row">
            Standard grid system content here
            </div>
        </div>
    </div>
</div>

css

.col-fixed-240{
    width:240px;
    background:red;
    position:fixed;
    height:100%;
    z-index:1;
}

.col-fixed-160{
    margin-left:240px;
    width:160px;
    background:blue;
    position:fixed;
    height:100%;
    z-index:1;
}

.col-offset-400{
    padding-left:415px;
    z-index:0;
}

Angular - How to apply [ngStyle] conditions

[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

GZIPInputStream reading line by line

BufferedReader in = new BufferedReader(new InputStreamReader(
        new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"))));

String content;

while ((content = in.readLine()) != null)

   System.out.println(content);

Get value (String) of ArrayList<ArrayList<String>>(); in Java

Because the second element is null after you clear the list.

Use:

String s = myList.get(0);

And remember, index 0 is the first element.

python - checking odd/even numbers and changing outputs on number size

The modulo 2 solutions with %2 is good, but that requires a division and a subtraction. Because computers use binary arithmetic, a much more efficient solution is:

# This first solution does not produce a Boolean value. 
is_odd_if_zero = value & 1

# or

is_odd = (value & 1) == 1

# or

is_even = (value & 1) == 0

Checking if a collection is null or empty in Groovy

There is indeed a Groovier Way.

if(members){
    //Some work
}

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

How do I use WPF bindings with RelativeSource?

I just posted another solution for accessing the DataContext of a parent element in Silverlight that works for me. It uses Binding ElementName.

CSS two div width 50% in one line with line break in file

<div id="wrapper" style="width: 400px">
    <div id="left" style="float: left; width: 200px;">Left</div>
    <div id="right" style="float: right; width: 200px;">Left</div>
    <div style="clear: both;"></div>
</div>

I know this question wanted inline block, but try to view http://jsfiddle.net/N9mzE/1/ in IE 7 (the oldest browser supported where I work). The divs are not side by side.

OP said he did not want to use floats because he did not like them. Well...in my opinion, making good webpages that does not look weird in any browsers should be the maingoal, and you do this by using floats.

Honestly, I can see the problem. Floats are fantastic.

JavaScript check if variable exists (is defined/initialized)

There is another short hand way to check this, when you perform simple assignments and related checks. Simply use Conditional (Ternary) Operator.

var values = typeof variable !== 'undefined' ? variable : '';

Also this will be helpful, when you try to declare the Global variable with instance assignment of the reference variable.

If you wanted to check variable shouldn't be undefined or null. Then perform below check.

When the variable is declared, and if you want to check the value, this is even Simple: and it would perform undefined and null checks together.

var values = variable ? variable : '';

How do you select a particular option in a SELECT element in jQuery?

i'll go with:-

$("select#my-select option") .each(function() { this.selected = (this.text == myVal); });

Access denied for user 'homestead'@'localhost' (using password: YES)

I just wanted to post this because this issue frustrated me for about 3 hours today. I have not tried any of the methods listed in the other answers, though they all seem reasonable. In fact, I was just about to try going through each of the above proposed solutions, but somehow I got this stroke of inspiration. Here is what worked for me to get me back working -- YMMV:

1) Find your .env file. 2) Rename your .env file to something else. Laravel 5 must be using this file as an override for settings somewhere else in the framework. I renamed mine to .env.old 3) You may need to restart your web server, but I did not have to.

Good luck!

How can I concatenate a string within a loop in JSTL/JSP?

You're using JSTL 2.0 right? You don't need to put <c:out/> around all variables. Have you tried something like this?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${myVar}${currentItem}" />
</c:forEach>

Edit: Beaten by the above

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

A better solution (mentioned by @KrisNuttycombe):

git diff fc17405...ee2de56

for the merge commit:

commit 0e1329e551a5700614a2a34d8101e92fd9f2cad6 (HEAD, master)
Merge: fc17405 ee2de56
Author: Tilman Vogel <email@email>
Date:   Tue Feb 22 00:27:17 2011 +0100

to show all of the changes on ee2de56 that are reachable from commits on fc17405. Note the order of the commit hashes - it's the same as shown in the merge info: Merge: fc17405 ee2de56

Also note the 3 dots ... instead of two!

For a list of changed files, you can use:

git diff fc17405...ee2de56 --name-only

Cookie blocked/not saved in IFRAME in Internet Explorer

For anyone trying to get the P3P Compact Policy working with static content:

It is only possible if you are able to send custom server-side response headers with the static content.

For a more detailed explanation see my answer here: Set P3P code in HTML

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

IMHO, the reason why 2 queries

SELECT * FROM count_test WHERE b = 666 ORDER BY c LIMIT 5;
SELECT count(*) FROM count_test WHERE b = 666;

are faster than using SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS * FROM count_test WHERE b = 555 ORDER BY c LIMIT 5;

has to be seen as a particular case.

It in facts depends on the selectivity of the WHERE clause compared to the selectivity of the implicit one equivalent to the ORDER + LIMIT.

As Arvids told in comment (http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-1174394), the fact that the EXPLAIN use, or not, a temporay table, should be a good base for knowing if SCFR will be faster or not.

But, as I added (http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-8166482), the result really, really depends on the case. For a particular paginator, you could get to the conclusion that “for the 3 first pages, use 2 queries; for the following pages, use a SCFR” !

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

My problem solved with these :

1- Add this to your head :

<base href="/" />

2- Use this in app.config

$locationProvider.html5Mode(true);

restrict edittext to single line

Everyone's showing the XML way, except one person showed calling EditText's setMaxLines method. However, when I did that, it didn't work. One thing that did work for me was setting the input type.

EditText editText = new EditText(this);
editText.setInputType(InputType.TYPE_CLASS_TEXT);

This allows A-Z, a-z, 0-9, and special characters, but does not allow enter to be pressed. When you press enter, it'll go to the next GUI component, if applicable in your application.

You may also want to set the maximum number of characters that can be put into that EditText, or else it'll push whatever's to the right of it off the screen, or just start trailing off the screen itself. You can do this like this:

InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(8);
editText.setFilters(filters);

This sets the max characters to 8 in that EditText. Hope all this helps you.

PowerShell: Comparing dates

I wanted to show how powerful it can be aside from just checking "-lt".

Example: I used it to calculate time differences take from Windows event view Application log:

Get the difference between the two date times:

PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))

Object created:

PS> $Obj


Days              : 0
Hours             : 0
Minutes           : 31
Seconds           : 0
Milliseconds      : 0
Ticks             : 18600000000
TotalDays         : 0.0215277777777778
TotalHours        : 0.516666666666667
TotalMinutes      : 31
TotalSeconds      : 1860
TotalMilliseconds : 1860000

Access an item directly:

PS> $Obj.Minutes
31

How can one run multiple versions of PHP 5.x on a development LAMP server?

Understanding that you're probably talking about a local/desktop machine and would probably like to continue talking about a local/desktop machine, I'll throw an alternative out there for you just in case it might help you or someone else:

Set up multiple virtual server instances in the cloud, and share your code between them as a git repository (or mercurial, I suppose, though I have no personal experience all you really need is something decentralized). This has the benefit of giving you as close to a production experience as possible, and if you have experience setting up servers then it's not that complicated (or expensive, if you just want to spin a server up, do what you need to do, then spin it down again, then you're talking about a few cents up to say 50 cents, up to a few bucks if you just leave it running).

I do all of my project development in the cloud these days and I've found it much simpler to manage the infrastructure than I ever did when using local/non-virtualized installs, and it makes this sort of side-by-side scenario fairly straight forward. I just wanted to throw the idea out there if you hadn't considered it.

Dropdown using javascript onchange

Something like this should do the trick

<select id="leave" onchange="leaveChange()">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

<div id="message"></div>

Javascript

function leaveChange() {
    if (document.getElementById("leave").value != "100"){
        document.getElementById("message").innerHTML = "Common message";
    }     
    else{
        document.getElementById("message").innerHTML = "Having a Baby!!";
    }        
}

jsFiddle Demo

A shorter version and more general could be

HTML

<select id="leave" onchange="leaveChange(this)">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

Javascript

function leaveChange(control) {
    var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
    document.getElementById("message").innerHTML = msg;
}

How I can check if an object is null in ruby on rails 2?

You can use the simple not flag to validate that. Example

if !@objectname

This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw

*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass

An ideal nil check would be like:

!@objectname || @objectname.nil? || @objectname.empty?

TempData keep() vs peek()

Just finished understanding Peek and Keep and had same confusion initially. The confusion arises becauses TempData behaves differently under different condition. You can watch this video which explains the Keep and Peek with demonstration https://www.facebook.com/video.php?v=689393794478113

Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”.

If we understand these 4 points you would see more clarity.Below is a diagram with all 4 conditions, read the third and fourth point which talks about Peek and Keep.

enter image description here

Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.

Condition 2 ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.

string str = TempData["MyData"];

Even if you are displaying it’s a normal read like the code below.

@TempData["MyData"];

Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.

@TempData["MyData"];
TempData.Keep("MyData");

Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.

string str = TempData.Peek("Td").ToString();

Reference :- http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion

How to draw a line with matplotlib?

Just want to mention another option here.

You can compute the coefficients using numpy.polyfit(), and feed the coefficients to numpy.poly1d(). This function can construct polynomials using the coefficients, you can find more examples here

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.poly1d.html

Let's say, given two data points (-0.3, -0.5) and (0.8, 0.8)

import numpy as np
import matplotlib.pyplot as plt

# compute coefficients
coefficients = np.polyfit([-0.3, 0.8], [-0.5, 0.8], 1) 

# create a polynomial object with the coefficients
polynomial = np.poly1d(coefficients)

# for the line to extend beyond the two points, 
# create the linespace using the min and max of the x_lim
# I'm using -1 and 1 here
x_axis = np.linspace(-1, 1)

# compute the y for each x using the polynomial
y_axis = polynomial(x_axis)

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
axes.set_xlim(-1, 1)
axes.set_ylim(-1, 1)
axes.plot(x_axis, y_axis)
axes.plot(-0.3, -0.5, 0.8, 0.8, marker='o', color='red')

enter image description here

Hope it helps.

Find location of a removable SD card

If you look at the source code for android.os.Environment you will see that Android relies heavily on environment variables for paths. You can use the "SECONDARY_STORAGE" environment variable to find the path to the removable sd card.

/**
 * Get a file using an environmental variable.
 *
 * @param variableName
 *         The Environment variable name.
 * @param paths
 *         Any paths to the file if the Environment variable was not found.
 * @return the File or {@code null} if the File could not be located.
 */
private static File getDirectory(String variableName, String... paths) {
    String path = System.getenv(variableName);
    if (!TextUtils.isEmpty(path)) {
        if (path.contains(":")) {
            for (String _path : path.split(":")) {
                File file = new File(_path);
                if (file.exists()) {
                    return file;
                }
            }
        } else {
            File file = new File(path);
            if (file.exists()) {
                return file;
            }
        }
    }
    if (paths != null && paths.length > 0) {
        for (String _path : paths) {
            File file = new File(_path);
            if (file.exists()) {
                return file;
            }
        }
    }
    return null;
}

Example usage:

public static final File REMOVABLE_STORAGE = getDirectory("SECONDARY_STORAGE");

Pointers, smart pointers or shared pointers?

To add a small bit to Sydius' answer, smart pointers will often provide a more stable solution by catching many easy to make errors. Raw pointers will have some perfromance advantages and can be more flexible in certain circumstances. You may also be forced to use raw pointers when linking into certain 3rd party libraries.

Load jQuery with Javascript and use jQuery

HTML:

<html>
  <head>

  </head>
  <body>

    <div id='status'>jQuery is not loaded yet.</div>
    <input type='button' value='Click here to load it.' onclick='load()' />

  </body>
</html>   

Script:

   <script>

        load = function() {
          load.getScript("jquery-1.7.2.js");
          load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
        }

        // dynamically load any javascript file.
        load.getScript = function(filename) {
          var script = document.createElement('script')
          script.setAttribute("type","text/javascript")
          script.setAttribute("src", filename)
          if (typeof script!="undefined")
          document.getElementsByTagName("head")[0].appendChild(script)
        }

        </script>

No appenders could be found for logger(log4j)?

First of all: Create a log4j.properties file

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Place it in src/main/resources/

After that, use this 2 dependencies:

<dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>

It is necessary to add this final dependency to POM file:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

This was enough for me:

sudo apt-get install build-essential

How to get JSON Key and Value?

First, I see you're using an explicit $.parseJSON(). If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.

To iterate through the first item in the array you've got there, use code like this:

var firstItem = response.d[0];

for(key in firstItem) {
  console.log(key + ':' + firstItem[key]);
}

If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d and then use this code inside that outer loop.

What is the javascript filename naming convention?

The question in the link you gave talks about naming of JavaScript variables, not about file naming, so forget about that for the context in which you ask your question.

As to file naming, it is purely a matter of preference and taste. I prefer naming files with hyphens because then I don't have to reach for the shift key, as I do when dealing with camelCase file names; and because I don't have to worry about differences between Windows and Linux file names (Windows file names are case-insensitive, at least through XP).

So the answer, like so many, is "it depends" or "it's up to you."

The one rule you should follow is to be consistent in the convention you choose.

Global environment variables in a shell script

When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:

. ./setfoo.sh

This executes it in the context of the current shell, not as a sub shell.

From the bash man page:

. filename [arguments]
source filename [arguments]

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

If filename does not contain a slash, file names in PATH are used to find the directory containing filename.

The file searched for in PATH need not be executable. When bash is not in POSIX mode, the current directory is searched if no file is found in PATH.

If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.

If any arguments are supplied, they become the positional parameters when filename is executed.

Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

Java swing application, close one window and open another when button is clicked

Here is an example:

enter image description here

enter image description here

StartupWindow.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class StartupWindow extends JFrame implements ActionListener
{
    private JButton btn;

    public StartupWindow()
    {
        super("Simple GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn = new JButton("Open the other JFrame!");
        btn.addActionListener(this);
        btn.setActionCommand("Open");
        add(btn);
        pack();

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();

        if(cmd.equals("Open"))
        {
            dispose();
            new AnotherJFrame();
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run()
            {
                new StartupWindow().setVisible(true);
            }

        });
    }
}

AnotherJFrame.java

import javax.swing.JFrame;
import javax.swing.JLabel;

public class AnotherJFrame extends JFrame
{
    public AnotherJFrame()
    {
        super("Another GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JLabel("Empty JFrame"));
        pack();
        setVisible(true);
    }
}

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

In my case, another developer had removed some of the tables from the underlying database. When I realised this, and removed these tables from the entity, the problem was solved. Wasn't as obvious as it sounds.

Create instance of generic type whose constructor requires a parameter?

It is still possible, with high performance, by doing the following:

    //
    public List<R> GetAllItems<R>() where R : IBaseRO, new() {
        var list = new List<R>();
        using ( var wl = new ReaderLock<T>( this ) ) {
            foreach ( var bo in this.items ) {
                T t = bo.Value.Data as T;
                R r = new R();
                r.Initialize( t );
                list.Add( r );
            }
        }
        return list;
    }

and

    //
///<summary>Base class for read-only objects</summary>
public partial interface IBaseRO  {
    void Initialize( IDTO dto );
    void Initialize( object value );
}

The relevant classes then have to derive from this interface and initialize accordingly. Please note, that in my case, this code is part of a surrounding class, which already has <T> as generic parameter. R, in my case, also is a read-only class. IMO, the public availability of Initialize() functions has no negative effect on the immutability. The user of this class could put another object in, but this would not modify the underlying collection.

Print page numbers on pages when printing html

   **@page {
            margin-top:21% !important; 
            @top-left{
            content: element(header);

            }

            @bottom-left {
            content: element(footer
 }
 div.header {

            position: running(header);

            }
            div.footer {

            position: running(footer);
            border-bottom: 2px solid black;


            }
           .pagenumber:before {
            content: counter(page);
            }
            .pagecount:before {
            content: counter(pages);
            }      
 <div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
                <span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
            </div >**

What is the difference between Swing and AWT?

As far as when AWT may be more useful than Swing -

  • you may be targeting an older JVM or platform that doesn't support Swing. This used to really come into play if you were building Applets - you wanted to target the lowest common denominator so people wouldn't have to install a newer Java plugin. I'm not sure what the current most widely installed version of the Java plugin is - this may be different today.
  • some people prefer the native look of AWT over Swing's 'not quite there' platform skins. (There are better 3rd party native looking skins than Swing's implementations BTW) Lots of people preferred using AWT's FileDialog over Swing's FileChooser because it gave the platform file dialog most people were used to rather than the 'weird' custom Swing one.

How do I combine two lists into a dictionary in Python?

>>> dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

If they are not the same size, zip will truncate the longer one.

Finding height in Binary Search Tree

int maxDepth(BinaryTreeNode root) {
    if(root == null || (root.left == null && root.right == null)) {
       return 0;
    }

    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

Create HTML table using Javascript

In the html file there are three input boxes with userid,username,department respectively.

These inputboxes are used to get the input from the user.

The user can add any number of inputs to the page.

When clicking the button the script will enable the debugger mode.

In javascript, to enable the debugger mode, we have to add the following tag in the javascript.

/************************************************************************\

    Tools->Internet Options-->Advanced-->uncheck
    Disable script debugging(Internet Explorer)
    Disable script debugging(Other)

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

    <title>Dynamic Table</title>

    <script language="javascript" type="text/javascript">

    // <!CDATA[

    function CmdAdd_onclick() {

    var newTable,startTag,endTag;



    //Creating a new table

    startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
    <TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"

    endTag="</TBODY></TABLE>"

    newTable=startTag;

    var trContents;

    //Get the row contents

    trContents=document.body.getElementsByTagName('TR');

    if(trContents.length>1)

    {

    for(i=1;i<trContents.length;i++)

    {

    if(trContents(i).innerHTML)

    {

    // Add previous rows

    newTable+="<TR>";

    newTable+=trContents(i).innerHTML;

    newTable+="</TR>";

    } 

    }

    }

    //Add the Latest row

    newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
        document.getElementById('userid').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('username').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('department').value +"</TD><TR>";

    newTable+=endTag;

    //Update the Previous Table With New Table.

    document.getElementById('tableDiv').innerHTML=newTable;

    }

    // ]]>

    </script>

    </head>

    <body>

    <form id="form1" runat="server">

    <div>

    <br />

    <label>UserID</label> 

    <input id="userid" type="text" /><br />

    <label>UserName</label> 

    <input id="username" type="text" /><br />

    <label>Department</label> 

    <input id="department" type="text" />

    <center>

    <input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />
    </center>



    </div>

    <div id="tableDiv" style="text-align:center" >

    <table id="mainTable">

    <tr style="width:120px " >

    <td >User ID</td>

    <td>User Name</td>

    <td>Department</td>

    </tr>

    </table>

    </div>

    </form>

    </body>

    </html>

How can I make my match non greedy in vim?

Plugin eregex.vim handles Perl-style non-greedy operators *? and +?

Accessing variables from other functions without using global variables

What you're looking for is technically known as currying.

function getMyCallback(randomValue)
{
    return function(otherParam)
    {
        return randomValue * otherParam //or whatever it is you are doing.
    }

}

var myCallback = getMyCallBack(getRand())

alert(myCallBack(1));
alert(myCallBack(2));

The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.

Convert to date format dd/mm/yyyy

Try this:

$old_date = Date_create("2010-04-19 18:31:27");
$new_date = Date_format($old_date, "d/m/Y");

Angular ngClass and click event for toggling class

Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-

<div (click)="status=!status"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

So when status is true the class success is applied. When it is false danger class is applied.

This will work without any additional code in the ts file.

How to calculate number of days between two given dates?

It also can be easily done with arrow:

import arrow

a = arrow.get('2017-05-09')
b = arrow.get('2017-05-11')

delta = (b-a)
print delta.days

For reference: http://arrow.readthedocs.io/en/latest/

applying css to specific li class

You are defining the color: #C1C1C1; for all the a elements with #sub-nav-container a.

Doing it again in li.sub-navigation-home-news won't do anything, as it is a parent of the a element.

Creating Dynamic button with click event in JavaScript

Wow you're close. Edits in comments:

_x000D_
_x000D_
function add(type) {_x000D_
  //Create an input type dynamically.   _x000D_
  var element = document.createElement("input");_x000D_
  //Assign different attributes to the element. _x000D_
  element.type = type;_x000D_
  element.value = type; // Really? You want the default value to be the type string?_x000D_
  element.name = type; // And the name too?_x000D_
  element.onclick = function() { // Note this is a function_x000D_
    alert("blabla");_x000D_
  };_x000D_
_x000D_
  var foo = document.getElementById("fooBar");_x000D_
  //Append the element in page (in span).  _x000D_
  foo.appendChild(element);_x000D_
}_x000D_
document.getElementById("btnAdd").onclick = function() {_x000D_
  add("text");_x000D_
};
_x000D_
<input type="button" id="btnAdd" value="Add Text Field">_x000D_
<p id="fooBar">Fields:</p>
_x000D_
_x000D_
_x000D_

Now, instead of setting the onclick property of the element, which is called "DOM0 event handling," you might consider using addEventListener (on most browsers) or attachEvent (on all but very recent Microsoft browsers) — you'll have to detect and handle both cases — as that form, called "DOM2 event handling," has more flexibility. But if you don't need multiple handlers and such, the old DOM0 way works fine.


Separately from the above: You might consider using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over browsers differences like the addEventListener / attachEvent thing, provide useful utility features, and various other things. Obviously there's nothing a library can do that you can't do without one, as the libraries are just JavaScript code. But when you use a good library with a broad user base, you get the benefit of a huge amount of work already done by other people dealing with those browsers differences, etc.

How to use jquery $.post() method to submit form values

Yor $.post has no data. You need to pass the form data. You can use serialize() to post the form data. Try this

$("#post-btn").click(function(){
    $.post("process.php", $('#reg-form').serialize() ,function(data){
        alert(data);
    });
});

Row Offset in SQL Server

This is one way (SQL2000)

SELECT * FROM
(
    SELECT TOP (@pageSize) * FROM
    (
        SELECT TOP (@pageNumber * @pageSize) *
        FROM tableName 
        ORDER BY columnName ASC
    ) AS t1 
    ORDER BY columnName DESC
) AS t2 
ORDER BY columnName ASC

and this is another way (SQL 2005)

;WITH results AS (
    SELECT 
        rowNo = ROW_NUMBER() OVER( ORDER BY columnName ASC )
        , *
    FROM tableName 
) 
SELECT * 
FROM results
WHERE rowNo between (@pageNumber-1)*@pageSize+1 and @pageNumber*@pageSize

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

Fragment's onSaveInstanceState(Bundle outState) will never be called unless fragment's activity call it on itself and attached fragments. Thus this method won't be called until something (typically rotation) force activity to SaveInstanceState and restore it later. But if you have only one activity and large set of fragments inside it (with intensive usage of replace) and application runs only in one orientation activity's onSaveInstanceState(Bundle outState) may not be called for a long time.

I know three possible workarounds.

The first:

use fragment's arguments to hold important data:

public class FragmentA extends Fragment {
    private static final String PERSISTENT_VARIABLE_BUNDLE_KEY = "persistentVariable";

    private EditText persistentVariableEdit;

    public FragmentA() {
        setArguments(new Bundle());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, null);

        persistentVariableEdit = (EditText) view.findViewById(R.id.editText);

        TextView proofTextView = (TextView) view.findViewById(R.id.textView);

        Bundle mySavedInstanceState = getArguments();
        String persistentVariable = mySavedInstanceState.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);

        proofTextView.setText(persistentVariable);


        view.findViewById(R.id.btnPushFragmentB).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager()
                        .beginTransaction()
                        .replace(R.id.frameLayout, new FragmentB())
                        .addToBackStack(null)
                        .commit();
            }
        });

        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        String persistentVariable = persistentVariableEdit.getText().toString();

        getArguments().putString(PERSISTENT_VARIABLE_BUNDLE_KEY, persistentVariable);
    }
}

The second but less pedantic way - hold variables in singletons

The third - don't replace() fragments but add()/show()/hide() them instead.

Statically rotate font-awesome icons

Before FontAwesome 5:

The standard declarations just contain .fa-rotate-90, .fa-rotate-180 and .fa-rotate-270. However you can easily create your own:

.fa-rotate-45 {
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
}

With FontAwesome 5:

You can use what’s so called “Power Transforms”. Example:

<i class="fas fa-snowman" data-fa-transform="rotate-90"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-180"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-270"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-30"></i>
<i class="fas fa-snowman" data-fa-transform="rotate--30"></i>

You need to add the data-fa-transform attribute with the value of rotate- and your desired rotation in degrees.

Source: https://fontawesome.com/how-to-use/on-the-web/styling/power-transforms

What is the easiest way to install BLAS and LAPACK for scipy?

Using conda install scipy instead of pip solved the problem for me!

Chrome doesn't delete session cookies

I had to both, unchecked, under advanced settings of Chrome :

  • 'Continue running background apps when Google Chrome is closed'
  • "Continue where I left off", "On startup"

How to hide html source & disable right click and text copy?

I have constructed a simple self checking php file, it only allows real loading by humans, and not robots like ( online source code viewer's ) ..

I'm not sure about View Source from Chrome, but it does block access to the html... Not just obfuscation, it uses a bounce back submittance to validate loads.

The short code was still visible in source viewers, so i obfuscated it also...

The page is loaded and bounces back, the bounce gets the real page, not the loader !

   // Create A New File called ( lock.php ) 

Copy this into it....

<?php 
// PAGE SOURCE GUARD by Elijah Cuff.
if (!hasParam('bounce'))
{
echo "
<script type='text/javascript'>
<!-- 
eval(unescape('%66%75%6e%63%74%69%6f%6e%20%63%36%36%32%32%30%36%62%32%63%28%73%29%20%7b%0a%09%76%61%72%20%72%20%3d%20%22%22%3b%0a%09%76%61%72%20%74%6d%70%20%3d%20%73%2e%73%70%6c%69%74%28%22%37%36%33%33%31%37%31%22%29%3b%0a%09%73%20%3d%20%75%6e%65%73%63%61%70%65%28%74%6d%70%5b%30%5d%29%3b%0a%09%6b%20%3d%20%75%6e%65%73%63%61%70%65%28%74%6d%70%5b%31%5d%20%2b%20%22%35%37%35%31%36%35%22%29%3b%0a%09%66%6f%72%28%20%76%61%72%20%69%20%3d%20%30%3b%20%69%20%3c%20%73%2e%6c%65%6e%67%74%68%3b%20%69%2b%2b%29%20%7b%0a%09%09%72%20%2b%3d%20%53%74%72%69%6e%67%2e%66%72%6f%6d%43%68%61%72%43%6f%64%65%28%28%70%61%72%73%65%49%6e%74%28%6b%2e%63%68%61%72%41%74%28%69%25%6b%2e%6c%65%6e%67%74%68%29%29%5e%73%2e%63%68%61%72%43%6f%64%65%41%74%28%69%29%29%2b%2d%36%29%3b%0a%09%7d%0a%09%72%65%74%75%72%6e%20%72%3b%0a%7d%0a'));
eval(unescape('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%63%36%36%32%32%30%36%62%32%63%28%27') + '%47%67%7f%76%73%44%15%15%45%69%74%7e%76%23%7a%6e%7f%6f%75%6c%46%2f%73%74%7f%7f%2d%2f%6a%6f%42%28%7e%62%7a%2d%45%15%15%47%66%71%73%7a%7a%20%7f%78%73%6a%45%2d%6b%66%6f%6f%6a%74%2e%23%73%62%72%6d%46%2d%61%70%7e%75%69%6d%2d%21%79%66%74%7e%6e%4a%2d%32%29%44%44%30%68%71%77%7d%7f%41%1a%15%47%34%6c%73%7d%74%41%12%16%47%7c%60%7d%6a%77%7a%42%16%17%23%7c%69%71%6f%7c%78%31%78%6b%7c%5f%68%76%6a%73%7e%7f%27%69%7e%75%69%7c%6a%72%71%2f%29%23%84%1a%15%23%6b%75%6f%7e%74%6e%75%7c%31%68%62%7f%4e%73%6b%75%6e%73%7f%49%79%4a%6f%27%67%28%79%67%7b%67%2a%2a%35%7f%7e%6d%7a%6a%7f%2f%2f%47%16%17%23%27%85%37%23%33%33%33%2e%41%15%15%45%30%78%6f%7d%6a%7f%7f%41%12%10%44%30%69%7f%72%74%417633171%35%39%35%35%31%30%36' + unescape('%27%29%29%3b'));
// -->
</script>
<noscript><i>Javascript required</i></noscript>
";
exit;
}
function hasParam($param)
{
    return isset($_POST[$param]);
}
?>

NOW ADD THIS TO THE VERY TOP OF
EVERY PAGE .. Example....

<?php
 // use require for more security...
include('lock.php'); 
?>

<HTML> 
etc.. etc...

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

In MAC OS, just rebooted the computer and it worked after the reboot.

Why I get 'list' object has no attribute 'items'?

You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.

If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:

result_list = [[int(v) for k,v in d.items()] for d in qs]

Which is the same as:

result_list = []
for d in qs:
    result_list.append([int(v) for k,v in d.items()])

The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:

result_list = [int(v) for d in qs for k,v in d.items()]

Query to display all tablespaces in a database and datafiles

Neither databases, nor tablespaces nor data files belong to any user. Are you coming to this from an MS SQL background?

select tablespace_name, 
       file_name
from dba_tablespaces
order by tablespace_name, 
         file_name;

What is the python keyword "with" used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

Why doesn't calling a Python string method do anything unless you assign its output?

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

IF - ELSE IF - ELSE Structure in Excel

Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:

=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))

Html Agility Pack get all elements by class

public static List<HtmlNode> GetTagsWithClass(string html,List<string> @class)
    {
        // LoadHtml(html);           
        var result = htmlDocument.DocumentNode.Descendants()
            .Where(x =>x.Attributes.Contains("class") && @class.Contains(x.Attributes["class"].Value)).ToList();          
        return result;
    }      

Python socket connection timeout

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

How to set URL query params in Vue with Vue-Router

To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):

    setQuery(query){
        let obj = Object.assign({}, this.$route.query);

        Object.keys(query).forEach(key => {
            let value = query[key];
            if(value){
                obj[key] = value
            } else {
                delete obj[key]
            }
        })
        this.$router.replace({
            ...this.$router.currentRoute,
            query: obj
        })
    },

    removeQuery(queryNameArray){
        let obj = {}
        queryNameArray.forEach(key => {
            obj[key] = null
        })
        this.setQuery(obj)
    },

LINQ-to-SQL vs stored procedures?

Both LINQ and SQL have their places. Both have their disadvantages and advantages.

Sometimes for complex data retrieval you might need stored procs. And sometimes you may want other people to use your stored proc in Sql Server Management Studio.

Linq to Entities is great for fast CRUD development.

Sure you can build an app using only one or the other. Or you can mix it up. It all comes down to your requirements. But SQL stored procs will no go away any time soon.

Convert Iterator to ArrayList

You can also use IteratorUtils from Apache commons-collections, although it doesn't support generics:

List list = IteratorUtils.toList(iterator);

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

Rounded corner for textview in android

Since your top level view already has android:background property set, you can use a <layer-list> (link) to create a new XML drawable that combines both your old background and your new rounded corners background.

Each <item> element in the list is drawn over the next, so the last item in the list is the one that ends up on top.

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/mydialogbox" />
    </item>
    <item>
        <shape>
            <stroke
                android:width="1dp"
                android:color="@color/common_border_color" />

            <solid android:color="#ffffff" />

            <padding
                    android:left="1dp"
                    android:right="1dp"
                    android:top="1dp" />

            <corners android:radius="5dp" />
        </shape>
    </item>
</layer-list>

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Disable ONLY_FULL_GROUP_BY

Add or Remove modes to sql_mode

MySQL 5.7.9 or later

To add or remove a mode from sql_mode, you can use list_add and list_drop functions.

To remove a mode from the current SESSION.sql_mode, you can use one of the following:

SET SESSION sql_mode = sys.list_drop(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY');
SET sql_mode = sys.list_drop(@@sql_mode, 'ONLY_FULL_GROUP_BY');
SET @@sql_mode = sys.list_drop(@@sql_mode, 'ONLY_FULL_GROUP_BY');

To remove a mode from the GLOBAL.sql_mode that persists for the current runtime operation, until the service is restarted.

SET GLOBAL sql_mode = sys.list_drop(@@GLOBAL.sql_mode, 'ONLY_FULL_GROUP_BY');

MySQL 5.7.8 or prior

Since the sql_mode value is a CSV string of modes, you would need to ensure that the string does not contain residual commas, which can be accomplished by using TRIM(BOTH ',' FROM ...).

To remove a mode from the sql_mode variable, you would want to use REPLACE() along with TRIM() to ensure any residual commas are removed.

SET SESSION sql_mode = TRIM(BOTH ',' FROM REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', ''));
SET GLOBAL sql_mode = TRIM(BOTH ',' FROM REPLACE(@@GLOBAL.sql_mode, 'ONLY_FULL_GROUP_BY', ''));

To add a mode to the sql_mode variable, you would want to use CONCAT_WS(',', ...), to ensure a comma is appended with the current modes and TRIM() to ensure any residual commas are removed.

SET SESSION sql_mode = TRIM(BOTH ',' FROM CONCAT_WS(',', 'ONLY_FULL_GROUP_BY', @@SESSION.sql_mode));
SET GLOBAL sql_mode = TRIM(BOTH ',' FROM CONCAT_WS(',', 'ONLY_FULL_GROUP_BY', @@GLOBAL.sql_mode));

NOTE: Changing the GLOBAL variable does not propagate to the SESSION variable, until a new connection is established.

The GLOBAL variable will persist until the running service is restarted.

The SESSION variable will persist for the current connection, until the connection is closed and a new connection is established.


Revert to GLOBAL.sql_mode

Since SET sql_mode = 'ONLY_FULL_GROUP_BY'; was executed without the GLOBAL modifier, the change only affected the current SESSION state value, which also pertains to @@sql_mode. To remove it and revert to the global default on server restart value, you would want to use the value from @@GLOBAL.sql_mode. [sic]

The current SESSION value is only valid for the current connection. Reconnecting to the server will revert the value back to the GLOBAL value.

To revert the current session state value to the current global value, you can use one of the following:

SET SESSION sql_mode = @@GLOBAL.sql_mode;
SET @@sql_mode = @@GLOBAL.sql_mode;
SET sql_mode = @@GLOBAL.sql_mode;

Change SESSION.sql_mode value to ONLY_FULL_GROUP_BY

SET sql_mode = 'ONLY_FULL_GROUP_BY';
SELECT @@sql_mode, @@GLOBAL.sql_mode;
+--------------------+----------------------------------------------+
| @@sql_mode         | @@GLOBAL.sql_mode                            |
+--------------------+----------------------------------------------+
| ONLY_FULL_GROUP_BY | NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION |
+--------------------+----------------------------------------------+

Revert the SESSION.sql_mode value to the GLOBAL.sql_mode value

SET sql_mode = @@GLOBAL.sql_mode;
SELECT @@sql_mode, @@GLOBAL.sql_mode;
+----------------------------------------------+----------------------------------------------+
| @@sql_mode                                   | @@GLOBAL.sql_mode                            |
+----------------------------------------------+----------------------------------------------+
| NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION | NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------+----------------------------------------------+

Server Restart Persistent sql_mode using the option file

To set the SQL mode at server startup, use the --sql-mode="modes" option on the command line, or sql-mode="modes" in an option file such as my.cnf (Unix operating systems) or my.ini (Windows). [sic]

Please see your version of MySQL to determine the supported and default modes.

MySQL >= 5.7.5, <= 5.7.6 default

[mysqld]
    
sql-mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"

Please see the Option File Syntax for more information.

The syntax for specifying options in an option file is similar to command-line syntax. However, in an option file, you omit the leading two dashes from the option name and you specify only one option per line. For example, --quick and --host=localhost on the command line should be specified as quick and host=localhost on separate lines in an option file. To specify an option of the form --loose-opt_name in an option file, write it as loose-opt_name.

The value optionally can be enclosed within single quotation marks or double quotation marks, which is useful if the value contains a # comment character.

Default sql_mode values

Since the MySQL documentation per-version values have been removed, I have added them here for your reference.

MySQL >= 8.0.11 8.0.5 - 8.0.10 Skipped

ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_ENGINE_SUBSTITUTION

MySQL >= 5.7.8, <= 8.0.4

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

MySQL 5.7.7

ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION

MySQL >= 5.7.5, <= 5.7.6

ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ENGINE_SUBSTITUTION

MySQL >= 5.6.6, <= 5.7.4

NO_ENGINE_SUBSTITUTION

MySQL <= 5.6.5

''

Sending JSON to PHP using ajax

That's because $_POST is pre-populated with form data.

To get JSON data (or any raw input), use php://input.

$json = json_decode(file_get_contents("php://input"));

C++ Calling a function from another class

    void CallFunction ()
    {   // <----- At this point the compiler knows
        //        nothing about the members of B.
        B b;
        b.bFunction();
    }

This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.

To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.

class A
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    { ... }
};

void A::CallFunction ()
{
    B b;
    b.bFunction();
}

Maven compile with multiple src directories

This worked for me

<build>
    <sourceDirectory>.</sourceDirectory>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
        <includes>
            <include>src/main/java/**/*.java</include>
            <include>src/main2/java/**/*.java</include>
        </includes>
        </configuration>
        </plugin>
    </plugins>
</build>

How to clear radio button in Javascript?

If you have a radio button with same id, then you can clear the selection

Radio Button definition :

<input type="radio" name="paymentType" id="paymentType" value="CASH" /> CASH
<input type="radio" name="paymentType" id="paymentType" value="CHEQUE" /> CHEQUE
<input type="radio" name="paymentType" id="paymentType" value="DD" /> DD

Clearing all values of radio button:

document.formName.paymentType[0].checked = false;
document.formName.paymentType[1].checked = false;
document.formName.paymentType[2].checked = false;
...

ETag vs Header Expires

Expires and Cache-Control are "strong caching headers"

Last-Modified and ETag are "weak caching headers"

First the browser check Expires/Cache-Control to determine whether or not to make a request to the server

If have to make a request, it will send Last-Modified/ETag in the HTTP request. If the Etag value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.

Google Chrome form autofill and its yellow background

Solution here:

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

Concatenate two string literals

You should always pay attention to types.

Although they all seem like strings, "Hello" and ",world" are literals.

And in your example, exclam is a std::string object.

C++ has an operator overload that takes a std::string object and adds another string to it. When you concatenate a std::string object with a literal it will make the appropriate casting for the literal.

But if you try to concatenate two literals, the compiler won't be able to find an operator that takes two literals.

Unit Testing C Code

I use CxxTest for an embedded c/c++ environment (primarily C++).

I prefer CxxTest because it has a perl/python script to build the test runner. After a small slope to get it setup (smaller still since you don't have to write the test runner), it's pretty easy to use (includes samples and useful documentation). The most work was setting up the 'hardware' the code accesses so I could unit/module test effectively. After that it's easy to add new unit test cases.

As mentioned previously it is a C/C++ unit test framework. So you will need a C++ compiler.

CxxTest User Guide CxxTest Wiki

How can I change the default Mysql connection timeout when connecting through python?

I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect call. For example,

con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
          connect_timeout=1000)

Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.

For detail about different arguments that you can pass to _mysql.connect, see MySQLdb API documentation

JavaScript - populate drop down list with array

You'll need to loop through your array elements, create a new DOM node for each and append it to your object.

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}?

Live example

e.printStackTrace equivalent in python

Adding to the other great answers, we can use the Python logging library's debug(), info(), warning(), error(), and critical() methods. Quoting from the docs for Python 3.7.4,

There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message.

What this means is, you can use the Python logging library to output a debug(), or other type of message, and the logging library will include the stack trace in its output. With this in mind, we can do the following:

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def f():
    a = { 'foo': None }
    # the following line will raise KeyError
    b = a['bar']

def g():
    f()

try:
    g()
except Exception as e:
    logger.error(str(e), exc_info=True)

And it will output:

'bar'
Traceback (most recent call last):
  File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
    g()
  File "<ipython-input-2-8ae09e08766b>", line 14, in g
    f()
  File "<ipython-input-2-8ae09e08766b>", line 10, in f
    b = a['bar']
KeyError: 'bar'

Node.js version on the command line? (not the REPL)

One cool tip if you are using the Atom editor.

$ apm -v
apm  1.12.5
npm  3.10.5
node 4.4.5
python 2.7.12
git 2.7.4

It will return you not only the node version but also few other things.

How can I record a Video in my Android App.?

The above example will work if you are using rear camera. If you are using front camera, you will have to adjust some things:

First off, you will need to add new permission in the manifest.

<uses-feature android:name="android.hardware.camera.front" android:required="false" />

In your initRecorder method, instead of

CamcorderProfile cpHigh = CamcorderProfile
                .get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);

You need to use:

CamcorderProfile profile = CamcorderProfile.get(Camera.CameraInfo.CAMERA_FACING_FRONT, CamcorderProfile.QUALITY_LOW);
recorder.setProfile(profile);

because CamcorderProfile.QUALITY_HIGH is reserved for the rear camera.

You will also have to set the video size for mediarecorder as it is in your surface view.

Here is the full example of recording video from front camera with a small preview display:

Android.manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />

activity_camera.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="CameraActivity">

    <SurfaceView
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/surfaceView"/>

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="REC"
        android:id="@+id/btnRecord"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="25dp" />
</RelativeLayout>

CameraActivity.java

public class SongVideoActivity extends BaseActivity implements SurfaceHolder.Callback {

    private int mCameraContainerWidth = 0;
    private SurfaceView mSurfaceView = null;
    private SurfaceHolder mSurfaceHolder = null;

    private Camera mCamera = null;
    private boolean mIsRecording = false;

    private int mPreviewHeight;
    private int mPreviewWidth;

    MediaRecorder mRecorder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_song_video);

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                releaseMediaRecorder();
                releaseCamera();
            }
        });

        mCamera = getCamera();

        //camera preview
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        mCameraContainerWidth = mSurfaceView.getLayoutParams().width;

        findViewById(R.id.btnRecord).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIsRecording) {
                    stopRecording();
                } else {
                    // initialize video camera
                    if (prepareVideoRecorder()) {

                        // Camera is available and unlocked, MediaRecorder is prepared,
                        // now you can start recording
                        mRecorder.start();

                        // inform the user that recording has started
                        Toast.makeText(getApplicationContext(), "Started recording", Toast.LENGTH_SHORT).show();
                        mIsRecording = true;
                    } else {
                        // prepare didn't work, release the camera
                        releaseMediaRecorder();
                        // inform user
                    }
                }
            }
        });
    }

    private void stopRecording() {
        mRecorder.stop();  // stop the recording
        releaseMediaRecorder(); // release the MediaRecorder object
        mCamera.lock();         // take camera access back from MediaRecorder

        // inform the user that recording has stopped
        Toast.makeText(this, "Recording complete", Toast.LENGTH_SHORT).show();
        mIsRecording = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private Camera getCamera() {

        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); camIdx++) {
            Camera.getCameraInfo(camIdx, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                try {
                    return mCamera = Camera.open(camIdx);
                } catch (RuntimeException e) {
                    Log.e("cameras", "Camera failed to open: " + e.getLocalizedMessage());
                }
            }
        }
        return null;
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private Camera.Size getBestPreviewSize(Camera.Parameters parameters) {
        Camera.Size result=null;

        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if(size.width < size.height) continue; //we are only interested in landscape variants

            if (result == null) {
                result = size;
            }
            else {
                int resultArea = result.width*result.height;
                int newArea = size.width*size.height;

                if (newArea > resultArea) {
                    result = size;
                }
            }
        }

        return(result);
    }

    private boolean prepareVideoRecorder(){
        mRecorder = new MediaRecorder();

        // Step 1: Unlock and set camera to MediaRecorder
        mCamera.unlock();
        mRecorder.setCamera(mCamera);

        // Step 2: Set sources
        mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
        //recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

        // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
        // Customise your profile based on a pre-existing profile
        CamcorderProfile profile = CamcorderProfile.get(Camera.CameraInfo.CAMERA_FACING_FRONT, CamcorderProfile.QUALITY_LOW);
        mRecorder.setProfile(profile);

        // Step 4: Set output file
        mRecorder.setOutputFile(new File(getFilesDir(), "movie-" + UUID.randomUUID().toString()).getAbsolutePath());
        //recorder.setMaxDuration(50000); // 50 seconds
        //recorder.setMaxFileSize(500000000); // Approximately 500 megabytes

        mRecorder.setVideoSize(mPreviewWidth, mPreviewHeight);

        // Step 5: Set the preview output
        mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

        // Step 6: Prepare configured MediaRecorder
        try {
            mRecorder.prepare();
        } catch (IllegalStateException e) {
            Toast.makeText(getApplicationContext(), "exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
            releaseMediaRecorder();
            return false;
        }
        return true;
    }

    private void releaseMediaRecorder(){
        if (mRecorder != null) {
            mRecorder.reset();   // clear recorder configuration
            mRecorder.release(); // release the recorder object
            mRecorder = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setRecordingHint(true);
            Camera.Size size = getBestPreviewSize(parameters);
        mCamera.setParameters(parameters);

            //resize the view to the specified surface view width in layout
            int newHeight = size.height / (size.width / mCameraContainerWidth);
            mSurfaceView.getLayoutParams().height = newHeight;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mPreviewHeight = mCamera.getParameters().getPreviewSize().height;
        mPreviewWidth = mCamera.getParameters().getPreviewSize().width;

        mCamera.stopPreview();
        try {
            mCamera.setPreviewDisplay(mSurfaceHolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mCamera.startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mIsRecording) {
            stopRecording();
        }

        releaseMediaRecorder();
        releaseCamera();
    }
}

Can we call the function written in one JavaScript in another JS file?

The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.

I.e.

File1.js

function alertNumber(number) {
    alert(number);
}

File2.js

function alertOne() {
     alertNumber("one");
}

HTML

<head>
....
    <script src="File1.js" type="text/javascript"></script> 
    <script src="File2.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

The other way won't work. As correctly pointed out by Stuart Wakefield. The other way will also work.

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

What will not work would be:

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script type="text/javascript">
       alertOne();
    </script>
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
</body>

Although alertOne is defined when calling it, internally it uses a function that is still not defined (alertNumber).

Python handling socket.error: [Errno 104] Connection reset by peer

You can try to add some time.sleep calls to your code.

It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.

In order to avoid your code from crashing, try to catch this error with try .. except around the urllib2 calls.

How to open some ports on Ubuntu?

If you want to open it for a range and for a protocol

ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

Finding the max/min value in an array of primitives using Java

import java.util.Random;

public class Main {

public static void main(String[] args) {
   int a[] = new int [100];
   Random rnd = new Random ();

    for (int i = 0; i< a.length; i++) {
        a[i] = rnd.nextInt(99-0)+0;
        System.out.println(a[i]);
    }

    int max = 0;          

    for (int i = 0; i < a.length; i++) {
        a[i] = max;


        for (int j = i+1; j<a.length; j++) {
            if (a[j] > max) {
               max = a[j];
            }

        }
    }

    System.out.println("Max element: " + max);
}
}

Creating random numbers with no duplicates

This would be a lot simpler in java-8:

Stream.generate(new Random()::ints)
            .distinct()
            .limit(16) // whatever limit you might need
            .toArray(Integer[]::new);

change the date format in laravel view page

You can check Date Mutators: https://laravel.com/docs/5.3/eloquent-mutators#date-mutators

You need set in your User model column from_date in $dates array and then you can change format in $dateFormat

The another option is also put this method to your User model:

public function getFromDateAttribute($value) {
    return \Carbon\Carbon::parse($value)->format('d-m-Y');
}

and then in view if you run {{ $user->from_date }} you will be see format that you want.

Cannot access wamp server on local network

I had the same issue, tried all nothing works, following works for me

Following is what i had

#onlineoffline tag - don't remove

Require local

Change to

Require all granted
Order Deny,Allow
Allow from all

Understanding colors on Android (six characters)

Android Material Design

These are the conversions for setting the text color opacity levels.

  • 100%: FF
  • 87%: DE
  • 70%: B3
  • 54%: 8A
  • 50%: 80
  • 38%: 61
  • 12%: 1F

Dark text on light backgrounds

enter image description here

  • Primary text: DE000000
  • Secondary text: 8A000000
  • Disabled text, hint text, and icons: 61000000
  • Dividers: 1F000000

White text on dark backgrounds

enter image description here

  • Primary text: FFFFFFFF
  • Secondary text: B3FFFFFF
  • Disabled text, hint text, and icons: 80FFFFFF
  • Dividers: 1FFFFFFF

See also

  • Look up any percentage here.

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

As noted the 3.1.0-beta4 release of the driver got "released into the wild" a little early by the looks of things. The release is part of work in progress to support newer features in the MongoDB 4.0 upcoming release and make some other API changes.

One such change triggering the current warning is the useNewUrlParser option, due to some changes around how passing the connection URI actually works. More on that later.

Until things "settle down", it would probably be advisable to "pin" at least to the minor version for 3.0.x releases:

  "dependencies": {
    "mongodb": "~3.0.8"
  }

That should stop the 3.1.x branch being installed on "fresh" installations to node modules. If you already did install a "latest" release which is the "beta" version, then you should clean up your packages ( and package-lock.json ) and make sure you bump that down to a 3.0.x series release.

As for actually using the "new" connection URI options, the main restriction is to actually include the port on the connection string:

const { MongoClient } = require("mongodb");
const uri = 'mongodb://localhost:27017';  // mongodb://localhost - will fail

(async function() {
  try {

    const client = await MongoClient.connect(uri,{ useNewUrlParser: true });
    // ... anything

    client.close();
  } catch(e) {
    console.error(e)
  }

})()

That's a more "strict" rule in the new code. The main point being that the current code is essentially part of the "node-native-driver" ( npm mongodb ) repository code, and the "new code" actually imports from the mongodb-core library which "underpins" the "public" node driver.

The point of the "option" being added is to "ease" the transition by adding the option to new code so the newer parser ( actually based around url ) is being used in code adding the option and clearing the deprecation warning, and therefore verifying that your connection strings passed in actually comply with what the new parser is expecting.

In future releases the 'legacy' parser would be removed and then the new parser will simply be what is used even without the option. But by that time, it is expected that all existing code had ample opportunity to test their existing connection strings against what the new parser is expecting.

So if you want to start using new driver features as they are released, then use the available beta and subsequent releases and ideally make sure you are providing a connection string which is valid for the new parser by enabling the useNewUrlParser option in MongoClient.connect().

If you don't actually need access to features related to preview of the MongoDB 4.0 release, then pin the version to a 3.0.x series as noted earlier. This will work as documented and "pinning" this ensures that 3.1.x releases are not "updated" over the expected dependency until you actually want to install a stable version.

list all files in the folder and also sub folders

You can return a List instead of an array and things gets much simpler.

    public static List<File> listf(String directoryName) {
        File directory = new File(directoryName);

        List<File> resultList = new ArrayList<File>();

        // get all the files from a directory
        File[] fList = directory.listFiles();
        resultList.addAll(Arrays.asList(fList));
        for (File file : fList) {
            if (file.isFile()) {
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                resultList.addAll(listf(file.getAbsolutePath()));
            }
        }
        //System.out.println(fList);
        return resultList;
    } 

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

jQuery: keyPress Backspace won't fire?

If you want to fire the event only on changes of your input use:

$('.s').bind('input', function(){
  console.log("search!");
  doSearch();
});

Simple state machine example in C#?

I haven't tried implementing a FSM in C# yet, but these all sound (or look) very complicated to the way I handled FSM's in the past in low-level languages like C or ASM.

I believe the method I've always known is called something like an "Iterative Loop". In it, you essentially have a 'while' loop that periodically exits based on events (interrupts), then returns to the main loop again.

Within the interrupt handlers, you would pass a CurrentState and return a NextState, which then overwrites the CurrentState variable in the main loop. You do this ad infinitum until the program closes (or the microcontroller resets).

What I'm seeing other answers all look very complicated compared with how a FSM is, in my mind, intended to be implemented; its beauty lies in its simplicity and FSM can be very complicated with many, many states and transitions, but they allow complicated process to be easily broken down and digested.

I realize my response shouldn't include another question, but I am forced to ask: why do these other proposed solutions appear to be so complicated?
They seem to be akin to hitting a small nail with a giant sledge hammer.

TypeError: not all arguments converted during string formatting python

I encounter the error as well,

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting 

But list args work well.

I use mysqlclient python lib. The lib looks like not to accept tuple args. To pass list args like ['arg1', 'arg2'] will work.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

in your view, instead of:

@Html.EditorFor(model => model.Comments[0].Comment)

just use:

@Html.TextAreaFor(model => model.Comments[0].Comment, 5, 1, null)

Saving an Object (Data persistence)

You can use anycache to do the job for you. It considers all the details:

  • It uses dill as backend, which extends the python pickle module to handle lambda and all the nice python features.
  • It stores different objects to different files and reloads them properly.
  • Limits cache size
  • Allows cache clearing
  • Allows sharing of objects between multiple runs
  • Allows respect of input files which influence the result

Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

@anycache(cachedir='/path/to/your/cache')    
def myfunc(name, value)
    return Company(name, value)

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the function name and its arguments) as filename. On any consecutive run, the pickled object is loaded. If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

For any further details see the documentation

What is the fastest factorial function in JavaScript?

Old question but i find this approach quite readable and straightforward

function factorialize(num) {
  var arr = [];
  var result;
  if ( num === 0 || num === 1 ) {
    return 1;
  } else {
    for (var i = num; i > 0; i--) {
      arr.push(i);
      result = arr.reduce(function(previousVal, nextVal){
                return previousVal * nextVal;
              });
    }
    return result;
  }
}

Create an ArrayList of unique values

If you need unique values, you should use the implementation of the SET interface

Embed Google Map code in HTML with marker

I would suggest this way, one line iframe. no javascript needed at all. In query ?q=,

_x000D_
_x000D_
<iframe src="http://maps.google.com/maps?q=12.927923,77.627108&z=15&output=embed"></iframe>
_x000D_
_x000D_
_x000D_

Does JavaScript guarantee object property order?

Major Difference between Object and MAP with Example :

it's Order of iteration in loop, In Map it follows the order as it was set while creation whereas in OBJECT does not.

SEE: OBJECT

const obj = {};
obj.prop1 = "Foo";
obj.prop2 = "Bar";
obj['1'] = "day";
console.log(obj)

**OUTPUT: {1: "day", prop1: "Foo", prop2: "Bar"}**

MAP

    const myMap = new Map()
    // setting the values
    myMap.set("foo", "value associated with 'a string'")
    myMap.set("Bar", 'value associated with keyObj')
    myMap.set("1", 'value associated with keyFunc')

OUTPUT:
**1.    ?0: Array[2]
1.   0: "foo"
2.   1: "value associated with 'a string'"
2.  ?1: Array[2]
1.   0: "Bar"
2.   1: "value associated with keyObj"
3.  ?2: Array[2]
1.   0: "1"
2.   1: "value associated with keyFunc"**

Retrieve Button value with jQuery

As a button value is an attribute you need to use the .attr() method in jquery. This should do it

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {
            alert($(this).attr("value"));
        });
    });
</script>

You can also use attr to set attributes, more info in the docs.

This only works in JQuery 1.6+. See postpostmodern's answer for older versions.

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

A slightly more efficient version of the bytes2String method is

private static final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String byteArray2Hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

How to bundle an Angular app for production

"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.

In the latter case Webpack is generally the best way since it supports code splitting.

For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)

I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds

The code can be found here: https://github.com/thelgevold/angular-2-samples

Angular version: 4.1.x

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

Failed to install Python Cryptography package with PIP and setup.py

Use conda instead

None of the proposed solutions worked for me on Raspbian 10 (buster) so I just installed it via conda and voila:

conda install -c anaconda cryptography

P.S. : I know that the question mentions pip but I see that OP is using a conda installation so I thought of sharing this solution anyway. Nevertheless, since this problem is apparently OS-specific, it's meaningful to remind one that conda is a cross-platform and language-agnostic solution which may also install necessary binaries apart from python packages - with just an one-liner.

How to allow http content within an iframe on a https site

You could try scraping whatever you need with PHP or another server side language, then put the iframe to the scraped content. Here's an example with PHP:

scrapedcontent.php:

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

index.html:

<iframe src="scrapedcontent.php"></iframe>

How to Validate Google reCaptcha on Form Submit

One issue I came up with that prevented these two files from working correctly was with my php.ini file for the website. Make sure this property is properly set, as follows:

allow_url_fopen = 

log4j configuration via JVM argument(s)?

If you are using gradle. You can apply 'aplication' plugin and use the following command

  applicationDefaultJvmArgs = [
             "-Dlog4j.configurationFile=your.xml",
                              ]

Using await outside of an async function

There is always this of course:

(async () => {
    await ...

    // all of the script.... 

})();
// nothing else

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

How to prevent downloading images and video files from my website?

In standard HTML, I don't know of anyway.

You didn't really say, but I'm guessing you are having problems with people deep linking into your content. If that's the case, and you are open to server side code, I believe this might work:

  1. Create a page that accepts a numeric id, maps it to a server file path, opens that file, writes the binary directly to the response stream.
  2. On the page request, generate a bunch of random ids, and map them to the actual media urls, and store that mapping object server side somewhere (in session?) with a limited life.
  3. Render your pages with your media links pointing to the new media page with the appropriate id as a query string argument.
  4. Clear the mapping object and generate all new links on every postback.

This :

  1. won't stop people from downloading from within your page
  2. definitely isn't as lightweight as standard HTML
  3. and has it's own set of issues.

But it's a general outline of a workable process which might help you prevent users from deep linking.

Hide axis values but keep axis tick labels in matplotlib

If you use the matplotlib object-oriented approach, this is a simple task using ax.set_xticklabels() and ax.set_yticklabels():

import matplotlib.pyplot as plt

# Create Figure and Axes instances
fig,ax = plt.subplots(1)

# Make your plot, set your axes labels
ax.plot(sim_1['t'],sim_1['V'],'k')
ax.set_ylabel('V')
ax.set_xlabel('t')

# Turn off tick labels
ax.set_yticklabels([])
ax.set_xticklabels([])

plt.show()

Java: How to Indent XML Generated by Transformer

The following code is working for me with Java 7. I set the indent (yes) and indent-amount (2) on the transformer (not the transformer factory) to get it working.

TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(source, result);

@mabac's solution to set the attribute didn't work for me, but @lapo's comment proved helpful.

How to use a table type in a SELECT FROM statement?

Thanks for all help at this issue. I'll post here my solution:

Package Header

CREATE OR REPLACE PACKAGE X IS
  TYPE exch_row IS RECORD(
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);
  TYPE exch_tbl IS TABLE OF X.exch_row;

  FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;

Package Body

CREATE OR REPLACE PACKAGE BODY X IS
  FUNCTION GetExchangeRate RETURN X.exch_tbl
    PIPELINED AS
    exch_rt_usd NUMBER := 1.0; --todo
    rw exch_row;
  BEGIN

    FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
                 FROM exch e, currency c
                WHERE c.currency_key = e.currency_key
                  ) LOOP
      PIPE ROW(rw);
    END LOOP;
  END;


  PROCEDURE DoIt IS
  BEGIN
    DECLARE
      CURSOR c0 IS
        SELECT i.DOC,
               i.doc_currency,
               i.net_value,
               i.net_value / rt.exch_rt_usd AS net_value_in_usd,
               i.net_value / rt.exch_rt_eur AS net_value_in_euro,
          FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
         WHERE i.doc_currency = rt.currency_cd;

      TYPE c0_type IS TABLE OF c0%ROWTYPE;

      items c0_type;
    BEGIN
      OPEN c0;

      LOOP
        FETCH c0 BULK COLLECT
          INTO items LIMIT batchsize;

        EXIT WHEN items.COUNT = 0;
        FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
          INSERT INTO detail_items VALUES items (i);

      END LOOP;

      CLOSE c0;

      COMMIT;

    EXCEPTION
      WHEN OTHERS THEN
        RAISE;
    END;
  END;

END X;

Please review.

How to make use of SQL (Oracle) to count the size of a string?

you need length() function

select length(customer_name) from ar.ra_customers

Spring cannot find bean xml configuration file when it does exist

If this problem is still flummoxing you and you are developing using Eclipse, have a look at this Eclipse bug: Resources files from "src/main/resources" are not correctly included in classpath

Solution seems to be look at properties of project, Java build path, source folders. Delete the /src/main/resources dir and add it again. This causes Eclipse to be reminded it needs to copy these files to the classpath.

This bug affected me when using the "Neon" release of Eclipse. (And was very frustrating until I realized the simple fix just described)

Generating an MD5 checksum of a file

There is a way that's pretty memory inefficient.

single file:

import hashlib
def file_as_bytes(file):
    with file:
        return file.read()

print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()

list of files:

[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]

Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:

[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]

If you only want 128 bits worth of digest you can do .digest()[:16].

This will give you a list of tuples, each tuple containing the name of its file and its hash.

Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.

Here is a way that is more complex, but memory efficient:

import hashlib

def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
    for block in bytesiter:
        hasher.update(block)
    return hasher.hexdigest() if ashexstr else hasher.digest()

def file_as_blockiter(afile, blocksize=65536):
    with afile:
        block = afile.read(blocksize)
        while len(block) > 0:
            yield block
            block = afile.read(blocksize)


[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
    for fname in fnamelst]

And, again, since MD5 is broken and should not really ever be used anymore:

[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
    for fname in fnamelst]

Again, you can put [:16] after the call to hash_bytestr_iter(...) if you only want 128 bits worth of digest.

how to make a div to wrap two float divs inside?

HTML

<div id="wrapper">
    <div id="nav"></div>
    <div id="content"></div>      
    <div class="clearFloat"></div>
</div>

CSS

.clearFloat {
    font-size: 0px;
    line-height: 0px;
    margin: 0px;
    padding: 0px;
    clear: both;
    height: 0px;
}

How to get a cookie from an AJAX response?

xhr.getResponseHeader('Set-Cookie');

It won't work for me.

I use this

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

success: function(output, status, xhr) {
    alert(getCookie("MyCookie"));
},

http://www.w3schools.com/js/js_cookies.asp

Leader Not Available Kafka in Console Producer

I had kafka running as a Docker container and similar messages were flooding to the log.
And KAFKA_ADVERTISED_HOST_NAME was set to 'kafka'.

In my case the reason for error was the missing /etc/hosts record for 'kafka' in 'kafka' container itself.
So, for example, running ping kafka inside 'kafka' container would fail with ping: bad address 'kafka'

In terms of Docker this problem gets solved by specifying hostname for the container.

Options to achieve it:

No submodule mapping found in .gitmodule for a path that's not a submodule

Following rajibchowdhury's answer (upvoted), use git rm command which is advised is for removing the special entry in the index indicating a submodule (a 'folder' with a special mode 160000).

If that special entry path isn't referenced in the .gitmodule (like 'Classes/Support/Three20' in the original question), then you need to remove it, in order to avoid the "No submodule mapping found in .gitmodules for path" error message.

You can check all the entries in the index which are referencing submodules:

git ls-files --stage | grep 160000

Previous answer (November 2010)

It is possible that you haven't declared your initial submodule correctly (i.e. without any tail '/' at the end, as described in my old answer, even though your .gitmodule has paths which looks ok in it).

This thread mentions:

do you get the same error when running 'git submodule init' from a fresh clone?
If so, you have something wrong.

If you have no submodules, delete .gitmodules, and any references to submodules in .git/config, and ensure the Pikimal dir does not have a .git dir in it.
If that fixes the problem, check in and do the same on your cruise working copy.

Obviously, don't delete your main .gitmodules file, but look after other extra .gitmodules files in your working tree.


Still in the topic of "incorrect submodule initialization", Jefromi mentions submodules which actually are gitlinks.

See How to track untracked content? in order to convert such a directory to a real submodule.

how to refresh page in angular 2

If you want to reload the page , you can easily go to your component then do :

location.reload();

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

In my case port 8080 are already use by my local xampp server during oracle installation software check un used port like pop window appear for me enter image description here

so for me url is http://127.0.0.1:8081/apex/f?p=4950:1:4076881202565564

Showing percentages above bars on Excel column graph

You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.

Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.

Here is a working code I have written for you:

https://www.funfun.io/1/#/edit/5a58c6368dfd67466879ed27

In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.

I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file): Percentage (%) = 100 x partial value / total value

It automatically calculates the total and pourcentage even if you add more categories.

I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:

var trace1 = {
    x: xValue, 
    y: data,
    type: 'bar',
    text: yValue,
    textposition: 'auto',
    hoverinfo: 'none',
    marker: {
    color: 'yellow',
    opacity: 0.6,
    line: {
      color: 'yellow',
      width: 1.5
    }
  }
};

It is rather self explanatory, the text is where you put the percentage.

Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:

final

I know it is an old post but I hope it helps people with the same problem !

Disclosure : I’m a developer of funfun

Delete specific line number(s) from a text file using sed?

and awk as well

awk 'NR!~/^(5|10|25)$/' file

How to create a floating action button (FAB) in android, using AppCompat v21?

@Justin Pollard xml code works really good. As a side note you can add a ripple effect with the following xml lines.

    <item>
    <ripple
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:colorControlHighlight" >
        <item android:id="@android:id/mask">
            <shape android:shape="oval" >
                <solid android:color="#FFBB00" />
            </shape>
        </item>
        <item>
            <shape android:shape="oval" >
                <solid android:color="@color/ColorPrimary" />
            </shape>
        </item>
    </ripple>
</item>

String replace a Backslash

 sSource = StringUtils.replace(sSource, "\\/", "/")

Find difference between timestamps in seconds in PostgreSQL

Try: 

SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamp_A))
FROM TableA

Details here: EXTRACT.

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

With Java 8 and later, use the java.time package.

ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();

ZonedDateTime.now() is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int value.

Split string using a newline delimiter with Python

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

print(data.split())       # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

str.split, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use

print(data.split("\n"))   # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Or as @Ashwini Chaudhary suggested in the comments, you can use

print(data.splitlines())

Batch not-equal (inequality) operator

NEQ is usually used for numbers and == is typically used for string comparison.

I cannot find any documentation that mentions a specific and equivalent inequality operand for string comparison (in place of NEQ). The solution using IF NOT == seems the most sound approach. I can't immediately think of a circumstance in which the evaluation of operations in a batch file would cause an issue or unexpected behavior when applying the IF NOT == comparison method to strings.

I wish I could offer insight into how the two functions behave differently on a lower level - would disassembling separate batch files (that use NEQ and IF NOT ==) offer any clues in terms of which (unofficially documented) native API calls conhost.exe is utilizing?

difference between css height : 100% vs height : auto

The default is height: auto in browser, but height: X% Defines the height in percentage of the containing block.

Remove composer

If you install the composer as global on Ubuntu, you just need to find the composer location.

Use command

type composer

or

where composer

For Mac users, use command:

which composer

and then just remove the folder using rm command.

Using find to locate files that match one of multiple patterns

I needed to remove all files in child dirs except for some files. The following worked for me (three patterns specified):

find . -depth -type f -not -name *.itp -and -not -name *ane.gro -and -not -name *.top -exec rm '{}' +

Foreach loop in C++ equivalent of C#

After getting used to the var keyword in C#, I'm starting to use the auto keyword in C++11. They both determine type by inference and are useful when you just want the compiler to figure out the type for you. Here's the C++11 port of your code:

#include <array>
#include <string>

using namespace std;

array<string, 3> strarr = {"ram", "mohan", "sita"};
for(auto str: strarr) {
  listbox.items.add(str);
}

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

Moment.js transform to date object

let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();

nice and clean!!!!

Mapping list in Yaml to list of objects in Spring Boot

I had much issues with this one too. I finally found out what's the final deal.

Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :

@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration  <-  you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {

    private String xyz;
    //initialize arraylist
    private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();

    public AvailableChannelsConfiguration() {
        for(ChannelConfiguration current : this.getChannelConfigurations()) {
            System.out.println(current.getName()); //TADAAA
        }
    }

    public List<ChannelConfiguration> getChannelConfigurations() {
        return this.channelConfigurations;
    }

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;
    }

}

And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)

Trying to SSH into an Amazon Ec2 instance - permission error

What did it for me is editing the default security group to allow for inbound TCP traffic at port 22:

enter image description here

How to center canvas in html5

I have had the same problem, as I have pictures with many different widths which I load only with height info. Setting a width allows the browser to stretch and squeeze the picture. I solve the problem by having the text line just before the image_tag line centred (also getting rid of float: left;). I would have liked the text to be left aligned, but this is a minor inconvienence, that I can tolerate.

How do I install jmeter on a Mac?

Download last version (not 2.5.1 or other old ones) from jmeter.apache.org

Unzip file

Ensure you install a version of JAVA which is compatible, Java 6 or 7 for JMeter 2.11

In bin folder click on jmeter.sh not on jar or execute sh ./apache-jmeter-x.x.x/bin/jmeter in the terminal.

x.x.x is the version you use.

Finally, when started you may want to select System Look and feel for Mac OSX better integration. Menu > Options > Look and Feel > System

How do I check if a type is a subtype OR the type of an object?

Apparently, no.

Here's the options:

Type.IsSubclassOf

As you've already found out, this will not work if the two types are the same, here's a sample LINQPad program that demonstrates:

void Main()
{
    typeof(Derived).IsSubclassOf(typeof(Base)).Dump();
    typeof(Base).IsSubclassOf(typeof(Base)).Dump();
}

public class Base { }
public class Derived : Base { }

Output:

True
False

Which indicates that Derived is a subclass of Base, but that Baseis (obviously) not a subclass of itself.

Type.IsAssignableFrom

Now, this will answer your particular question, but it will also give you false positives. As Eric Lippert has pointed out in the comments, while the method will indeed return True for the two above questions, it will also return True for these, which you probably don't want:

void Main()
{
    typeof(Base).IsAssignableFrom(typeof(Derived)).Dump();
    typeof(Base).IsAssignableFrom(typeof(Base)).Dump();
    typeof(int[]).IsAssignableFrom(typeof(uint[])).Dump();
}

public class Base { }
public class Derived : Base { }

Here you get the following output:

True
True
True

The last True there would indicate, if the method only answered the question asked, that uint[] inherits from int[] or that they're the same type, which clearly is not the case.

So IsAssignableFrom is not entirely correct either.

is and as

The "problem" with is and as in the context of your question is that they will require you to operate on the objects and write one of the types directly in code, and not work with Type objects.

In other words, this won't compile:

SubClass is BaseClass
^--+---^
   |
   +-- need object reference here

nor will this:

typeof(SubClass) is typeof(BaseClass)
                    ^-------+-------^
                            |
                            +-- need type name here, not Type object

nor will this:

typeof(SubClass) is BaseClass
^------+-------^
       |
       +-- this returns a Type object, And "System.Type" does not
           inherit from BaseClass

Conclusion

While the above methods might fit your needs, the only correct answer to your question (as I see it) is that you will need an extra check:

typeof(Derived).IsSubclassOf(typeof(Base)) || typeof(Derived) == typeof(Base);

which of course makes more sense in a method:

public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
    return potentialDescendant.IsSubclassOf(potentialBase)
           || potentialDescendant == potentialBase;
}

How can I process each letter of text using Javascript?

You can simply iterate it as in an array:

for(var i in txt){
    console.log(txt[i]);
}

prevent refresh of page when button inside form clicked

Let getData() return false. This will fix it.

<form method="POST">
    <button name="data" onclick="return getData()">Click</button>
</form>

What is the order of precedence for CSS?

Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest: CSS styling order

Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.

HTML table with 100% width, with vertical scroll inside tbody

Create two tables one after other, put second table in a div of fixed height and set the overflow property to auto. Also keep all the td's inside thead in second table empty.

<div>
    <table>
        <thead>
            <tr>
                <th>Head 1</th>
                <th>Head 2</th>
                <th>Head 3</th>
                <th>Head 4</th>
                <th>Head 5</th>
            </tr>
        </thead>
    </table>
</div>

<div style="max-height:500px;overflow:auto;">
    <table>
        <thead>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <tr>
            <td>Content 1</td>
            <td>Content 2</td>
            <td>Content 3</td>
            <td>Content 4</td>
            <td>Content 5</td>
        </tr>
        </tbody>
    </table>    
</div>