Programs & Examples On #Fjcore

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I also faced it and encorrected it like below successfully.

File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution

Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version

You may need to upgrade your gradle version.

JPanel Padding in Java

I will suppose your JPanel contains JTextField, for the sake of the demo.

Those components provides JTextComponent#setMargin() method which seems to be what you're looking for.

If you're looking for an empty border of any size around your text, well, use EmptyBorder

How to launch Safari and open URL from iOS app

Swift 4 solution:

UIApplication.shared.open(NSURL(string:"http://yo.lo")! as URL, options: [String : Any](), completionHandler: nil)

How to get the file name from a full path using JavaScript?

Just for the sake of performance, I tested all the answers given here:

var substringTest = function (str) {
    return str.substring(str.lastIndexOf('/')+1);
}

var replaceTest = function (str) {
    return str.replace(/^.*(\\|\/|\:)/, '');
}

var execTest = function (str) {
    return /([^\\]+)$/.exec(str)[1];
}

var splitTest = function (str) {
    return str.split('\\').pop().split('/').pop();
}

substringTest took   0.09508600000000023ms
replaceTest   took   0.049203000000000004ms
execTest      took   0.04859899999999939ms
splitTest     took   0.02505500000000005ms

And the winner is the Split and Pop style answer, Thanks to bobince !

Intel's HAXM equivalent for AMD on Windows OS

Posting a new answer since it is 2019.

TLDR: AMD is now supported on both Windows and Linux via WHPX and yes, Genymotion is faster as it is using x86 architecture virtualization.

From the Android docs (January 2019):

Though we recommend using HAXM on Windows, it is possible to use Windows Hypervisor Platform (WHPX) with the emulator. You should use WHPX with the emulator if you are using an AMD CPU or if you need to use Hyper-V at the same time.

To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.

Additionally, the following changes must be made in the BIOS settings:

Intel CPU: VT-x must be enabled. AMD CPU: Virtualization or SVM must be enabled.

Diff from 2016:

Virtualization extension requirements

Before attempting to use acceleration, you should first determine if your CPU supports one of the following virtualization extensions technologies:

  1. Intel Virtualization Technology (VT, VT-x, vmx) extensions
  2. AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

Most modern computers do. If you use an older computer and you're not sure, consult the specifications from the manufacturer of your CPU to determine if it supports virtualization extensions. If your CPU doesn't support one of these virtualization technologies, then you can't use VM acceleration.

Virtualization extensions are typically enabled through your computer BIOS and are frequently turned off by default. Check the documentation for your motherboard to find out how to enable virtualization extensions.

Combination of async function + await + setTimeout

This is a quicker fix in one-liner.

Hope this will help.

// WAIT FOR 200 MILISECONDS TO GET DATA //
await setTimeout(()=>{}, 200);

What is an undefined reference/unresolved external symbol error and how do I fix it?

Also if you're using 3rd party libraries make sure you have the correct 32/64 bit binaries

Retrofit 2: Get JSON from Response body

try {                                                                           
    JSONObject jsonObject = new JSONObject(response.body().string());           
    System.out.println(jsonObject);                                             
} catch (JSONException | IOException e ) {                                      
    e.printStackTrace();                                                        
}

Better way to right align text in HTML Table

This doesn't work in IE6, which may be an issue, but it'll work in IE7+ and Firefox, Safari etc. It'll align the 3rd column right and all of the subsequent columns left.

td + td + td { text-align: right; }
td + td + td + td { text-align: left; }

When does Git refresh the list of remote branches?

I believe that if you run git branch --all from Bash that the list of remote and local branches you see will reflect what your local Git "knows" about at the time you run the command. Because your Git is always up to date with regard to the local branches in your system, the list of local branches will always be accurate.

However, for remote branches this need not be the case. Your local Git only knows about remote branches which it has seen in the last fetch (or pull). So it is possible that you might run git branch --all and not see a new remote branch which appeared after the last time you fetched or pulled.

To ensure that your local and remote branch list be up to date you can do a git fetch before running git branch --all.

For further information, the "remote" branches which appear when you run git branch --all are not really remote at all; they are actually local. For example, suppose there be a branch on the remote called feature which you have pulled at least once into your local Git. You will see origin/feature listed as a branch when you run git branch --all. But this branch is actually a local Git branch. When you do git fetch origin, this tracking branch gets updated with any new changes from the remote. This is why your local state can get stale, because there may be new remote branches, or your tracking branches can become stale.

Scanning Java annotations at runtime

Spring has something called a AnnotatedTypeScanner class.
This class internally uses

ClassPathScanningCandidateComponentProvider

This class has the code for actual scanning of the classpath resources. It does this by using the class metadata available at runtime.

One can simply extend this class or use the same class for scanning. Below is the constructor definition.

/**
     * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
     * 
     * @param considerInterfaces whether to consider interfaces as well.
     * @param annotationTypes the annotations to scan for.
     */
    public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {

        this.annotationTypess = Arrays.asList(annotationTypes);
        this.considerInterfaces = considerInterfaces;
    }

POST Multipart Form Data using Retrofit 2.0 including image

I am highlighting the solution in both 1.9 and 2.0 since it is useful for some

In 1.9, I think the better solution is to save the file to disk and use it as Typed file like:

RetroFit 1.9

(I don't know about your server-side implementation) have an API interface method similar to this

@POST("/en/Api/Results/UploadFile")
void UploadFile(@Part("file") TypedFile file,
                @Part("folder") String folder,
                Callback<Response> callback);

And use it like

TypedFile file = new TypedFile("multipart/form-data",
                                       new File(path));

For RetroFit 2 Use the following method

RetroFit 2.0 ( This was a workaround for an issue in RetroFit 2 which is fixed now, for the correct method refer jimmy0251's answer)

API Interface:

public interface ApiInterface {

    @Multipart
    @POST("/api/Accounts/editaccount")
    Call<User> editUser(@Header("Authorization") String authorization,
                        @Part("file\"; filename=\"pp.png\" ") RequestBody file,
                        @Part("FirstName") RequestBody fname,
                        @Part("Id") RequestBody id);
}

Use it like:

File file = new File(imageUri.getPath());

RequestBody fbody = RequestBody.create(MediaType.parse("image/*"),
                                       file);

RequestBody name = RequestBody.create(MediaType.parse("text/plain"),
                                      firstNameField.getText()
                                                    .toString());

RequestBody id = RequestBody.create(MediaType.parse("text/plain"),
                                    AZUtils.getUserId(this));

Call<User> call = client.editUser(AZUtils.getToken(this),
                                  fbody,
                                  name,
                                  id);

call.enqueue(new Callback<User>() {

    @Override
    public void onResponse(retrofit.Response<User> response,
                           Retrofit retrofit) {

        AZUtils.printObject(response.body());
    }

    @Override
    public void onFailure(Throwable t) {

        t.printStackTrace();
    }
});

pandas read_csv and filter columns with usecols

You have to just add the index_col=False parameter

df1 = pd.read_csv('foo.csv',
     header=0,
     index_col=False,
     names=["dummy", "date", "loc", "x"], 
     usecols=["dummy", "date", "loc", "x"],
     parse_dates=["date"])
  print df1

How to sort pandas data frame using values from several columns?

Note : Everything up here is correct,just replace sort --> sort_values() So, it becomes:

 import pandas as pd
 df = pd.read_csv('data.csv')
 df.sort_values(ascending=False,inplace=True)

Refer to the official website here.

Retrofit 2 - Dynamic URL

If you already have your code setup and you don’t want to make changes on the different interfaces you can, use the solution described in this link. The main point is the method changeApiBaseUrl that updates the URL and recreates the Retrofit builder.

public class ServiceGenerator {  
public static String apiBaseUrl = "http://futurestud.io/api";
private static Retrofit retrofit;

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(apiBaseUrl);

private static OkHttpClient.Builder httpClient =
        new OkHttpClient.Builder();

// No need to instantiate this class.
private ServiceGenerator() {
}

public static void changeApiBaseUrl(String newApiBaseUrl) {
    apiBaseUrl = newApiBaseUrl;

    builder = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(apiBaseUrl);
}

public static <S> S createService(Class<S> serviceClass, AccessToken token) {
    String authToken = token.getTokenType().concat(token.getAccessToken());
    return createService(serviceClass, authToken);
}

// more methods
// ...
}

You can use it as follows:

public class DynamicBaseUrlActivity extends AppCompatActivity {

public static final String TAG = "CallInstances";
private Callback<ResponseBody> downloadCallback;

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

    downloadCallback = new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d(TAG, "server contacted at: " + call.request().url());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d(TAG, "call failed against the url: " + call.request().url());
        }
    };

    // first request
    FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);
    Call<ResponseBody> originalCall = downloadService.downloadFileWithFixedUrl();
    originalCall.enqueue(downloadCallback);

    // change base url
    ServiceGenerator.changeApiBaseUrl("http://development.futurestud.io/api");

    // new request against new base url
    FileDownloadService newDownloadService = ServiceGenerator.create(FileDownloadService.class);
    Call<ResponseBody> newCall = newDownloadService.downloadFileWithFixedUrl();
    newCall.enqueue(downloadCallback);
    }
}

How can I convert a Timestamp into either Date or DateTime object?

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");

        System.out.println(simpleDateFormat.format(timestamp));
        System.out.println(simpleDateFormat.format(date));
    }
}

How to Animate Addition or Removal of Android ListView Rows

call listView.scheduleLayoutAnimation(); before changing the list

How to read an entire file to a string using C#?

you can read a text from a text file in to string as follows also

string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
  str = str + sr.ReadLine();
}

Is there a job scheduler library for node.js?

I am using kue: https://github.com/learnboost/kue . It is pretty nice.

The official features and my comments:

  1. delayed jobs.
    • If you want to let the job run at a specific time, calculate the milliseconds between that time and now. Call job.delay(milliseconds) (The doc says minutes, which is wrong.) Don't forget to add "jobs.promote();" when you init jobs.
  2. job event and progress pubsub.
    • I don't understand it.
  3. rich integrated UI.
    • Very useful. You can check the job status (done, running, delayed) in integrated UI and don't need to write any code. And you can delete old records in UI.
  4. infinite scrolling
    • Sometimes not working. Have to refresh.
  5. UI progress indication
    • Good for the time-consuming jobs.
  6. job specific logging
    • Because they are delayed jobs, you should log useful info in the job and check later through UI.
  7. powered by Redis
    • Very useful. When you restart your node.js app, all job records are still there and the scheduled jobs will execute too!
  8. optional retries
    • Nice.
  9. full-text search capabilities
    • Good.
  10. RESTful JSON API
    • Sound good, but I never use it.

Edit:

  1. kue is not a cron like library.
  2. By default kue does not supports job which runs repeatedly (e.g. every Sunday).

Is there a function in python to split a word into a list?

The easiest way is probably just to use list(), but there is at least one other option as well:

s = "Word to Split"
wordlist = list(s)               # option 1, 
wordlist = [ch for ch in s]      # option 2, list comprehension.

They should both give you what you need:

['W','o','r','d',' ','t','o',' ','S','p','l','i','t']

As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:

[doSomethingWith(ch) for ch in s]

correct PHP headers for pdf file download

$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;

Change fill color on vector asset in Android Studio

Go to you MainActivity.java and below this code
-> NavigationView navigationView = findViewById(R.id.nav_view);
Add single line of code -> navigationView.setItemIconTintList(null);
i.e. the last line of my code

I hope this might solve your problem.

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);

How to enumerate an enum with String type?

As with @Kametrixom answer here I believe returning an array would be better than returning AnySequence, since you can have access to all of Array's goodies such as count, etc.

Here's the re-write:

public protocol EnumCollection : Hashable {}
extension EnumCollection {
    public static func allValues() -> [Self] {
        typealias S = Self
        let retVal = AnySequence { () -> AnyGenerator<S> in
            var raw = 0
            return AnyGenerator {
                let current : Self = withUnsafePointer(&raw) { UnsafePointer($0).memory }
                guard current.hashValue == raw else { return nil }
                raw += 1
                return current
            }
        }

        return [S](retVal)
    }
}

Serializing an object as UTF-8 XML in .NET

I found this blog post which explains the problem very well, and defines a few different solutions:

(dead link removed)

I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.

As @Jon Hanna mentions, this can be done with an XmlWriter created like this:

XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });

Run-time error '1004' - Method 'Range' of object'_Global' failed

Change

Range(DataImportColumn & DataImportRow).Offset(0, 2).Value

to

Cells(DataImportRow,DataImportColumn).Value

When you just have the row and the column then you can use the cells() object. The syntax is Cells(Row,Column)

Also one more tip. You might want to fully qualify your Cells object. for example

ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value

How to clear APC cache entries?

The stable of APC is having option to clear a cache in its interface itself. To clear those entries you must login to apc interface.

APC is having option to set username and password in apc.php file.

enter image description here

Scroll to bottom of Div on page load (jQuery)

All the answers that I can see here, including the currently "accepted" one, is actually wrong in that they set:

scrollTop = scrollHeight

Whereas the correct approach is to set:

scrollTop = scrollHeight - clientHeight

In other words:

$('#div1').scrollTop($('#div1')[0].scrollHeight - $('#div1')[0].clientHeight);

Or animated:

$("#div1").animate({
  scrollTop: $('#div1')[0].scrollHeight - $('#div1')[0].clientHeight
}, 1000);

Can I use complex HTML with Twitter Bootstrap's Tooltip?

The html data attribute does exactly what it says it does in the docs. Try this little example, no JavaScript necessary (broken into lines for clarification):

<span rel="tooltip" 
     data-toggle="tooltip" 
     data-html="true" 
     data-title="<table><tr><td style='color:red;'>complex</td><td>HTML</td></tr></table>"
>
hover over me to see HTML
</span>


JSFiddle demos:

Bootstrap 3 Glyphicons are not working

I'm working with Angular2 and SCSS, as a best practice I copied to my project only the bootstrap files that I'm modifying the other are imported from node_modules.. the only problem was with Glyphicons. After many tries I found that the best solution to me is to copy the font files to my project and set directly this path to $ icon-font-path as shown in the image:

enter image description here

What is the meaning of "__attribute__((packed, aligned(4))) "

  • packed means it will use the smallest possible space for struct Ball - i.e. it will cram fields together without padding
  • aligned means each struct Ball will begin on a 4 byte boundary - i.e. for any struct Ball, its address can be divided by 4

These are GCC extensions, not part of any C standard.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

I found a solution on this site where someone had a valuable comment:

The solution is:

if (Function('/*@cc_on return document.documentMode===10@*/')()){
    document.documentElement.className+=' ie10';
}

It

  • doesn’t need conditional comments;
  • works even if comment stripping compression/processing;
  • no ie10 class added in Internet Explorer 11;
  • more likely to work as intended with Internet Explorer 11 running in Internet Explorer 10 compatibility mode;
  • doesn’t need standalone script tag (can just be added to other JavaScript code in the head).
  • doesn't need jQuery to test

Python read in string from file and split it into values

>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]

how do you filter pandas dataframes by multiple columns

In case somebody wonders what is the faster way to filter (the accepted answer or the one from @redreamality):

import pandas as pd
import numpy as np

length = 100_000
df = pd.DataFrame()
df['Year'] = np.random.randint(1950, 2019, size=length)
df['Gender'] = np.random.choice(['Male', 'Female'], length)

%timeit df.query('Gender=="Male" & Year=="2014" ')
%timeit df[(df['Gender']=='Male') & (df['Year']==2014)]

Results for 100,000 rows:

6.67 ms ± 557 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
5.54 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Results for 10,000,000 rows:

326 ms ± 6.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
472 ms ± 25.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So results depend on the size and the data. On my laptop, query() gets faster after 500k rows. Further, the string search in Year=="2014" has an unnecessary overhead (Year==2014 is faster).

Remove space above and below <p> tag HTML

Look here: http://www.w3schools.com/tags/tag_p.asp

The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.

you could remove the extra space by using css

p {
   margin: 0px;
   padding: 0px;
}

or use the element <span> which has no default margins and is an inline element.

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

C++ Singleton design pattern

Has anyone mentioned std::call_once and std::once_flag? Most other approaches - including double checked locking - are broken.

One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag is the mechanism to get guaranteed safe initialization.

Uses of content-disposition in an HTTP response header

For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition

Basic usage:

var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());

What is the difference between state and props in React?

You have some data that is being entered by users somewhere in the application.

  1. the component in which the data is being entered should have this data in its state because it needs to manipulate and change it during data entry

  2. anywhere else in the application the data should be passed down as props to all the other components

So yes the props are changing but they are changed at the 'source' and will then simply flow down from there. So props are immutable in the context of the component receiving them.

E.g. a reference data screen where users edit a list of suppliers would manage this in state, which would then have an action cause the updated data to be saved in ReferenceDataState which could be one level below AppState and then this supplier list would be passed as props to all the components that needed to use it.

How to convert String into Hashmap in java

This is one solution. If you want to make it more generic, you can use the StringUtils library.

String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1);           //remove curly brackets
String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();               

for(String pair : keyValuePairs)                        //iterate over the pairs
{
    String[] entry = pair.split("=");                   //split the pairs to get key and value 
    map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
}

For example you can switch

 value = value.substring(1, value.length()-1);

to

 value = StringUtils.substringBetween(value, "{", "}");

if you are using StringUtils which is contained in apache.commons.lang package.

Get text of the selected option with jQuery

$(document).ready(function() {
    $('select#select_2').change(function() {
        var selectedText = $(this).find('option:selected').text();
        alert(selectedText);
    });
});

Fiddle

Increasing nesting function calls limit

This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:

xdebug.max_nesting_level = 200

or in your PHP code:

ini_set('xdebug.max_nesting_level', 200);

As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.

Primary key or Unique index?

As long as you do not allow NULL for a value, they should be handled the same, but the value NULL is handled differently on databases(AFAIK MS-SQL do not allow more than one(1) NULL value, mySQL and Oracle allow this, if a column is UNIQUE) So you must define this column NOT NULL UNIQUE INDEX

How to execute an .SQL script file using c#

Using EntityFramework, you can go with a solution like this. I use this code to initialize e2e tests. De prevent sql injection attacks, make sure not to generate this script based on user input or use command parameters for this (see overload of ExecuteSqlCommand that accepts parameters).

public static void ExecuteSqlScript(string sqlScript)
{
    using (MyEntities dataModel = new MyEntities())
    {
        // split script on GO commands
        IEnumerable<string> commands = 
            Regex.Split(
                sqlScript, 
                @"^\s*GO\s*$",
                RegexOptions.Multiline | RegexOptions.IgnoreCase);

        foreach (string command in commands)
        {
            if (command.Trim() != string.Empty)
            {
                dataModel.Database.ExecuteSqlCommand(command);
            }
        }              
    }
}

What's the difference between & and && in MATLAB?

&& and || take scalar inputs and short-circuit always. | and & take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.

See these doc pages for more information.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

If you didn't change anything related to certificates (didn't replace or update them) just do a Product -> Clean. It helped me several times. (Xcode 6.2)

How do you implement a Stack and a Queue in JavaScript?

you can use WeakMaps for implementing private property in ES6 class and benefits of String propeties and methods in JavaScript language like below:

const _items = new WeakMap();

class Stack {
  constructor() {
    _items.set(this, []);
  }

push(obj) {
  _items.get(this).push(obj);
}

pop() {
  const L = _items.get(this).length;
  if(L===0)
    throw new Error('Stack is empty');
  return _items.get(this).pop();
}

peek() {
  const items = _items.get(this);
  if(items.length === 0)
    throw new Error ('Stack is empty');
  return items[items.length-1];
}

get count() {
  return _items.get(this).length;
}
}

const stack = new Stack();

//now in console:
//stack.push('a')
//stack.push(1)
//stack.count   => 2
//stack.peek()  => 1
//stack.pop()   => 1
//stack.pop()   => "a"
//stack.count   => 0
//stack.pop()   => Error Stack is empty

How do I count columns of a table

$cs = mysql_query("describe tbl_info");
$column_count = mysql_num_rows($cs);

Or just:

$column_count = mysql_num_rows(mysql_query("describe tbl_info"));

What is the difference between C and embedded C?

C is a only programming language its used in system programming. but embedded C is used to implement the projects like real time applications

Forcing anti-aliasing using css: Is this a myth?

The px to pt fix worked for me on a site that uses a font from Google Web Fonts. On Win7 - IE8 it correctly fixed the lack of anti-alias rendering.

HintPath vs ReferencePath in Visual Studio

My own experience has been that it's best to stick to one of two kinds of assembly references:

  • A 'local' assembly in the current build directory
  • An assembly in the GAC

I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.

Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).

This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D

Hope that helps!

How to check if a textbox is empty using javascript

<pre><form name="myform"  method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" /> 
<input type="submit"/>
</form></pre>

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false); 
    frmvalidator.EnableMsgsTogether(); 
    frmvalidator.addValidation("name","req","Plese Enter Name"); 

</script>

Note: before using the code above you have to add the gen_validatorv31.js file.

My httpd.conf is empty

OK - what you're missing is that its designed to be more industrial and serve many sites, so the config you want is probably:

/etc/apache2/sites-available/default

which on my system is linked to from /etc/apache2/sites-enabled/

if you want to have different sites with different options, copy the file and then change those...

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

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

I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.

How can I do DNS lookups in Python, including referring to /etc/hosts?

This code works well for returning all of the IP addresses that might belong to a particular URI. Since many systems are now in a hosted environment (AWS/Akamai/etc.), systems may return several IP addresses. The lambda was "borrowed" from @Peter Silva.

def get_ips_by_dns_lookup(target, port=None):
    '''
        this function takes the passed target and optional port and does a dns
        lookup. it returns the ips that it finds to the caller.

        :param target:  the URI that you'd like to get the ip address(es) for
        :type target:   string
        :param port:    which port do you want to do the lookup against?
        :type port:     integer
        :returns ips:   all of the discovered ips for the target
        :rtype ips:     list of strings

    '''
    import socket

    if not port:
        port = 443

    return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))

ips = get_ips_by_dns_lookup(target='google.com')

Reading e-mails from Outlook with Python through MAPI

I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content

Sqlite in chrome

You can use Web SQL API which is an ordinary SQLite database in your browser and you can open/modify it like any other SQLite databases for example with Lita.

Chrome locates databases automatically according to domain names or extension id. A few months ago I posted on my blog short article on how to delete Chrome's database because when you're testing some functionality it's quite useful.

Is #pragma once a safe include guard?

The performance benefit is from not having to reopen the file once the #pragma once have been read. With guards, the compiler have to open the file (that can be costly in time) to get the information that it shouldn't include it's content again.

That is theory only because some compilers will automatically not open files that didn't have any read code in, for each compilation unit.

Anyway, it's not the case for all compilers, so ideally #pragma once have to be avoided for cross-platform code has it's not standard at all / have no standardized definition and effect. However, practically, it's really better than guards.

In the end, the better suggestion you can get to be sure to have the best speed from your compiler without having to check the behavior of each compiler in this case, is to use both pragma once and guards.

#ifndef NR_TEST_H
#define NR_TEST_H
#pragma once

#include "Thing.h"

namespace MyApp
{
 // ...
}

#endif

That way you get the best of both (cross-platform and help compilation speed).

As it's longer to type, I personally use a tool to help generate all that in a very wick way (Visual Assist X).

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

Expand/collapse section in UITableView in iOS

So, based on the 'button in header' solution, here is a clean and minimalist implementation:

  • you keep track of collapsed (or expanded) sections in a property
  • you tag the button with the section index
  • you set a selected state on that button to change the arrow direction (like ? and ?)

Here is the code:

@interface MyTableViewController ()
@property (nonatomic, strong) NSMutableIndexSet *collapsedSections;
@end

...

@implementation MyTableViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (!self)
        return;
    self.collapsedSections = [NSMutableIndexSet indexSet];
    return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // if section is collapsed
    if ([self.collapsedSections containsIndex:section])
        return 0;

    // if section is expanded
#warning incomplete implementation
    return [super tableView:tableView numberOfRowsInSection:section];
}

- (IBAction)toggleSectionHeader:(UIView *)sender
{
    UITableView *tableView = self.tableView;
    NSInteger section = sender.tag;

    MyTableViewHeaderFooterView *headerView = (MyTableViewHeaderFooterView *)[self tableView:tableView viewForHeaderInSection:section];

    if ([self.collapsedSections containsIndex:section])
    {
        // section is collapsed
        headerView.button.selected = YES;
        [self.collapsedSections removeIndex:section];
    }
    else
    {
        // section is expanded
        headerView.button.selected = NO;
        [self.collapsedSections addIndex:section];
    }

    [tableView beginUpdates];
    [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView endUpdates];
}

@end

Push method in React Hooks (useState)?

You can append array of Data at the end of custom state:

  const [vehicleData, setVehicleData] = React.useState<any[]>([]);
  setVehicleData(old => [...old, ...newArrayData]);

For example, In below, you appear an example of axios:

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        {
          url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
          method: 'get',
        }
      );
      setVehicleData(old => [...old, ...result.data.data]);
    };

    fetchData();
  }, [page]);

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

Convert Variable Name to String?

TL;DR: Not possible. See 'conclusion' at the end.


There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.

This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.

What would be needed, is the reverse of the eval() function:

get_indentifier_name_missing_function()

which would take an identifier name ('variable','dictionary',etc) as an argument, and return a string containing the identifier’s name.


Consider the following current state of affairs:

random_function(argument_data)

If one is passing an identifier name ('function','variable','dictionary',etc) argument_data to a random_function() (another identifier name), one actually passes an identifier (e.g.: <argument_data object at 0xb1ce10>) to another identifier (e.g.: <function random_function at 0xafff78>):

<function random_function at 0xafff78>(<argument_data object at 0xb1ce10>)

From my understanding, only the memory address is passed to the function:

<function at 0xafff78>(<object at 0xb1ce10>)

Therefore, one would need to pass a string as an argument to random_function() in order for that function to have the argument's identifier name:

random_function('argument_data')

Inside the random_function()

def random_function(first_argument):

, one would use the already supplied string 'argument_data' to:

  1. serve as an 'identifier name' (to display, log, string split/concat, whatever)

  2. feed the eval() function in order to get a reference to the actual identifier, and therefore, a reference to the real data:

    print("Currently working on", first_argument)
    some_internal_var = eval(first_argument)
    print("here comes the data: " + str(some_internal_var))
    

Unfortunately, this doesn't work in all cases. It only works if the random_function() can resolve the 'argument_data' string to an actual identifier. I.e. If argument_data identifier name is available in the random_function()'s namespace.

This isn't always the case:

# main1.py
import some_module1

argument_data = 'my data'

some_module1.random_function('argument_data')


# some_module1.py
def random_function(first_argument):
    print("Currently working on", first_argument)
    some_internal_var = eval(first_argument)
    print("here comes the data: " + str(some_internal_var))
######

Expected results would be:

Currently working on: argument_data
here comes the data: my data

Because argument_data identifier name is not available in the random_function()'s namespace, this would yield instead:

Currently working on argument_data
Traceback (most recent call last):
  File "~/main1.py", line 6, in <module>
    some_module1.random_function('argument_data')
  File "~/some_module1.py", line 4, in random_function
    some_internal_var = eval(first_argument)
  File "<string>", line 1, in <module>
NameError: name 'argument_data' is not defined

Now, consider the hypotetical usage of a get_indentifier_name_missing_function() which would behave as described above.

Here's a dummy Python 3.0 code: .

# main2.py
import some_module2
some_dictionary_1       = { 'definition_1':'text_1',
                            'definition_2':'text_2',
                            'etc':'etc.' }
some_other_dictionary_2 = { 'key_3':'value_3',
                            'key_4':'value_4', 
                            'etc':'etc.' }
#
# more such stuff
#
some_other_dictionary_n = { 'random_n':'random_n',
                            'etc':'etc.' }

for each_one_of_my_dictionaries in ( some_dictionary_1,
                                     some_other_dictionary_2,
                                     ...,
                                     some_other_dictionary_n ):
    some_module2.some_function(each_one_of_my_dictionaries)


# some_module2.py
def some_function(a_dictionary_object):
    for _key, _value in a_dictionary_object.items():
        print( get_indentifier_name_missing_function(a_dictionary_object)    +
               "    " +
               str(_key) +
               "  =  " +
               str(_value) )
######

Expected results would be:

some_dictionary_1    definition_1  =  text_1
some_dictionary_1    definition_2  =  text_2
some_dictionary_1    etc  =  etc.
some_other_dictionary_2    key_3  =  value_3
some_other_dictionary_2    key_4  =  value_4
some_other_dictionary_2    etc  =  etc.
......
......
......
some_other_dictionary_n    random_n  =  random_n
some_other_dictionary_n    etc  =  etc.

Unfortunately, get_indentifier_name_missing_function() would not see the 'original' identifier names (some_dictionary_,some_other_dictionary_2,some_other_dictionary_n). It would only see the a_dictionary_object identifier name.

Therefore the real result would rather be:

a_dictionary_object    definition_1  =  text_1
a_dictionary_object    definition_2  =  text_2
a_dictionary_object    etc  =  etc.
a_dictionary_object    key_3  =  value_3
a_dictionary_object    key_4  =  value_4
a_dictionary_object    etc  =  etc.
......
......
......
a_dictionary_object    random_n  =  random_n
a_dictionary_object    etc  =  etc.

So, the reverse of the eval() function won't be that useful in this case.


Currently, one would need to do this:

# main2.py same as above, except:

    for each_one_of_my_dictionaries_names in ( 'some_dictionary_1',
                                               'some_other_dictionary_2',
                                               '...',
                                               'some_other_dictionary_n' ):
        some_module2.some_function( { each_one_of_my_dictionaries_names :
                                     eval(each_one_of_my_dictionaries_names) } )
    
    
    # some_module2.py
    def some_function(a_dictionary_name_object_container):
        for _dictionary_name, _dictionary_object in a_dictionary_name_object_container.items():
            for _key, _value in _dictionary_object.items():
                print( str(_dictionary_name) +
                       "    " +
                       str(_key) +
                       "  =  " +
                       str(_value) )
    ######

In conclusion:

  • Python passes only memory addresses as arguments to functions.
  • Strings representing the name of an identifier, can only be referenced back to the actual identifier by the eval() function if the name identifier is available in the current namespace.
  • A hypothetical reverse of the eval() function, would not be useful in cases where the identifier name is not 'seen' directly by the calling code. E.g. inside any called function.
  • Currently one needs to pass to a function:
    1. the string representing the identifier name
    2. the actual identifier (memory address)

This can be achieved by passing both the 'string' and eval('string') to the called function at the same time. I think this is the most 'general' way of solving this egg-chicken problem across arbitrary functions, modules, namespaces, without using corner-case solutions. The only downside is the use of the eval() function which may easily lead to unsecured code. Care must be taken to not feed the eval() function with just about anything, especially unfiltered external-input data.

Base 64 encode and decode example code

First:

  • Choose an encoding. UTF-8 is generally a good choice; stick to an encoding which will definitely be valid on both sides. It would be rare to use something other than UTF-8 or UTF-16.

Transmitting end:

  • Encode the string to bytes (e.g. text.getBytes(encodingName))
  • Encode the bytes to base64 using the Base64 class
  • Transmit the base64

Receiving end:

  • Receive the base64
  • Decode the base64 to bytes using the Base64 class
  • Decode the bytes to a string (e.g. new String(bytes, encodingName))

So something like:

// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");

Or with StandardCharsets:

// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);

Replace forward slash "/ " character in JavaScript string?

Remove all forward slash occurrences with blank char in Javascript.

modelData = modelData.replace(/\//g, '');

android adb turn on wifi via adb

No need to edit any database directly, there is a command for it :)

svc wifi [enable|disable]

Spring - download response as a file

I have written comments below to understand code sample. Some one if using, they can follow it , as I named the files accordingly.

  1. IF server is sending blob in the response, then our client should be able to produce it.

  2. As my purpose is solved by using these. I can able to download files, as I have used type: 'application/*' for all files.

  3. Created "downloadLink" variable is just technique used in response so that, it would fill like some clicked on link, then response comes and then its href would be triggered.

_x000D_
_x000D_
controller.js_x000D_
//this function is in controller, which will be trigered on download button hit. _x000D_
_x000D_
  $scope.downloadSampleFile = function() {_x000D_
//create sample hidden link in document, to accept Blob returned in the response from back end_x000D_
    _x000D_
  var downloadLink = document.createElement("a");_x000D_
_x000D_
  document.body.appendChild(downloadLink);_x000D_
  downloadLink.style = "display: none";_x000D_
_x000D_
//This service is written Below how does it work, by aceepting necessary params_x000D_
  downloadFile.downloadfile(data).then(function (result) {_x000D_
_x000D_
   var fName = result.filename;_x000D_
   var file = new Blob([result.data], {type: 'application/*'});_x000D_
   var fileURL = (window.URL || window.webkitURL).createObjectURL(file);_x000D_
_x000D_
          _x000D_
//Blob, client side object created to with holding browser specific download popup, on the URL created with the help of window obj._x000D_
          _x000D_
   downloadLink.href = fileURL;_x000D_
   downloadLink.download = fName;_x000D_
   downloadLink.click();_x000D_
  });_x000D_
 };_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
services.js_x000D_
_x000D_
.factory('downloadFile', ["$http", function ($http) {_x000D_
 return {_x000D_
  downloadfile : function () {_x000D_
   return $http.get(//here server endpoint to which you want to hit the request_x000D_
              , {_x000D_
    responseType: 'arraybuffer',_x000D_
    params: {_x000D_
     //Required params_x000D_
    },_x000D_
   }).then(function (response, status, headers, config) {_x000D_
    return response;_x000D_
   });_x000D_
  },_x000D_
 };_x000D_
}])
_x000D_
_x000D_
_x000D_

How do I print the content of httprequest request?

Rewrite @Juned Ahsan solution via stream in one line (headers are treated the same way):

public static String printRequest(HttpServletRequest req) {
    String params = StreamSupport.stream(
            ((Iterable<String>) () -> req.getParameterNames().asIterator()).spliterator(), false)
            .map(pName -> pName + '=' + req.getParameter(pName))
            .collect(Collectors.joining("&"));
    return req.getRequestURI() + '?' + params;
}

See also how to convert an iterator to a stream solution.

TypeScript typed array usage

The translation is correct, the typing of the expression isn't. TypeScript is incorrectly typing the expression new Thing[100] as an array. It should be an error to index Thing, a constructor function, using the index operator. In C# this would allocate an array of 100 elements. In JavaScript this calls the value at index 100 of Thing as if was a constructor. Since that values is undefined it raises the error you mentioned. In JavaScript and TypeScript you want new Array(100) instead.

You should report this as a bug on CodePlex.

Passing argument to alias in bash

Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:

function __t2d {                                                                
         if [ "$1x" != 'x' ]; then                                              
            date -d "@$1"                                                       
         fi                                                                     
} 

alias t2d='__t2d'                                                               

Relative imports in Python 3

Put this inside your package's __init__.py file:

# For relative imports to work in Python 3.6
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))

Assuming your package is like this:

+-- project
¦   +-- package
¦   ¦   +-- __init__.py
¦   ¦   +-- module1.py
¦   ¦   +-- module2.py
¦   +-- setup.py

Now use regular imports in you package, like:

# in module2.py
from module1 import class1

This works in both python 2 and 3.

How do I know if jQuery has an Ajax request pending?

We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.

HTML

<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />

JS Code

//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");

//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)

if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
  ajaxRequestVariable.abort();
  $("#test").html("Ajax Request Cancelled.");
}
});

//Ajax Process Starts
ajaxRequestVariable = $.ajax({
            method: "POST",
            url: '/echo/json/',
            contentType: "application/json",
            cache: false,
            dataType: "json",
            data: {
        json: JSON.encode({
         data:
             [
                            {"prop1":"prop1Value"},
                    {"prop1":"prop2Value"}
                  ]         
        }),
        delay: 11
    },

            success: function (response) {
            $("#test").show();
            $("#test").html("Request is completed");           
            },
            error: function (error) {

            },
            complete: function () {

            }
        });

Exception thrown in catch and finally clause

class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}

public class C1 {
    public static void main(String[] args) throws Exception {
        try {
            System.out.print("TryA L1\n");
            q();
            System.out.print("TryB L1\n");
        }
        catch (Exception i) {
            System.out.print("Catch L1\n");                
        }
        finally {
            System.out.print("Finally L1\n");
            throw new MyExc1();
        }
    }

    static void q() throws Exception {
        try {
            System.out.print("TryA L2\n");
            q2();
            System.out.print("TryB L2\n");
        }
        catch (Exception y) {
            System.out.print("Catch L2\n");
            throw new MyExc2();  
        }
        finally {
            System.out.print("Finally L2\n");
            throw new Exception();
        }
    }

    static void q2() throws Exception {
        throw new MyExc1();
    }
}

Order:

TryA L1
TryA L2
Catch L2
Finally L2
Catch L1
Finally L1        
Exception in thread "main" MyExc1 at C1.main(C1.java:30)

https://www.compilejava.net/

JQuery addclass to selected div, remove class if another div is selected

Are you looking something like this short and effective:

http://jsfiddle.net/XBfMV/

$('div').on('click',function(){
  $('div').removeClass('active');
  $(this).addClass('active');
});

you can simply add a general class 'active' for selected div. when a div is clicked, remove the 'active' class, and add it to the clicked div.

Bootstrap Carousel Full Screen

You can do it without forcing html and body to me 100% height. Use view port height instead. And with mouse wheel control too.

_x000D_
_x000D_
function debounce(func, wait, immediate) {_x000D_
  var timeout;_x000D_
  return function() {_x000D_
    var context = this,_x000D_
      args = arguments;_x000D_
    var later = function() {_x000D_
      timeout = null;_x000D_
      if (!immediate) func.apply(context, args);_x000D_
    };_x000D_
    var callNow = immediate && !timeout;_x000D_
    clearTimeout(timeout);_x000D_
    timeout = setTimeout(later, wait);_x000D_
    if (callNow) func.apply(context, args);_x000D_
  };_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
  //console.log(direction);_x000D_
  if (direction == false) {_x000D_
   $('.carousel-control-next').click();_x000D_
  } else {_x000D_
   $('.carousel-control-prev').click();_x000D_
  }_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
  e.preventDefault();_x000D_
  var delta;_x000D_
  if (event.wheelDelta) {_x000D_
    delta = event.wheelDelta;_x000D_
  } else {_x000D_
    delta = -1 * event.deltaY;_x000D_
  }_x000D_
_x000D_
  onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
  height: 100vh;_x000D_
  background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
  width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
  display: flex !important;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
    color: #fff;_x000D_
    font-size: 72px;_x000D_
    padding: 0 10%;_x000D_
 }
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
  <!-- The slideshow -->_x000D_
  <div class="carousel-inner">_x000D_
    <div class="carousel-item active">_x000D_
      <h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
      <h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
     <h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- Left and right controls -->_x000D_
  <a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
    <span class="carousel-control-prev-icon"></span>_x000D_
  </a>_x000D_
  <a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
    <span class="carousel-control-next-icon"></span>_x000D_
  </a>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Passing a dictionary to a function as keyword parameters

In python, this is called "unpacking", and you can find a bit about it in the tutorial. The documentation of it sucks, I agree, especially because of how fantasically useful it is.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

Update: This will create a second context same as in applicationContext.xml

or you can add this code snippet to your web.xml

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

instead of

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

Integer value in TextView

TextView tv = new TextView(this);
tv.setText(String.valueOf(number));

or

tv.setText(""+number);

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

Delete all nodes and relationships in neo4j 1.8

if the name of node is for example : abcd then below query will work :

MATCH (n:abcd)
DETACH DELETE n

This will only delete the node with label "abcd" and all its relation-ships.

What is the difference between max-device-width and max-width for mobile web?

max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.

• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;

• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.

Conversion of a datetime2 data type to a datetime data type results out-of-range value

What kind of dates do you have in the column?

Do all of them fit within the range of the type?


As an aside, the correct way to get a Type object for the DataColumn constructor is the typeof keyword, which is orders of magnitude faster.

Therefore, to create the column, you should write

new DataColumn("myDate", typeof(DateTime))

Perform an action in every sub-directory using Bash

You could try:

#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/

for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
  cd "$f"
  <your job here>
done

or similar...

Explanation:

find . -maxdepth 1 -mindepth 1 -type d : Only find directories with a maximum recursive depth of 1 (only the subdirectories of $1) and minimum depth of 1 (excludes current folder .)

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

I was having same issue, way i have resolved is:

opened the MySQL installer. i was having a Reconfigure link on MYSQL Server row. MYSQL Server having Reconfigure Link

Clicked on it, it does reinstalled MySQL Server. after that opened MySQL Workbench, and it was working fine.

VBoxManage: error: Failed to create the host-only adapter

In my case, I was able to solve this issue by reinstalling virtual box. I was trying to use laravel's homestead and was having this error. Reinstalling helps creating the directories that are needed for virtual box again. Took me an hour to figure out.

Windows Task Scheduler doesn't start batch file task

Make sure you set the 'Start in' and 'Program/script' options correctly. If your file address is: C:\Temp\foo.bat, set the 'start in' option to 'C:\Temp' and the 'Program/script' option to 'foo.bat'.

To set the 'Start in' option: Right click task in the task scheduler > Properties > Actions > Edit.

If this alone doesn't work then try moving the .bat file to a directory with basic permissions (maybe a shared directory for example).

I had a problem where my .bat file was located in a folder with some restrictive permissions on it, so that only my user account could access it. Even though I had set up the task scheduler to use my credentials it still failed. Moving the .bat file to another directory sorted the issue.

Importing CommonCrypto in a Swift framework

Good news! Swift 4.2 (Xcode 10) finally provides CommonCrypto!

Just add import CommonCrypto in your swift file.

Is there a way to view past mysql queries with phpmyadmin?

you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe

it run your last mysql and you can see it in phpmyadmin and other section of your system.

notice: stop your current mysql version.

S F My English.

How to change the font size on a matplotlib plot

Based on the above stuff:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)

fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)

plot = fig.add_subplot(1, 1, 1)

plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)

for label in (plot.get_xticklabels() + plot.get_yticklabels()):
    label.set_fontproperties(font)

How do you join tables from two different SQL Server instances in one SQL query

The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:

SELECT *
FROM server1table
    INNER JOIN server2.database.dbo.server2table ON .....

How to update fields in a model without creating a new record in django?

You should do it this way ideally

t = TemperatureData.objects.get(id=1)
t.value = 999
t.save(['value'])

This allow you to specify which column should be saved and rest are left as they currently are in database. (https://code.djangoproject.com/ticket/4102)!

Difference between <input type='submit' /> and <button type='submit'>text</button>

With <button>, you can use img tags, etc. where text is

<button type='submit'> text -- can be img etc.  </button>

with <input> type, you are limited to text

Is optimisation level -O3 dangerous in g++?

In my somewhat checkered experience, applying -O3 to an entire program almost always makes it slower (relative to -O2), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2 relative to -Os!

The intended use pattern for -O3 is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3 optimizations to hot functions -- effectively automating this process.

SQL Server Management Studio – tips for improving the TSQL coding process

Using bookmarks is great way to keep your sanity if you're working with or troubleshooting a really long procedure. Let's say you're working with a derived field in an outer query and it's definition is another 200 lines down inside the inner query. You can bookmark both locations and then quickly go back and forth between the two.

Mock HttpContext.Current in Test Init Method

Below Test Init will also do the job.

[TestInitialize]
public void TestInit()
{
  HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();
}

How to merge multiple lists into one list in python?

a = ['it']
b = ['was']
c = ['annoying']

a.extend(b)
a.extend(c)

# a now equals ['it', 'was', 'annoying']

Force uninstall of Visual Studio

So Soumyaansh's Revo Uninstaller Pro fix worked for me :) ( After 2 days of troubleshooting other options {screams internally 😀} ).

I did run into the an issue with his method though, "Could not find a suitable SDK to target" even though I selected to install Visual Studio with custom settings and selected the SDK I wanted to install. You may need to download the Windows 10 Standalone SDK to resolved this, in order to develop UWP apps if you see this same error after reinstalling Visual Studio.

To do this

  1. Uninstall any Windows 10 SDKs that me on the system (the naming schem for them looks like Windows 10 SDK (WINDOWS_VERSION_NUMBER_HERE) -> Windows 10 SDK (14393) etc . . .). If there are no SDKs on your system go to step 2!
  2. All that's left is to download the SDKs you want by Checking out the SDK Archive for all available SDKs and you should be good to go in developing for the UWP!

How to change progress bar's progress color in Android

ProgressBar freeRamPb = findViewById(R.id.free_ram_progress_bar);

freeRamPb.getProgressDrawable().setColorFilter(
Color.BLUE, android.graphics.PorterDuff.Mode.SRC_IN);

How to change DatePicker dialog color for Android 5.0

You don't have create theme just write it in your dialog creation object

DatePickerDialog datePicker = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT,this, mYear, mMonth, mDay);

follow this it will give you all type date picker style it's really work

http://www.android-examples.com/change-datepickerdialog-theme-in-android-using-dialogfragment/

SQL Query - Using Order By in UNION

SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
ORDER BY field1

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

PHP - iterate on string characters

Iterate string:

for ($i = 0; $i < strlen($str); $i++){
    echo $str[$i];
}

What can cause a “Resource temporarily unavailable” on sock send() command

That's because you're using a non-blocking socket and the output buffer is full.

From the send() man page

   When the message does not fit into  the  send  buffer  of  the  socket,
   send() normally blocks, unless the socket has been placed in non-block-
   ing I/O mode.  In non-blocking mode it  would  return  EAGAIN  in  this
   case.  

EAGAIN is the error code tied to "Resource temporarily unavailable"

Consider using select() to get a better control of this behaviours

Match groups in Python

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can now capture the condition value re.search(pattern, statement) in a variable (let's all it match) in order to both check if it's not None and then re-use it within the body of the condition:

if match := re.search('I love (\w+)', statement):
  print(f'He loves {match.group(1)}')
elif match := re.search("Ich liebe (\w+)", statement):
  print(f'Er liebt {match.group(1)}')
elif match := re.search("Je t'aime (\w+)", statement):
  print(f'Il aime {match.group(1)}')

Validation of radio button group using jQuery validation plugin

Puts the error message on top.

   <style> 

 .radio-group{ 
      position:relative; margin-top:40px; 
 } 

 #myoptions-error{ 
     position:absolute; 
     top: -25px; 
  } 

 </style> 

 <div class="radio-group"> 
 <input type="radio" name="myoptions" value="blue" class="required"> Blue<br /> 
 <input type="radio" name="myoptions" value="red"> Red<br /> 
 <input type="radio" name="myoptions" value="green"> Green </div>
 </div><!-- end radio-group -->

how to drop database in sqlite?

If you want to delete database programatically you can use deleteDatabase from Context class:

deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.

Best way to check for IE less than 9 in JavaScript without library

This link contains relevant information on detecting versions of Internet Explorer:

http://tanalin.com/en/articles/ie-version-js/

Example:

if (document.all && !document.addEventListener) {
    alert('IE8 or older.');
}

org.hibernate.MappingException: Could not determine type for: java.util.Set

Solution:

@Entity
@Table(name = "USER")
@Access(AccessType.FIELD)
public class User implements UserDetails, Serializable {

    private static final long serialVersionUID = 2L;

    @Id
    @Column(name = "USER_ID", updatable=false, nullable=false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "USERNAME")
    private String username;

    @Column(name = "PASSWORD")
    private String password;

    @Column(name = "NAME")
    private String name;

    @Column(name = "EMAIL")
    private String email;

    @Column(name = "LOCKED")
    private boolean locked;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = Role.class)
    @JoinTable(name = "USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
    private Set<Role> roles;

    @Override
    public GrantedAuthority[] getAuthorities() {
        List<GrantedAuthorityImpl> list = new ArrayList<GrantedAuthorityImpl>(0);
        for (Role role : roles) {
            list.add(new GrantedAuthorityImpl(role.getRole()));
        }
        return (GrantedAuthority[]) list.toArray(new GrantedAuthority[list.size()]);
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !isLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}

Role.java same as above.

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

Multidimensional Array [][] vs [,]

double[,] is a 2d array (matrix) while double[][] is an array of arrays (jagged arrays) and the syntax is:

double[][] ServicePoint = new double[10][];

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

How to compile for Windows on Linux with gcc/g++?

Install a cross compiler, like mingw64 from your package manager. Then compile in the following way: instead of simply calling gcc call i686-w64-mingw32-gcc for 32-bit Windows or x86_64-w64-mingw32-gcc" for 64-bit Windows. I would also use the --static option, as the target system may not have all the libraries.

If you want to compile other language, like Fortran, replace -gcc with -gfortran in the previous commands.

Dynamically allocating an array of objects

The constructor of your A object allocates another object dynamically and stores a pointer to that dynamically allocated object in a raw pointer.

For that scenario, you must define your own copy constructor , assignment operator and destructor. The compiler generated ones will not work correctly. (This is a corollary to the "Law of the Big Three": A class with any of destructor, assignment operator, copy constructor generally needs all 3).

You have defined your own destructor (and you mentioned creating a copy constructor), but you need to define both of the other 2 of the big three.

An alternative is to store the pointer to your dynamically allocated int[] in some other object that will take care of these things for you. Something like a vector<int> (as you mentioned) or a boost::shared_array<>.

To boil this down - to take advantage of RAII to the full extent, you should avoid dealing with raw pointers to the extent possible.

And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling delete - delete handles that case by doing nothing so you don't have to clutter you code with the checks.

Git: How to find a deleted file in the project commit history?

Below is a simple command, where a dev or a git user can pass a deleted file name from the repository root directory and get the history:

git log --diff-filter=D --summary | grep filename | awk '{print $4; exit}' | xargs git log --all -- 

If anybody, can improve the command, please do.

adb server version doesn't match this client

You need to make sure that your project is set to target the AVD that you want to launch.

Right click (ctrl-click MAC) on the project folder in Eclipse. Then click on Properties. In the window that shows up, click on "Android" and then click on the build target you want to launch. Hope that helps.

How to Split Image Into Multiple Pieces in Python

Here is a concise, pure-python solution that works in both python 3 and 2:

from PIL import Image

infile = '20190206-135938.1273.Easy8thRunnersHopefully.jpg'
chopsize = 300

img = Image.open(infile)
width, height = img.size

# Save Chops of original image
for x0 in range(0, width, chopsize):
   for y0 in range(0, height, chopsize):
      box = (x0, y0,
             x0+chopsize if x0+chopsize <  width else  width - 1,
             y0+chopsize if y0+chopsize < height else height - 1)
      print('%s %s' % (infile, box))
      img.crop(box).save('zchop.%s.x%03d.y%03d.jpg' % (infile.replace('.jpg',''), x0, y0))

Notes:

  • The crops that go over the right and bottom of the original image are adjusted to the original image limit and contain only the original pixels.
  • It's easy to choose a different chopsize for w and h by using two chopsize vars and replacing chopsize as appropriate in the code above.

  • Escape single quote character for use in an SQLite query

    I believe you'd want to escape by doubling the single quote:

    INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');
    

    c# open file with default application and parameters

    If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.

    On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:


    You can do it without telling the full Acrobat path, like this:

    Process myProcess = new Process();    
    myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
    myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
    myProcess.Start();
    

    If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:

    myProcess.StartInfo.FileName = "Acrobat.exe";
    

    You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.

    Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows

    Test if characters are in a string

    Answer

    Sigh, it took me 45 minutes to find the answer to this simple question. The answer is: grepl(needle, haystack, fixed=TRUE)

    # Correct
    > grepl("1+2", "1+2", fixed=TRUE)
    [1] TRUE
    > grepl("1+2", "123+456", fixed=TRUE)
    [1] FALSE
    
    # Incorrect
    > grepl("1+2", "1+2")
    [1] FALSE
    > grepl("1+2", "123+456")
    [1] TRUE
    

    Interpretation

    grep is named after the linux executable, which is itself an acronym of "Global Regular Expression Print", it would read lines of input and then print them if they matched the arguments you gave. "Global" meant the match could occur anywhere on the input line, I'll explain "Regular Expression" below, but the idea is it's a smarter way to match the string (R calls this "character", eg class("abc")), and "Print" because it's a command line program, emitting output means it prints to its output string.

    Now, the grep program is basically a filter, from lines of input, to lines of output. And it seems that R's grep function similarly will take an array of inputs. For reasons that are utterly unknown to me (I only started playing with R about an hour ago), it returns a vector of the indexes that match, rather than a list of matches.

    But, back to your original question, what we really want is to know whether we found the needle in the haystack, a true/false value. They apparently decided to name this function grepl, as in "grep" but with a "Logical" return value (they call true and false logical values, eg class(TRUE)).

    So, now we know where the name came from and what it's supposed to do. Lets get back to Regular Expressions. The arguments, even though they are strings, they are used to build regular expressions (henceforth: regex). A regex is a way to match a string (if this definition irritates you, let it go). For example, the regex a matches the character "a", the regex a* matches the character "a" 0 or more times, and the regex a+ would match the character "a" 1 or more times. Hence in the example above, the needle we are searching for 1+2, when treated as a regex, means "one or more 1 followed by a 2"... but ours is followed by a plus!

    1+2 as a regex

    So, if you used the grepl without setting fixed, your needles would accidentally be haystacks, and that would accidentally work quite often, we can see it even works for the OP's example. But that's a latent bug! We need to tell it the input is a string, not a regex, which is apparently what fixed is for. Why fixed? No clue, bookmark this answer b/c you're probably going to have to look it up 5 more times before you get it memorized.

    A few final thoughts

    The better your code is, the less history you have to know to make sense of it. Every argument can have at least two interesting values (otherwise it wouldn't need to be an argument), the docs list 9 arguments here, which means there's at least 2^9=512 ways to invoke it, that's a lot of work to write, test, and remember... decouple such functions (split them up, remove dependencies on each other, string things are different than regex things are different than vector things). Some of the options are also mutually exclusive, don't give users incorrect ways to use the code, ie the problematic invocation should be structurally nonsensical (such as passing an option that doesn't exist), not logically nonsensical (where you have to emit a warning to explain it). Put metaphorically: replacing the front door in the side of the 10th floor with a wall is better than hanging a sign that warns against its use, but either is better than neither. In an interface, the function defines what the arguments should look like, not the caller (because the caller depends on the function, inferring everything that everyone might ever want to call it with makes the function depend on the callers, too, and this type of cyclical dependency will quickly clog a system up and never provide the benefits you expect). Be very wary of equivocating types, it's a design flaw that things like TRUE and 0 and "abc" are all vectors.

    using scp in terminal

    I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.

    scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop
    

    The username@remotecomputer is the same string you used with ssh initially.

    Android: Scale a Drawable or background image?

    You can use one of following:

    android:gravity="fill_horizontal|clip_vertical"

    Or

    android:gravity="fill_vertical|clip_horizontal"

    Default value in an asp.net mvc view model

    What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.

    If you load the search criteria from elsewhere, then you should probably have some mapping logic.

    Go back button in a page

    onclick="history.go(-1)" Simply

    Why does make think the target is up to date?

    my mistake was making the target name "filename.c:" instead of just "filename:"

    SQL Order By Count

    Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.

    event_id show_id event_name judge_id
    0101    01  Dressage        01
    0102    01  Jumping         02
    0103    01  Led in          01
    0201    02  Led in          02
    0301    03  Led in          01
    0401    04  Dressage        04
    0501    05  Dressage        01
    0502    05  Flag and Pole   02
    

    Ans:

    select event_name, count(show_id) as held_times from event 
    group by event_name 
    order by count(show_id) desc
    

    Can I use a binary literal in C or C++?

    The C++ over-engineering mindset is already well accounted for in the other answers here. Here's my attempt at doing it with a C, keep-it-simple-ffs mindset:

    unsigned char x = 0xF; // binary: 00001111
    

    MSOnline can't be imported on PowerShell (Connect-MsolService error)

    After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.

    As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline and Connect-MsolService, you will need to install the following applications (64-bit only):

    1. Applicable Operating Systems: Windows 7 to 10
      Name: "Microsoft Online Services Sign-in Assistant for IT Professionals RTW"
      Version: 7.250.4556.0 (latest)
      Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=41950
      Installer file name: msoidcli_64.msi
    2. Applicable Operating Systems: Windows 7 to 10
      Name: "Windows Azure Active Directory Module for Windows PowerShell"
      Version: Unknown but the latest installer file's SHA-256 hash is D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
      Installer URL: https://technet.microsoft.com/en-us/library/dn975125.aspx
      Installer file name: AdministrationConfig-en.msi
    3. Applicable Operating Systems: Windows 7 only
      Name: "Windows PowerShell 3.0"
      Version: 3.0 (later versions will probably work too)
      Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=34595
      Installer file name: Windows6.1-KB2506143-x64.msu

     

    enter image description here enter image description here enter image description here

    I want to get the type of a variable at runtime

    So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:

    val x = 5
    def f[T](v: T) = v
    f(x) // T is Int, the type of x
    

    But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:

    val x: Any = 5
    def f[T](v: T) = v match {
      case _: Int    => "Int"
      case _: String => "String"
      case _         => "Unknown"
    }
    f(x)
    

    Here it doesn't matter what is the type of the variable, Any. What matters, what is checked is the type of 5, the value. In fact, T is useless -- you might as well have written it def f(v: Any) instead. Also, this uses either ClassTag or a value's Class, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_] (List of something), but not whether it is, for example, a List[Int] or List[String].

    Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag or a TypeTag. For example:

    val x: Any = 5
    import scala.reflect.ClassTag
    def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
    f(x) // returns the string "Any"
    

    A ClassTag will also let you use type parameters you received on match. This won't work:

    def f[A, B](a: A, b: B) = a match {
      case _: B => "A is a B"
      case _ => "A is not a B"
    }
    

    But this will:

    val x = 'c'
    val y = 5
    val z: Any = 5
    import scala.reflect.ClassTag
    def f[A, B: ClassTag](a: A, b: B) = a match {
      case _: B => "A is a B"
      case _ => "A is not a B"
    }
    f(x, y) // A (Char) is not a B (Int)
    f(x, z) // A (Char) is a B (Any)
    

    Here I'm using the context bounds syntax, B : ClassTag, which works just like the implicit parameter in the previous ClassTag example, but uses an anonymous variable.

    One can also get a ClassTag from a value's Class, like this:

    val x: Any = 5
    val y = 5
    import scala.reflect.ClassTag
    def f(a: Any, b: Any) = {
      val B = ClassTag(b.getClass)
      ClassTag(a.getClass) match {
        case B => "a is the same class as b"
        case _ => "a is not the same class as b"
      }
    }
    f(x, y) == f(y, x) // true, a is the same class as b
    

    A ClassTag is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag for List[Int] and List[String] is the same, List. If you need type parameters, then you must use a TypeTag instead. A TypeTag however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.

    Examples with TypeTag can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:

    import scala.reflect.runtime.universe.TypeTag
    def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
    type X = Int
    val x: X = 5
    val y = 5
    f(x, y) // false, X is not the same type as Int
    

    Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag, so I'll stop here.

    Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:

    val x = 5
    x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it
    

    It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.

    How to merge remote master to local branch

    From your feature branch (e.g configUpdate) run:

    git fetch
    git rebase origin/master
    

    Or the shorter form:

    git pull --rebase
    

    Why this works:

    • git merge branchname takes new commits from the branch branchname, and adds them to the current branch. If necessary, it automatically adds a "Merge" commit on top.

    • git rebase branchname takes new commits from the branch branchname, and inserts them "under" your changes. More precisely, it modifies the history of the current branch such that it is based on the tip of branchname, with any changes you made on top of that.

    • git pull is basically the same as git fetch; git merge origin/master.

    • git pull --rebase is basically the same as git fetch; git rebase origin/master.

    So why would you want to use git pull --rebase rather than git pull? Here's a simple example:

    • You start working on a new feature.

    • By the time you're ready to push your changes, several commits have been pushed by other developers.

    • If you git pull (which uses merge), your changes will be buried by the new commits, in addition to an automatically-created merge commit.

    • If you git pull --rebase instead, git will fast forward your master to upstream's, then apply your changes on top.

    An example of how to use getopts in bash

    The example packaged with getopt (my distro put it in /usr/share/getopt/getopt-parse.bash) looks like it covers all of your cases:

    #!/bin/bash
    
    # A small example program for using the new getopt(1) program.
    # This program will only work with bash(1)
    # An similar program using the tcsh(1) script language can be found
    # as parse.tcsh
    
    # Example input and output (from the bash prompt):
    # ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
    # Option a
    # Option c, no argument
    # Option c, argument `more'
    # Option b, argument ` very long '
    # Remaining arguments:
    # --> `par1'
    # --> `another arg'
    # --> `wow!*\?'
    
    # Note that we use `"$@"' to let each command-line parameter expand to a 
    # separate word. The quotes around `$@' are essential!
    # We need TEMP as the `eval set --' would nuke the return value of getopt.
    TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
         -n 'example.bash' -- "$@"`
    
    if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
    
    # Note the quotes around `$TEMP': they are essential!
    eval set -- "$TEMP"
    
    while true ; do
        case "$1" in
            -a|--a-long) echo "Option a" ; shift ;;
            -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
            -c|--c-long) 
                # c has an optional argument. As we are in quoted mode,
                # an empty parameter will be generated if its optional
                # argument is not found.
                case "$2" in
                    "") echo "Option c, no argument"; shift 2 ;;
                    *)  echo "Option c, argument \`$2'" ; shift 2 ;;
                esac ;;
            --) shift ; break ;;
            *) echo "Internal error!" ; exit 1 ;;
        esac
    done
    echo "Remaining arguments:"
    for arg do echo '--> '"\`$arg'" ; done
    

    Run batch file from Java code

    try following

    try {
                String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
                Process p =  Runtime.getRuntime().exec(command);           
            } catch (IOException ex) {
            }
    

    How to enable file upload on React's Material UI simple input?

    Here's an example using an IconButton to capture input (photo/video capture) using v3.9.2:

    import React, { Component, Fragment } from 'react';
    import PropTypes from 'prop-types';
    
    import { withStyles } from '@material-ui/core/styles';
    import IconButton from '@material-ui/core/IconButton';
    import PhotoCamera from '@material-ui/icons/PhotoCamera';
    import Videocam from '@material-ui/icons/Videocam';
    
    const styles = (theme) => ({
        input: {
            display: 'none'
        }
    });
    
    class MediaCapture extends Component {
        static propTypes = {
            classes: PropTypes.object.isRequired
        };
    
        state: {
            images: [],
            videos: []
        };
    
        handleCapture = ({ target }) => {
            const fileReader = new FileReader();
            const name = target.accept.includes('image') ? 'images' : 'videos';
    
            fileReader.readAsDataURL(target.files[0]);
            fileReader.onload = (e) => {
                this.setState((prevState) => ({
                    [name]: [...prevState[name], e.target.result]
                }));
            };
        };
    
        render() {
            const { classes } = this.props;
    
            return (
                <Fragment>
                    <input
                        accept="image/*"
                        className={classes.input}
                        id="icon-button-photo"
                        onChange={this.handleCapture}
                        type="file"
                    />
                    <label htmlFor="icon-button-photo">
                        <IconButton color="primary" component="span">
                            <PhotoCamera />
                        </IconButton>
                    </label>
    
                    <input
                        accept="video/*"
                        capture="camcorder"
                        className={classes.input}
                        id="icon-button-video"
                        onChange={this.handleCapture}
                        type="file"
                    />
                    <label htmlFor="icon-button-video">
                        <IconButton color="primary" component="span">
                            <Videocam />
                        </IconButton>
                    </label>
                </Fragment>
            );
        }
    }
    
    export default withStyles(styles, { withTheme: true })(MediaCapture);
    

    Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

    I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.

    jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
    

    I was then able to use the JObject.Parse(jsonResult) and everything worked.

    Function vs. Stored Procedure in SQL Server

    Functions are computed values and cannot perform permanent environmental changes to SQL Server (i.e., no INSERT or UPDATE statements allowed).

    A function can be used inline in SQL statements if it returns a scalar value or can be joined upon if it returns a result set.

    A point worth noting from comments, which summarize the answer. Thanks to @Sean K Anderson:

    Functions follow the computer-science definition in that they MUST return a value and cannot alter the data they receive as parameters (the arguments). Functions are not allowed to change anything, must have at least one parameter, and they must return a value. Stored procs do not have to have a parameter, can change database objects, and do not have to return a value.

    What is the Java ?: operator called and what does it do?

    You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:

    String s = mayBeNull?.toString() ?: "null";
    

    It would be especially convenient where auto-unboxing takes place.

    Integer ival = ...;  // may be null
    int i = ival ?: -1;  // no NPE from unboxing
    

    It has been selected for further consideration under JDK 7's "Project Coin."

    Use querystring variables in MVC controller

    public ActionResult SomeAction(string start, string end)
    

    The framework will map the query string parameters to the method parameters.

    Add line break within tooltips

    You can use bootstrap tooltip, and don't forget to set the html option to true.

    <div id="tool"> tooltip</div>
    
    $('#tool').tooltip({
         title: 'line one' +'<br />'+ 'line two',
         html: true
    });
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    

    Rename multiple files in cmd

    The below command would do the job.

    forfiles /M *.txt /C "cmd /c rename @file \"@fname 1.1.txt\""
    

    source: Rename file extensions in bulk

    How to kill a process in MacOS?

    If you're trying to kill -9 it, you have the correct PID, and nothing happens, then you don't have permissions to kill the process.

    Solution:

    $ sudo kill -9 PID
    

    Okay, sure enough Mac OS/X does give an error message for this case:

    $ kill -9 196
    -bash: kill: (196) - Operation not permitted
    

    So, if you're not getting an error message, you somehow aren't getting the right PID.

    Find a value anywhere in a database

    Thanks for the really useful script.

    You may need to add the following modification to the code if your tables have non-convertable fields:

    SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE NOT IN ('text', 'image', 'ntext')                 
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )
    

    Chris

    How to connect android emulator to the internet

    I'm not sure if this is your issue, but here's how I fixed mine.

    I always had this "No DNS servers found" error when starting the emulator and did a lot of research on google to no avail. Anyway, I found a post somewhere (can't find it anymore) that was saying that the number of NICs, number of DNS entries could affect the emulator. Also, knowing that the emulator uses a Windows API function (GetNetworkParams()) to resolve DNS entries, I couldn't rely on the %WINDOWS%\System32\Hosts file.

    However, I did went in the NICs properties (on Windows 7) to find that I was specifying a static IP, but no DNS entries. So, I got the DNS entries from my router and plugged them in the NICs property. I restarted the emulator and it is now using the correct DNS entries!

    I can use my internet connection with the emulator now, and it works wonders!

    Hope it helps!

    Select first 4 rows of a data.frame in R

    Use head:

    dnow <- data.frame(x=rnorm(100), y=runif(100))
    head(dnow,4) ## default is 6
    

    How can I confirm a database is Oracle & what version it is using SQL?

    You can either use

    SELECT * FROM v$version;
    

    or

    SET SERVEROUTPUT ON
    EXEC dbms_output.put_line( dbms_db_version.version );
    

    if you don't want to parse the output of v$version.

    How to debug Javascript with IE 8

    I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?


    Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:

    myLog = function() {
    
        var _div = null;
    
        this.toJson = function(obj) {
    
            if (typeof window.uneval == 'function') { return uneval(obj); }
            if (typeof obj == 'object') {
                if (!obj) { return 'null'; }
                var list = [];
                if (obj instanceof Array) {
                        for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
                        return '[' + list.join(',') + ']';
                } else {
                        for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
                        return '{' + list.join(',') + '}';
                }
            } else if (typeof obj == 'string') {
                return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
            } else {
                return new String(obj);
            }
    
        };
    
        this.createDiv = function() {
    
            myLog._div = document.body.appendChild(document.createElement('div'));
    
            var props = {
                position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
                color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
                fontSize: '11px', whiteSpace: 'nowrap'
            }
    
            for (var key in props) { myLog._div.style[key] = props[key]; }
    
        };
    
    
        if (!myLog._div) { this.createDiv(); }
    
        var logEntry = document.createElement('span');
    
        for (var i=0; i < arguments.length; i++) {
            logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
        }
    
        logEntry.innerHTML += '<br />';
    
        myLog._div.appendChild(logEntry);
    
        // Scroll automatically to the bottom
        myLog._div.scrollTop = myLog._div.scrollHeight;
    
    }
    

    Is there a way to suppress JSHint warning for one given line?

    As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval:

    /*jshint evil:true */
    
    function helloEval(str) {
        /*jshint evil:true */
        eval(str);
    }
    

    Open Jquery modal dialog on click event

    If you want to put some page in the dialog then you can use these

    function Popup()
    {
     $("#pop").load('login.html').dialog({
     height: 625,
     width: 600,
     modal:true,
     close: function(event,ui){
         $("pop").dialog('destroy');
    
            }
     }); 
    
    }
    

    HTML:

    <Div id="pop"  style="display:none;">
    
    </Div>
    

    How can I fetch all items from a DynamoDB table without specifying the primary key?

    Hi you can download using boto3. In python

    import boto3
    from boto3.dynamodb.conditions import Key, Attr
    
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Table')
    response = table.scan()
    items = response['Items']
    while 'LastEvaluatedKey' in response:
        print(response['LastEvaluatedKey'])
        response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
        items.extend(response['Items'])
    
    

    How to get MD5 sum of a string using python?

    You can do the following:

    Python 2.x

    import hashlib
    print hashlib.md5("whatever your string is").hexdigest()
    

    Python 3.x

    import hashlib
    print(hashlib.md5("whatever your string is".encode('utf-8')).hexdigest())
    

    However in this case you're probably better off using this helpful Python module for interacting with the Flickr API:

    ... which will deal with the authentication for you.

    Official documentation of hashlib

    When do I need to use a semicolon vs a slash in Oracle SQL?

    I wanted to clarify some more use between the ; and the /

    In SQLPLUS:

    1. ; means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
    2. <newline> after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;), it means, store the statement to the buffer but do not run it.
    3. / after entering a statement into the buffer (with a blank <newline>) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.
    4. RUN or R is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement.
    5. / during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"

    NOTE: Because ; are used for PL/SQL to end a statement ; cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:

    END;
    /
    

    Duplicate keys in .NET dictionaries?

    In answer to the original question. Something like Dictionary<string, List<object>> is implemented in a class called MultiMap in The Code Project.

    You could find more info to the below link : http://www.codeproject.com/KB/cs/MultiKeyDictionary.aspx

    Remove trailing spaces automatically or with a shortcut

    Menu FilePreferenceSettings

    Enter image description here

    Check the "Trim Trailing Whitespace" option - "When enabled, will trim trailing whitespace when saving a file".

    Creating stored procedure and SQLite?

    If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite

    How to export html table to excel using javascript

    Only works in Mozilla, Chrome and Safari..

    _x000D_
    _x000D_
    $(function() {
      $('button').click(function() {
        var url = 'data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html())
        location.href = url
        return false
      })
    });
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    
    </script>
    <button>click me</button>
    <div id="tableWrap">
      <table>
        <thead>
          <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
          </tr>
          <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
          </tr>
          <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
          </tr>
          <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
          </tr>
        </tbody>
      </table>
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to format background color using twitter bootstrap?

    Just add a div around the container so it looks like:

    <div style="background: red;">
      <div class="container marketing">
        <h2 style="padding-top: 60px;"></h2>
      </div>
    </div>
    

    Applying CSS styles to all elements inside a DIV

    Alternate solution. Include your external CSS in your HTML file by

    <link rel="stylesheet" href="css/applyCSS.css"/> 
    

    inside the applyCSS.css:

       #applyCSS {
          /** Your Style**/
        }
    

    Sorting using Comparator- Descending order (User defined classes)

    For whats its worth here is my standard answer. The only thing new here is that is uses the Collections.reverseOrder(). Plus it puts all suggestions into one example:

    /*
    **  Use the Collections API to sort a List for you.
    **
    **  When your class has a "natural" sort order you can implement
    **  the Comparable interface.
    **
    **  You can use an alternate sort order when you implement
    **  a Comparator for your class.
    */
    import java.util.*;
    
    public class Person implements Comparable<Person>
    {
        String name;
        int age;
    
        public Person(String name, int age)
        {
            this.name = name;
            this.age = age;
        }
    
        public String getName()
        {
            return name;
        }
    
        public int getAge()
        {
            return age;
        }
    
        public String toString()
        {
            return name + " : " + age;
        }
    
        /*
        **  Implement the natural order for this class
        */
        public int compareTo(Person p)
        {
            return getName().compareTo(p.getName());
        }
    
        static class AgeComparator implements Comparator<Person>
        {
            public int compare(Person p1, Person p2)
            {
                int age1 = p1.getAge();
                int age2 = p2.getAge();
    
                if (age1 == age2)
                    return 0;
                else if (age1 > age2)
                    return 1;
                else
                    return -1;
            }
        }
    
        public static void main(String[] args)
        {
            List<Person> people = new ArrayList<Person>();
            people.add( new Person("Homer", 38) );
            people.add( new Person("Marge", 35) );
            people.add( new Person("Bart", 15) );
            people.add( new Person("Lisa", 13) );
    
            // Sort by natural order
    
            Collections.sort(people);
            System.out.println("Sort by Natural order");
            System.out.println("\t" + people);
    
            // Sort by reverse natural order
    
            Collections.sort(people, Collections.reverseOrder());
            System.out.println("Sort by reverse natural order");
            System.out.println("\t" + people);
    
            //  Use a Comparator to sort by age
    
            Collections.sort(people, new Person.AgeComparator());
            System.out.println("Sort using Age Comparator");
            System.out.println("\t" + people);
    
            //  Use a Comparator to sort by descending age
    
            Collections.sort(people,
                Collections.reverseOrder(new Person.AgeComparator()));
            System.out.println("Sort using Reverse Age Comparator");
            System.out.println("\t" + people);
        }
    }
    

    Android: resizing imageview in XML

    Please try this one works for me:

    <ImageView android:id="@+id/image_view"     
      android:layout_width="wrap_content"  
      android:layout_height="wrap_content"  
      android:adjustViewBounds="true"  
      android:maxWidth="60dp" 
      android:layout_gravity="center" 
      android:maxHeight="60dp"  
      android:scaleType="fitCenter"  
      android:src="@drawable/icon"  
      /> 
    

    Pandas DataFrame concat vs append

    So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.

    I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.

    In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))
    
    In [18]: df1
    Out[18]: 
    <class 'pandas.core.frame.DataFrame'>
    DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
    Freq: S
    Data columns (total 1 columns):
    A    10000  non-null values
    dtypes: int64(1)
    
    In [19]: df4 = pd.DataFrame()
    
    The concat
    
    In [20]: %timeit pd.concat([df1,df2,df3])
    1000 loops, best of 3: 270 us per loop
    
    This is equavalent of your append
    
    In [21]: %timeit pd.concat([df4,df1,df2,df3])
    10 loops, best of 
    
     3: 56.8 ms per loop
    

    How do I POST with multipart form data using fetch?

    I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:

    curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"
    

    The basic idea is that each part (split by string in boundary with --) has it's own headers (Content-Type in the second part, for example.) The FormData object manages all this for you, so it's a better way to accomplish our goals.

    This translates to fetch API like this:

    const formData = new FormData()
    formData.append('blob', new Blob(['Hello World!\n']), 'test')
    
    fetch('http://localhost:5001/api/v0/add', {
      method: 'POST',
      body: formData
    })
    .then(r => r.json())
    .then(data => {
      console.log(data)
    })
    

    Where and how is the _ViewStart.cshtml layout file linked?

    From ScottGu's blog:

    Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

    The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

    Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

    Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

    This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

    Also see this.


    In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

    Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

    Wikipedia

    There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

    HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

    Change the

    private static final long serialVersionUID = 1L;
    

    to any other value like

    private static final long serialVersionUID = 102831973239L;
    

    also you can generate it automatically in eclipse.

    It is because each servlet in a app has a unique id.and tomcat causes problem with two servlets having same id...

    AngularJS : The correct way of binding to a service properties

    To bind any data,which sends service is not a good idea (architecture),but if you need it anymore I suggest you 2 ways to do that

    1) you can get the data not inside you service.You can get data inside your controller/directive and you will not have a problem to bind it anywhere

    2) you can use angularjs events.Whenever you want,you can send a signal(from $rootScope) and catch it wherever you want.You can even send a data on that eventName.

    Maybe this can help you. If you need more with examples,here is the link

    http://www.w3docs.com/snippets/angularjs/bind-value-between-service-and-controller-directive.html

    Print a list in reverse order with range()?

    For those who are interested in the "efficiency" of the options collected so far...

    Jaime RGP's answer led me to restart my computer after timing the somewhat "challenging" solution of Jason literally following my own suggestion (via comment). To spare the curious of you the downtime, I present here my results (worst-first):

    Jason's answer (maybe just an excursion into the power of list comprehension):

    $ python -m timeit "[9-i for i in range(10)]"
    1000000 loops, best of 3: 1.54 usec per loop
    

    martineau's answer (readable if you are familiar with the extended slices syntax):

    $ python -m timeit "range(10)[::-1]"
    1000000 loops, best of 3: 0.743 usec per loop
    

    Michal Šrajer's answer (the accepted one, very readable):

    $ python -m timeit "reversed(range(10))"
    1000000 loops, best of 3: 0.538 usec per loop
    

    bene's answer (the very first, but very sketchy at that time):

    $ python -m timeit "range(9,-1,-1)"
    1000000 loops, best of 3: 0.401 usec per loop
    

    The last option is easy to remember using the range(n-1,-1,-1) notation by Val Neekman.

    No connection could be made because the target machine actively refused it?

    It was a silly issue on my side, I had added a defaultproxy to my web.config in order to intercept traffic in Fiddler, and then forgot to remove it!

    How to get memory usage at runtime using C++?

    in additional to your way
    you could call system ps command and get memory usage from it output.
    or read info from /proc/pid ( see PIOCPSINFO struct )

    Firebase FCM notifications click_action payload

    Update:

    So just to verify, it is not currently possible to set the click_action parameter via the Firebase Console.


    So I've been trying to do this in the Firebase Notifications Console with no luck. Since I can't seem to find anywhere to place the click_action value in the console, what I mainly did to test this out is to add a custom key/value pair in the Notification (Advance Options > Custom Data):

    Key: click_action
    Value: <your_preferred_value>
    

    then tried calling RemoteMessage.getNotification().getClickAction() in onMessageReceived() to see if it was retrieving the correct value, but it always returns null. So next I tried calling RemoteMessage.getData().get(< specified_key >) and was able to retrieve the value I added.

    NOTE: I am not entirely sure if that is okay to be used as a workaround, or if it's against best practice. I would suggest using your own app server but your post is specific to the Firebase Console.

    The way the client app and the notification behaves still depends on how you program it. With that said, I think you can use the above as a workaround, using the value retrieved from the getData(), then having the Notification call this or that. Hope this helps somehow. Cheers! :D

    HTML button opening link in new tab

    You can use the following.

    window.open(
      'https://google.com',
      '_blank' // <- This is what makes it open in a new window.
    );
    

    in HTML

     <button class="btn btn-success" onclick=" window.open('http://google.com','_blank')"> Google</button>
    

    plunkr

    How do I create a nice-looking DMG for Mac OS X using command-line tools?

    Bringing this question up to date by providing this answer.

    appdmg is a simple, easy-to-use, open-source command line program that creates dmg-files from a simple json specification. Take a look at the readme at the official website:

    https://github.com/LinusU/node-appdmg

    Quick example:

    1. Install appdmg

      npm install -g appdmg
      
    2. Write a json file (spec.json)

      {
        "title": "Test Title",
        "background": "background.png",
        "icon-size": 80,
        "contents": [
          { "x": 192, "y": 344, "type": "file", "path": "TestApp.app" },
          { "x": 448, "y": 344, "type": "link", "path": "/Applications" }
        ]
      }
      
    3. Run program

      appdmg spec.json test.dmg
      

    (disclaimer. I'm the creator of appdmg)

    A fast way to delete all rows of a datatable at once

    Just use dt.Clear()

    Also you can set your TableAdapter/DataAdapter to clear before it fills with data.

    Convert URL to File or Blob for FileReader.readAsDataURL

    I know this is an expansion off of @tibor-udvari's answer, but for a nicer copy and paste.

    async function createFile(url, type){
      if (typeof window === 'undefined') return // make sure we are in the browser
      const response = await fetch(url)
      const data = await response.blob()
      const metadata = {
        type: type || 'video/quicktime'
      }
      return new File([data], url, metadata)
    }
    

    Incrementing a variable inside a Bash loop

    minimalist

    counter=0
    ((counter++))
    echo $counter
    

    Flexbox: 4 items per row

    I believe this example is more barebones and easier to understand then @dowomenfart.

    .child {
        display: inline-block;
        margin: 0 1em;
        flex-grow: 1;
        width: calc(25% - 2em);
    }
    

    This accomplishes the same width calculations while cutting straight to the meat. The math is way easier and em is the new standard due to its scalability and mobile-friendliness.

    How to find NSDocumentDirectory in Swift?

    The modern recommendation is to use NSURLs for files and directories instead of NSString based paths:

    enter image description here

    So to get the Document directory for the app as an NSURL:

    func databaseURL() -> NSURL? {
    
        let fileManager = NSFileManager.defaultManager()
    
        let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    
        if let documentDirectory: NSURL = urls.first as? NSURL {
            // This is where the database should be in the documents directory
            let finalDatabaseURL = documentDirectory.URLByAppendingPathComponent("items.db")
    
            if finalDatabaseURL.checkResourceIsReachableAndReturnError(nil) {
                // The file already exists, so just return the URL
                return finalDatabaseURL
            } else {
                // Copy the initial file from the application bundle to the documents directory
                if let bundleURL = NSBundle.mainBundle().URLForResource("items", withExtension: "db") {
                    let success = fileManager.copyItemAtURL(bundleURL, toURL: finalDatabaseURL, error: nil)
                    if success {
                        return finalDatabaseURL
                    } else {
                        println("Couldn't copy file to final location!")
                    }
                } else {
                    println("Couldn't find initial database in the bundle!")
                }
            }
        } else {
            println("Couldn't get documents directory!")
        }
    
        return nil
    }
    

    This has rudimentary error handling, as that sort of depends on what your application will do in such cases. But this uses file URLs and a more modern api to return the database URL, copying the initial version out of the bundle if it does not already exist, or a nil in case of error.

    Oracle: is there a tool to trace queries, like Profiler for sql server?

    You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks.

    See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955

    Go to Instance -> sessions and watch the SQL Tab of each session.

    There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage

    And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache.

    Convert XLS to CSV on command line

    Here is a version that will handle multiple files drag and dropped from windows. Based on the above works by

    Christian Lemer
    plang
    ScottF
    

    Open Notepad, create a file called XlsToCsv.vbs and paste this in:

    '* Usage: Drop .xl* files on me to export each sheet as CSV
    
    '* Global Settings and Variables
    Dim gSkip
    Set args = Wscript.Arguments
    
    For Each sFilename In args
        iErr = ExportExcelFileToCSV(sFilename)
        ' 0 for normal success
        ' 404 for file not found
        ' 10 for file skipped (or user abort if script returns 10)
    Next
    
    WScript.Quit(0)
    
    Function ExportExcelFileToCSV(sFilename)
        '* Settings
        Dim oExcel, oFSO, oExcelFile
        Set oExcel = CreateObject("Excel.Application")
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        iCSV_Format = 6
    
        '* Set Up
        sExtension = oFSO.GetExtensionName(sFilename)
        if sExtension = "" then
            ExportExcelFileToCSV = 404
            Exit Function
        end if
        sTest = Mid(sExtension,1,2) '* first 2 letters of the extension, vb's missing a Like operator
        if not (sTest =  "xl") then
            if (PromptForSkip(sFilename,oExcel)) then
                ExportExcelFileToCSV = 10
                Exit Function
            end if
        End If
        sAbsoluteSource = oFSO.GetAbsolutePathName(sFilename)
        sAbsoluteDestination = Replace(sAbsoluteSource,sExtension,"{sheet}.csv")
    
        '* Do Work
        Set oExcelFile = oExcel.Workbooks.Open(sAbsoluteSource)
        For Each oSheet in oExcelFile.Sheets
            sThisDestination = Replace(sAbsoluteDestination,"{sheet}",oSheet.Name)
            oExcelFile.Sheets(oSheet.Name).Select
            oExcelFile.SaveAs sThisDestination, iCSV_Format
        Next
    
        '* Take Down
        oExcelFile.Close False
        oExcel.Quit
    
        ExportExcelFileToCSV = 0
        Exit Function
    End Function
    
    Function PromptForSkip(sFilename,oExcel)
        if not (VarType(gSkip) = vbEmpty) then
            PromptForSkip = gSkip
            Exit Function
        end if
    
        Dim oFSO
        Set oFSO = CreateObject("Scripting.FileSystemObject")
    
        sPrompt = vbCRLF & _
            "A filename was received that doesn't appear to be an Excel Document." & vbCRLF & _
            "Do you want to skip this and all other unrecognized files?  (Will only prompt this once)" & vbCRLF & _
            "" & vbCRLF & _
            "Yes    - Will skip all further files that don't have a .xl* extension" & vbCRLF & _
            "No     - Will pass the file to excel regardless of extension" & vbCRLF & _
            "Cancel - Abort any further conversions and exit this script" & vbCRLF & _
            "" & vbCRLF & _
            "The unrecognized file was:" & vbCRLF & _
            sFilename & vbCRLF & _
            "" & vbCRLF & _
            "The path returned by the system was:" & vbCRLF & _
            oFSO.GetAbsolutePathName(sFilename) & vbCRLF
    
        sTitle = "Unrecognized File Type Encountered"
    
        sResponse =  MsgBox (sPrompt,vbYesNoCancel,sTitle)
        Select Case sResponse
        Case vbYes
            gSkip = True
        Case vbNo
            gSkip = False
        Case vbCancel
            oExcel.Quit
            WScript.Quit(10)    '*  10 Is the error code I use to indicate there was a user abort (1 because wasn't successful, + 0 because the user chose to exit)
        End Select
    
        PromptForSkip = gSkip
        Exit Function
    End Function
    

    Create a button with rounded border

    Use OutlineButton instead of FlatButton.

    new OutlineButton(
      child: new Text("Button text"),
      onPressed: null,
      shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
    )
    

    Python: TypeError: cannot concatenate 'str' and 'int' objects

    Apart from other answers, one could also use format()

    print("a + b as integers: {}".format(c))

    For example -

    hours = 13
    minutes = 32
    print("Time elapsed - {} hours and {} minutes".format(hours, minutes))
    

    will result in output - Time elapsed - 13 hours and 32 minutes

    Check out docs for more information.

    How do I convert datetime to ISO 8601 in PHP

    Object Oriented

    This is the recommended way.

    $datetime = new DateTime('2010-12-30 23:21:46');
    
    echo $datetime->format(DateTime::ATOM); // Updated ISO8601
    

    Procedural

    For older versions of PHP, or if you are more comfortable with procedural code.

    echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));
    

    Oracle 11g Express Edition for Windows 64bit?

    I just installed the 32bit 11g R2 Express edition version on 64bit windows, created a new database and performed some queries. Seems to work like it should work! :-) I followed the following easy guide!

    How to get past the login page with Wget?

    I wanted a one-liner that didn't download any files; here is an example of piping the cookie output into the next request. I only tested the following on Gentoo, but it should work in most *nix environments:

    wget -q -O /dev/null --save-cookies /dev/stdout --post-data 'u=user&p=pass' 'http://example.com/login' | wget -q -O - --load-cookies /dev/stdin 'http://example.com/private/page'
    

    (This is one line, though it likely wraps on your browser)

    If you want the output saved to a file, change -O - to -O /some/file/name.ext

    Assert that a method was called in a Python unit test

    Yes, I can give you the outline but my Python is a bit rusty and I'm too busy to explain in detail.

    Basically, you need to put a proxy in the method that will call the original, eg:

     class fred(object):
       def blog(self):
         print "We Blog"
    
    
     class methCallLogger(object):
       def __init__(self, meth):
         self.meth = meth
    
       def __call__(self, code=None):
         self.meth()
         # would also log the fact that it invoked the method
    
     #example
     f = fred()
     f.blog = methCallLogger(f.blog)
    

    This StackOverflow answer about callable may help you understand the above.

    In more detail:

    Although the answer was accepted, due to the interesting discussion with Glenn and having a few minutes free, I wanted to enlarge on my answer:

    # helper class defined elsewhere
    class methCallLogger(object):
       def __init__(self, meth):
         self.meth = meth
         self.was_called = False
    
       def __call__(self, code=None):
         self.meth()
         self.was_called = True
    
    #example
    class fred(object):
       def blog(self):
         print "We Blog"
    
    f = fred()
    g = fred()
    f.blog = methCallLogger(f.blog)
    g.blog = methCallLogger(g.blog)
    f.blog()
    assert(f.blog.was_called)
    assert(not g.blog.was_called)
    

    jQuery posting valid json in request body

    An actual JSON request would look like this:

    data: '{"command":"on"}',
    

    Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

    data: JSON.stringify({ "command": "on" }),
    

    To support older browsers that don't have the JSON object, use json2.js which will add it in.


    What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

    pandas DataFrame: replace nan values with average of columns

    Pandas: How to replace NaN (nan) values with the average (mean), median or other statistics of one column

    Say your DataFrame is df and you have one column called nr_items. This is: df['nr_items']

    If you want to replace the NaN values of your column df['nr_items'] with the mean of the column:

    Use method .fillna():

    mean_value=df['nr_items'].mean()
    df['nr_item_ave']=df['nr_items'].fillna(mean_value)

    I have created a new df column called nr_item_ave to store the new column with the NaN values replaced by the mean value of the column.

    You should be careful when using the mean. If you have outliers is more recommendable to use the median

    How to implement swipe gestures for mobile devices?

    NOTE: Greatly inspired by EscapeNetscape's answer, I've made an edit of his script using modern javascript in a comment. I made an answer of this due to user interest and a massive 4h jsfiddle.net downtime. I chose not to edit the original answer since it would change everything...


    Here is a detectSwipe function, working pretty well (used on one of my websites). I'd suggest you read it before you use it. Feel free to review it/edit the answer.

    _x000D_
    _x000D_
    // usage example_x000D_
    detectSwipe('swipeme', (el, dir) => alert(`you swiped on element with id ${el.id} to ${dir} direction`))_x000D_
    _x000D_
    // source code_x000D_
    _x000D_
    // Tune deltaMin according to your needs. Near 0 it will almost_x000D_
    // always trigger, with a big value it can never trigger._x000D_
    function detectSwipe(id, func, deltaMin = 90) {_x000D_
      const swipe_det = {_x000D_
        sX: 0,_x000D_
        sY: 0,_x000D_
        eX: 0,_x000D_
        eY: 0_x000D_
      }_x000D_
      // Directions enumeration_x000D_
      const directions = Object.freeze({_x000D_
        UP: 'up',_x000D_
        DOWN: 'down',_x000D_
        RIGHT: 'right',_x000D_
        LEFT: 'left'_x000D_
      })_x000D_
      let direction = null_x000D_
      const el = document.getElementById(id)_x000D_
      el.addEventListener('touchstart', function(e) {_x000D_
        const t = e.touches[0]_x000D_
        swipe_det.sX = t.screenX_x000D_
        swipe_det.sY = t.screenY_x000D_
      }, false)_x000D_
      el.addEventListener('touchmove', function(e) {_x000D_
        // Prevent default will stop user from scrolling, use with care_x000D_
        // e.preventDefault();_x000D_
        const t = e.touches[0]_x000D_
        swipe_det.eX = t.screenX_x000D_
        swipe_det.eY = t.screenY_x000D_
      }, false)_x000D_
      el.addEventListener('touchend', function(e) {_x000D_
        const deltaX = swipe_det.eX - swipe_det.sX_x000D_
        const deltaY = swipe_det.eY - swipe_det.sY_x000D_
        // Min swipe distance, you could use absolute value rather_x000D_
        // than square. It just felt better for personnal use_x000D_
        if (deltaX ** 2 + deltaY ** 2 < deltaMin ** 2) return_x000D_
        // horizontal_x000D_
        if (deltaY === 0 || Math.abs(deltaX / deltaY) > 1)_x000D_
          direction = deltaX > 0 ? directions.RIGHT : directions.LEFT_x000D_
        else // vertical_x000D_
          direction = deltaY > 0 ? directions.UP : directions.DOWN_x000D_
    _x000D_
        if (direction && typeof func === 'function') func(el, direction)_x000D_
    _x000D_
        direction = null_x000D_
      }, false)_x000D_
    }
    _x000D_
    #swipeme {_x000D_
      width: 100%;_x000D_
      height: 100%;_x000D_
      background-color: orange;_x000D_
      color: black;_x000D_
      text-align: center;_x000D_
      padding-top: 20%;_x000D_
      padding-bottom: 20%;_x000D_
    }
    _x000D_
    <div id='swipeme'>_x000D_
      swipe me_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Why is __dirname not defined in node REPL?

    I was running a script from batch file as SYSTEM user and all variables like process.cwd() , path.resolve() and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.

    Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.

    // this should be the name of currently executed file
    const currentFilename = 'index.js';
    
    function veryHackyGetFolder() {
      try {
        throw new Error();
      } catch(e) {
        const fullMsg = e.stack.toString();
        const beginning = fullMsg.indexOf('file:///') + 8;
        const end = fullMsg.indexOf('\/' + currentFilename);
        const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
        return dir;
      }
    }
    

    Usage

    const dir = veryHackyGetFolder();
    

    Clear variable in python

    var = None "clears the value", setting the value of the variable to "null" like value of "None", however the pointer to the variable remains.

    del var removes the definition for the variable totally.

    In case you want to use the variable later, e.g. set a new value for it, i.e. retain the variable, None would be better.

    When to use extern in C++

    It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.

    For example:

    in file1.cpp:

    int global_int = 1;
    

    in file2.cpp:

    extern int global_int;
    //in some function
    cout << "global_int = " << global_int;
    

    How to define relative paths in Visual Studio Project?

    If I get you right, you need ..\..\src

    Preserve line breaks in angularjs

    Well it depends, if you want to bind datas, there shouldn't be any formatting in it, otherwise you can bind-html and do description.replace(/\\n/g, '<br>') not sure it's what you want though.

    How can I create a link to a local file on a locally-run web page?

    You need to use the file:/// protocol (yes, that's three slashes) if you want to link to local files.

    <a href="file:///C:\Programs\sort.mw">Link 1</a>
    <a href="file:///C:\Videos\lecture.mp4">Link 2</a>
    

    These will never open the file in your local applications automatically. That's for security reasons which I'll cover in the last section. If it opens, it will only ever open in the browser. If your browser can display the file, it will, otherwise it will probably ask you if you want to download the file.

    You cannot cross from http(s) to the file protocol

    Modern versions of many browsers (e.g. Firefox and Chrome) will refuse to cross from the http(s) protocol to the file protocol to prevent malicious behaviour.

    This means a webpage hosted on a website somewhere will never be able to link to files on your hard drive. You'll need to open your webpage locally using the file protocol if you want to do this stuff at all.

    Why does it get stuck without file:///?

    The first part of a URL is the protocol. A protocol is a few letters, then a colon and two slashes. HTTP:// and FTP:// are valid protocols; C:/ isn't and I'm pretty sure it doesn't even properly resemble one.

    C:/ also isn't a valid web address. The browser could assume it's meant to be http://c/ with a blank port specified, but that's going to fail.

    Your browser may not assume it's referring to a local file. It has little reason to make that assumption because webpages generally don't try to link to peoples' local files.

    So if you want to access local files: tell it to use the file protocol.

    Why three slashes?

    Because it's part of the File URI scheme. You have the option of specifying a host after the first two slashes. If you skip specifying a host it will just assume you're referring to a file on your own PC. This means file:///C:/etc is a shortcut for file://localhost/C:/etc.

    These files will still open in your browser and that is good

    Your browser will respond to these files the same way they'd respond to the same file anywhere on the internet. These files will not open in your default file handler (e.g. MS Word or VLC Media Player), and you will not be able to do anything like ask File Explorer to open the file's location.

    This is an extremely good thing for your security.

    Sites in your browser cannot interact with your operating system very well. If a good site could tell your machine to open lecture.mp4 in VLC.exe, a malicious site could tell it to open virus.bat in CMD.exe. Or it could just tell your machine to run a few Uninstall.exe files or open File Explorer a million times.

    This may not be convenient for you, but HTML and browser security weren't really designed for what you're doing. If you want to be able to open lecture.mp4 in VLC.exe consider writing a desktop application instead.

    What is a lambda expression in C++11?

    One of the best explanation of lambda expression is given from author of C++ Bjarne Stroustrup in his book ***The C++ Programming Language*** chapter 11 (ISBN-13: 978-0321563842):

    What is a lambda expression?

    A lambda expression, sometimes also referred to as a lambda function or (strictly speaking incorrectly, but colloquially) as a lambda, is a simplified notation for defining and using an anonymous function object. Instead of defining a named class with an operator(), later making an object of that class, and finally invoking it, we can use a shorthand.

    When would I use one?

    This is particularly useful when we want to pass an operation as an argument to an algorithm. In the context of graphical user interfaces (and elsewhere), such operations are often referred to as callbacks.

    What class of problem do they solve that wasn't possible prior to their introduction?

    Here i guess every action done with lambda expression can be solved without them, but with much more code and much bigger complexity. Lambda expression this is the way of optimization for your code and a way of making it more attractive. As sad by Stroustup :

    effective ways of optimizing

    Some examples

    via lambda expression

    void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0
    {
        for_each(begin(v),end(v),
            [&os,m](int x) { 
               if (x%m==0) os << x << '\n';
             });
    }
    

    or via function

    class Modulo_print {
             ostream& os; // members to hold the capture list int m;
         public:
             Modulo_print(ostream& s, int mm) :os(s), m(mm) {} 
             void operator()(int x) const
               { 
                 if (x%m==0) os << x << '\n'; 
               }
    };
    

    or even

    void print_modulo(const vector<int>& v, ostream& os, int m) 
         // output v[i] to os if v[i]%m==0
    {
        class Modulo_print {
            ostream& os; // members to hold the capture list
            int m; 
            public:
               Modulo_print (ostream& s, int mm) :os(s), m(mm) {}
               void operator()(int x) const
               { 
                   if (x%m==0) os << x << '\n';
               }
         };
         for_each(begin(v),end(v),Modulo_print{os,m}); 
    }
    

    if u need u can name lambda expression like below:

    void print_modulo(const vector<int>& v, ostream& os, int m)
        // output v[i] to os if v[i]%m==0
    {
          auto Modulo_print = [&os,m] (int x) { if (x%m==0) os << x << '\n'; };
          for_each(begin(v),end(v),Modulo_print);
     }
    

    Or assume another simple sample

    void TestFunctions::simpleLambda() {
        bool sensitive = true;
        std::vector<int> v = std::vector<int>({1,33,3,4,5,6,7});
    
        sort(v.begin(),v.end(),
             [sensitive](int x, int y) {
                 printf("\n%i\n",  x < y);
                 return sensitive ? x < y : abs(x) < abs(y);
             });
    
    
        printf("sorted");
        for_each(v.begin(), v.end(),
                 [](int x) {
                     printf("x - %i;", x);
                 }
                 );
    }
    

    will generate next

    0

    1

    0

    1

    0

    1

    0

    1

    0

    1

    0 sortedx - 1;x - 3;x - 4;x - 5;x - 6;x - 7;x - 33;

    [] - this is capture list or lambda introducer: if lambdas require no access to their local environment we can use it.

    Quote from book:

    The first character of a lambda expression is always [. A lambda introducer can take various forms:

    []: an empty capture list. This implies that no local names from the surrounding context can be used in the lambda body. For such lambda expressions, data is obtained from arguments or from nonlocal variables.

    [&]: implicitly capture by reference. All local names can be used. All local variables are accessed by reference.

    [=]: implicitly capture by value. All local names can be used. All names refer to copies of the local variables taken at the point of call of the lambda expression.

    [capture-list]: explicit capture; the capture-list is the list of names of local variables to be captured (i.e., stored in the object) by reference or by value. Variables with names preceded by & are captured by reference. Other variables are captured by value. A capture list can also contain this and names followed by ... as elements.

    [&, capture-list]: implicitly capture by reference all local variables with names not men- tioned in the list. The capture list can contain this. Listed names cannot be preceded by &. Variables named in the capture list are captured by value.

    [=, capture-list]: implicitly capture by value all local variables with names not mentioned in the list. The capture list cannot contain this. The listed names must be preceded by &. Vari- ables named in the capture list are captured by reference.

    Note that a local name preceded by & is always captured by reference and a local name not pre- ceded by & is always captured by value. Only capture by reference allows modification of variables in the calling environment.

    Additional

    Lambda expression format

    enter image description here

    Additional references:

    What is the benefit of zerofill in MySQL?

    One example in order to understand, where the usage of ZEROFILL might be interesting:

    In Germany, we have 5 digit zipcodes. However, those Codes may start with a Zero, so 80337 is a valid zipcode for munic, 01067 is a zipcode of Berlin.

    As you see, any German citizen expects the zipcodes to be displayed as a 5 digit code, so 1067 looks strange.

    In order to store those data, you could use a VARCHAR(5) or INT(5) ZEROFILL whereas the zerofilled integer has two big advantages:

    1. Lot lesser storage space on hard disk
    2. If you insert 1067, you still get 01067 back

    Maybe this example helps understanding the use of ZEROFILL.

    Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

    To enable GZIP compression, you need to modify the configuration of the embedded Tomcat instance. To do so, you declare a EmbeddedServletContainerCustomizer bean in your Java configuration and then register a TomcatConnectorCustomizer with it.

    For example:

    @Bean
    public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
                ((TomcatEmbeddedServletContainerFactory) factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
                    @Override
                    public void customize(Connector connector) {
                        AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
                        httpProtocol.setCompression("on");
                        httpProtocol.setCompressionMinSize(64);
                    }
                });
            }
        };
    }
    

    See the Tomcat documentation for more details on the various compression configuration options that are available.

    You say that you want to selectively enable compression. Depending on your selection criteria, then the above approach may be sufficient. It enables you to control compression by the request's user-agent, the response's size, and the response's mime type.

    If this doesn't meet your needs then I believe you will have to perform the compression in your controller and return a byte[] response with a gzip content-encoding header.

    Advantages of std::for_each over for loop

    Like many of the algorithm functions, an initial reaction is to think it's more unreadable to use foreach than a loop. It's been a topic of many flame wars.

    Once you get used to the idiom you may find it useful. One obvious advantage is that it forces the coder to separate the inner contents of the loop from the actual iteration functionality. (OK, I think it's an advantage. Other's say you're just chopping up the code with no real benifit).

    One other advantage is that when I see foreach, I know that either every item will be processed or an exception will be thrown.

    A for loop allows several options for terminating the loop. You can let the loop run its full course, or you can use the break keyword to explicitly jump out of the loop, or use the return keyword to exit the entire function mid-loop. In contrast, foreach does not allow these options, and this makes it more readable. You can just glance at the function name and you know the full nature of the iteration.

    Here's an example of a confusing for loop:

    for(std::vector<widget>::iterator i = v.begin(); i != v.end(); ++i)
    {
       /////////////////////////////////////////////////////////////////////
       // Imagine a page of code here by programmers who don't refactor
       ///////////////////////////////////////////////////////////////////////
       if(widget->Cost < calculatedAmountSofar)
       {
            break;
       }
       ////////////////////////////////////////////////////////////////////////
       // And then some more code added by a stressed out juniour developer
       // *#&$*)#$&#(#)$#(*$&#(&*^$#(*$#)($*#(&$^#($*&#)$(#&*$&#*$#*)$(#*
       /////////////////////////////////////////////////////////////////////////
       for(std::vector<widgetPart>::iterator ip = widget.GetParts().begin(); ip != widget.GetParts().end(); ++ip)
       {
          if(ip->IsBroken())
          {
             return false;
          }
       }
    }