Programs & Examples On #Vtune

This is a tag for Intel VTune Amplifier XE profiling tool questions.

What's the best free C++ profiler for Windows?

You can use EmbeddedProfiler, it's free for both Linux and Windwos.

The profiler is intrusive (by functionality) but it doens't require any code modifications. Just add a specific compiler flag (-finstrument-functios for gcc/MinGW or /GH for MSVC) and link the profiler's library. It can provide you a full call tree or just a funciton list. It has it's own analyzer GUI.

Rounding to 2 decimal places in SQL

Try this...

SELECT TO_CHAR(column_name,'99G999D99MI')
as format_column
FROM DUAL;

Modify tick label text

This also works in matplotlib 3:

x1 = [0,1,2,3]
squad = ['Fultz','Embiid','Dario','Simmons']

plt.xticks(x1, squad, rotation=45)

Reading a registry key in C#

If you want it casted to a specific type you can use this method. Most non primitive types won't by default support direct casting so you will have to handle those accordingly.

  public T GetValue<T>(string registryKeyPath, string value, T defaultValue = default(T))
  {
    T retVal = default(T);

      retVal = (T)Registry.GetValue(registryKeyPath, value, defaultValue);

      return retVal;
  }

How to change bower's default components folder?

Something worth mentioning...

As noted above by other contributors, using a .bowerrc file with the JSON

{ "directory": "some/path" }

is necessary -- HOWEVER, you may run into an issue on Windows while creating that file. If Windows gives you a message imploring you to add a "file name", simply use a text editor / IDE such as Notepad++.

Add the JSON to an unnamed file, save it as .bowerrc -- you're good to go!

Probably an easy assumption, but I hope this save others the unnecessary headache :)

Is it possible to set the stacking order of pseudo-elements below their parent element?

I fixed it very simple:

.parent {
  position: relative;
  z-index: 1;
}

.child {
  position: absolute;
  z-index: -1;
}

What this does is stack the parent at z-index: 1, which gives the child room to 'end up' at z-index: 0 since other dom elements 'exist' on z-index: 0. If we don't give the parent an z-index of 1 the child will end up below the other dom elements and thus will not be visible.

This also works for pseudo elements like :after

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

    public int getMin(int[] values){
        int ret = values[0];
        for(int i = 1; i < values.length; i++)
            ret = Math.min(ret,values[i]);
        return ret;
    }

Determine if a String is an Integer in Java

public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}

How can I listen for a click-and-hold in jQuery?

I wrote some code to make it easy

_x000D_
_x000D_
//Add custom event listener_x000D_
$(':root').on('mousedown', '*', function() {_x000D_
    var el = $(this),_x000D_
        events = $._data(this, 'events');_x000D_
    if (events && events.clickHold) {_x000D_
        el.data(_x000D_
            'clickHoldTimer',_x000D_
            setTimeout(_x000D_
                function() {_x000D_
                    el.trigger('clickHold')_x000D_
                },_x000D_
                el.data('clickHoldTimeout')_x000D_
            )_x000D_
        );_x000D_
    }_x000D_
}).on('mouseup mouseleave mousemove', '*', function() {_x000D_
    clearTimeout($(this).data('clickHoldTimer'));_x000D_
});_x000D_
_x000D_
//Attach it to the element_x000D_
$('#HoldListener').data('clickHoldTimeout', 2000); //Time to hold_x000D_
$('#HoldListener').on('clickHold', function() {_x000D_
    console.log('Worked!');_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
<img src="http://lorempixel.com/400/200/" id="HoldListener">
_x000D_
_x000D_
_x000D_

See on JSFiddle

Now you need just to set the time of holding and add clickHold event on your element

Unable to execute dex: Multiple dex files define

As others mentioned, this occurs when you have multiple copies of the same class in your build path, or elsewhere in your setup.

I had added android-support-v4.jar to my libs/ folder, and somehow eclipse added a second copy to bin/classes/android-support-v4.jar.

You can test for this with

grep -r YourOffendingClassName YourApp | grep jar

Deleting the extra copy in bin/classes solved the problem - unsure why Eclipse made a copy there.

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

AJAX POST and Plus Sign ( + ) -- How to Encode?

To make it more interesting and to hopefully enable less hair pulling for someone else. Using python, built dictionary for a device which we can use curl to configure.

Problem: {"timezone":"+5"} //throws an error " 5"

Solution: {"timezone":"%2B"+"5"} //Works

So, in a nutshell:

var = {"timezone":"%2B"+"5"}
json = JSONEncoder().encode(var)
subprocess.call(["curl",ipaddress,"-XPUT","-d","data="+json])

Thanks to this post!

How can I change the width and height of slides on Slick Carousel?

I found good solution myself. Since slick slider is still used nowadays i'll post my approach.

@RuivBoas answer is partly correct. - It can change the width of the slide but it can break the slider. Why?

Slick slider may exceed browser width. Actual container width is set to value that can accomodate all it's slides.

The best solution for setting slide width is to use width of the actual browser window. It works best with responsive design.

For example 2 slides with absorbed width

CSS

.slick-slide {
    width: 50vw;
    // for absorbing width from @Ken Wheeler answer
    box-sizing: border-box;
}

JS

$(document).on('ready', function () {
            $("#container").slick({
                variableWidth: true,
                slidesToShow: 2,
                slidesToScroll: 2
            });
        });

HTML markup

<div id="container">
    <div><img/></div>
    <div><img/></div>
    <div><img/></div>
</div>

Android SQLite Example

The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.

Javascript Click on Element by Class

class of my button is "input-addon btn btn-default fileinput-exists"

below code helped me

document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();

but I want to click second button, I have two buttons in my screen so I used querySelectorAll

var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
                elem[1].click();

here elem[1] is the second button object that I want to click.

How can I select records ONLY from yesterday?

This comment is for readers who have found this entry but are using mysql instead of oracle! on mysql you can do the following: Today

SELECT  * 
FROM 
WHERE date(tran_date) = CURRENT_DATE()

Yesterday

SELECT  * 
FROM yourtable 
WHERE date(tran_date) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)

Android AudioRecord example

Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues

Real-world examples of recursion

I just wrote a recursive function to figure out if a class needed to be serialized using a DataContractSerializer. The big issue came with templates/generics where a class could contain other types that needed to be datacontract serialized... so it's go through each type, if it's not datacontractserializable check it's types.

Recommended way to get hostname in Java

The most portable way to get the hostname of the current computer in Java is as follows:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class getHostName {

    public static void main(String[] args) throws UnknownHostException {
        InetAddress iAddress = InetAddress.getLocalHost();
        String hostName = iAddress.getHostName();
        //To get  the Canonical host name
        String canonicalHostName = iAddress.getCanonicalHostName();

        System.out.println("HostName:" + hostName);
        System.out.println("Canonical Host Name:" + canonicalHostName);
    }
}

from jquery $.ajax to angular $http

you can use $.param to assign data :

 $http({
  url: "http://example.appspot.com/rest/app",
  method: "POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $scope.data = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;
 });

look at this : AngularJS + ASP.NET Web API Cross-Domain Issue

What is the argument for printf that formats a long?

It depends, if you are referring to unsigned long the formatting character is "%lu". If you're referring to signed long the formatting character is "%ld".

How to develop Android app completely using python?

You could try BeeWare - as described on their website:

Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.

Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.

Here's the Tutorial for Android Apps.

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

How to redirect to previous page in Ruby On Rails?

In your edit action, store the requesting url in the session hash, which is available across multiple requests:

session[:return_to] ||= request.referer

Then redirect to it in your update action, after a successful save:

redirect_to session.delete(:return_to)

How to use a typescript enum value in an Angular2 ngSwitch statement

You can create a reference to the enum in your component class (I just changed the initial character to be lower-case) and then use that reference from the template (plunker):

import {Component} from 'angular2/core';

enum CellType {Text, Placeholder}
class Cell {
  constructor(public text: string, public type: CellType) {}
}
@Component({
  selector: 'my-app',
  template: `
    <div [ngSwitch]="cell.type">
      <div *ngSwitchCase="cellType.Text">
        {{cell.text}}
      </div>
      <div *ngSwitchCase="cellType.Placeholder">
        Placeholder
      </div>
    </div>
    <button (click)="setType(cellType.Text)">Text</button>
    <button (click)="setType(cellType.Placeholder)">Placeholder</button>
  `,
})
export default class AppComponent {

  // Store a reference to the enum
  cellType = CellType;
  public cell: Cell;

  constructor() {
    this.cell = new Cell("Hello", CellType.Text)
  }

  setType(type: CellType) {
    this.cell.type = type;
  }
}

Store query result in a variable using in PL/pgSQL

The usual pattern is EXISTS(subselect):

BEGIN
  IF EXISTS(SELECT name
              FROM test_table t
             WHERE t.id = x
               AND t.name = 'test')
  THEN
     ---
  ELSE
     ---
  END IF;

This pattern is used in PL/SQL, PL/pgSQL, SQL/PSM, ...

AngularJS: How can I pass variables between controllers?

Ah, have a bit of this new stuff as another alternative. It's localstorage, and works where angular works. You're welcome. (But really, thank the guy)

https://github.com/gsklee/ngStorage

Define your defaults:

$scope.$storage = $localStorage.$default({
    prop1: 'First',
    prop2: 'Second'
});

Access the values:

$scope.prop1 = $localStorage.prop1;
$scope.prop2 = $localStorage.prop2;

Store the values

$localStorage.prop1 = $scope.prop1;
$localStorage.prop2 = $scope.prop2;

Remember to inject ngStorage in your app and $localStorage in your controller.

What is the meaning of "this" in Java?

The following is a copy & paste from here, but explains very well all different uses of the this keyword:

Definition: Java’s this keyword is used to refer the current instance of the method on which it is used.

Following are the ways to use this:

  1. To specifically denote that the instance variable is used instead of static or local variable. That is,

    private String javaFAQ;
    void methodName(String javaFAQ) {
        this.javaFAQ = javaFAQ;
    }
    

    Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the this denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.

  2. This is used to refer the constructors

     public JavaQuestions(String javapapers) {
         this(javapapers, true);
     }
    

    This invokes the constructor of the same java class which has two parameters.

  3. This is used to pass the current java instance as parameter

    obj.itIsMe(this);
    
  4. Similar to the above this can also be used to return the current instance

    CurrentClassName startMethod() {
         return this;
    }
    

    Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.

  5. This can be used to get the handle of the current class

    Class className = this.getClass(); // this methodology is preferable in java
    

    Though this can be done by

    Class className = ABC.class; // here ABC refers to the class name and you need to know that!
    

As always, this is associated with its instance and this will not work in static methods.

Bootstrap 4 - Glyphicons migration?

The glyphicons.less file from Bootstrap 3 is available on GitHub. https://github.com/twbs/bootstrap/blob/master/less/glyphicons.less

It needs these variables:

@icon-font-path:          "../fonts/";
@icon-font-name:          "glyphicons-halflings-regular";
@icon-font-svg-id:        "glyphicons_halflingsregular";

Then you can convert the .less file to a .css file which you can use directly. You can do this online on lesscss.org/less-preview/. Here I've done it for you, save it as glyphicons.css and include it in your HTML files.

<link href="/Content/glyphicons.css" rel="stylesheet" />

You also need the Glyphicon fonts which is in the Bootstrap 3 package, place them in a /fonts/ directory.

Now you can just keep on using Glyphicons with Bootstrap 4 as usual.

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

rand() between 0 and 1

This is the right way:

double randd() {
  return (double)rand() / ((double)RAND_MAX + 1);
}

or

double randd() {
  return (double)rand() / (RAND_MAX + 1.0);
}

What are the First and Second Level caches in (N)Hibernate?

Here some basic explanation of hibernate cache...

First level cache is associated with “session” object. The scope of cache objects is of session. Once session is closed, cached objects are gone forever. First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

Second level cache is apart from first level cache which is available to be used globally in session factory scope. second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory. It also means that once session factory is closed, all cache associated with it die and cache manager also closed down. Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session). If cached copy of entity is present in first level cache, it is returned as result of load method. If there is no cached entity in first level cache, then second level cache is looked up for cached entity. If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again. If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

Is there a way to get a list of all current temporary tables in SQL Server?

Is this what you are after?

select * from tempdb..sysobjects
--for sql-server 2000 and later versions

select * from tempdb.sys.objects
--for sql-server 2005 and later versions

How to convert string to boolean php

This method was posted by @lauthiamkok in the comments. I'm posting it here as an answer to call more attention to it.

Depending on your needs, you should consider using filter_var() with the FILTER_VALIDATE_BOOLEAN flag.

filter_var(    true, FILTER_VALIDATE_BOOLEAN); // true
filter_var(    'true', FILTER_VALIDATE_BOOLEAN); // true
filter_var(         1, FILTER_VALIDATE_BOOLEAN); // true
filter_var(       '1', FILTER_VALIDATE_BOOLEAN); // true
filter_var(      'on', FILTER_VALIDATE_BOOLEAN); // true
filter_var(     'yes', FILTER_VALIDATE_BOOLEAN); // true

filter_var(   false, FILTER_VALIDATE_BOOLEAN); // false
filter_var(   'false', FILTER_VALIDATE_BOOLEAN); // false
filter_var(         0, FILTER_VALIDATE_BOOLEAN); // false
filter_var(       '0', FILTER_VALIDATE_BOOLEAN); // false
filter_var(     'off', FILTER_VALIDATE_BOOLEAN); // false
filter_var(      'no', FILTER_VALIDATE_BOOLEAN); // false
filter_var('asdfasdf', FILTER_VALIDATE_BOOLEAN); // false
filter_var(        '', FILTER_VALIDATE_BOOLEAN); // false
filter_var(      null, FILTER_VALIDATE_BOOLEAN); // false

HTML embedded PDF iframe

It's downloaded probably because there is not Adobe Reader plug-in installed. In this case, IE (it doesn't matter which version) doesn't know how to render it, and it'll simply download the file (Chrome, for example, has its own embedded PDF renderer).

That said. <iframe> is not best way to display a PDF (do not forget compatibility with mobile browsers, for example Safari). Some browsers will always open that file inside an external application (or in another browser window). Best and most compatible way I found is a little bit tricky but works on all browsers I tried (even pretty outdated):

Keep your <iframe> but do not display a PDF inside it, it'll be filled with an HTML page that consists of an <object> tag. Create an HTML wrapping page for your PDF, it should look like this:

<html>
<body>
    <object data="your_url_to_pdf" type="application/pdf">
        <embed src="your_url_to_pdf" type="application/pdf" />
    </object>
</body>
</html>

Of course, you still need the appropriate plug-in installed in the browser. Also, look at this post if you need to support Safari on mobile devices.

1st. Why nesting <embed> inside <object>? You'll find the answer here on SO. Instead of a nested <embed> tag, you may (should!) provide a custom message for your users (or a built-in viewer, see next paragraph). Nowadays, <object> can be used without worries, and <embed> is useless.

2nd. Why an HTML page? So you can provide a fallback if PDF viewer isn't supported. Internal viewer, plain HTML error messages/options, and so on...

It's tricky to check PDF support so that you may provide an alternate viewer for your customers, take a look at PDF.JS project; it's pretty good but rendering quality - for desktop browsers - isn't as good as a native PDF renderer (I didn't see any difference in mobile browsers because of screen size, I suppose).

AND/OR in Python?

For the updated question, you can replace what you want with something like:

someList = filter(lambda x: x not in ("a", "á", "à", "ã", "â"), someList)

filter evaluates every element of the list by passing it to the lambda provided. In this lambda we check if the element is not one of the characters provided, because these should stay in the list.

Alternatively, if the items in someList should be unique, you can make someList a set and do something like this:

someList = list(set(someList)-set(("a", "á", "à", "ã", "â")))

This essentially takes the difference between the sets, which does what you want, but also makes sure every element occurs only once, which is different from a list. Note you could store someList as a set from the beginning in this case, it will optimize things a bit.

Can I multiply strings in Java to repeat sequences?

The simplest way is:

String someNum = "123000";
System.out.println(someNum);

Drawing rotated text on a HTML5 canvas

Posting this in an effort to help others with similar problems. I solved this issue with a five step approach -- save the context, translate the context, rotate the context, draw the text, then restore the context to its saved state.

I think of translations and transforms to the context as manipulating the coordinate grid overlaid on the canvas. By default the origin (0,0) starts in the upper left hand corner of the canvas. X increases from left to right, Y increases from top to bottom. If you make an "L" w/ your index finger and thumb on your left hand and hold it out in front of you with your thumb down, your thumb would point in the direction of increasing Y and your index finger would point in the direction of increasing X. I know it's elementary, but I find it helpful when thinking about translations and rotations. Here's why:

When you translate the context, you move the origin of the coordinate grid to a new location on the canvas. When you rotate the context, think of rotating the "L" you made with your left hand in a clockwise direction the amount indicated by the angle you specify in radians about the origin. When you strokeText or fillText, specify your coordinates in relation to the newly aligned axes. To orient your text so it's readable from bottom to top, you would translate to a position below where you want to start your labels, rotate by -90 degrees and fill or strokeText, offsetting each label along the rotated x axis. Something like this should work:

 context.save();
 context.translate(newx, newy);
 context.rotate(-Math.PI/2);
 context.textAlign = "center";
 context.fillText("Your Label Here", labelXposition, 0);
 context.restore();

.restore() resets the context back to the state it had when you called .save() -- handy for returning things back to "normal".


How to get browser width using JavaScript code?

From W3schools and its cross browser back to the dark ages of IE!

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";

alert("Browser inner window width: " + w + ", height: " + h + ".");

</script>

</body>
</html>

How to convert a date to milliseconds

The SimpleDateFormat class allows you to parse a String into a java.util.Date object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime().

The full example:

String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();

Note that this gives you a long and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat class has tons on information on how to set it up to parse different formats.

MySQL Trigger: Delete From Table AFTER DELETE

create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;

How to make a TextBox accept only alphabetic characters?

works for me, even though not the simplest one.

private void Alpha_Click(object sender, EventArgs e)
        {
            int count = 0;
            foreach (char letter in inputTXT.Text)
            {
                if (Char.IsLetter(letter))
                {
                    count++;
                }
                else
                {
                    count = 0;
                }
            }
            if (count != inputTXT.Text.Length)
            {
                errorBox.Text = "The input text must contain only alphabetic characters";
            }
            else
            {
                errorBox.Text = "";
            }
        }

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

How can I select random files from a directory in bash?

If you have more files in your folder, you can use the below piped command I found in unix stackexchange.

find /some/dir/ -type f -print0 | xargs -0 shuf -e -n 8 -z | xargs -0 cp -vt /target/dir/

Here I wanted to copy the files, but if you want to move files or do something else, just change the last command where I have used cp.

recyclerview No adapter attached; skipping layout

In your RecyclerView adapter class, for example MyRecyclerViewAdapter, make a constructor with the following params.

MyRecyclerViewAdapter(Context context, List<String> data) {
    this.mInflater = LayoutInflater.from(context); // <-- This is the line most people include me miss
    this.mData = data;
}

mData is the data that you'll pass to the adapter. It is optional if you have no data to be passed. mInflater is the LayoutInflater object that you have created and you use in the OnCreateViewHolder function of the adapter.

After this, you attach the adapter in the MainActivity or wherever you want to on the main/UI thread properly like

MyRecyclerViewAdapter recyclerAdapter;
OurDataStuff mData;

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

        //Like this:

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerAdapter = new RecyclerAdapter(this, mData); //this, is the context. mData is the data you want to pass if you have any
        recyclerView.setAdapter(recyclerAdapter);
    }
   ....

How to crop a CvMat in OpenCV?

I know this question is already solved.. but there is a very easy way to crop. you can just do it in one line-

Mat cropedImage = fullImage(Rect(X,Y,Width,Height));

Make scrollbars only visible when a Div is hovered over?

Answer by @Calvin Froedge is the shortest answer but have an issue also mentioned by @kizu. Due to inconsistent width of the div the div will flick on hover. To solve this issue add minus margin to the right on hover

#div { 
     overflow:hidden;
     height:whatever px; 
}
#div:hover { 
     overflow-y:scroll; 
     margin-right: -15px; // adjust according to scrollbar width  
}

How to validate white spaces/empty spaces? [Angular 2]

This is a slightly different answer to one below that worked for me:

_x000D_
_x000D_
public static validate(control: FormControl): { whitespace: boolean } {_x000D_
    const valueNoWhiteSpace = control.value.trim();_x000D_
    const isValid = valueNoWhiteSpace === control.value;_x000D_
    return isValid ? null : { whitespace: true };_x000D_
}
_x000D_
_x000D_
_x000D_

Page scroll when soft keyboard popped up

well the simplest answer i tried is just remove your code which makes the activity go full screen .I had a code like this which was responsible for making my activity go fullscreen :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

i just removed my code and it works completely fine although if you want to achieve this with your fullscreen on then you'll have to try some other methods

Embed Youtube video inside an Android app

The video quality depends upon the Connection speed using API

alternatively for other than API means without YouTube app you can follow this link

Printing variables in Python 3.4

one can print values using the format method in python. This small example will help take input of two numbers a and b. Print a+b in first line and a-b in second line

print('{:d}\n{:d}'.format(a+b,a-b))

Similarly in the answer we can do

print ("{0}. {1} appears {2} times.".format(22, 'c', 9999))

The python method format() for string is used to specify a string format. So {0},{1},{2} are like array indexes called as positional parameters. Therefore {0} is assigned first value written in format (a+b), {1} is assigned the second value (a-b) and so on. We can also use keyword instead of positional parameter like for example

print("Hi! my name is {name}".format(name="rashi"))

Therefore name here is the keyword and its value is Rashi Hope it helps :)

What is HEAD in Git?

Git is all about commits.
And Head points to the commit which you currently checked out.

$ git cat-file -t HEAD
commit

Whenever you checkout a branch, the HEAD points to the latest commit on that branch. Contents of HEAD can checked as below (for master branch):

$ cat .git/refs/heads/master
  b089141cc8a7d89d606b2f7c15bfdc48640a8e25

select2 onchange event only works once

This is what I am using:

$("#search_code").live('change', function(){
  alert(this.value)
});

For latest jQuery users, this one should work:

$(document.body).on("change","#search_code",function(){
 alert(this.value);
});

How can I check for NaN values?

Here are three ways where you can test a variable is "NaN" or not.

import pandas as pd
import numpy as np
import math

#For single variable all three libraries return single boolean
x1 = float("nan")

print(f"It's pd.isna  : {pd.isna(x1)}")
print(f"It's np.isnan  : {np.isnan(x1)}")
print(f"It's math.isnan : {math.isnan(x1)}")

Output

It's pd.isna  : True
It's np.isnan  : True
It's math.isnan  : True

When to use the different log levels

Btw, I am a great fan of capturing everything and filtering the information later.

What would happen if you were capturing at Warning level and want some Debug info related to the warning, but were unable to recreate the warning?

Capture everything and filter later!

This holds true even for embedded software unless you find that your processor can't keep up, in which case you might want to re-design your tracing to make it more efficient, or the tracing is interfering with timing (you might consider debugging on a more powerful processor, but that opens up a whole nother can of worms).

Capture everything and filter later!!

(btw, capture everything is also good because it lets you develop tools to do more than just show debug trace (I draw Message Sequence Charts from mine, and histograms of memory usage. It also gives you a basis for comparison if something goes wrong in future (keep all logs, whether pass or fail, and be sure to include build number in the log file)).

How to get the fields in an Object via reflection?

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
    field.setAccessible(true); // You might want to set modifier to public first.
    Object value = field.get(someObject); 
    if (value != null) {
        System.out.println(field.getName() + "=" + value);
    }
}

To learn more about reflection, check the Sun tutorial on the subject.


That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {
    if (Modifier.isPublic(method.getModifiers())
        && method.getParameterTypes().length == 0
        && method.getReturnType() != void.class
        && (method.getName().startsWith("get") || method.getName().startsWith("is"))
    ) {
        Object value = method.invoke(someObject);
        if (value != null) {
            System.out.println(method.getName() + "=" + value);
        }
    }
}

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.

Outlets cannot be connected to repeating content iOS

Create a table view cell subclass and set it as the class of the prototype. Add the outlets to that class and connect them. Now when you configure the cell you can access the outlets.

Create a OpenSSL certificate on Windows

You can certainly use putty (puttygen.exe) to do that.

Or you can get Cygwin to use the utilities you just described.

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

Span inside anchor or anchor inside span or doesn't matter?

3 - It doesn't matter.

BUT, I tend to only use a <span> inside an <a> if it's only for a part of the contents of the tag i.e.

<a href="#">some <span class="red">text</span></a>

Rather than:

<a href="#"><span class="red">some text</span></a>

Which should obviously just be:

<a href="#" class="red">some text</a>

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

The problem is in new PHP Version in macOS Sierra

Please add

stream_context_set_option($ctx, 'ssl', 'verify_peer', false);

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

SQL Server add auto increment primary key to existing table

Here is an idea you can try. Original table - no identity column table1 create a new table - call table2 along with identity column. copy the data from table1 to table2 - the identity column is populated automatically with auto incremented numbers.

rename the original table - table1 to table3 rename the new table - table2 to table1 (original table) Now you have the table1 with identity column included and populated for the existing data. after making sure there is no issue and working properly, drop the table3 when no longer needed.

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now

"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "

Unable to establish SSL connection, how do I fix my SSL cert?

I meet this same question. The port 443 wasn't open in Centos.

Check the 443 port with the following command:

sudo lsof -i tcp:443

In the first line of /etc/httpd/conf.d/ssl.conf add this two lines:

LoadModule ssl_module modules/mod_ssl.so
Listen 443

symfony2 : failed to write cache directory

For a GOOD and definite solution see the Setting up Permissions section in Installing and Configuring Symfony section :

Setting up Permissions

One common issue when installing Symfony is that the app/cache and app/logs directories must be writable both by the web server and the command line user. On a UNIX system, if your web server user is different from your command line user, you can try one of the following solutions.

  1. Use the same user for the CLI and the web server

In development environments, it is a common practice to use the same UNIX user for the CLI and the web server because it avoids any of these permissions issues when setting up new projects. This can be done by editing your web server configuration (e.g. commonly httpd.conf or apache2.conf for Apache) and setting its user to be the same as your CLI user (e.g. for Apache, update the User and Group values).

  1. Using ACL on a system that supports chmod +a

Many systems allow you to use the chmod +a command. Try this first, and if you get an error - try the next method. This uses a command to try to determine your web server user and set it as HTTPDUSER:

$ rm -rf app/cache/*
$ rm -rf app/logs/*

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo chmod +a "$HTTPDUSER allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
$ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
  1. Using ACL on a system that does not support chmod +a

Some systems don't support chmod +a, but do support another utility called setfacl. You may need to enable ACL support on your partition and install setfacl before using it (as is the case with Ubuntu). This uses a command to try to determine your web server user and set it as HTTPDUSER:

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs
$ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs

For Symfony 3 it would be:

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs
$ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs

If this doesn't work, try adding -n option.

  1. Without using ACL

If none of the previous methods work for you, change the umask so that the cache and log directories will be group-writable or world-writable (depending if the web server user and the command line user are in the same group or not). To achieve this, put the following line at the beginning of the app/console, web/app.php and web/app_dev.php files:

umask(0002); // This will let the permissions be 0775

// or

umask(0000); // This will let the permissions be 0777

Note that using the ACL is recommended when you have access to them on your server because changing the umask is not thread-safe.

http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup

source : Failed to write cache file "/var/www/myapp/app/cache/dev/classes.php" when clearing the cache

Pandas - replacing column values

You can also try using apply with get method of dictionary, seems to be little faster than replace:

data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Testing with timeit:

%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)

Result:

The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop

Using apply:

%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Result:

The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop

Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

A 'for' loop to iterate over an enum in Java

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type:

 for (Direction d : Direction.values()) {
     System.out.println(d);
 }

How to create Custom Ratings bar in Android

For SVG RatingBar I used RatingBar custom Vector Drawables superimposing and the answer of erdomester here. This solution traverses all drawables inside SvgRatingBar view of your layout, so in RecyclerView it has an overhead.

SvgRatingBar.java:

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.VectorDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;

import androidx.appcompat.graphics.drawable.DrawableWrapper;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;

import com.example.R; // Your R.java file for R.attr.ratingBarStyle.

public class SvgRatingBar extends androidx.appcompat.widget.AppCompatRatingBar {

    private Bitmap sampleTile;

    public SvgRatingBar(Context context) {
        this(context, null);
    }

    public SvgRatingBar(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.ratingBarStyle);
    }

    public SvgRatingBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayerDrawable drawable = (LayerDrawable) createTile(getProgressDrawable(), false);
        setProgressDrawable(drawable);
    }

    /**
     * Converts a drawable to a tiled version of itself. It will recursively
     * traverse layer and state list drawables.
     */
    @SuppressLint("RestrictedApi")
    private Drawable createTile(Drawable drawable, boolean clip) {
        if (drawable instanceof DrawableWrapper) {
            Drawable inner = ((DrawableWrapper) drawable).getWrappedDrawable();
            if (inner != null) {
                inner = createTile(inner, clip);
                ((DrawableWrapper) drawable).setWrappedDrawable(inner);
            }
        } else if (drawable instanceof LayerDrawable) {
            LayerDrawable background = (LayerDrawable) drawable;
            final int n = background.getNumberOfLayers();
            Drawable[] outDrawables = new Drawable[n];

            for (int i = 0; i < n; i++) {
                int id = background.getId(i);
                outDrawables[i] = createTile(background.getDrawable(i),
                        (id == android.R.id.progress || id == android.R.id.secondaryProgress));
            }
            LayerDrawable newBg = new LayerDrawable(outDrawables);

            for (int i = 0; i < n; i++) {
                newBg.setId(i, background.getId(i));
            }

            return newBg;

        } else if (drawable instanceof BitmapDrawable) {
            final BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            final Bitmap tileBitmap = bitmapDrawable.getBitmap();
            if (sampleTile == null) {
                sampleTile = tileBitmap;
            }

            final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
            final BitmapShader bitmapShader = new BitmapShader(tileBitmap,
                    Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
            shapeDrawable.getPaint().setShader(bitmapShader);
            shapeDrawable.getPaint().setColorFilter(bitmapDrawable.getPaint().getColorFilter());
            return (clip) ? new ClipDrawable(shapeDrawable, Gravity.START,
                    ClipDrawable.HORIZONTAL) : shapeDrawable;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable instanceof VectorDrawable) {
            return createTile(getBitmapDrawableFromVectorDrawable(drawable), clip);
        } else if (drawable instanceof VectorDrawableCompat) {
            // API 19 support.
            return createTile(getBitmapDrawableFromVectorDrawable(drawable), clip);
        }
        return drawable;
    }

    private BitmapDrawable getBitmapDrawableFromVectorDrawable(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return new BitmapDrawable(getResources(), bitmap);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (sampleTile != null) {
            final int width = sampleTile.getWidth() * getNumStars();
            setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),
                    getMeasuredHeight());
        }
    }

    private Shape getDrawableShape() {
        final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
        return new RoundRectShape(roundedCorners, null, null);
    }
}

In your layout:

<com.example.common.control.SvgRatingBar
    android:id="@+id/rate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minHeight="13dp"
    android:numStars="5"
    android:progressDrawable="@drawable/rating_bar"
    android:rating="3.5"
    android:stepSize="0.01"
    />

You also have to create rating_bar.xml with two SVG drawables:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/ic_unfilled_star"
        />

    <item
        android:id="@android:id/secondaryProgress"
        android:drawable="@drawable/ic_unfilled_star"
        />

    <item
        android:id="@android:id/progress"
        android:drawable="@drawable/ic_filled_star"
        />

</layer-list>

enter image description here

If you see in Design/Split view only one star, refresh layout:

enter image description here

In Kotlin.

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Shader
import android.graphics.drawable.*
import android.graphics.drawable.shapes.RoundRectShape
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import androidx.appcompat.graphics.drawable.DrawableWrapper
import androidx.appcompat.widget.AppCompatRatingBar
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.example.R; // Your R.java file for R.attr.ratingBarStyle.

class SvgRatingBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null,
                                             defStyleAttr: Int = R.attr.ratingBarStyle) :
    AppCompatRatingBar(context, attrs, defStyleAttr) {

    private var sampleTile: Bitmap? = null
    private val roundedCorners = floatArrayOf(5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f)
    private val roundRectShape = RoundRectShape(roundedCorners, null, null)

    init {
        progressDrawable = createTile(progressDrawable, false) as LayerDrawable
    }

    /**
     * Converts a drawable to a tiled version of itself. It will recursively
     * traverse layer and state list drawables.
     */
    private fun createTile(drawable: Drawable, clip: Boolean): Drawable =
        when {
            drawable is DrawableWrapper -> {
                @SuppressLint("RestrictedApi")
                var inner = drawable.wrappedDrawable
                if (inner != null) {
                    inner = createTile(inner, clip)
                    @SuppressLint("RestrictedApi")
                    drawable.wrappedDrawable = inner
                }
                drawable
            }
            drawable is LayerDrawable -> {
                val n = drawable.numberOfLayers
                val outDrawables = arrayOfNulls<Drawable>(n)
                for (i in 0 until n) {
                    val id = drawable.getId(i)
                    outDrawables[i] = createTile(drawable.getDrawable(i),
                        id == android.R.id.progress || id == android.R.id.secondaryProgress)
                }
                val newBg = LayerDrawable(outDrawables)
                for (i in 0 until n) {
                    newBg.setId(i, drawable.getId(i))
                }
                newBg
            }
            drawable is BitmapDrawable -> {
                val tileBitmap = drawable.bitmap
                if (sampleTile == null) {
                    sampleTile = tileBitmap
                }
                val bitmapShader = BitmapShader(tileBitmap, Shader.TileMode.REPEAT,
                    Shader.TileMode.CLAMP)
                val shapeDrawable = ShapeDrawable(roundRectShape).apply {
                    paint.shader = bitmapShader
                    paint.colorFilter = drawable.paint.colorFilter
                }
                if (clip) ClipDrawable(shapeDrawable, Gravity.START, ClipDrawable.HORIZONTAL)
                else shapeDrawable
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable is VectorDrawable -> {
                createTile(getBitmapDrawableFromVectorDrawable(drawable), clip)
            }
            drawable is VectorDrawableCompat -> {
                // Pre-Lollipop support.
                createTile(getBitmapDrawableFromVectorDrawable(drawable), clip)
            }
            else -> drawable
        }

    private fun getBitmapDrawableFromVectorDrawable(drawable: Drawable): BitmapDrawable {
        val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight,
            Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        return BitmapDrawable(resources, bitmap)
    }

    @Synchronized override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (sampleTile != null) {
            val width = sampleTile!!.width * numStars
            setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),
                measuredHeight)
        }
    }
}

How to convert jsonString to JSONObject in Java

I like to use google-gson for this, and it's precisely because I don't need to work with JSONObject directly.

In that case I'd have a class that will correspond to the properties of your JSON Object

class Phone {
 public String phonetype;
 public String cat;
}


...
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Gson gson = new Gson();
Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
...

However, I think your question is more like, How do I endup with an actual JSONObject object from a JSON String.

I was looking at the google-json api and couldn't find anything as straight forward as org.json's api which is probably what you want to be using if you're so strongly in need of using a barebones JSONObject.

http://www.json.org/javadoc/org/json/JSONObject.html

With org.json.JSONObject (another completely different API) If you want to do something like...

JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
System.out.println(jsonObject.getString("phonetype"));

I think the beauty of google-gson is that you don't need to deal with JSONObject. You just grab json, pass the class to want to deserialize into, and your class attributes will be matched to the JSON, but then again, everyone has their own requirements, maybe you can't afford the luxury to have pre-mapped classes on the deserializing side because things might be too dynamic on the JSON Generating side. In that case just use json.org.

php variable in html no other way than: <?php echo $var; ?>

Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.

echo <<<MYTAG
  <tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;

What is 'Currying'?

It can be a way to use functions to make other functions.

In javascript:

let add = function(x){
  return function(y){ 
   return x + y
  };
};

Would allow us to call it like so:

let addTen = add(10);

When this runs the 10 is passed in as x;

let add = function(10){
  return function(y){
    return 10 + y 
  };
};

which means we are returned this function:

function(y) { return 10 + y };

So when you call

 addTen();

you are really calling:

 function(y) { return 10 + y };

So if you do this:

 addTen(4)

it's the same as:

function(4) { return 10 + 4} // 14

So our addTen() always adds ten to whatever we pass in. We can make similar functions in the same way:

let addTwo = add(2)       // addTwo(); will add two to whatever you pass in
let addSeventy = add(70)  // ... and so on...

Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y into one that can be stepped through lazily, meaning we can do at least two things 1. cache expensive operations 2. achieve abstractions in the functional paradigm.

Imagine our curried function looked like this:

let doTheHardStuff = function(x) {
  let z = doSomethingComputationallyExpensive(x)
  return function (y){
    z + y
  }
}

We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:

let finishTheJob = doTheHardStuff(10)
finishTheJob(20)
finishTheJob(30)

We can get abstractions in a similar way.

making matplotlib scatter plots from dataframes in Python's pandas

Try passing columns of the DataFrame directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.

df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100

In [5]: df
Out[5]: 
       col1      col2  col3
0 -1.000075 -0.759910   100
1  0.510382  0.972615   200
2  1.872067 -0.731010   500
3  0.131612  1.075142  1000
4  1.497820  0.237024  1700

Vary scatter point size based on another column

plt.scatter(df.col1, df.col2, s=df.col3)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=df.col3)

enter image description here

Vary scatter point color based on another column

colors = np.where(df.col3 > 300, 'r', 'k')
plt.scatter(df.col1, df.col2, s=120, c=colors)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=120, c=colors)

enter image description here

Scatter plot with legend

However, the easiest way I've found to create a scatter plot with legend is to call plt.scatter once for each point type.

cond = df.col3 > 300
subset_a = df[cond].dropna()
subset_b = df[~cond].dropna()
plt.scatter(subset_a.col1, subset_a.col2, s=120, c='b', label='col3 > 300')
plt.scatter(subset_b.col1, subset_b.col2, s=60, c='r', label='col3 <= 300') 
plt.legend()

enter image description here

Update

From what I can tell, matplotlib simply skips points with NA x/y coordinates or NA style settings (e.g., color/size). To find points skipped due to NA, try the isnull method: df[df.col3.isnull()]

To split a list of points into many types, take a look at numpy select, which is a vectorized if-then-else implementation and accepts an optional default value. For example:

df['subset'] = np.select([df.col3 < 150, df.col3 < 400, df.col3 < 600],
                         [0, 1, 2], -1)
for color, label in zip('bgrm', [0, 1, 2, -1]):
    subset = df[df.subset == label]
    plt.scatter(subset.col1, subset.col2, s=120, c=color, label=str(label))
plt.legend()

enter image description here

notifyDataSetChanged not working on RecyclerView

Clear your old viewmodel and set the new data to the adapter and call notifyDataSetChanged()

HTML5 record audio to file

Update now Chrome also supports MediaRecorder API from v47. The same thing to do would be to use it( guessing native recording method is bound to be faster than work arounds), the API is really easy to use, and you would find tons of answers as to how to upload a blob for the server.

Demo - would work in Chrome and Firefox, intentionally left out pushing blob to server...

Code Source


Currently, there are three ways to do it:

  1. as wav[ all code client-side, uncompressed recording], you can check out --> Recorderjs. Problem: file size is quite big, more upload bandwidth required.
  2. as mp3[ all code client-side, compressed recording], you can check out --> mp3Recorder. Problem: personally, I find the quality bad, also there is this licensing issue.
  3. as ogg [ client+ server(node.js) code, compressed recording, infinite hours of recording without browser crash ], you can check out --> recordOpus, either only client-side recording, or client-server bundling, the choice is yours.

    ogg recording example( only firefox):

    var mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();  // to start recording.    
    ...
    mediaRecorder.stop();   // to stop recording.
    mediaRecorder.ondataavailable = function(e) {
        // do something with the data.
    }
    

    Fiddle Demo for ogg recording.

How to test valid UUID/GUID?

thanks to @usertatha with some modification

function isUUID ( uuid ) {
    let s = "" + uuid;

    s = s.match('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$');
    if (s === null) {
      return false;
    }
    return true;
}

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

I know it's been a while, but I thought i would update the answer since there are new (faster and simpler) ways to solve this problem. Since ECMAscript 5.1 yo can use the isArray() method avaiable in the Array class.

Yo can see it's documentation in MDN here.

I think you shouldn't have a compatibility problem nowadays, but just in case, if you add this to your code you should be always safe that Array.isArray() is polyfilled:

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

How to split a delimited string in Ruby and convert it to an array?

"12345".each_char.map(&:to_i)

each_char does basically the same as split(''): It splits a string into an array of its characters.

hmmm, I just realize now that in the original question the string contains commas, so my answer is not really helpful ;-(..

Remove all whitespace in a string

If you want to remove leading and ending spaces, use str.strip():

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'

If you want to remove all space characters, use str.replace():

(NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace)

sentence = ' hello  apple'
sentence.replace(" ", "")
>>> 'helloapple'

If you want to remove duplicated spaces, use str.split():

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

Javascript dynamic array of strings

var junk=new Array();
junk.push('This is a string.');

Et cetera.

Submit Button Image

You have to remove the borders and add a background image on the input.

.imgClass { 
    background-image: url(path to image) no-repeat;
    width: 186px;
    height: 53px;
    border: none;
}

It should be good now, normally.

Angular 2 Checkbox Two Way Data Binding

I prefer something more explicit:

component.html

<input #saveUserNameCheckBox
    id="saveUserNameCheckBox" 
    type="checkbox" 
    [checked]="saveUsername" 
    (change)="onSaveUsernameChanged(saveUserNameCheckBox.checked)" />

component.ts

public saveUsername:boolean;

public onSaveUsernameChanged(value:boolean){
    this.saveUsername = value;
}

Dynamically updating plot in matplotlib

Is there a way in which I can update the plot just by adding more point[s] to it...

There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.

Each method basically sets the data property of the object being drawn, so doesn't require clearing the screen or figure. The data property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).

Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:

import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()

Then when you receive data from the serial port just call update_line.

What does "while True" mean in Python?

True is always True, so while True will loop forever.

The while keyword takes an expression, and loops while the expression is true. True is an expression that is always true.

As a possibly clarifying example, consider the following:

a = 1
result = a == 1

Here, a == 1 will return True, and hence put True into result. Hence,

a = 1
while a == 1:
  ...

is equivalent to:

while True:
  ...

provided you don't alter the value of a inside the while loop.

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

Try to add auth method explicitly as below, because sometimes it is required:

session.setConfig("PreferredAuthentications", "password");

How to download videos from youtube on java?

Ref :Youtube Video Download (Android/Java)

Edit 3

You can use the Lib : https://github.com/HaarigerHarald/android-youtubeExtractor

Ex :

String youtubeLink = "http://youtube.com/watch?v=xxxx";

new YouTubeExtractor(this) {
@Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
    if (ytFiles != null) {
        int itag = 22;
    String downloadUrl = ytFiles.get(itag).getUrl();
    }
}
}.extract(youtubeLink, true, true);

They decipherSignature using :

private boolean decipherSignature(final SparseArray<String> encSignatures) throws IOException {
    // Assume the functions don't change that much
    if (decipherFunctionName == null || decipherFunctions == null) {
        String decipherFunctUrl = "https://s.ytimg.com/yts/jsbin/" + decipherJsFileName;

        BufferedReader reader = null;
        String javascriptFile;
        URL url = new URL(decipherFunctUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", USER_AGENT);
        try {
            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder sb = new StringBuilder("");
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append(" ");
            }
            javascriptFile = sb.toString();
        } finally {
            if (reader != null)
                reader.close();
            urlConnection.disconnect();
        }

        if (LOGGING)
            Log.d(LOG_TAG, "Decipher FunctURL: " + decipherFunctUrl);
        Matcher mat = patSignatureDecFunction.matcher(javascriptFile);
        if (mat.find()) {
            decipherFunctionName = mat.group(1);
            if (LOGGING)
                Log.d(LOG_TAG, "Decipher Functname: " + decipherFunctionName);

            Pattern patMainVariable = Pattern.compile("(var |\\s|,|;)" + decipherFunctionName.replace("$", "\\$") +
                    "(=function\\((.{1,3})\\)\\{)");

            String mainDecipherFunct;

            mat = patMainVariable.matcher(javascriptFile);
            if (mat.find()) {
                mainDecipherFunct = "var " + decipherFunctionName + mat.group(2);
            } else {
                Pattern patMainFunction = Pattern.compile("function " + decipherFunctionName.replace("$", "\\$") +
                        "(\\((.{1,3})\\)\\{)");
                mat = patMainFunction.matcher(javascriptFile);
                if (!mat.find())
                    return false;
                mainDecipherFunct = "function " + decipherFunctionName + mat.group(2);
            }

            int startIndex = mat.end();

            for (int braces = 1, i = startIndex; i < javascriptFile.length(); i++) {
                if (braces == 0 && startIndex + 5 < i) {
                    mainDecipherFunct += javascriptFile.substring(startIndex, i) + ";";
                    break;
                }
                if (javascriptFile.charAt(i) == '{')
                    braces++;
                else if (javascriptFile.charAt(i) == '}')
                    braces--;
            }
            decipherFunctions = mainDecipherFunct;
            // Search the main function for extra functions and variables
            // needed for deciphering
            // Search for variables
            mat = patVariableFunction.matcher(mainDecipherFunct);
            while (mat.find()) {
                String variableDef = "var " + mat.group(2) + "={";
                if (decipherFunctions.contains(variableDef)) {
                    continue;
                }
                startIndex = javascriptFile.indexOf(variableDef) + variableDef.length();
                for (int braces = 1, i = startIndex; i < javascriptFile.length(); i++) {
                    if (braces == 0) {
                        decipherFunctions += variableDef + javascriptFile.substring(startIndex, i) + ";";
                        break;
                    }
                    if (javascriptFile.charAt(i) == '{')
                        braces++;
                    else if (javascriptFile.charAt(i) == '}')
                        braces--;
                }
            }
            // Search for functions
            mat = patFunction.matcher(mainDecipherFunct);
            while (mat.find()) {
                String functionDef = "function " + mat.group(2) + "(";
                if (decipherFunctions.contains(functionDef)) {
                    continue;
                }
                startIndex = javascriptFile.indexOf(functionDef) + functionDef.length();
                for (int braces = 0, i = startIndex; i < javascriptFile.length(); i++) {
                    if (braces == 0 && startIndex + 5 < i) {
                        decipherFunctions += functionDef + javascriptFile.substring(startIndex, i) + ";";
                        break;
                    }
                    if (javascriptFile.charAt(i) == '{')
                        braces++;
                    else if (javascriptFile.charAt(i) == '}')
                        braces--;
                }
            }

            if (LOGGING)
                Log.d(LOG_TAG, "Decipher Function: " + decipherFunctions);
            decipherViaWebView(encSignatures);
            if (CACHING) {
                writeDeciperFunctToChache();
            }
        } else {
            return false;
        }
    } else {
        decipherViaWebView(encSignatures);
    }
    return true;
}

Now with use of this library High Quality Videos Lossing Audio so i use the MediaMuxer for Murging Audio and Video for Final Output

Edit 1

https://stackoverflow.com/a/15240012/9909365

Why the previous answer not worked

 Pattern p2 = Pattern.compile("sig=(.*?)[&]");
        Matcher m2 = p2.matcher(url);
        String sig = null;
        if (m2.find()) {
            sig = m2.group(1);
        }

As of November 2016, this is a little rough around the edges, but displays the basic principle. The url_encoded_fmt_stream_map today does not have a space after the colon (better make this optional) and "sig" has been changed to "signature"

and while i am debuging the code i found the new keyword its signature&s in many video's URL

here edited answer

private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();

initTypeMap(); call first

class Meta {
    public String num;
    public String type;
    public String ext;

    Meta(String num, String ext, String type) {
        this.num = num;
        this.ext = ext;
        this.type = type;
    }
}

class Video {
    public String ext = "";
    public String type = "";
    public String url = "";

    Video(String ext, String type, String url) {
        this.ext = ext;
        this.type = type;
        this.url = url;
    }
}

public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
        throws IOException {
    if (ytUrl == null) {
        return null;
    }

    // Remove any query params in query string after the watch?v=<vid> in
    // e.g.
    // http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
    int andIdx = ytUrl.indexOf('&');
    if (andIdx >= 0) {
        ytUrl = ytUrl.substring(0, andIdx);
    }

    // Get the HTML response
    /* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
   /* HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            userAgent);
    HttpGet request = new HttpGet(ytUrl);
    HttpResponse response = client.execute(request);*/
    String html = "";
    HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    InputStream in = c.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        str.append(line.replace("\\u0026", "&"));
    }
    in.close();
    html = str.toString();

    // Parse the HTML response and extract the streaming URIs
    if (html.contains("verify-age-thumb")) {
        Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
        return null;
    }

    if (html.contains("das_captcha")) {
        Log.e("Downloader", "Captcha found, please try with different IP address.");
        return null;
    }

    Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
    // Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
    Matcher m = p.matcher(html);
    List<String> matches = new ArrayList<String>();
    while (m.find()) {
        matches.add(m.group());
    }

    if (matches.size() != 1) {
        Log.e("Downloader", "Found zero or too many stream maps.");
        return null;
    }

    String urls[] = matches.get(0).split(",");
    HashMap<String, String> foundArray = new HashMap<String, String>();
    for (String ppUrl : urls) {
        String url = URLDecoder.decode(ppUrl, "UTF-8");
        Log.e("URL","URL : "+url);

        Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
        Matcher m1 = p1.matcher(url);
        String itag = null;
        if (m1.find()) {
            itag = m1.group(1);
        }

        Pattern p2 = Pattern.compile("signature=(.*?)[&]");
        Matcher m2 = p2.matcher(url);
        String sig = null;
        if (m2.find()) {
            sig = m2.group(1);
        } else {
            Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
            Matcher m23 = p23.matcher(url);
            if (m23.find()) {
                sig = m23.group(1);
            }
        }

        Pattern p3 = Pattern.compile("url=(.*?)[&]");
        Matcher m3 = p3.matcher(ppUrl);
        String um = null;
        if (m3.find()) {
            um = m3.group(1);
        }

        if (itag != null && sig != null && um != null) {
            Log.e("foundArray","Adding Value");
            foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
                    + "signature=" + sig);
        }
    }
    Log.e("foundArray","Size : "+foundArray.size());
    if (foundArray.size() == 0) {
        Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
        return null;
    }


    ArrayList<Video> videos = new ArrayList<Video>();

    for (String format : typeMap.keySet()) {
        Meta meta = typeMap.get(format);

        if (foundArray.containsKey(format)) {
            Video newVideo = new Video(meta.ext, meta.type,
                    foundArray.get(format));
            videos.add(newVideo);
            Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
                    + ", type:" + newVideo.type + ", url:" + newVideo.url);
        }
    }

    return videos;
}

private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(webViewActivity.this, "",
                "Connecting to YouTube...", true);
    }

    @Override
    protected ArrayList<Video> doInBackground(String... params) {
        ArrayList<Video> fVideos = new ArrayList<>();
        String url = params[0];
        try {
            ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
            /*                Log.e("Downloader","Size of Video : "+videos.size());*/
            if (videos != null && !videos.isEmpty()) {
                for (Video video : videos)
                {
                    Log.e("Downloader", "ext : " + video.ext);
                    if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
                        ext = video.ext.toLowerCase();
                        fVideos.add(new Video(video.ext,video.type,video.url));
                    }
                }


                return fVideos;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
        }
        Log.e("Downloader", "Couldn't get stream URI for " + url);
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<Video> streamingUrl) {
        super.onPostExecute(streamingUrl);
        progressDialog.dismiss();
        if (streamingUrl != null) {
            if (!streamingUrl.isEmpty()) {
                //Log.e("Steaming Url", "Value : " + streamingUrl);

                for (int i = 0; i < streamingUrl.size(); i++) {
                    Video fX = streamingUrl.get(i);
                    Log.e("Founded Video", "URL : " + fX.url);
                    Log.e("Founded Video", "TYPE : " + fX.type);
                    Log.e("Founded Video", "EXT : " + fX.ext);
                }
                //new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
            }
        }
    }
}
public void initTypeMap()
{
    typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
    typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
    typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
    typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
    typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
    typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
    typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
    typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
    typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
    typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
    typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
    typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
    typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
    typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}

Edit 2:

Some time This Code Not worked proper

Same-origin policy

https://en.wikipedia.org/wiki/Same-origin_policy

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1]. 

Ref : https://superuser.com/questions/773719/how-do-all-of-these-save-video-from-youtube-services-work/773998#773998

url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts              // DASH: contains video or audio stream

Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this

url  // direct HTTP link to a video
itag // code specifying the quality
s    // signature, security measure to counter downloading

Each URL will be encoded so you will need to decode them. Now the tricky part.

YouTube has at least 3 security levels for their videos

unsecured // as expected, you can download these with just the unencoded URL
s         // see below
RTMPE     // uses "rtmpe://" protocol, no known method for these

The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.

The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as

AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this

function mo(a) {
  a = a.split("");
  a = lo.rw(a, 1);
  a = lo.rw(a, 32);
  a = lo.IC(a, 1);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 44);
  return a.join("")
}

This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as

http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js

this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header

Access-Control-Allow-Origin: http://www.youtube.com

and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests

Access-Control-Allow-Origin: *

So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.

How to use multiple conditions (With AND) in IIF expressions in ssrs

You don't need an IIF() at all here. The comparisons return true or false anyway.

Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.

=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And 
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0

But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:

=Sum(
    IIF(
        Fields!OpeningStock.Value=0 AND
        Fields!GrossDispatched.Value=0 AND
        Fields!TransferOutToMW.Value=0 AND
        Fields!TransferOutToDW.Value=0 AND 
        Fields!TransferOutToOW.Value=0 AND
        Fields!NetDispatched.Value=0 AND
        Fields!QtySold.Value=0 AND
        Fields!StockAdjustment.Value=0 AND
        Fields!ClosingStock.Value=0,
        0,
        1
    )
) = 0

This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

just create environment variable like this

create environment variable like in the screenshot and make sure to replace with your sdk path in my case it was C:\Users\zeesh\AppData\Local\Android\sdk replace zeesh with your username and make sure to restart android studio to take effect.

What is the difference between "expose" and "publish" in Docker?

Basically, you have three options:

  1. Neither specify EXPOSE nor -p
  2. Only specify EXPOSE
  3. Specify EXPOSE and -p

1) If you specify neither EXPOSE nor -p, the service in the container will only be accessible from inside the container itself.

2) If you EXPOSE a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.

3) If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker.

The reason why both are separated is IMHO because:

  • choosing a host port depends on the host and hence does not belong to the Dockerfile (otherwise it would be depending on the host),
  • and often it's enough if a service in a container is accessible from other containers.

The documentation explicitly states:

The EXPOSE instruction exposes ports for use within links.

It also points you to how to link containers, which basically is the inter-container communication I talked about.

PS: If you do -p, but do not EXPOSE, Docker does an implicit EXPOSE. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p includes EXPOSE. That's why I didn't list it above as a fourth case.

enable/disable zoom in Android WebView

I've looked at the source code for WebView and I concluded that there is no elegant way to accomplish what you are asking.

What I ended up doing was subclassing WebView and overriding OnTouchEvent. In OnTouchEvent for ACTION_DOWN, I check how many pointers there are using MotionEvent.getPointerCount(). If there is more than one pointer, I call setSupportZoom(true), otherwise I call setSupportZoom(false). I then call the super.OnTouchEvent().

This will effectively disable zooming when scrolling (thus disabling the zoom controls) and enable zooming when the user is about to pinch zoom. Not a nice way of doing it, but it has worked well for me so far.

Note that getPointerCount() was introduced in 2.1 so you'll have to do some extra stuff if you support 1.6.

Changing the git user inside Visual Studio Code

This could be because of the reason that the credentials are saved and you need to update those credentials and you can do that by following the below steps

control panel-> credential manager ->under generic credential you will be able to see the credentials related to git

Try to update them if that does not work delete them and add new ones

for other platforms or different versions of the operating system you need to find out where the credentails are saved related to git and update them.

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

const [name, setName] = useState()

generates error as soon as you type in the text field

const [name, setName] = useState('') // <-- by putting in quotes 

will fix the issue on this string example.

cancelling a handler.postdelayed process

Here is a class providing a cancel method for a delayed action

public class DelayedAction {

private Handler _handler;
private Runnable _runnable;

/**
 * Constructor
 * @param runnable The runnable
 * @param delay The delay (in milli sec) to wait before running the runnable
 */
public DelayedAction(Runnable runnable, long delay) {
    _handler = new Handler(Looper.getMainLooper());
    _runnable = runnable;
    _handler.postDelayed(_runnable, delay);
}

/**
 * Cancel a runnable
 */
public void cancel() {
    if ( _handler == null || _runnable == null ) {
        return;
    }
    _handler.removeCallbacks(_runnable);
}}

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

Check if process returns 0 with batch file

To check whether a process/command returned 0 or not, use the operators && == 0 or not == 0 ||:

Just add operator to your script:

execute_command && (

       echo\Return 0, with no execution error
) || (
        echo\Return non 0, something went wrong
     )

command && echo\Return 0 || echo\Return non 0

How to make a JSON call to a url?

A standard http GET request should do it. Then you can use JSON.parse() to make it into a json object.

function Get(yourUrl){
    var Httpreq = new XMLHttpRequest(); // a new request
    Httpreq.open("GET",yourUrl,false);
    Httpreq.send(null);
    return Httpreq.responseText;          
}

then

var json_obj = JSON.parse(Get(yourUrl));
console.log("this is the author name: "+json_obj.author_name);

that's basically it

Search input with an icon Bootstrap 4

I made another variant with dropdown menu (perhaps for advanced search etc).. Here is how it looks like:

Bootstrap 4 searh bar with dropdown menu

<div class="input-group my-4 col-6 mx-auto">
    <input class="form-control py-2 border-right-0 border" type="search" placeholder="Type something..." id="example-search-input">
    <span class="input-group-append">
        <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split border border-left-0 border-right-0 rounded-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <span class="sr-only">Toggle Dropdown</span>
        </button>
        <button class="btn btn-outline-primary rounded-right" type="button">
            <i class="fas fa-search"></i>
        </button>
        <div class="dropdown-menu dropdown-menu-right">
            <a class="dropdown-item" href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
            <a class="dropdown-item" href="#">Something else here</a>
            <div role="separator" class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Separated link</a>
        </div>
    </span>
</div>

Note: It appears green in the screenshot because my site main theme is green.

How to check what version of jQuery is loaded?

My preference is:

console.debug("jQuery "+ (jQuery ? $().jquery : "NOT") +" loaded")

Result:

jQuery 1.8.0 loaded

How to update a value, given a key in a hashmap?

Use Java8 built in fuction 'computeIfPresent'

Example:

public class ExampleToUpdateMapValue {

    public static void main(String[] args) {
        Map<String,String> bookAuthors = new TreeMap<>();
        bookAuthors.put("Genesis","Moses");
        bookAuthors.put("Joshua","Joshua");
        bookAuthors.put("Judges","Samuel");

        System.out.println("---------------------Before----------------------");
        bookAuthors.entrySet().stream().forEach(System.out::println);
        // To update the existing value using Java 8
        bookAuthors.computeIfPresent("Judges", (k,v) -> v = "Samuel/Nathan/Gad");

        System.out.println("---------------------After----------------------");
        bookAuthors.entrySet().stream().forEach(System.out::println);
    }
}

Is it possible to install another version of Python to Virtualenv?

This procedure installs Python2.7 anywhere and eliminates any absolute path references within your env folder (managed by virtualenv). Even virtualenv isn't installed absolutely.

Thus, theoretically, you can drop the top level directory into a tarball, distribute, and run anything configured within the tarball on a machine that doesn't have Python (or any dependencies) installed.

Contact me with any questions. This is just part of an ongoing, larger project I am engineering. Now, for the drop...

  1. Set up environment folders.

    $ mkdir env
    $ mkdir pyenv
    $ mkdir dep
    
  2. Get Python-2.7.3, and virtualenv without any form of root OS installation.

    $ cd dep
    $ wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
    $ wget https://raw.github.com/pypa/virtualenv/master/virtualenv.py
    
  3. Extract and install Python-2.7.3 into the pyenv dir. make clean is optional if you are doing this a 2nd, 3rd, Nth time...

    $ tar -xzvf Python-2.7.3.tgz
    $ cd Python-2.7.3
    $ make clean
    $ ./configure --prefix=/path/to/pyenv
    $ make && make install
    $ cd ../../
    $ ls
    dep    env    pyenv
    
  4. Create your virtualenv

    $ dep/virtualenv.py --python=/path/to/pyenv/bin/python --verbose env
    
  5. Fix the symlink to python2.7 within env/include/

    $ ls -l env/include/
    $ cd !$
    $ rm python2.7
    $ ln -s ../../pyenv/include/python2.7 python2.7
    $ cd ../../
    
  6. Fix the remaining python symlinks in env. You'll have to delete the symbolically linked directories and recreate them, as above. Also, here's the syntax to force in-place symbolic link creation.

    $ ls -l env/lib/python2.7/
    $ cd !$
    $ ln -sf ../../../pyenv/lib/python2.7/UserDict.py UserDict.py
    [...repeat until all symbolic links are relative...]
    $ cd ../../../
    
  7. Test

    $ python --version
    Python 2.7.1
    $ source env/bin/activate
    (env)
    $ python --version
    Python 2.7.3
    

Aloha.

Generate C# class from XML

You should consider svcutil (svcutil question)

Both xsd.exe and svcutil operate on the XML schema file (.xsd). Your XML must conform to a schema file to be used by either of these two tools.

Note that various 3rd party tools also exist for this.

Propagate all arguments in a bash shell script

Sometimes you want to pass all your arguments, but preceded by a flag (e.g. --flag)

$ bar --flag "$1" --flag "$2" --flag "$3"

You can do this in the following way:

$ bar $(printf -- ' --flag "%s"' "$@")

note: to avoid extra field splitting, you must quote %s and $@, and to avoid having a single string, you cannot quote the subshell of printf.

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

T-SQL and the WHERE LIKE %Parameter% clause

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

I know this is not the solution to OPs post. However, this post is the first one indexed by Google when I searched for answers to this error. For this reason I feel this will benefit others.

The following error...

The POST method is not supported for this route. Supported methods: GET, HEAD.

was caused by not clearing the routing cache

php artisan route:cache

iOS 7 status bar overlapping UI

I've got a problem opening the inApp browser with phonegap. Gimi's fix worked well, but everytime I opened the inApp browser the screen was shrinked at the bottom. So I've added an if statement to check if the webview's y origin was 0. The inApp browser hasn't the y origin 0 anymore so it solved my problem.

// ios 7 status bar fix
- (void)viewWillAppear:(BOOL)animated
{
    // View defaults to full size.  If you want to customize the view's size, or its subviews (e.g. webView),
    // you can do so here.
    //Lower screen 20px on ios 7
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        if(self.webView.frame.origin.y == 0) {
            CGRect viewBounds = [self.webView bounds];
            viewBounds.origin.y = 20;
            viewBounds.size.height = viewBounds.size.height - 20;
            self.webView.frame = viewBounds;
        }
    }

    [super viewWillAppear:animated];
}

The solution is not really mine but I can't find the source. Hope it helps!

Why does the C preprocessor interpret the word "linux" as the constant "1"?

From info gcc (emphasis mine):

-ansi

In C mode, this is equivalent to -std=c90. In C++ mode, it is equivalent to -std=c++98. This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as the asm and typeof keywords, and predefined macros such as 'unix' and 'vax' that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature. For the C compiler, it disables recognition of C++ style // comments as well as the inline keyword.

(It uses vax in the example instead of linux because when it was written maybe it was more popular ;-).

The basic idea is that GCC only tries to fully comply with the ISO standards when it is invoked with the -ansi option.

AngularJS: How to run additional code after AngularJS has rendered a template?

Following Misko's advice, if you want async operation, then instead of $timeout() (which doesn't work)

$timeout(function () { $scope.assignmentsLoaded(data); }, 1000);

use $evalAsync() (which does work)

$scope.$evalAsync(function() { $scope.assignmentsLoaded(data); } );

Fiddle. I also added a "remove row of data" link that will modify $scope.assignments, simulating a change to the data/model -- to show that changing the data works.

The Runtime section of the Conceptual Overview page explains that evalAsync should be used when you need something to occur outside the current stack frame, but before the browser renders. (Guessing here... "current stack frame" probably includes Angular DOM updates.) Use $timeout if you need something to occur after the browser renders.

However, as you already found out, I don't think there is any need for async operation here.

How to add hamburger menu in bootstrap

CSS only (no icon sets) Codepen

_x000D_
_x000D_
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
   <!-- <a class="navbar-brand" href="#">_x000D_
      <img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
      Bootstrap_x000D_
      </a> -->_x000D_
   <!-- https://stackoverflow.com/questions/26317679 -->_x000D_
   <a class="nav-link" href="#">_x000D_
      <div id="navBars">_x000D_
         <input type="checkbox" /><span></span>_x000D_
         <span></span>_x000D_
         <span></span>_x000D_
      </div>_x000D_
   </a>_x000D_
   <!-- /26317679 -->_x000D_
   <div class="collapse navbar-collapse" id="navbarNav">_x000D_
      <ul class="navbar-nav">_x000D_
         <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
         <li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
      </ul>_x000D_
   </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to detect when an @Input() value changes in Angular?

Here ngOnChanges will trigger always when your input property changes:

ngOnChanges(changes: SimpleChanges): void {
 console.log(changes.categoryId.currentValue)
}

how to deal with google map inside of a hidden div (Updated picture)

Add this code before the div or pass it to a js file:

<script>
    $(document).on("pageshow","#div_name",function(){
       initialize();
    });

   function initialize() {
   // create the map

      var myOptions = {
         zoom: 14,
         center: new google.maps.LatLng(0.0, 0.0),
         mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById("div_name"), myOptions);
   }


</script>

This event will be triggered after the div loads so it will refresh the map content without having to press F5

Embedding DLLs in a compiled executable

Generally you would need some form of post build tool to perform an assembly merge like you are describing. There is a free tool called Eazfuscator (eazfuscator.blogspot.com/) which is designed for bytecode mangling that also handles assembly merging. You can add this into a post build command line with Visual Studio to merge your assemblies, but your mileage will vary due to issues that will arise in any non trival assembly merging scenarios.

You could also check to see if the build make untility NANT has the ability to merge assemblies after building, but I am not familiar enough with NANT myself to say whether the functionality is built in or not.

There are also many many Visual Studio plugins that will perform assembly merging as part of building the application.

Alternatively if you don't need this to be done automatically, there are a number of tools like ILMerge that will merge .net assemblies into a single file.

The biggest issue I've had with merging assemblies is if they use any similar namespaces. Or worse, reference different versions of the same dll (my problems were generally with the NUnit dll files).

Can you have if-then-else logic in SQL?

Instead of using EXISTS and COUNT just use @@ROWCOUNT:

select product, price from table1 where project = 1

IF @@ROWCOUNT = 0
BEGIN
    select product, price from table1 where customer = 2

    IF @@ROWCOUNT = 0
    select product, price from table1 where company = 3
END

Wavy shape with css

I think this is the right way to make a shape like you want. By using the SVG possibilities, and an container to keep the shape responsive.

_x000D_
_x000D_
svg {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
.container {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 100%;_x000D_
  vertical-align: middle;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">_x000D_
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:red;"></path>_x000D_
  </svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Will iOS launch my app into the background if it was force-quit by the user?

This might help you

In most cases, the system does not relaunch apps after they are force quit by the user. One exception is location apps, which in iOS 8 and later are relaunched after being force quit by the user. In other cases, though, the user must launch the app explicitly or reboot the device before the app can be launched automatically into the background by the system. When password protection is enabled on the device, the system does not launch an app in the background before the user first unlocks the device.

Source: https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

MSSQL Error 'The underlying provider failed on Open'

In my case I had a mismatch between the connection string name I was registering in the context's constructor vs the name in my web.config. Simple mistake caused by copy and paste :D

    public DataContext()
        : base(nameOrConnectionString: "ConnStringName")
    {
        Database.SetInitializer<DataContext>(null);
    }

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

This cannot be done with the native javascript dialog box, but a lot of javascript libraries include more flexible dialogs. You can use something like jQuery UI's dialog box for this.

See also these very similar questions:

Here's an example, as demonstrated in this jsFiddle:

<html><head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/normalize.css">
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
</head>
<body>
    <a class="checked" href="http://www.google.com">Click here</a>
    <script type="text/javascript">

        $(function() {
            $('.checked').click(function(e) {
                e.preventDefault();
                var dialog = $('<p>Are you sure?</p>').dialog({
                    buttons: {
                        "Yes": function() {alert('you chose yes');},
                        "No":  function() {alert('you chose no');},
                        "Cancel":  function() {
                            alert('you chose cancel');
                            dialog.dialog('close');
                        }
                    }
                });
            });
        });

    </script>
</body><html>

Deleting folders in python recursively

Here's my pure pathlib recursive directory unlinker:

from pathlib import Path

def rmdir(directory):
    directory = Path(directory)
    for item in directory.iterdir():
        if item.is_dir():
            rmdir(item)
        else:
            item.unlink()
    directory.rmdir()

rmdir(Path("dir/"))

Inheritance and init method in Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

GCC dump preprocessor defines

I usually do it this way:

$ gcc -dM -E - < /dev/null

Note that some preprocessor defines are dependent on command line options - you can test these by adding the relevant options to the above command line. For example, to see which SSE3/SSE4 options are enabled by default:

$ gcc -dM -E - < /dev/null | grep SSE[34]
#define __SSE3__ 1
#define __SSSE3__ 1

and then compare this when -msse4 is specified:

$ gcc -dM -E -msse4 - < /dev/null | grep SSE[34]
#define __SSE3__ 1
#define __SSE4_1__ 1
#define __SSE4_2__ 1
#define __SSSE3__ 1

Similarly you can see which options differ between two different sets of command line options, e.g. compare preprocessor defines for optimisation levels -O0 (none) and -O3 (full):

$ gcc -dM -E -O0 - < /dev/null > /tmp/O0.txt
$ gcc -dM -E -O3 - < /dev/null > /tmp/O3.txt
$ sdiff -s /tmp/O0.txt /tmp/O3.txt 
#define __NO_INLINE__ 1        <
                               > #define __OPTIMIZE__ 1

How to encrypt String in Java

You might want to consider some automated tool to do the encryption / decryption code generation eg. https://www.stringencrypt.com/java-encryption/

It can generate different encryption and decryption code each time for the string or file encryption.

It's pretty handy when it comes to fast string encryption without using RSA, AES etc.

Sample results:

// encrypted with https://www.stringencrypt.com (v1.1.0) [Java]
// szTest = "Encryption in Java!"
String szTest = "\u9E3F\uA60F\uAE07\uB61B\uBE1F\uC62B\uCE2D\uD611" +
                "\uDE03\uE5FF\uEEED\uF699\uFE3D\u071C\u0ED2\u1692" +
                "\u1E06\u26AE\u2EDC";

for (int iatwS = 0, qUJQG = 0; iatwS < 19; iatwS++)
{
        qUJQG = szTest.charAt(iatwS);
        qUJQG ++;
        qUJQG = ((qUJQG << 5) | ( (qUJQG & 0xFFFF) >> 11)) & 0xFFFF;
        qUJQG -= iatwS;
        qUJQG = (((qUJQG & 0xFFFF) >> 6) | (qUJQG << 10)) & 0xFFFF;
        qUJQG ^= iatwS;
        qUJQG -= iatwS;
        qUJQG = (((qUJQG & 0xFFFF) >> 3) | (qUJQG << 13)) & 0xFFFF;
        qUJQG ^= 0xFFFF;
        qUJQG ^= 0xB6EC;
        qUJQG = ((qUJQG << 8) | ( (qUJQG & 0xFFFF) >> 8)) & 0xFFFF;
        qUJQG --;
        qUJQG = (((qUJQG & 0xFFFF) >> 5) | (qUJQG << 11)) & 0xFFFF;
        qUJQG ++;
        qUJQG ^= 0xFFFF;
        qUJQG += iatwS;
        szTest = szTest.substring(0, iatwS) + (char)(qUJQG & 0xFFFF) + szTest.substring(iatwS + 1);
}

System.out.println(szTest);

We use it all the time in our company.

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Import a module from a relative path

This is the relevant PEP:

http://www.python.org/dev/peps/pep-0328/

In particular, presuming dirFoo is a directory up from dirBar...

In dirFoo\Foo.py:

from ..dirBar import Bar

How to prevent ENTER keypress to submit a web form?

How about:

<script>
function isok(e) {
  var name = e.explicitOriginalTarget.name;
  if (name == "button") {
    return true
  }
  return false;
}
</script>
<form onsubmit="return isok(event);">
<input type="text" name="serial"/>
<input type="submit" name="button" value="Create Thing"/>
</form>

And just name your button right and it will still submit, but text fields i.e. the explicitOriginalTarget when you hit return in one, will not have the right name.

changing textbox border colour using javascript

You may try

document.getElementById('name').style.borderColor='#e52213';
document.getElementById('name').style.border='solid';

What does "|=" mean? (pipe equal operator)

You have already got sufficient answer for your question. But may be my answer help you more about |= kind of binary operators.

I am writing table for bitwise operators:
Following are valid:

----------------------------------------------------------------------------------------
Operator   Description                                   Example
----------------------------------------------------------------------------------------
|=        bitwise inclusive OR and assignment operator   C |= 2 is same as C = C | 2
^=        bitwise exclusive OR and assignment operator   C ^= 2 is same as C = C ^ 2
&=        Bitwise AND assignment operator                C &= 2 is same as C = C & 2
<<=       Left shift AND assignment operator             C <<= 2 is same as C = C << 2
>>=       Right shift AND assignment operator            C >>= 2 is same as C = C >> 2  
----------------------------------------------------------------------------------------

note all operators are binary operators.

Also Note: (for below points I wanted to add my answer)

  • >>> is bitwise operator in Java that is called Unsigned shift
    but >>>= not an operator in Java. >>>= operator

  • ~ is bitwise complement bits, 0 to 1 and 1 to 0 (Unary operator) but ~= not an operator.

  • Additionally, ! Called Logical NOT Operator, but != Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. e.g. (A != B) is true. where as A=!B means if B is true then A become false (and if B is false then A become true).

side note: | is not called pipe, instead its called OR, pipe is shell terminology transfer one process out to next..

Unique constraint violation during insert: why? (Oracle)

Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.

CREATE TABLE [DB] (
    [DBId] bigint NOT NULL IDENTITY,
    ...

    CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),

); 

Converting an array to a function arguments list

A very readable example from another post on similar topic:

var args = [ 'p0', 'p1', 'p2' ];

function call_me (param0, param1, param2 ) {
    // ...
}

// Calling the function using the array with apply()
call_me.apply(this, args);

And here a link to the original post that I personally liked for its readability

select data up to a space?

An alternative if you sometimes do not have spaces do not want to use the CASE statement

select REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))

This works in SQL Server, and according to my searching MySQL has the same functions

What is the maximum length of a Push Notification alert text?

It should be 236 bytes. There is no restriction on the size of the alert text as far as I know, but only the total payload size. So considering if the payload is minimal and only contains the alert information, it should look like:

{"aps":{"alert":""}}

That takes up 20 characters (20 bytes), leaving 236 bytes to put inside the alert string. With ASCII that will be 236 characters, and could be lesser with UTF8 and UTF16.

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

Number input type that takes only integers?

Pattern are always preferable for restriction, try oninput and min occur 1 for inputting only numbers from 1 onwards

<input type="text" min="1" oninput="this.value=this.value.replace(/[^0-9]/g,'');"
                                value=${var} >

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

How to initialize a List<T> to a given size (as opposed to capacity)?

The accepted answer (the one with the green check mark) has an issue.

The problem:

var result = Lists.Repeated(new MyType(), sizeOfList);
// each item in the list references the same MyType() object
// if you edit item 1 in the list, you are also editing item 2 in the list

I recommend changing the line above to perform a copy of the object. There are many different articles about that:

If you want to initialize every item in your list with the default constructor, rather than NULL, then add the following method:

public static List<T> RepeatedDefaultInstance<T>(int count)
    {
        List<T> ret = new List<T>(count);
        for (var i = 0; i < count; i++)
        {
            ret.Add((T)Activator.CreateInstance(typeof(T)));
        }
        return ret;
    }

How to determine if object is in array

Having been recently bitten by the FP bug reading many wonderful accounts of how neatly the functional paradigm fits with Javascript

I replicate the code for completeness sake and suggest two ways this can be done functionally.

    var carBrands = [];

  var car1 = {name:'ford'};
  var car2 = {name:'lexus'};
  var car3 = {name:'maserati'};
  var car4 = {name:'ford'};
  var car5 = {name:'toyota'};

  carBrands.push(car1);
  carBrands.push(car2);
  carBrands.push(car3);
  carBrands.push(car4);

  // ES6 approach which uses the includes method (Chrome47+, Firefox43+)

  carBrands.includes(car1) // -> true
  carBrands.includes(car5) // -> false

If you need to support older browsers use the polyfill, it seems IE9+ and Edge do NOT support it. Located in polyfill section of MSDN page

Alternatively I would like to propose an updated answer to cdhowie

// ES2015 syntax
function containsObject(obj, list) {

    return list.some(function(elem) {
      return elem === obj
    })
}

// or ES6+ syntax with cool fat arrows
function containsObject(obj, list) {

    return list.some(elem => elem === obj)
}

Can you use a trailing comma in a JSON object?

As stated it is not allowed. But in JavaScript this is:

var a = Array()
for(let i=1; i<=5; i++) {
    a.push(i)
}
var s = "[" + a.join(",") + "]"

(works fine in Firefox, Chrome, Edge, IE11, and without the let in IE9, 8, 7, 5)

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

if variable contains

If you have a lot of these to check you might want to store a list of the mappings and just loop over that, instead of having a bunch of if/else statements. Something like:

var CODE_TO_LOCATION = {
  'ST1': 'stoke central',
  'ST2': 'stoke north',
  // ...
};

function getLocation(text) {
  for (var code in CODE_TO_LOCATION) {
    if (text.indexOf(code) != -1) {
      return CODE_TO_LOCATION[code];
    }
  }
  return null;
}

This way you can easily add more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.

jquery ajax function not working

you need to prevent the default behavior of your form when submitting

by adding this:

$("#postcontent").on('submit' , function(e) {

  e.preventDefault();

  //then the rest of your code
}

Build the full path filename in Python

Um, why not just:

>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

Check if date is in the past Javascript

var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}

Colors in JavaScript console

Try this:

var funcNames = ["log", "warn", "error"];
var colors = ['color:green', 'color:orange', 'color:red'];

for (var i = 0; i < funcNames.length; i++) {
    let funcName = funcNames[i];
    let color = colors[i];
    let oldFunc = console[funcName];
    console[funcName] = function () {
        var args = Array.prototype.slice.call(arguments);
        if (args.length) args = ['%c' + args[0]].concat(color, args.slice(1));
        oldFunc.apply(null, args);
    };
}

now they all are as you wanted:

console.log("Log is green.");
console.warn("Warn is orange.");
console.error("Error is red.");

note: formatting like console.log("The number = %d", 123); is not broken.

how to toggle (hide/show) a table onClick of <a> tag in java script

You need to modify your function as:

function toggleTable()
{
   if (document.getElementById("loginTable").style.display == "table" ) {
       document.getElementById("loginTable").style.display="none";

   } else {
      document.getElementById("loginTable").style.display="table";

}

currently it is checking based on the boolean parameter, you don't have to pass the parameter with your function.

You need to modify your anchor tag as:

<a id="loginLink" onclick="toggleTable();" href="#">Login</a>

How to read a CSV file from a URL with Python?

This question is tagged python-2.x so it didn't seem right to tamper with the original question, or the accepted answer. However, Python 2 is now unsupported, and this question still has good google juice for "python csv urllib", so here's an updated Python 3 solution.

It's now necessary to decode urlopen's response (in bytes) into a valid local encoding, so the accepted answer has to be modified slightly:

import csv, urllib.request

url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib.request.urlopen(url)
lines = [l.decode('utf-8') for l in response.readlines()]
cr = csv.reader(lines)

for row in cr:
    print(row)

Note the extra line beginning with lines =, the fact that urlopen is now in the urllib.request module, and print of course requires parentheses.

It's hardly advertised, but yes, csv.reader can read from a list of strings.

And since someone else mentioned pandas, here's a one-liner to display the CSV in a console-friendly output:

python3 -c 'import pandas
df = pandas.read_csv("http://winterolympicsmedals.com/medals.csv")
print(df.to_string())'

(Yes, it's three lines, but you can copy-paste it as one command. ;)

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

How do I create a new class in IntelliJ without using the mouse?

For Mac Os, command + 1 , then press control + return

jQuery add class .active on menu

Check this out this WORKS

Html

<div class="menu">

    <ul>
        <li><a href="~/link1/">LINK 1</a>
        <li><a href="www.xyz.com/other/link1">LINK 2</a>
        <li><a href="~/link3/">LINK 3</a>
    </ul>

</div>

Jquery

$(document).ready(function(){
    $(".menu ul li a").each(function(){
        if($(this).attr("href")=="www.xyz.com/other/link1")
            $(this).addClass("active");
    })
})

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

Replace non-numeric with empty string

You don't need to use Regex.

phone = new String(phone.Where(c => char.IsDigit(c)).ToArray())

Stop MySQL service windows

Start Powershell as administrator and run:

net start [MySQL-service-name]

Find the service name:

run 'services.msc', look for MySQL and click on properties

enter image description here

changing default x range in histogram matplotlib

import matplotlib.pyplot as plt


...


plt.xlim(xmin=6.5, xmax = 12.5)

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):

Option Explicit

Public Sub ExportWorksheetAndSaveAsCSV()

Dim wbkExport As Workbook
Dim shtToExport As Worksheet

Set shtToExport = ThisWorkbook.Worksheets("Sheet1")     'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False                       'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False

End Sub

How to trigger an event after using event.preventDefault()

A more recent answer skillfully uses jQuery.one()

$('form').one('submit', function(e) {
    e.preventDefault();
    // do your things ...

    // and when you done:
    $(this).submit();
});

https://stackoverflow.com/a/41440902/510905

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

I am also facing the same issue and i resolve it by putting web.xml file and the applicationcontext.xml file in WEB-INF folder.

Hope this helps :)

What is the difference between Cloud Computing and Grid Computing?

There are a lot of good answers to this question already but another way to take a look at it is the cloud (ala Amazon's AWS) is good for interactive use cases and the grid (ala High Performance Computing) is good for batch use cases.

Cloud is interactive in that you can get resources on demand via self service. The code you run on VMs in the cloud, such as the Apache web server, can server clients interactively.

Grid is batch in that you submit jobs to a job queue after obtaining the credentials from some HPC authority to do so. The code you run on the grid waits in that queue until there are sufficient resources to execute it.

There are good use cases for both styles of computing.

Add a border outside of a UIView (instead of inside)

I liked solution of @picciano & @Maksim Kniazev. We can also create annular border with following:

func addExternalAnnularBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.white) {
    let externalBorder = CALayer()
    externalBorder.frame = CGRect(x: -borderWidth*2, y: -borderWidth*2, width: frame.size.width + 4 * borderWidth, height: frame.size.height + 4 * borderWidth)
    externalBorder.borderColor = borderColor.cgColor
    externalBorder.borderWidth = borderWidth
    externalBorder.cornerRadius = (frame.size.width + 4 * borderWidth) / 2
    externalBorder.name = Constants.ExternalBorderName
    layer.insertSublayer(externalBorder, at: 0)
    layer.masksToBounds = false
}

Multiple Updates in MySQL

There is a setting you can alter called 'multi statement' that disables MySQL's 'safety mechanism' implemented to prevent (more than one) injection command. Typical to MySQL's 'brilliant' implementation, it also prevents user from doing efficient queries.

Here (http://dev.mysql.com/doc/refman/5.1/en/mysql-set-server-option.html) is some info on the C implementation of the setting.

If you're using PHP, you can use mysqli to do multi statements (I think php has shipped with mysqli for a while now)

$con = new mysqli('localhost','user1','password','my_database');
$query = "Update MyTable SET col1='some value' WHERE id=1 LIMIT 1;";
$query .= "UPDATE MyTable SET col1='other value' WHERE id=2 LIMIT 1;";
//etc
$con->multi_query($query);
$con->close();

Hope that helps.

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

How I would write it:

var left: Node? = null

fun show() {
     val left = left ?: return
     queue.add(left) // no error because we return if it is null
}

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

Create a one to many relationship using SQL Server

This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.

You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:

enter image description here

In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.

I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.

You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:

Foreign key constraint

The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID column. In the right grid, select the CustomerID column. Close the dialog, and the next. Press Ctrl+S to save.

Having this constraint will ensure that no Order records can exist without an accompanying Customer record.

To effectively query a database like this, you might want to read up on JOINs.

Python timedelta in years

Late to the party, but this will give you the age (in years) accurately and easily:

b = birthday
today = datetime.datetime.today()
age = today.year - b.year + (today.month - b.month > 0 or 
                             (today.month == b.month > 0 and 
                              today.day - b.day > 0))

Convert Datetime column from UTC to local time in select statement

You have to reformat the string as well as converting to the correct time. In this case I needed Zulu time.

Declare @Date datetime;
Declare @DateString varchar(50);
set @Date = GETDATE(); 
declare @ZuluTime datetime;

Declare @DateFrom varchar (50);
Declare @DateTo varchar (50);
set @ZuluTime = DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), @Date);
set @DateString =  FORMAT(@ZuluTime, 'yyyy-MM-ddThh:mm:ssZ', 'en-US' )  
select @DateString;

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

As far as I can see, all other answers so far used a collector to add elements to an existing stream. However, there's a shorter solution, and it works for both sequential and parallel streams. You can simply use the method forEachOrdered in combination with a method reference.

List<String> source = ...;
List<Integer> target = ...;

source.stream()
      .map(String::length)
      .forEachOrdered(target::add);

The only restriction is, that source and target are different lists, because you are not allowed to make changes to the source of a stream as long as it is processed.

Note that this solution works for both sequential and parallel streams. However, it does not benefit from concurrency. The method reference passed to forEachOrdered will always be executed sequentially.

How to use GNU Make on Windows?

While make itself is available as a standalone executable (gnuwin32.sourceforge.net package make), using it in a proper development environment means using msys2.

Git 2.24 (Q4 2019) illustrates that:

See commit 4668931, commit b35304b, commit ab7d854, commit be5d88e, commit 5d65ad1, commit 030a628, commit 61d1d92, commit e4347c9, commit ed712ef, commit 5b8f9e2, commit 41616ef, commit c097b95 (04 Oct 2019), and commit dbcd970 (30 Sep 2019) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 6d5291b, 15 Oct 2019)

test-tool run-command: learn to run (parts of) the testsuite

Signed-off-by: Johannes Schindelin

Git for Windows jumps through hoops to provide a development environment that allows to build Git and to run its test suite.

To that end, an entire MSYS2 system, including GNU make and GCC is offered as "the Git for Windows SDK".
It does come at a price: an initial download of said SDK weighs in with several hundreds of megabytes, and the unpacked SDK occupies ~2GB of disk space.

A much more native development environment on Windows is Visual Studio. To help contributors use that environment, we already have a Makefile target vcxproj that generates a commit with project files (and other generated files), and Git for Windows' vs/master branch is continuously re-generated using that target.

The idea is to allow building Git in Visual Studio, and to run individual tests using a Portable Git.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

1)check the package name is the same in google-services.json file

2)make sure that no other project exist with same package name

3)make sure that there is internet access

4)try syncing project and running it again

variable or field declared void

It for example happens in this case here:

void initializeJSP(unknownType Experiment);

Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.

How to run crontab job every week on Sunday

The crontab website gives the real time results display: https://crontab.guru/#5_8_*_*_0

enter image description here

How can I insert vertical blank space into an html document?

write it like this

p {
    padding-bottom: 3cm;
}

or

p {
    margin-bottom: 3cm;
}

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

What is the default scope of a method in Java?

If you are not giving any modifier to your method then as default it will be Default modifier which has scope within package.
for more info you can refer http://wiki.answers.com/Q/What_is_default_access_specifier_in_Java

SyntaxError: unexpected EOF while parsing

The SyntaxError: unexpected EOF while parsing means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100): and requires at least one line afterwards that contains code that should be in it.

It seems like you were executing your program line by line in the ipython console. This works for single statements like a = 3 but not for code blocks like for loops. See the following example:

In [1]: for i in range(100):
  File "<ipython-input-1-ece1e5c2587f>", line 1
    for i in range(100):
                        ^
SyntaxError: unexpected EOF while parsing

To avoid this error, you have to enter the whole code block as a single input:

In [2]: for i in range(5):
   ...:     print(i, end=', ')
0, 1, 2, 3, 4,

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

How do I install Keras and Theano in Anaconda Python on Windows?

In windows environment with Anconda. Go to anconda prompt from start. Then if you are behind proxy then .copndarc file needs to eb updated with the proxy details.

ssl_verify: false channels: - defaults proxy_servers: http: http://xx.xx.xx.xx:xxxx https: https://xx.xx.xx.xx:xxxx

I had ssl_verify initially marked as 'True' then I was getting ssl error. So i turned it to false as above and then ran the below commands

conda update conda conda update --all conda install --channel https://conda.anaconda.org/conda-forge keras conda install --channel https://conda.anaconda.org/conda-forge tensorflow

My python version is 3.6.7

How can I reverse a NSArray in Objective-C?

As for me, have you considered how the array was populated in the first place? I was in the process of adding MANY objects to an array, and decided to insert each one at the beginning, pushing any existing objects up by one. Requires a mutable array, in this case.

NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithCapacity:1];
[myMutableArray insertObject:aNewObject atIndex:0];

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

  1. The optimal solution could be to try to transform your solution into a form where you don't need to have two readers open at a time. Ideally it could be a single query. I don't have time to do that now.
  2. If your problem is so special that you really need to have more readers open simultaneously, and your requirements allow not older than SQL Server 2005 DB backend, then the magic word is MARS (Multiple Active Result Sets). http://msdn.microsoft.com/en-us/library/ms345109%28v=SQL.90%29.aspx. Bob Vale's linked topic's solution shows how to enable it: specify MultipleActiveResultSets=true in your connection string. I just tell this as an interesting possibility, but you should rather transform your solution.

    • in order to avoid the mentioned SQL injection possibility, set the parameters to the SQLCommand itself instead of embedding them into the query string. The query string should only contain the references to the parameters what you pass into the SqlCommand.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

In my case, I was getting this error in AndroidStudio 4.1.1 while updating compileSdkVersion to 29.

If you are having dependent project in build.gradle, All you need to do is Update same compileSdkVersion in dependent project's build.gradle as well.

Steps:

  1. Click on your app folder in Project view of AndroidStudio.
  2. Select Open Module Settings.
  3. In Project Structure >> Check how many modules are there?
  4. If there are more than one modules, you will have to update compileSdkVersion, buildToolsVersion & Project dependency as well.

That worked for me :)

Append data to a POST NSURLRequest

Any one looking for a swift solution

let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)

"Active Directory Users and Computers" MMC snap-in for Windows 7?

Per Noalt's answer is correct. However, if you want the snap-in mentioned in the title (Users and Computers), you'll also have to run these commands at a command-line afterwards, as an Administrator:

dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-SnapIns

Note - I had to run these in order for AD Users and Computers to show up, as they were disabled on my computer after the install. This might not be the case for all users.

Divide a number by 3 without using *, /, +, -, % operators

How about this approach (c#)?

private int dividedBy3(int n) {
        List<Object> a = new Object[n].ToList();
        List<Object> b = new List<object>();
        while (a.Count > 2) {
            a.RemoveRange(0, 3);
            b.Add(new Object());
        }
        return b.Count;
    }

gdb: how to print the current line or find the current line number?

All the answers above are correct, What I prefer is to use tui mode (ctrl+X A or 'tui enable') which shows your location and the function in a separate window which is very helpful for the users. Hope that helps too.

How to pass values arguments to modal.show() function in Bootstrap

You could do it like this:

<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>

Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:

$(document).ready(function(){
   $(".announce").click(function(){ // Click to only happen on announce links
     $("#cafeId").val($(this).data('id'));
     $('#createFormId').modal('show');
   });
});

Disable browsers vertical and horizontal scrollbars

So far we have overflow:hidden on the body. However IE doesn't always honor that and you need to put scroll="no" on the body element as well and/or place overflow:hidden on the html element as well.

You can take this further when you need to 'take control' of the view port you can do this:-

<style>
 body {width:100%; height:100%; overflow:hidden; margin:0; }
 html {width:100%; height:100%; overflow:hidden; }
</style>

An element granted height 100% in the body has the full height of the window viewport, and element positioned absolutely using bottom:nnPX will be set nn pixels above the bottom edge of the window, etc.

PL/SQL, how to escape single quote in a string?

In addition to DCookie's answer above, you can also use chr(39) for a single quote.

I find this particularly useful when I have to create a number of insert/update statements based on a large amount of existing data.

Here's a very quick example:

Lets say we have a very simple table, Customers, that has 2 columns, FirstName and LastName. We need to move the data into Customers2, so we need to generate a bunch of INSERT statements.

Select 'INSERT INTO Customers2 (FirstName, LastName) ' ||
       'VALUES (' || chr(39) || FirstName || chr(39) ',' || 
       chr(39) || LastName || chr(39) || ');' From Customers;

I've found this to be very useful when moving data from one environment to another, or when rebuilding an environment quickly.

How to use a variable for the database name in T-SQL?

Unfortunately you can't declare database names with a variable in that format.

For what you're trying to accomplish, you're going to need to wrap your statements within an EXEC() statement. So you'd have something like:

DECLARE @Sql varchar(max) ='CREATE DATABASE ' + @DBNAME

Then call

EXECUTE(@Sql) or sp_executesql(@Sql)

to execute the sql string.

Random alpha-numeric string in JavaScript?

Random character:

String.fromCharCode(i); //where is an int

Random int:

Math.floor(Math.random()*100);

Put it all together:

function randomNum(hi){
    return Math.floor(Math.random()*hi);
} 
function randomChar(){
    return String.fromCharCode(randomNum(100));
}
function randomString(length){
   var str = "";
   for(var i = 0; i < length; ++i){
        str += randomChar();
   }
   return str;
}
var RandomString = randomString(32); //32 length string

Fiddle: http://jsfiddle.net/maniator/QZ9J2/

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

And if you simply want to cut part of a file - say from line 26 to 142 - and input it to a newfile : cat file-to-cut.txt | sed -n '26,142p' >> new-file.txt

Make footer stick to bottom of page using Twitter Bootstrap

just add the class navbar-fixed-bottom to your footer.

<div class="footer navbar-fixed-bottom">

Update for Bootstrap 4 -

as mentioned by Sara Tibbetts - class is fixed-bottom

<div class="footer fixed-bottom">

How to determine equality for two JavaScript objects?

In Node.js, you can use its native require("assert").deepStrictEqual. More info: http://nodejs.org/api/assert.html

For example:

var assert = require("assert");
assert.deepStrictEqual({a:1, b:2}, {a:1, b:3}); // will throw AssertionError

Another example that returns true / false instead of returning errors:

var assert = require("assert");

function deepEqual(a, b) {
    try {
      assert.deepEqual(a, b);
    } catch (error) {
      if (error.name === "AssertionError") {
        return false;
      }
      throw error;
    }
    return true;
};

how to execute php code within javascript

You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:

alert("<?php echo "asdasda";?>");

don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

$.ajax({
  url: 'test.php',
  success: function(data) {
    $('.result').html(data);
  }
});

and test.php would be:

<?php 
  echo 'asdasda';
?>

it would write the contents of test.php to whatever element has the result class.

Pointer-to-pointer dynamic two-dimensional array

The first method cannot be used to create dynamic 2D arrays because by doing:

int *board[4];

you essentially allocated an array of 4 pointers to int on stack. Therefore, if you now populate each of these 4 pointers with a dynamic array:

for (int i = 0; i < 4; ++i) {
  board[i] = new int[10];
}

what you end-up with is a 2D array with static number of rows (in this case 4) and dynamic number of columns (in this case 10). So it is not fully dynamic because when you allocate an array on stack you should specify a constant size, i.e. known at compile-time. Dynamic array is called dynamic because its size is not necessary to be known at compile-time, but can rather be determined by some variable in runtime.

Once again, when you do:

int *board[4];

or:

const int x = 4; // <--- `const` qualifier is absolutely needed in this case!
int *board[x];

you supply a constant known at compile-time (in this case 4 or x) so that compiler can now pre-allocate this memory for your array, and when your program is loaded into the memory it would already have this amount of memory for the board array, that's why it is called static, i.e. because the size is hard-coded and cannot be changed dynamically (in runtime).

On the other hand, when you do:

int **board;
board = new int*[10];

or:

int x = 10; // <--- Notice that it does not have to be `const` anymore!
int **board;
board = new int*[x];

the compiler does not know how much memory board array will require, and therefore it does not pre-allocate anything. But when you start your program, the size of array would be determined by the value of x variable (in runtime) and the corresponding space for board array would be allocated on so-called heap - the area of memory where all programs running on your computer can allocate unknown beforehand (at compile-time) amounts memory for personal usage.

As a result, to truly create dynamic 2D array you have to go with the second method:

int **board;
board = new int*[10]; // dynamic array (size 10) of pointers to int

for (int i = 0; i < 10; ++i) {
  board[i] = new int[10];
  // each i-th pointer is now pointing to dynamic array (size 10) of actual int values
}

We've just created an square 2D array with 10 by 10 dimensions. To traverse it and populate it with actual values, for example 1, we could use nested loops:

for (int i = 0; i < 10; ++i) {   // for each row
  for (int j = 0; j < 10; ++j) { // for each column
    board[i][j] = 1;
  }
}

How to identify server IP address in PHP

I just created a simple script that will bring back the $_SERVER['REMOTE_ADDR'] and $_SERVER['SERVER_ADDR'] in IIS so you don't have to change every variable. Just paste this text in your php file that is included in every page.

/** IIS IP Check **/
if(!$_SERVER['SERVER_ADDR']){ $_SERVER['SERVER_ADDR'] = $_SERVER['LOCAL_ADDR']; }
if(!$_SERVER['REMOTE_ADDR']){ $_SERVER['REMOTE_ADDR'] = $_SERVER['LOCAL_ADDR']; }

jQuery AutoComplete Trigger Change Event

Well it works for me just binding a keypress event to the search input, like this:

... Instantiate your autofill here...

    $("#CompanyList").bind("keypress", function(){
    if (nowDoing==1) {
        nowDoing = 0;
        $('#form_459174').clearForm();
    }        
});

How do multiple clients connect simultaneously to one port, say 80, on a server?

TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port

So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.

Intuitively (and wrongly), most people assume that it looks something like this:

    Local Computer    | Remote Computer
    --------------------------------
    <local_ip>:80     | <foreign_ip>:80

    ^^ not actually what happens, but this is the conceptual model a lot of people have in mind.

This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.

Three things must be understood:

1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.

2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.

3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.

So, this is really what gets created when a client connects to a server:

    Local Computer   | Remote Computer           | Role
    -----------------------------------------------------------
    0.0.0.0:80       | <none>                    | LISTENING
    127.0.0.1:80     | 10.1.2.3:<random_port>    | ESTABLISHED

Looking at What Actually Happens

First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).

    netstat -atnp | grep -i ":500 "

As expected, the output is blank. Now let's start a web server:

    sudo python3 -m http.server 500

Now, here is the output of running netstat again:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      - 

So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all". An easy mistake to make is to listen on address 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.

So now, let's connect a user to our machine:

    quicknet -m tcp -t localhost:500 -p Test payload.

This is a simple script (https://github.com/grokit/dcore/tree/master/apps/quicknet) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:54240      ESTABLISHED -

If you connect with another client and do netstat again, you will see the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:26813      ESTABLISHED -

... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.

Unit Testing: DateTime.Now

I'm surprised no one has suggested one of the most obvious ways to go:

public class TimeDependentClass
{
    public void TimeDependentMethod(DateTime someTime)
    {
        if (GetCurrentTime() > someTime) DoSomething();
    }

    protected virtual DateTime GetCurrentTime()
    {
        return DateTime.Now; // or UtcNow
    }
}

Then you can simply override this method in your test double.

I also kind of like injecting a TimeProvider class in some cases, but for others, this is more than enough. I'd probably favor the TimeProvider version if you need to reuse this in several classes though.

EDIT: For anyone interested, this is called adding a "seam" to your class, a point where you can hook in to it's behavior to modify it (for testing purposes or otherwise) without actually having to change the code in the class.

How can I get a vertical scrollbar in my ListBox?

I added a "Height" to my ListBox and it added the scrollbar nicely.

Change default icon

The Icon property for a project specifies the icon file (.ico) that will be displayed for the compiled application in Windows Explorer and in the Windows taskbar.

The Icon property can be accessed in the Application pane of the Project Designer; it contains a list of icons that have been added to a project either as resources or as content files.

To specify an application icon

  1. With a project selected in Solution Explorer, on the Project menu click Properties.
  2. Select the Application pane.
  3. Select an icon (.ico) file from the Icon drop-down list.

To specify an application icon and add it to your project

  1. With a project selected in Solution Explorer, on the Project menu, click Properties.
  2. Select the Application pane.
  3. Select Browse from the Icon drop-down list and browse to the location of the icon file that you want.

The icon file is added to your project as a content file and can be seen on top left corner.

And if you want to show separate icons for every form you have to go to each form's properties, select icon attribute and browse for an icon you want.

Here's MSDN link for the same purpose...

Hope this helps.