Programs & Examples On #Syntax highlighting

Syntax highlighting is a feature of some text editors that display text (especially source code) in different colors and fonts according to the category of terms.

Copy Notepad++ text with formatting?

Select the Text

From the menu, go to Plugins > NPPExport > Copy RTF to clipboard

In MS Word go to Edit > Paste Special

This will open the Paste Special dialog box. Select the Paste radio button and from the list select Formatted Text (RTF)

You should be able to see the Formatted Text.

Set language for syntax highlighting in Visual Studio Code

Note that for "Untitled" editor ("Untitled-1", "Untitled-2"), you now can set the language in the settings.

The previous setting was:

"files.associations": {
        "untitled-*": "javascript"
 }

This will not always work anymore, because with VSCode 1.42 (Q1 2020) will change the title of those untitled editors.
The title will now be the first line of the document for the editor title, along the generic name as part of the description.
It won't start anymore with "untitled-"

See "Untitled editor improvements"

Regarding the associated language for those "Untitled" editors:

By default, untitled files do not have a specific language mode configured.

VS Code has a setting, files.defaultLanguage, to configure a default language for untitled files.

With this release, the setting can take a new value {activeEditorLanguage} that will dynamically use the language mode of the currently active editor instead of a fixed default.

In addition, when you copy and paste text into an untitled editor, VS Code will now automatically change the language mode of the untitled editor if the text was copied from a VS Code editor:

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_42/untitled-copy2.gif

And see workbench.editor.untitled.labelFormat in VSCode 1.43.

How can I enable auto complete support in Notepad++?

You can also add your own suggestion.

Open this path:

C:\Program Files\Notepad++\plugins\APIs

And open the XML file of the language, such as php.xml. Here suppose, you would like to add addcslashes, so just add this XML code.

<KeyWord name="addcslashes" func="yes">
    <Overload retVal="void">
        <Param name="void"/>
    </Overload>
</KeyWord>

How To Format A Block of Code Within a Presentation?

An on-line syntax highlighter:

http://markup.su/highlighter/

or

http://hilite.me/

Just copy and paste into your document.

How to customise file type to syntax associations in Sublime Text?

In Sublime Text (confirmed in both v2.x and v3.x) there is a menu command:

View -> Syntax -> Open all with current extension as ...

Change / Add syntax highlighting for a language in Sublime 2/3

The "this" is already coloured in Javascript.

View->Syntax-> and choose your language to highlight.

IPhone/IPad: How to get screen width programmatically?

use:

NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;

Adding a default value in dropdownlist after binding with database

You can add it programmatically or in the markup, but if you add it programmatically, rather than Add the item, you should Insert it as position zero so that it is the first item:

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");

The default item is expected to be the first item in the list. If you just Add it, it will be on the bottom and will not be selected by default.

C/C++ switch case with string

The best way is to use source generation, so that you could use

if (hash(str) == HASH("some string") ..

in your main source, and an pre-build step would convert the HASH(const char*) expression to an integer value.

What is the equivalent of the C++ Pair<L,R> in Java?

The biggest problem is probably that one can't ensure immutability on A and B (see How to ensure that type parameters are immutable) so hashCode() may give inconsistent results for the same Pair after is inserted in a collection for instance (this would give undefined behavior, see Defining equals in terms of mutable fields). For a particular (non generic) Pair class the programmer may ensure immutability by carefully choosing A and B to be immutable.

Anyway, clearing generic's warnings from @PeterLawrey's answer (java 1.7) :

public class Pair<A extends Comparable<? super A>,
                    B extends Comparable<? super B>>
        implements Comparable<Pair<A, B>> {

    public final A first;
    public final B second;

    private Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public static <A extends Comparable<? super A>,
                    B extends Comparable<? super B>>
            Pair<A, B> of(A first, B second) {
        return new Pair<A, B>(first, second);
    }

    @Override
    public int compareTo(Pair<A, B> o) {
        int cmp = o == null ? 1 : (this.first).compareTo(o.first);
        return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
    }

    @Override
    public int hashCode() {
        return 31 * hashcode(first) + hashcode(second);
    }

    // TODO : move this to a helper class.
    private static int hashcode(Object o) {
        return o == null ? 0 : o.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Pair))
            return false;
        if (this == obj)
            return true;
        return equal(first, ((Pair<?, ?>) obj).first)
                && equal(second, ((Pair<?, ?>) obj).second);
    }

    // TODO : move this to a helper class.
    private boolean equal(Object o1, Object o2) {
        return o1 == o2 || (o1 != null && o1.equals(o2));
    }

    @Override
    public String toString() {
        return "(" + first + ", " + second + ')';
    }
}

Additions/corrections much welcome :) In particular I am not quite sure about my use of Pair<?, ?>.

For more info on why this syntax see Ensure that objects implement Comparable and for a detailed explanation How to implement a generic max(Comparable a, Comparable b) function in Java?

How do I debug error ECONNRESET in Node.js?

I had the same issue and it appears that the Node.js version was the problem.

I installed the previous version of Node.js (10.14.2) and everything was ok using nvm (allow you to install several version of Node.js and quickly switch from a version to another).

It is not a "clean" solution, but it can serve you temporarly.

Datetime BETWEEN statement not working in SQL Server

You need to convert the date field to varchar to strip out the time, then convert it back to datetime, this will reset the time to '00:00:00.000'.

SELECT *
FROM [TableName]
WHERE
    (
        convert(datetime,convert(varchar,GETDATE(),1)) 

        between 

        convert(datetime,convert(varchar,[StartDate],1)) 

        and  

        convert(datetime,convert(varchar,[EndDate],1))
    )

How to display Oracle schema size with SQL query?

You probably want

SELECT sum(bytes)
  FROM dba_segments
 WHERE owner = <<owner of schema>>

If you are logged in as the schema owner, you can also

SELECT SUM(bytes)
  FROM user_segments

That will give you the space allocated to the objects owned by the user in whatever tablespaces they are in. There may be empty space allocated to the tables that is counted as allocated by these queries.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

Java, unlike languages like C and C++, treats boolean as a completely separate data type which has 2 distinct values: true and false. The values 1 and 0 are of type int and are not implicitly convertible to boolean.

<> And Not In VB.NET

I'm a total noob, I came here to figure out VB's 'not equal to' syntax, so I figured I'd throw it in here in case someone else needed it:

<%If Not boolean_variable%>Do this if boolean_variable is false<%End If%>

Change some value inside the List<T>

I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:

 foreach (var mc in list.Where(x => x.Name == "height"))  
     mc.Value = 30;

using where and inner join in mysql

Try this:

SELECT Locations.Name, Schools.Name
FROM Locations
INNER JOIN School_Locations ON School_Locations.Locations_Id = Locations.Id
INNER JOIN Schools ON School.Id = Schools_Locations.School_Id
WHERE Locations.Type = "coun"

You can join Locations to School_Locations and then School_Locations to School. This forms a set of all related Locations and Schools, which you can then widdle down using the WHERE clause to those whose Location is of type "coun."

How to suppress "unused parameter" warnings in C?

I've seen this style being used:

if (when || who || format || data || len);

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

How to check for DLL dependency?

The safest thing is have some clean virtual machine, on which you can test your program. On every version you'd like to test, restore the VM to its initial clean value. Then install your program using its setup, and see if it works.

Dll problems have different faces. If you use Visual Studio and dynamically link to the CRT, you have to distribute the CRT DLLs. Update your VS, and you have to distribute another version of the CRT. Just checking dependencies is not enough, as you might miss those. Doing a full install on a clean machine is the only safe solution, IMO.

If you don't want to setup a full-blown test environment and have Windows 7, you can use XP-Mode as the initial clean machine, and XP-More to duplicate the VM.

Get loop count inside a Python FOR loop

Using zip function we can get both element and index.

countries = ['Pakistan','India','China','Russia','USA']

for index, element zip(range(0,countries),countries):

         print('Index : ',index)
         print(' Element : ', element,'\n')

output : Index : 0 Element : Pakistan ...

See also :

Python.org

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Matplotlib - global legend and title aside subplots

suptitle seems the way to go, but for what it's worth, the figure has a transFigure property that you can use:

fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')

How to allow CORS in react.js?

I deal with this issue for some hours. Let's consider the request is Reactjs (javascript) and backend (API) is Asp .Net Core.

in the request, you must set in header Content-Type:

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/json'},
            url: 'https://localhost:44346/Order/Order/GiveOrder',
            data: order,
          }).then(function (response) {
            console.log(response);
          });

and in backend (Asp .net core API) u must have some setting:

1. in Startup --> ConfigureServices:

#region Allow-Orgin
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
            #endregion

2. in Startup --> Configure before app.UseMvc() :

app.UseCors(builder => builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());

3. in controller before action:

[EnableCors("AllowOrigin")]

Where does Chrome store extensions?

For older versions of windows (2k, 2k3, xp)

"%Userprofile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions" 

read subprocess stdout line by line

You can also read lines w/o loop. Works in python3.6.

import os
import subprocess

process = subprocess.Popen(command, stdout=subprocess.PIPE)
list_of_byte_strings = process.stdout.readlines()

How to format a DateTime in PowerShell

A simple and nice way is:

$time = (Get-Date).ToString("yyyy:MM:dd")

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

How to write a cursor inside a stored procedure in SQL Server 2008

You can create a trigger which updates NoofUses column in Coupon table whenever couponid is used in CouponUse table

query :

CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
  BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end 

How do I remove link underlining in my HTML email?

All you have to do is:

<a href="" style="text-decoration:#none; letter-spacing: -999px;">

Java, Calculate the number of days between two dates

Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.

I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:

int days = Days.daysBetween(date1, date2).getDays();

Is it correct to use DIV inside FORM?

It is completely acceptable to use a DIV inside a <form> tag.

If you look at the default CSS 2.1 stylesheet, div and p are both in the display: block category. Then looking at the HTML 4.01 specification for the form element, they include not only <p> tags, but <table> tags, so of course <div> would meet the same criteria. There is also a <legend> tag inside the form in the documentation.

For instance, the following passes HTML4 validation in strict mode:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
</head>
<body>
<form id="test" action="test.php">
<div>
  Test: <input name="blah" value="test" type="text">
</div>
</form>
</body>
</html>

How to include a PHP variable inside a MySQL statement

The text inside $type is substituted directly into the insert string, therefore MySQL gets this:

... VALUES(testing, 'john', 'whatever')

Notice that there are no quotes around testing, you need to put these in like so:

$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");

I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:

Postgresql - unable to drop database because of some auto connections to DB

I found a solution for this problem try to run this command in terminal

ps -ef | grep postgres

kill process by this command

sudo kill -9 PID

Bad Request, Your browser sent a request that this server could not understand

Here is a detailed explanation & solution for this problem from ibm.

Problem(Abstract)

Request to HTTP Server fails with Response code 400.

Symptom

Response from the browser could be shown like this:

Bad Request Your browser sent a request that this server could not understand. Size of a request header field exceeds server limit.

HTTP Server Error.log shows the following message: "request failed: error reading the headers"

Cause

This is normally caused by having a very large Cookie, so a request header field exceeded the limit set for Web Server.

Diagnosing the problem

To assist with diagnose of the problem you can add the following to the LogFormat directive in the httpd.conf: error-note: %{error-notes}n

Resolving the problem

For server side: Increase the value for the directive LimitRequestFieldSize in the httpd.conf: LimitRequestFieldSize 12288 or 16384 For How to set the LimitRequestFieldSize, check Increase the value of LimitRequestFieldSize in Apache

For client side: Clear the cache of your web browser should be fine.

How can I control the width of a label tag?

Giving width to Label is not a proper way. you should take one div or table structure to manage this. but still if you don't want to change your whole code then you can use following code.

label {
  width:200px;
  float: left;
}

How can I hide a TD tag using inline JavaScript or CSS?

You can simply hide the <td> tag content by just including a style attribute: style = "display:none"

For e.g

<td style = "display:none" >
<p> I'm invisible </p>
</td>

Python: Get HTTP headers from urllib2.urlopen call?

def _GetHtmlPage(self, addr):
  headers = { 'User-Agent' : self.userAgent,
            '  Cookie' : self.cookies}

  req = urllib2.Request(addr)
  response = urllib2.urlopen(req)

  print "ResponseInfo="
  print response.info()

  resultsHtml = unicode(response.read(), self.encoding)
  return resultsHtml  

How to remove the querystring and get only the url?

You can try:

<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>

How to assign an action for UIImageView object in Swift

You can put a UIButton with a transparent background over top of the UIImageView, and listen for a tap on the button before loading the image

Send Email Intent

use Anko - kotlin

context.email(email, subject, body)

How do the post increment (i++) and pre increment (++i) operators work in Java?

i = ++a + ++a + a++;

is

i = 6 + 7 + 7

Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.

i = a++ + ++a + ++a;

is

i = 5 + 7 + 8

Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.

Styling the last td in a table with css

you could use the last-child psuedo class

table tr td:last-child {
    border: none;
}

This will style the last td only. It's not fully supported yet so it may be unsuitable

how to open .mat file without using MATLAB?

If you are using the free software R, you can open the matlab files in Rstudio. Very easy!

seek() function?

For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.

How to run a stored procedure in oracle sql developer?

-- If no parameters need to be passed to a procedure, simply:

BEGIN
   MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;

How to keep two folders automatically synchronized?

Just simple modification of @silgon answer:

while true; do 
  inotifywait -r -e modify,create,delete /directory
  rsync -avz /directory /target
done

(@silgon version sometimes crashes on Ubuntu 16 if you run it in cron)

How do I type a TAB character in PowerShell?

TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Typically, to troubleshoot this, you go to SQL Server Configuration Manager (SSCM) and:

  1. ensure Shared Memory protocol is enabled
  2. ensure Named Pipes protocol is enabled
  3. ensure TCP/IP is enabled, and is ahead of the Named Pipes in the settings

Maybe it can help: Could not open a connection to SQL Server

LINQ to read XML

Try this.

using System.Xml.Linq;

void Main()
{
    StringBuilder result = new StringBuilder();

    //Load xml
    XDocument xdoc = XDocument.Load("data.xml");

    //Run query
    var lv1s = from lv1 in xdoc.Descendants("level1")
               select new { 
                   Header = lv1.Attribute("name").Value,
                   Children = lv1.Descendants("level2")
               };

    //Loop through results
    foreach (var lv1 in lv1s){
            result.AppendLine(lv1.Header);
            foreach(var lv2 in lv1.Children)
                 result.AppendLine("     " + lv2.Attribute("name").Value);
    }

    Console.WriteLine(result);
}

Copy files on Windows Command Line with Progress

The Esentutl /y option allows copyng (single) file files with progress bar like this :

enter image description here

the command should look like :

esentutl /y "FILE.EXT" /d "DEST.EXT" /o

The command is available on every windows machine but the y option is presented in windows vista. As it works only with single files does not look very useful for a small ones. Other limitation is that the command cannot overwrite files. Here's a wrapper script that checks the destination and if needed could delete it (help can be seen by passing /h).

How to disable manual input for JQuery UI Datepicker field?

I think you should add style="background:white;" to make looks like it is writable

<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly"   style="background:white;"/>

How to choose an AWS profile when using boto3 to connect to CloudFront

Do this to use a profile with name 'dev':

session = boto3.session.Session(profile_name='dev')
s3 = session.resource('s3')
for bucket in s3.buckets.all():
    print(bucket.name)

How do I make Java register a string input with spaces?

I found a very weird thing in Java today, so it goes like -

If you are inputting more than 1 thing from the user, say

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s

But, the output that you will get is -

10
2.5

And that's it, it doesn't even prompt for the String input. Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().

So changing my code to something like this -

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.

Please if anybody knows help me with an explanation for this.

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

Try surrounding the path in quotes. i.e "C:\Program Files\Appname\config.file"

Installing and Running MongoDB on OSX

Make sure you are logged in as root user in your terminal.

Steps to start mongodb server in your mac

  1. Open Terminal
  2. Run the command sudo su
  3. Enter your administrator password
  4. run the command mongod
  5. MongoDb Server starts

Hope it helps you. Thanks

How does facebook, gmail send the real time notification?

The way Facebook does this is pretty interesting.

A common method of doing such notifications is to poll a script on the server (using AJAX) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.

The way Facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug's Console tab while on Facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to 'fire' events.

Behind this, in terms of the actual content returned from those polls, it's a JSON response, with what appears to be a list of events, and info about them. It's minified though, so is a bit hard to read.

In terms of the actual technology, AJAX is the way to go here, because you can control request timeouts, and many other things. I'd recommend (Stack overflow cliche here) using jQuery to do the AJAX, it'll take a lot of the cross-compability problems away. In terms of PHP, you could simply poll an event log database table in your PHP script, and only return to the client when something happens? There are, I expect, many ways of implementing this.

Implementing:

Server Side:

There appear to be a few implementations of comet libraries in PHP, but to be honest, it really is very simple, something perhaps like the following pseudocode:

while(!has_event_happened()) {
   sleep(5);
}

echo json_encode(get_events());
  • The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.

  • Don't forget to change your PHP max execution time, otherwise it will timeout early!

Client Side:

Take a look at the jQuery plugin for doing Comet interaction:

That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jQuery) something like:

function doPoll() {
   $.get("events.php", {}, function(result) {
      $.each(result.events, function(event) { //iterate over the events
          //do something with your event
      });
      doPoll(); 
      //this effectively causes the poll to run again as
      //soon as the response comes back
   }, 'json'); 
}

$(document).ready(function() {
    $.ajaxSetup({
       timeout: 1000*60//set a global AJAX timeout of a minute
    });
    doPoll(); // do the first poll
});

The whole thing depends a lot on how your existing architecture is put together.

convert a list of objects from one type to another using lambda expression

We will consider first List type is String and want to convert it to Integer type of List.

List<String> origList = new ArrayList<>(); // assume populated

Add values in the original List.

origList.add("1");
origList.add("2");
    origList.add("3");
    origList.add("4");
    origList.add("8");

Create target List of Integer Type

List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());

Print List values using forEach:

    targetLambdaList.forEach(System.out::println);

Load arrayList data into JTable

You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.

 PingScan p = new PingScan();
 List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
                for (final Future<String> f : scanResult) {
                    try {
                        if (f.get() instanceof String) {
                            String ip = f.get();
                            Object[] data = {ip};
                            tableModel.addRow(data);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

How to open the Chrome Developer Tools in a new window?

enter image description here

  1. click on three dots in the top right ->
  2. click on "Undock into separate window" icon

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

How to add multiple values to a dictionary key in python?

How about

a["abc"] = [1, 2]

This will result in:

>>> a
{'abc': [1, 2]}

Is that what you were looking for?

What is the difference between Forking and Cloning on GitHub?

In case you did what the questioner hinted at (forgot to fork and just locally cloned a repo, made changes and now need to issue a pull request) you can get back on track:

  1. fork the repo you want to send pull request to
  2. push your local changes to your remote
  3. issue pull request

How do I launch a program from command line without opening a new cmd window?

You can use the call command...

Type: call /?

Usage: call [drive:][path]filename [batch-parameters]

For example call "Example File/Input File/My Program.bat" [This is also capable with calling files that have a .exe, .cmd, .txt, etc.

NOTE: THIS COMMAND DOES NOT ALWAYS WORK!!!

Not all computers are capable to run this command, but if it does work than it is very useful, and you won't have to open a brand new window...

no suitable HttpMessageConverter found for response type

From a Spring point of view, none of the HttpMessageConverter instances registered with the RestTemplate can convert text/html content to a ProductList object. The method of interest is HttpMessageConverter#canRead(Class, MediaType). The implementation for all of the above returns false, including Jaxb2RootElementHttpMessageConverter.

Since no HttpMessageConverter can read your HTTP response, processing fails with an exception.

If you can control the server response, modify it to set the Content-type to application/xml, text/xml, or something matching application/*+xml.

If you don't control the server response, you'll need to write and register your own HttpMessageConverter (which can extend the Spring classes, see AbstractXmlHttpMessageConverter and its sub classes) that can read and convert text/html.

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

Is there a good Valgrind substitute for Windows?

Check out this question: Is there a good Valgrind substitute for Windows? . Though general substitute for valgrind is asked, it mainly discusses memory leak detectors and not race conditions detections.

ASP.NET Core Identity - get current user

Assuming your code is inside an MVC controller:

public class MyController : Microsoft.AspNetCore.Mvc.Controller

From the Controller base class, you can get the IClaimsPrincipal from the User property

System.Security.Claims.ClaimsPrincipal currentUser = this.User;

You can check the claims directly (without a round trip to the database):

bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:

Other fields can be fetched from the database's User entity:

  1. Get the user manager using dependency injection

    private UserManager<ApplicationUser> _userManager;
    
    //class constructor
    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    
  2. And use it:

    var user = await _userManager.GetUserAsync(User);
    var email = user.Email;
    

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

If the user cancel the request, the data will be returned as NULL. The thread will throw a nullPointerException when you call data.getExtras().get("data");. I think you just need to add a conditional to check if the data returned is null.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST) {
       if (data != null)
       {         
           Bitmap photo = (Bitmap) data.getExtras().get("data"); 
           imageView.setImageBitmap(photo);
       }
}  

How do I change the font-size of an <option> element within <select>?

Like most form controls in HTML, the results of applying CSS to <select> and <option> elements vary a lot between browsers. Chrome, as you've found, won't let you apply and font styles to an <option> element directly --- if you do Inspect Element on it, you'll see the font-size: 14px declaration is crossed through as if it's been overridden by the cascade, but it's actually because Chrome is ignoring it.

However, Chrome will let you apply font styles to the <optgroup> element, so to achieve the result you want you can wrap all the <option>s in an <optgroup> and then apply your font styles to a .styled-select optgroup selector. If you want the optgroup sans-label, you may have to do some clever CSS with positioning or something to hide the white area at the top where the label would be shown, but that should be possible.

Forked to a new JSFiddle to show you what I mean:

http://jsfiddle.net/zRtbZ/

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Daemon Threads Explanation

Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:

  1. Connect to the mail server and ask how many unread messages you have.
  2. Signal the GUI with the updated count.
  3. Sleep for a little while.

When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.

Angular HttpClient "Http failure during parsing"

Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);

Becuase if you turn it to text but backend asks for json, it will return an error...

SQL Server: Difference between PARTITION BY and GROUP BY

They're used in different places. group by modifies the entire query, like:

select customerId, count(*) as orderCount
from Orders
group by customerId

But partition by just works on a window function, like row_number:

select row_number() over (partition by customerId order by orderId)
    as OrderNumberForThisCustomer
from Orders

A group by normally reduces the number of rows returned by rolling them up and calculating averages or sums for each row. partition by does not affect the number of rows returned, but it changes how a window function's result is calculated.

Set element focus in angular way

I prefered to use an expression. This lets me do stuff like focus on a button when a field is valid, reaches a certain length, and of course after load.

<button type="button" moo-focus-expression="form.phone.$valid">
<button type="submit" moo-focus-expression="smsconfirm.length == 6">
<input type="text" moo-focus-expression="true">

On a complex form this also reduces need to create additional scope variables for the purposes of focusing.

See https://stackoverflow.com/a/29963695/937997

Export to csv in jQuery

I recently posted a free software library for this: "html5csv.js" -- GitHub

It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.

After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:

CSV.begin('#PrintDiv').download('MyData.csv').go();

Here is a JSFiddle demo of your example with this code.

Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE

The CSV.begin() call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download() generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.

According to caniuse IE10 doesn't support <a download=...>. So for IE my library calls navigator.msSaveBlob() internally, as suggested by @Manu Sharma

Convert DateTime to TimeSpan

You can just use the TimeOfDay property of date time, which is TimeSpan type:

DateTime.TimeOfDay

This property has been around since .NET 1.1

More information: http://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx

Two HTML tables side by side, centered on the page

Unfortunately, all of these solutions rely on specifying a fixed width. Since the tables are generated dynamically (statistical results pulled from a database), the width can not be known in advance.

The desired result can be achieved by wrapping the two tables within another table:

<table align="center"><tr><td>
//code for table on the left
</td><td>
//code for table on the right
</td></tr></table>

and the result is a perfectly centered pair of tables that responds fluidly to arbitrary widths and page (re)sizes (and the align="center" table attribute could be hoisted out into an outer div with margin autos).

I conclude that there are some layouts that can only be achieved with tables.

How to add elements of a Java8 stream into an existing List

Lets say we have existing list, and gonna use java 8 for this activity `

import java.util.*;
import java.util.stream.Collectors;

public class AddingArray {

    public void addArrayInList(){
        List<Integer> list = Arrays.asList(3, 7, 9);

   // And we have an array of Integer type 

        int nums[] = {4, 6, 7};

   //Now lets add them all in list
   // converting array to a list through stream and adding that list to previous list
        list.addAll(Arrays.stream(nums).map(num -> 
                                       num).boxed().collect(Collectors.toList()));
     }
}

`

Escaping ampersand character in SQL string

--SUBSTITUTION VARIABLES
-- these variables are used to store values TEMPorarily.
-- The values can be stored temporarily through
-- Single Ampersand (&)
-- Double Ampersand(&&)
-- The single ampersand substitution variable applies for each instance when the
--SQL statement is created or executed.
-- The double ampersand substitution variable is applied for all instances until
--that SQL statement is existing.
INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');
--Using double ampersand substitution variable
INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,'&gender');

Convert an integer to an array of digits

Let's solve that using recursion...

ArrayList<Integer> al = new ArrayList<>();

void intToArray(int num){
    if( num != 0){
        int temp = num %10;
        num /= 10;
        intToArray(num);
        al.add(temp);
    }
}

Explanation:

Suppose the value of num is 12345.

During the first call of the function, temp holds the value 5 and a value of num = 1234. It is again passed to the function, and now temp holds the value 4 and the value of num is 123... This function calls itself till the value of num is not equal to 0.

Stack trace:

 temp - 5 | num - 1234
 temp - 4 | num - 123
 temp - 3 | num - 12
 temp - 2 | num - 1
 temp - 1 | num - 0

And then it calls the add method of ArrayList and the value of temp is added to it, so the value of list is:

 ArrayList - 1
 ArrayList - 1,2
 ArrayList - 1,2,3
 ArrayList - 1,2,3,4
 ArrayList - 1,2,3,4,5

How to Get a Sublist in C#

Reverse the items in a sub-list

int[] l = {0, 1, 2, 3, 4, 5, 6};
var res = new List<int>();
res.AddRange(l.Where((n, i) => i < 2));
res.AddRange(l.Where((n, i) => i >= 2 && i <= 4).Reverse());
res.AddRange(l.Where((n, i) => i > 4));

Gives 0,1,4,3,2,5,6

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

PHP has a built in function called bool chmod(string $filename, int $mode )

http://php.net/function.chmod

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);
    chmod($file, 0777);  //changed to add the zero
    return true;
}

T-SQL query to show table definition?

Use this little Windows command-line app that gets the CREATE TABLE script (with constraints) for any table. I've written it in C#. Just compile it and carry it on a memory stick. Perhaps someone can port it to Powershell.

using System;
using System.Linq;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ViewSource
{
    public class ViewSource
    {
        public static void Main(string[] args)
        {
            if (args.Length != 6)
            {
                Console.Error.WriteLine("Syntax: ViewSource.exe <server>" +
                     " <user> <password> <database> <schema> <table>");
            }

            Script(args[0], args[1], args[2], args[3], args[4], args[5]);
        }
        private static void Script(string server, string user,
            string password, string database, string schema, string table)
        {
            new Server(new ServerConnection(server, user, password))
                .Databases[database]
                .Tables[table, schema]
                .Script(new ScriptingOptions { SchemaQualify = true,
                                               DriAll = true })
                .Cast<string>()
                .Select(s => s + "\n" + "GO")
                .ToList()
                .ForEach(Console.WriteLine);
        }
    }
}

Laravel - Session store not set on request

in my case it was just to put return ; at the end of function where i have set session

Django - makemigrations - No changes detected

It is a comment but should probably be an answer.

Make sure that your app name is in settings.py INSTALLED_APPS otherwise no matter what you do it will not run the migrations.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'blog',
]

Then run:

./manage.py makemigrations blog

What is the difference between Java RMI and RPC?

The only real difference between RPC and RMI is that there is objects involved in RMI: instead of invoking functions through a proxy function, we invoke methods through a proxy.

AngularJS - Building a dynamic table based on a json

First off all I would like to thanks @MaximShoustin.

Thanks of you I have really nice table.

I provide some small modification in $scope.range and $scope.setPage.

In this way I have now possibility to go to the last page or come back to the first page. Also when I'm going to next or prev page the navigation is changing when $scope.gap is crossing. And the current page is not always on first position. For me it's looking more nicer.

Here is the new fiddle example: http://jsfiddle.net/qLBRZ/3/

Can a foreign key refer to a primary key in the same table?

Other answers have given clear enough examples of a record referencing another record in the same table.

There are even valid use cases for a record referencing itself in the same table. For example, a point of sale system accepting many tenders may need to know which tender to use for change when the payment is not the exact value of the sale. For many tenders that's the same tender, for others that's domestic cash, for yet other tenders, no form of change is allowed.

All this can be pretty elegantly represented with a single tender attribute which is a foreign key referencing the primary key of the same table, and whose values sometimes match the respective primary key of same record. In this example, the absence of value (also known as NULL value) might be needed to represent an unrelated meaning: this tender can only be used at its full value.

Popular relational database management systems support this use case smoothly.

Take-aways:

  1. When inserting a record, the foreign key reference is verified to be present after the insert, rather than before the insert.

  2. When inserting multiple records with a single statement, the order in which the records are inserted matters. The constraints are checked for each record separately.

  3. Certain other data patterns, such as those involving circular dependences on record level going through two or more tables, cannot be purely inserted at all, or at least not with all the foreign keys enabled, and they have to be established using a combination of inserts and updates (if they are truly necessary).

Add params to given URL in Python

I find this more elegant than the two top answers:

from urllib.parse import urlencode, urlparse, parse_qs

def merge_url_query_params(url: str, additional_params: dict) -> str:
    url_components = urlparse(url)
    original_params = parse_qs(url_components.query)
    # Before Python 3.5 you could update original_params with 
    # additional_params, but here all the variables are immutable.
    merged_params = {**original_params, **additional_params}
    updated_query = urlencode(merged_params, doseq=True)
    # _replace() is how you can create a new NamedTuple with a changed field
    return url_components._replace(query=updated_query).geturl()

assert merge_url_query_params(
    'http://example.com/search?q=question',
    {'lang':'en','tag':'python'},
) == 'http://example.com/search?q=question&lang=en&tag=python'

The most important things I dislike in the top answers (they are nevertheless good):

  • Lukasz: having to remember the index at which the query is in the URL components
  • Sapphire64: the very verbose way of creating the updated ParseResult

What's bad about my response is the magically looking dict merge using unpacking, but I prefer that to updating an already existing dictionary because of my prejudice against mutability.

Generating a random & unique 8 character string using MySQL

This problem consists of two very different sub-problems:

  • the string must be seemingly random
  • the string must be unique

While randomness is quite easily achieved, the uniqueness without a retry loop is not. This brings us to concentrate on the uniqueness first. Non-random uniqueness can trivially be achieved with AUTO_INCREMENT. So using a uniqueness-preserving, pseudo-random transformation would be fine:

  • Hash has been suggested by @paul
  • AES-encrypt fits also
  • But there is a nice one: RAND(N) itself!

A sequence of random numbers created by the same seed is guaranteed to be

  • reproducible
  • different for the first 8 iterations
  • if the seed is an INT32

So we use @AndreyVolk's or @GordonLinoff's approach, but with a seeded RAND:

e.g. Assumin id is an AUTO_INCREMENT column:

INSERT INTO vehicles VALUES (blah); -- leaving out the number plate
SELECT @lid:=LAST_INSERT_ID();
UPDATE vehicles SET numberplate=concat(
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@lid)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed)*36+1, 1)
)
WHERE id=@lid;

Getting the thread ID from a thread

GetThreadId returns the ID of a given native thread. There are ways to make it work with managed threads, I'm sure, all you need to find is the thread handle and pass it to that function.

GetCurrentThreadId returns the ID of the current thread.

GetCurrentThreadId has been deprecated as of .NET 2.0: the recommended way is the Thread.CurrentThread.ManagedThreadId property.

Random / noise functions for GLSL

For very simple pseudorandom-looking stuff, I use this oneliner that I found on the internet somewhere:

float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

You can also generate a noise texture using whatever PRNG you like, then upload this in the normal fashion and sample the values in your shader; I can dig up a code sample later if you'd like.

Also, check out this file for GLSL implementations of Perlin and Simplex noise, by Stefan Gustavson.

Bootstrap 4 File Input

Here is the answer with blue box-shadow,border,outline removed with file name fix in custom-file input of bootstrap appear on choose filename and if you not choose any file then show No file chosen.

_x000D_
_x000D_
    $(document).on('change', 'input[type="file"]', function (event) { _x000D_
        var filename = $(this).val();_x000D_
        if (filename == undefined || filename == ""){_x000D_
        $(this).next('.custom-file-label').html('No file chosen');_x000D_
        }_x000D_
        else _x000D_
        { $(this).next('.custom-file-label').html(event.target.files[0].name); }_x000D_
    });
_x000D_
    input[type=file]:focus,.custom-file-input:focus~.custom-file-label {_x000D_
        outline:none!important;_x000D_
        border-color: transparent;_x000D_
        box-shadow: none!important;_x000D_
    }_x000D_
    .custom-file,_x000D_
    .custom-file-label,_x000D_
    .custom-file-input {_x000D_
        cursor: pointer;_x000D_
    }
_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    <div class="container py-5">_x000D_
    <div class="input-group mb-3">_x000D_
      <div class="input-group-prepend">_x000D_
        <span class="input-group-text">Upload</span>_x000D_
      </div>_x000D_
      <div class="custom-file">_x000D_
        <input type="file" class="custom-file-input" id="inputGroupFile01">_x000D_
        <label class="custom-file-label" for="inputGroupFile01">Choose file</label>_x000D_
      </div>_x000D_
    </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

imagecreatefromjpeg and similar functions are not working in PHP

For php 7 on Ubuntu:

sudo apt-get install php7.0-gd

Finding Number of Cores in Java

If you want to dubbel check the amount of cores you have on your machine to the number your java program is giving you.

In Linux terminal: lscpu

In Windows terminal (cmd): echo %NUMBER_OF_PROCESSORS%

In Mac terminal: sysctl -n hw.ncpu

E11000 duplicate key error index in mongodb mongoose

The error message is saying that there's already a record with null as the email. In other words, you already have a user without an email address.

The relevant documentation for this:

If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.

You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.

unique indexes

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.

In other words, a sparse index is ok with multiple documents all having null values.

sparse indexes


From comments:

Your error says that the key is named mydb.users.$email_1 which makes me suspect that you have an index on both users.email and users.local.email (The former being old and unused at the moment). Removing a field from a Mongoose model doesn't affect the database. Check with mydb.users.getIndexes() if this is the case and manually remove the unwanted index with mydb.users.dropIndex(<name>).

Rebasing remote branches in Git

Because you rebased feature on top of the new master, your local feature is not a fast-forward of origin/feature anymore. So, I think, it's perfectly fine in this case to override the fast-forward check by doing git push origin +feature. You can also specify this in your config

git config remote.origin.push +refs/heads/feature:refs/heads/feature

If other people work on top of origin/feature, they will be disturbed by this forced update. You can avoid that by merging in the new master into feature instead of rebasing. The result will indeed be a fast-forward.

PostgreSQL wildcard LIKE for any of a list of words

All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE.

Reference: https://www.postgresql.org/docs/current/functions-matching.html

Combine two pandas Data Frames (join on a common column)

In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!

T1 and T2 are dataframes that have the same indices

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

P.S. I had to use merge because append would fill NaNs in unnecessarily.

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

How to catch a click event on a button?

Change your onCreate to

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

for me this update worked

Sorting data based on second column of a file

You can use the sort command:

sort -k2 -n yourfile

-n, --numeric-sort compare according to string numerical value

For example:

$ cat ages.txt 
Bob 12
Jane 48
Mark 3
Tashi 54

$ sort -k2 -n ages.txt 
Mark 3
Bob 12
Jane 48
Tashi 54

Using GPU from a docker container?

We just released an experimental GitHub repository which should ease the process of using NVIDIA GPUs inside Docker containers.

What are the JavaScript KeyCodes?

Here are some useful links:

The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.

Create an Android GPS tracking application

Basically you need following things to make location detector android app

Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.

Using all these resources, you will be able to create an flawless android location detection app.

1. Location Listening

You will first need to listen for current location of user. You can use any of below libraries to quick start.

Google Play Location Samples

This library provide last known location, location updates

Location Manager

With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.

Live Location Sharing

Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.

2. Markers Library

Google Maps Android API utility library

  • Marker clustering — handles the display of a large number of points
  • Heat maps — display a large number of points as a heat map
  • IconGenerator — display text on your Markers
  • Poly decoding and encoding — compact encoding for paths, interoperability with Maps API web services
  • Spherical geometry — for example: computeDistance, computeHeading, computeArea
  • KML — displays KML data
  • GeoJSON — displays and styles GeoJSON data

3. Polyline Libraries

DrawRouteMaps

If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.

trail-android

Simple, smooth animation for route / polylines on google maps using projections. (WIP)

Google-Directions-Android

This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.

A map demo app for quick start with maps

Circle drawing with SVG's arc path

Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.

function(cx, cy, r, deg){
    var theta = deg*Math.PI/180,
        dx = r*Math.cos(theta),
        dy = -r*Math.sin(theta);
    return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}

Is there a way to avoid null check before the for-each loop iteration starts?

Apache Commons

for (String code: ListUtils.emptyIfNull(codes)) {

}           

Google Guava

for (String code: Optional.of(codes).get()) {

}

How to vertically center a <span> inside a div?

Quick answer for single line span

Make the child (in this case a span) the same line-height as the parent <div>'s height

<div class="parent">
  <span class="child">Yes mom, I did my homework lol</span>
</div>

You should then add the CSS rules

.parent { height: 20px; }
.child { line-height: 20px; vertical-align: middle; }



Or you can target it with a child selector

.parent { height: 20px; }
.parent > span { line-height: 20px; vertical-align: middle; }

Background on my own use of this

I ran into this similar issue where I needed to vertically center items in a mobile menu. I made the div and spans inside the same line height. Note that this is for a meteor project and therefore not using inline css ;)

HTML

<div class="international">        
  <span class="intlFlag">
    {{flag}}        
  </span>

  <span class="intlCurrent">
    {{country}}
  </span>

  <span class="intlButton">
    <i class="fa fa-globe"></i>
  </span> 
</div>

CSS (option for multiple spans in a div)

.international {
  height: 42px;
}

.international > span {
  line-height: 42px;
}

In this case if I just had one span I could have added the CSS rule directly to that span.

CSS (option for one specific span)

.intlFlag { line-height: 42px; }

Here is how it displayed for me

enter image description here

PHP 7 RC3: How to install missing MySQL PDO

First install php-mysql

sudo apt-get install php7.0-mysql
//change the version number based on the php version

then enable the module

sudo phpenmod pdo_mysql

and restart apache

sudo service apache2 restart 

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc();

main.cpp

#include "other.h"
int main() {
    MyFunc();
}

other.cpp

#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

How to check Django version

Type the following command in Python shell

import django
django.get_version()

Extracting the top 5 maximum values in excel

Put the data into a Pivot Table and do a top n filter on it

Excel Demo

Can I give the col-md-1.5 in bootstrap?

As @bodi0 correctly said, it is not possible. You either have to extent Bootstrap's grid system (you can search and find various solutions, here is a 7-column example) or use nested rows e.g. http://bootply.com/dd50he9tGe.

In the case of nested rows you might not always get the exact result but a similar one

<div class="row">
    <div class="col-lg-5">
        <div class="row">
            <div class="col-lg-4">1.67 (close to 1.5)</div>
            <div class="col-lg-8">3.33 (close to 3.5)</div>
        </div>    
    </div>
    <div class="col-lg-7">
        <div class="row">
            <div class="col-lg-6">3.5</div>
            <div class="col-lg-6">3.5</div>
        </div>    
    </div>
</div>

Change values of select box of "show 10 entries" of jquery datatable

enter image description here pageLength: 50,

worked for me Thanks

Versions for reference

jquery-3.3.1.js

/1.10.19/js/jquery.dataTables.min.js

/buttons/1.5.2/js/dataTables.buttons.min.js

Simple example of threading in C++

There is also a POSIX library for POSIX operating systems. Check for compatability

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>

void *task(void *argument){
      char* msg;
      msg = (char*)argument;
      std::cout<<msg<<std::endl;
}

int main(){
    pthread_t thread1, thread2;
    int i1,i2;
    i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
    i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;

}

compile with -lpthread

http://en.wikipedia.org/wiki/POSIX_Threads

Change DIV content using ajax, php and jQuery

You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load() method to send an AJAX request and replace the contents of the summary div:

$(function() {
    $('.movie').click(function() {
        $('#summary').load(this.href);

        // it's important to return false from the click
        // handler in order to cancel the default action
        // of the link which is to redirect to the url and
        // execute the AJAX request
        return false;
    });
});

How do you list volumes in docker containers?

if you want to list all the containers name with the relevant volumes that attached to each container you can try this:

docker ps -q | xargs docker container inspect -f '{{ .Name }} {{ .HostConfig.Binds }}'

example output:

/opt_rundeck_1 [/opt/var/lib/mysql:/var/lib/mysql:rw /var/lib/rundeck/var/storage:/var/lib/rundeck/var/storage:rw /opt/var/rundeck/.ssh:/var/lib/rundeck/.ssh:rw /opt/etc/rundeck:/etc/rundeck:rw /var/log/rundeck:/var/log/rundeck:rw /opt/rundeck-plugins:/opt/rundeck-plugins:rw /opt/var/rundeck:/var/rundeck:rw]

/opt_rundeck_1 - container name

[..] - volumes attached to the conatiner

String Pattern Matching In Java

You can do it using string.indexOf("{item}"). If the result is greater than -1 {item} is in the string

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC,datechat desc LIMIT 50

If you have a date field that is storing the date(and time) on which the chat was sent or any field that is filled with incrementally(order by DESC) or desinscrementally( order by ASC) data per row put it as second column on which the data should be order.

That's what worked for me!!!! hope it will help!!!!

How to read AppSettings values from a .json file in ASP.NET Core

I doubt this is good practice but it's working locally. I'll update this if it fails when I publish/deploy (to an IIS web service).

Step 1 - Add this assembly to the top of your class (in my case, controller class):

using Microsoft.Extensions.Configuration;

Step 2 - Add this or something like it:

var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();

Step 3 - Call your key's value by doing this (returns string):

config["NameOfYourKey"]

Flexbox not working in Internet Explorer 11

According to Flexbugs:

In IE 10-11, min-height declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.

Here are a couple of workarounds:

1. Always fill the viewport + scrollable <aside> and <section>:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1;
  display: flex;
}

aside, section {
  overflow: auto;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

2. Fill the viewport initially + normal page scroll with more content:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1 0 auto;
  display: flex;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

How to send email from Terminal?

Go into Terminal and type man mail for help.

You will need to set SMTP up:

http://hints.macworld.com/article.php?story=20081217161612647

See also:

http://www.mactricksandtips.com/2008/09/send-mail-over-your-network.html

Eg:

mail -s "hello" "[email protected]" <<EOF
hello
world
EOF

This will send an email to [email protected] with the subject hello and the message

Hello

World

center a row using Bootstrap 3

Add this to your css:

.row-centered {
   text-align:center;
}


.col-centered {
   display:inline-block;
   float:none;
   /* reset the text-align */
   text-align:left;
   /* inline-block space fix */
   margin-right:-4px;
}

Then, in your HTML code:

    <div class=" row row-centered">
        <div class="col-*-*  col-centered>
           Your content
        </div>
    </div>

how to convert a string to an array in php

here, Use explode() function to convert string into array, by a string

click here to know more about explode()

$str = "this is string";
$delimiter = ' ';  // use any string / character by which, need to split string into Array
$resultArr = explode($delimiter, $str);  
var_dump($resultArr);

Output :

Array
(
    [0] => "this",
    [1] => "is",
    [2] => "string "
)

it is same as the requirements:

  arr[0]="this";
  arr[1]="is";
  arr[2]="string";

Is there a way to programmatically minimize a window

this.WindowState = FormWindowState.Minimized;

What does $1 [QSA,L] mean in my .htaccess file?

If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,

RewriteCond %{REQUEST_FILENAME} !-d

and if the requested filename is not a regular file that exists,

RewriteCond %{REQUEST_FILENAME} !-f

and if the requested filename is not a symbolic link,

RewriteCond %{REQUEST_FILENAME} !-l

then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Apache docs #flag_qsa

Another Example:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for

/pages/123?one=two

will be mapped to

/page.php?page=123&one=two

Failed to find 'ANDROID_HOME' environment variable

April 11, 2019

None of the answers above solved my problem so I wanted to include a current solution (as of April 2019) for people using Ubuntu 18.04. This is how I solved the question above...

  1. I installed the Android SDK from the website, and put it in this folder: /usr/lib/Android/
  2. Search for where the SDK is installed and the version. In my case it was here:

    /usr/lib/Android/Sdk/build-tools/28.0.3

    Note: that I am using version 28.0.3, your version may differ.

  3. Add ANDROID_HOME to the environment path. To do this, open /etc/environment with a text editor:

    sudo nano /etc/environment

    Add a line for ANDROID_HOME for your specific version and path. In my case it was:

    ANDROID_HOME="/usr/lib/Android/Sdk/build-tools/28.0.3"

  4. Finally, source the updated environment with: source /etc/environment

    Confirm this by trying: echo $ANDROID_HOME in the terminal. You should get the path of your newly created variable.

    One additionally note about sourcing, I did have to restart my computer for the VScode terminal to recognize my changes. After the restart, the environment was set and I haven't had any issues since.

angularjs ng-style: background-image isn't working

It is possible to parse dynamic values in a couple of way.

Interpolation with double-curly braces:

ng-style="{'background-image':'url({{myBackgroundUrl}})'}"

String concatenation:

ng-style="{'background-image': 'url(' + myBackgroundUrl + ')'}"

ES6 template literals:

ng-style="{'background-image': `url(${myBackgroundUrl})`}"

Django DateField default options

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(default=datetime.now)

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

LINQ to SQL - Left Outer Join with multiple join conditions

I know it's "a bit late" but just in case if anybody needs to do this in LINQ Method syntax (which is why I found this post initially), this would be how to do that:

var results = context.Periods
    .GroupJoin(
        context.Facts,
        period => period.id,
        fk => fk.periodid,
        (period, fact) => fact.Where(f => f.otherid == 17)
                              .Select(fact.Value)
                              .DefaultIfEmpty()
    )
    .Where(period.companyid==100)
    .SelectMany(fact=>fact).ToList();

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

The first error you're getting - permissions - is the most indicative. Bump wp-content and wp-admin to 777 and try it, and if it works, then change them both back to 755 and see if it still works. What are you using to change folder permissions? An FTP client?

Is Eclipse the best IDE for Java?

There is no best IDE. You make it as good as you get used using it.

How to have multiple CSS transitions on an element?

Here's a LESS mixin for transitioning two properties at once:

.transition-two(@transition1, @transition1-duration, @transition2, @transition2-duration) {
 -webkit-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
    -moz-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
      -o-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
          transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
}

jQuery animate margin top

use the following code to apply some margin

$(".button").click(function() {
  $('html, body').animate({
    scrollTop: $(".scrolltothis").offset().top + 50;
  }, 500);
});

See this ans: Scroll down to div + a certain margin

Get connection string from App.config

It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.

converting epoch time with milliseconds to datetime

those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

How to output git log with the first line only?

Without commit messages, only the hash:

git log --pretty=oneline | awk '{print $1}'

How to setup virtual environment for Python in VS Code?

The question is how to create a new virtual environment in VSCode, that is why telling the following Anaconda solution might not the needed answer to the question. It is just relevant for Anaconda users.

Just create a venv using conda, see here. Afterwards open VSCode and left-click on the VSCode interpreter shown in VSCode at the bottom left:

vscode interpreter info

Choose a virtual environment that pops up in a dropdown of the settings window, and you are done. Mind the answer of @RamiMa.

Add Header and Footer for PDF using iTextsharp

This link will help you out completely(the Shortest and Most Elegant way):

Header Footer with PageEvent

        PdfPTable tbheader = new PdfPTable(3);
        tbheader.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
        tbheader.DefaultCell.Border = 0;
        tbheader.AddCell(new Paragraph());
        tbheader.AddCell(new Paragraph());
        var _cell2 = new PdfPCell(new Paragraph("This is my header", arial_italic));
        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
        _cell2.Border = 0;
        tbheader.AddCell(_cell2);
        float[] widths = new float[] { 20f, 20f, 60f };
        tbheader.SetWidths(widths);
        tbheader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin), writer.DirectContent);

        PdfPTable tbfooter = new PdfPTable(3);
        tbfooter.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
        tbfooter.DefaultCell.Border = 0;
        tbfooter.AddCell(new Paragraph());
        tbfooter.AddCell(new Paragraph());
        var _cell2 = new PdfPCell(new Paragraph("This is my footer", arial_italic));
        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
        _cell2.Border = 0;
        tbfooter.AddCell(_cell2);
        tbfooter.AddCell(new Paragraph());
        tbfooter.AddCell(new Paragraph());
        var _celly = new PdfPCell(new Paragraph(writer.PageNumber.ToString()));//For page no.
        _celly.HorizontalAlignment = Element.ALIGN_RIGHT;
        _celly.Border = 0;
        tbfooter.AddCell(_celly);
        float[] widths1 = new float[] { 20f, 20f, 60f };
        tbfooter.SetWidths(widths1);
        tbfooter.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);

How can I find the length of a number?

I would like to correct the @Neal answer which was pretty good for integers, but the number 1 would return a length of 0 in the previous case.

function Longueur(numberlen)
{
    var length = 0, i; //define `i` with `var` as not to clutter the global scope
    numberlen = parseInt(numberlen);
    for(i = numberlen; i >= 1; i)
    {
        ++length;
        i = Math.floor(i/10);
    }
    return length;
}

Formatting "yesterday's" date in python

To expand on the answer given by Chris

if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

If you want it as an integer (which can be useful)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

SQL: Combine Select count(*) from multiple tables

select 
  (select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...

Best equivalent VisualStudio IDE for Mac to program .NET/C#

The question is quite old so I feel like I need to give a more up to date response to this question.

Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/

Apply CSS to jQuery Dialog Buttons

You can use the open event handler to apply additional styling:

 open: function(event) {
     $('.ui-dialog-buttonpane').find('button:contains("Cancel")').addClass('cancelButton');
 }

Visual Studio Error: (407: Proxy Authentication Required)

Using IDE configuration:

  1. Open Visual Studio 2012, click on Tools from the file menu bar and then click Options,

  2. From the Options window, expand the Source Control option, click on Plug-in Selection and make sure that the Current source control plug-in is set to Visual Studio Team Foundation Server.

  3. Next, click on the Visual Studio Team Foundation Server option under Source Control and perform the following steps: Check Use proxy server for file downloads. Enter the host name of your preferred Team Foundation Server 2010 Proxy server. Set the port to 443. Check Use SSL encryption (https) to connect.

  4. Click the OK button.

Using exe.config:

Modify the devenv.exe.config where IDE executable is like this:

<system.net> 
  <defaultProxy>  
   <proxy proxyaddress=”http://proxy:3128”
     bypassonlocal=”True” autoDetect=”True” /> 
   <bypasslist> 
   <add address=”http://URL”/>  
  </bypasslist> 
 </defaultProxy> 

Declare your proxy at proxyaddress and remember bypasslist urls and ip addresses will be excluded from proxy traffic.

Then restart visual studio to update changes.

Spring MVC: How to perform validation?

Put this bean in your configuration class.

 @Bean
  public Validator localValidatorFactoryBean() {
    return new LocalValidatorFactoryBean();
  }

and then You can use

 <T> BindingResult validate(T t) {
    DataBinder binder = new DataBinder(t);
    binder.setValidator(validator);
    binder.validate();
    return binder.getBindingResult();
}

for validating a bean manually. Then You will get all result in BindingResult and you can retrieve from there.

How do I get the name of the rows from the index of a data frame?

df.index

  • outputs the row names as pandas Index object.

list(df.index)

  • casts to a list.

df.index['Row 2':'Row 5']

  • supports label slicing similar to columns.

List of encodings that Node.js supports

The list of encodings that node supports natively is rather short:

  • ascii
  • base64
  • hex
  • ucs2/ucs-2/utf16le/utf-16le
  • utf8/utf-8
  • binary/latin1 (ISO8859-1, latin1 only in node 6.4.0+)

If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:

Use iconv-lite to recode files:

var iconvlite = require('iconv-lite');
var fs = require('fs');

function readFileSync_encoding(filename, encoding) {
    var content = fs.readFileSync(filename);
    return iconvlite.decode(content, encoding);
}

Alternatively, use iconv:

var Iconv = require('iconv').Iconv;
var fs = require('fs');

function readFileSync_encoding(filename, encoding) {
    var content = fs.readFileSync(filename);
    var iconv = new Iconv(encoding, 'UTF-8');
    var buffer = iconv.convert(content);
    return buffer.toString('utf8');
}

Bootstrap button - remove outline on Chrome OS X

If someone is using bootstrap sass note the code is on the _reboot.scss file like this:

button:focus {
  outline: 1px dotted;
  outline: 5px auto -webkit-focus-ring-color;
}

So if you want to keep the _reboot file I guess feel free to override with plain css instead of trying to look for a variable to change.

How can I get browser to prompt to save password?

Simple 2020 aproach

This will automatically enable autocomplete and save password in browsers.

  • autocomplete="on" (form)
  • autocomplete="username" (input, email/username)
  • autocomplete="current-password" (input, password)
<form autocomplete="on">
  <input id="user-text-field" type="email" autocomplete="username"/>
  <input id="password-text-field" type="password" autocomplete="current-password"/>
</form>

Check out more at Apple's documentation: Enabling Password AutoFill on an HTML Input Element

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

Execute PHP script in cron job

I had the same problem... I had to run it as a user.

00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php

Javascript foreach loop on associative array object

The .length property only tracks properties with numeric indexes (keys). You're using strings for keys.

You can do this:

var arr_jq_TabContents = {}; // no need for an array

arr_jq_TabContents["Main"] = jq_TabContents_Main;
arr_jq_TabContents["Guide"] = jq_TabContents_Guide;
arr_jq_TabContents["Articles"] = jq_TabContents_Articles;
arr_jq_TabContents["Forum"] = jq_TabContents_Forum;

for (var key in arr_jq_TabContents) {
    console.log(arr_jq_TabContents[key]);
}

To be safe, it's a good idea in loops like that to make sure that none of the properties are unexpected results of inheritance:

for (var key in arr_jq_TabContents) {
  if (arr_jq_TabContents.hasOwnProperty(key))
    console.log(arr_jq_TabContents[key]);
}

edit — it's probably a good idea now to note that the Object.keys() function is available on modern browsers and in Node etc. That function returns the "own" keys of an object, as an array:

Object.keys(arr_jq_TabContents).forEach(function(key, index) {
  console.log(this[key]);
}, arr_jq_TabContents);

The callback function passed to .forEach() is called with each key and the key's index in the array returned by Object.keys(). It's also passed the array through which the function is iterating, but that array is not really useful to us; we need the original object. That can be accessed directly by name, but (in my opinion) it's a little nicer to pass it explicitly, which is done by passing a second argument to .forEach() — the original object — which will be bound as this inside the callback. (Just saw that this was noted in a comment below.)

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

How to load image (and other assets) in Angular an project?

Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes. For example :

  • 'my-image-name.png' should be 'myImageName.png'
  • 'my image name.png' should be 'myImageName.png'

If you put the image in the assets/img folder, then this line of code should work in your templates :

<img alt="My image name" src="./assets/img/myImageName.png">

If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.

Altering column size in SQL Server

ALTER TABLE [Employee]
ALTER COLUMN [Salary] NUMERIC(22,5) NOT NULL

Insert current date/time using now() in a field using MySQL/PHP

Currently, and with the new versions of Mysql can insert the current date automatically without adding a code in your PHP file. You can achieve that from Mysql while setting up your database as follows:

enter image description here

Now, any new post will automatically get a unique date and time. Hope this can help.

Understanding timedelta

Because timedelta is defined like:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

All arguments are optional and default to 0.

You can easily say "Three days and four milliseconds" with optional arguments that way.

>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)

And for str casting, it returns a nice formatted value instead of __repr__ to improve readability. From docs:

str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'

Checkout documentation:

http://docs.python.org/library/datetime.html#timedelta-objects

Load HTML File Contents to Div [without the use of iframes]

2019
Using fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

How to set a bitmap from resource

If you have declare a bitmap object and you want to display it or store this bitmap object. but first you have to assign any image , and you may use the button click event, this code will only demonstrate that how to store the drawable image in bitmap Object.

Bitmap contact_pic = BitmapFactory.decodeResource(
                           v.getContext().getResources(),
                           R.drawable.android_logo
                     );

Now you can use this bitmap object, whether you want to store it, or to use it in google maps while drawing a pic on fixed latitude and longitude, or to use some where else

PostgreSQL: Show tables in PostgreSQL

The most straightforward way to list all tables at command line is, for my taste :

psql -a -U <user> -p <port> -h <server> -c "\dt"

For a given database just add the database name :

psql -a -U <user> -p <port> -h <server> -c "\dt" <database_name>

It works on both Linux and Windows.

printf formatting (%d versus %u)

If I understand your question correctly, you need %p to show the address that a pointer is using, for example:

int main() {
    int a = 5;
    int *p = &a;
    printf("%d, %u, %p", p, p, p);

    return 0;
}

will output something like:

-1083791044, 3211176252, 0xbf66a93c

Why do Twitter Bootstrap tables always have 100% width?

Bootstrap 3:

Why fight it? Why not simply control your table width using the bootstrap grid?

<div class="row">
    <div class="col-sm-6">
        <table></table>
    </div>
</div>

This will create a table that is half (6 out of 12) of the width of the containing element.

I sometimes use inline styles as per the other answers, but it is discouraged.

Bootstrap 4:

Bootstrap 4 has some nice helper classes for width like w-25, w-50, w-75, w-100, and w-auto. This will make the table 50% width:

<table class="w-50"></table>

Here's the doc: https://getbootstrap.com/docs/4.0/utilities/sizing/

How do you set the title color for the new Toolbar?

Very simple, this worked for me (title and icon white):

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/PrimaryColor"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:elevation="4dp" />

How to while loop until the end of a file in Python without checking for empty line?

for line in f

reads all file to a memory, and that can be a problem.

My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:

with open("blablabla.txt", "r") as fl_in:
   while True:
      line = fl_in.readline()

        if not line:
            break

      line = line.strip()
      # do what You want

Using :: in C++

look at it is informative [Qualified identifiers

A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.

The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1

Incrementing a date in JavaScript

Getting the next 5 days:

var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();


for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}

How to parse/read a YAML file into a Python object?

Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file appropriately:

load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])

Count Vowels in String Python

...

vowels = "aioue"
text = input("Please enter your text: ")
count = 0

for i in text:
    if i in vowels:
        count += 1

print("There are", count, "vowels in your text")

...

New warnings in iOS 9: "all bitcode will be dropped"

After Xcode 7, the bitcode option will be enabled by default. If your library was compiled without bitcode, but the bitcode option is enabled in your project settings, you can:

  1. Update your library with bit code,
  2. Say NO to Enable Bitcode in your target Build Settings

Enter image description here

And the Library Build Settings to remove the warnings.

For more information, go to documentation of bitcode in developer library.

And WWDC 2015 Session 102: "Platforms State of the Union"

Enter image description here

Unique device identification

It looks like the phoneGap plugin will allow you to get the device's uid.

http://docs.phonegap.com/en/3.0.0/cordova_device_device.md.html#device.uuid

Update: This is dependent on running native code. We used this solution writing javascript that was being compiled to native code for a native phone application we were creating.

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

This happens to me every time I add a pod to the podfile.

I constantly try and find the problem but I just go round in circles again and again!

The error messages range, however the way to fix it is the same every time!

Comment out(#) ALL of the pods in the podfile and run pod install in terminal.

Then...

Uncomment out all of the pods in the podfile and run pod install again.

This has worked for me every single time!

How to toggle font awesome icon on click?

You can change the code by using class definition for the i element:

<a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>

Then you can switch the classes rapresenting the plus/minus state using toggleClass with multiple classes:

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
});

Demo: http://jsfiddle.net/Zcn2u/

Stretch and scale a CSS image in the background - with CSS only

Use the Backstretch plugin. One could even have several images slide. It also works within containers. This way for example one could have only a portion of the background been covered with an background image.

Since even I could get it to work proves it to be an easy to use plugin :).

Using G++ to compile multiple .cpp and .h files

I know this question has been asked years ago but still wanted to share how I usually compile multiple c++ files.

  1. Let's say you have 5 cpp files, all you have to do is use the * instead of typing each cpp files name E.g g++ -c *.cpp -o myprogram.
  2. This will generate "myprogram"
  3. run the program ./myprogram

that's all!!

The reason I'm using * is that what if you have 30 cpp files would you type all of them? or just use the * sign and save time :)

p.s Use this method only if you don't care about makefile.

How to display image from database using php

For example if you use this code , you can load image from db (mysql) and display it in php5 ;)

<?php
   $con =mysql_connect("localhost", "root" , "");
   $sdb= mysql_select_db("my_database",$con);
   $sql = "SELECT * FROM `news` WHERE 1";
   $mq = mysql_query($sql) or die ("not working query");
   $row = mysql_fetch_array($mq) or die("line 44 not working");
   $s=$row['photo'];
   echo $row['photo'];

   echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
   ?>

How do I Convert DateTime.now to UTC in Ruby?

The string representation of a DateTime can be parsed by the Time class.

> Time.parse(DateTime.now.to_s).utc
=> 2015-10-06 14:53:51 UTC

How to write LDAP query to test if user is member of a group?

I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Creating composite primary key in SQL Server

it simple, select columns want to insert primary key and click on Key icon on header and save tablesql composite key

happy coding..,

How do I count columns of a table

To count the columns of your table precisely, you can get form information_schema.columns with passing your desired Database(Schema) Name and Table Name.


Reference the following Code:

SELECT count(*)
FROM information_schema.columns
WHERE table_schema = 'myDB'  
AND table_name = 'table1';

Iterating Through a Dictionary in Swift

This is a user-defined function to iterate through a dictionary:

func findDic(dict: [String: String]){
    for (key, value) in dict{
    print("\(key) : \(value)")
  }
}

findDic(dict: ["Animal":"Lion", "Bird":"Sparrow"])
//prints Animal : Lion 
         Bird : Sparrow

Does JavaScript guarantee object property order?

This whole answer is in the context of spec compliance, not what any engine does at a particular moment or historically.

Generally, no

The actual question is very vague.

will the properties be in the same order that I added them

In what context?

The answer is: it depends on a number of factors. In general, no.

Sometimes, yes

Here is where you can count on property key order for plain Objects:

  • ES2015 compliant engine
  • Own properties
  • Object.getOwnPropertyNames(), Reflect.ownKeys(), Object.getOwnPropertySymbols(O)

In all cases these methods include non-enumerable property keys and order keys as specified by [[OwnPropertyKeys]] (see below). They differ in the type of key values they include (String and / or Symbol). In this context String includes integer values.

Object.getOwnPropertyNames(O)

Returns O's own String-keyed properties (property names).

Reflect.ownKeys(O)

Returns O's own String- and Symbol-keyed properties.

Object.getOwnPropertySymbols(O)

Returns O's own Symbol-keyed properties.

[[OwnPropertyKeys]]

The order is essentially: integer-like Strings in ascending order, non-integer-like Strings in creation order, Symbols in creation order. Depending which function invokes this, some of these types may not be included.

The specific language is that keys are returned in the following order:

  1. ... each own property key P of O [the object being iterated] that is an integer index, in ascending numeric index order

  2. ... each own property key P of O that is a String but is not an integer index, in property creation order

  3. ... each own property key P of O that is a Symbol, in property creation order

Map

If you're interested in ordered maps you should consider using the Map type introduced in ES2015 instead of plain Objects.

Loading resources using getClass().getResource()

getResource by example:

package szb.testGetResource;
public class TestGetResource {
    private void testIt() {
        System.out.println("test1: "+TestGetResource.class.getResource("test.css"));
        System.out.println("test2: "+getClass().getResource("test.css"));
    }
    public static void main(String[] args) {
        new TestGetResource().testIt();
    }
}

enter image description here

output:

test1: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
test2: file:/home/szb/projects/test/bin/szb/testGetResource/test.css

How can I configure my makefile for debug and release builds?

you can have a variable

DEBUG = 0

then you can use a conditional statement

  ifeq ($(DEBUG),1)

  else

  endif

git - pulling from specific branch

This worked perfectly for me, although fetching all branches could be a bit too much:

git init
git remote add origin https://github.com/Vitosh/VBA_personal.git
git fetch --all
git checkout develop

enter image description here

How to add a footer to the UITableView?

Initially I was just trying the method:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

but after using this along with:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

problem was solved. Sample Program-

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *sampleView = [[UIView alloc] init];
    sampleView.frame = CGRectMake(SCREEN_WIDTH/2, 5, 60, 4);
    sampleView.backgroundColor = [UIColor blackColor];
    return sampleView;
}

and include UITableViewDelegate protocol.

@interface TestViewController : UIViewController <UITableViewDelegate>

How to append a newline to StringBuilder

you can use line.seperator for appending new line in

Pandas join issue: columns overlap but no suffix specified

Your error on the snippet of data you posted is a little cryptic, in that because there are no common values, the join operation fails because the values don't overlap it requires you to supply a suffix for the left and right hand side:

In [173]:

df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')
Out[173]:
       mukey_left  DI  PI  mukey_right  niccdcd
index                                          
0          100000  35  14          NaN      NaN
1         1000005  44  14          NaN      NaN
2         1000006  44  14          NaN      NaN
3         1000007  43  13          NaN      NaN
4         1000008  43  13          NaN      NaN

merge works because it doesn't have this restriction:

In [176]:

df_a.merge(df_b, on='mukey', how='left')
Out[176]:
     mukey  DI  PI  niccdcd
0   100000  35  14      NaN
1  1000005  44  14      NaN
2  1000006  44  14      NaN
3  1000007  43  13      NaN
4  1000008  43  13      NaN

how to create virtual host on XAMPP

Just change the port to 8081 and following virtual host will work:

<VirtualHost *:8081>
ServerName comm-app.local
DocumentRoot "C:/xampp/htdocs/CommunicationApp/public"
SetEnv APPLICATION_ENV "development"
    <Directory "C:/xampp/htdocs/CommunicationApp/public">
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory> 
</VirtualHost>

How to add local jar files to a Maven project?

One way is to upload it to your own Maven repository manager (such as Nexus). It's good practice to have an own repository manager anyway.

Another nice way I've recently seen is to include the Maven Install Plugin in your build lifecycle: You declare in the POM to install the files to the local repository. It's a little but small overhead and no manual step involved.

http://maven.apache.org/plugins/maven-install-plugin/install-file-mojo.html

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

Using DataContractSerializer to serialize, but can't deserialize back

I ended up doing the following and it works.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.

Java serialization - java.io.InvalidClassException local class incompatible

@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver program on all your old classes. put these serialVersionUID values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID on all Serializable classes)

if the new versions are not serial compatible, then you need to do some magic with a custom readObject implementation (you would only need a custom writeObject if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.

Of course, even if the new class is serial compatible, you may still want a custom readObject implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).

Shell Script — Get all files modified after <date>

If you have GNU find, then there are a legion of relevant options. The only snag is that the interface to them is less than stellar:

  • -mmin n (modification time in minutes)
  • -mtime n (modification time in days)
  • -newer file (modification time newer than modification time of file)
  • -daystart (adjust start time from current time to start of day)
  • Plus alternatives for access time and 'change' or 'create' time.

The hard part is determining the number of minutes since a time.

One option worth considering: use touch to create a file with the required modification time stamp; then use find with -newer.

touch -t 200901031231.43 /tmp/wotsit
find . -newer /tmp/wotsit -print
rm -f /tmp/wotsit

This looks for files newer than 2009-01-03T12:31:43. Clearly, in a script, /tmp/wotsit would be a name with the PID or other value to make it unique; and there'd be a trap to ensure it gets removed even if the user interrupts, and so on and so forth.

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

Go to "app manager", then go to "all", then click on "Google Services Framework" and then "Clear Data". Reboot and it is done.

Checkbox for nullable boolean

Checkbox only offer you 2 values (true, false). Nullable boolean has 3 values (true, false, null) so it's impossible to do it with a checkbox.

A good option is to use a drop down instead.

Model

public bool? myValue;
public List<SelectListItem> valueList;

Controller

model.valueList = new List<SelectListItem>();
model.valueList.Add(new SelectListItem() { Text = "", Value = "" });
model.valueList.Add(new SelectListItem() { Text = "Yes", Value = "true" });
model.valueList.Add(new SelectListItem() { Text = "No", Value = "false" });

View

@Html.DropDownListFor(m => m.myValue, valueList)

Dynamically select data frame columns using $ and a character value

if you want to select column with specific name then just do

A=mtcars[,which(conames(mtcars)==cols[1])]
#and then
colnames(mtcars)[A]=cols[1]

you can run it in loop as well reverse way to add dynamic name eg if A is data frame and xyz is column to be named as x then I do like this

A$tmp=xyz
colnames(A)[colnames(A)=="tmp"]=x

again this can also be added in loop