Programs & Examples On #Noise

Noise is random variation in a signal, for example errors in measurements of the position of a moving object.

Random / noise functions for GLSL

Please see below an example how to add white noise to the rendered texture. The solution is to use two textures: original and pure white noise, like this one: wiki white noise

private static final String VERTEX_SHADER =
    "uniform mat4 uMVPMatrix;\n" +
    "uniform mat4 uMVMatrix;\n" +
    "uniform mat4 uSTMatrix;\n" +
    "attribute vec4 aPosition;\n" +
    "attribute vec4 aTextureCoord;\n" +
    "varying vec2 vTextureCoord;\n" +
    "varying vec4 vInCamPosition;\n" +
    "void main() {\n" +
    "    vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
    "    gl_Position = uMVPMatrix * aPosition;\n" +
    "}\n";

private static final String FRAGMENT_SHADER =
        "precision mediump float;\n" +
        "uniform sampler2D sTextureUnit;\n" +
        "uniform sampler2D sNoiseTextureUnit;\n" +
        "uniform float uNoseFactor;\n" +
        "varying vec2 vTextureCoord;\n" +
        "varying vec4 vInCamPosition;\n" +
        "void main() {\n" +
                "    gl_FragColor = texture2D(sTextureUnit, vTextureCoord);\n" +
                "    vec4 vRandChosenColor = texture2D(sNoiseTextureUnit, fract(vTextureCoord + uNoseFactor));\n" +
                "    gl_FragColor.r += (0.05 * vRandChosenColor.r);\n" +
                "    gl_FragColor.g += (0.05 * vRandChosenColor.g);\n" +
                "    gl_FragColor.b += (0.05 * vRandChosenColor.b);\n" +
        "}\n";

The fragment shared contains parameter uNoiseFactor which is updated on every rendering by main application:

float noiseValue = (float)(mRand.nextInt() % 1000)/1000;
int noiseFactorUniformHandle = GLES20.glGetUniformLocation( mProgram, "sNoiseTextureUnit");
GLES20.glUniform1f(noiseFactorUniformHandle, noiseFactor);

Load resources from relative path using local html in uiwebview

This is how to load/use a local html with relative references.

  1. Drag the resource into your xcode project (I dragged a folder named www from my finder window), you will get two options "create groups for any added folders" and "create folders references for any added folders".
  2. Select the "create folder references.." option.
  3. Use the below given code. It should work like a charm.

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];

Now all your relative links(like img/.gif, js/.js) in the html should get resolved.

Swift 3

    if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
        webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
    }

Java: Best way to iterate through a Collection (here ArrayList)

The first option is better performance wise (As ArrayList implement RandomAccess interface). As per the java doc, a List implementation should implement RandomAccess interface if, for typical instances of the class, this loop:

 for (int i=0, n=list.size(); i < n; i++)
     list.get(i);

runs faster than this loop:

 for (Iterator i=list.iterator(); i.hasNext(); )
     i.next();

I hope it helps. First option would be slow for sequential access lists.

How to add a column in TSQL after a specific column?

This is absolutely possible. Although you shouldn't do it unless you know what you are dealing with. Took me about 2 days to figure it out. Here is a stored procedure where i enter: ---database name (schema name is "_" for readability) ---table name ---column ---column data type (column added is always null, otherwise you won't be able to insert) ---the position of the new column.

Since I'm working with tables from SAM toolkit (and some of them have > 80 columns) , the typical variable won't be able to contain the query. That forces the need of external file. Now be careful where you store that file and who has access on NTFS and network level.

Cheers!

USE [master]
GO
/****** Object:  StoredProcedure [SP_Set].[TrasferDataAtColumnLevel]    Script Date: 8/27/2014 2:59:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SP_Set].[TrasferDataAtColumnLevel]
(
    @database varchar(100),
    @table varchar(100),
    @column varchar(100),
    @position int,
    @datatype varchar(20)    
)
AS
BEGIN
set nocount on
exec  ('
declare  @oldC varchar(200), @oldCDataType varchar(200), @oldCLen int,@oldCPos int
create table Test ( dummy int)
declare @columns varchar(max) = ''''
declare @columnVars varchar(max) = ''''
declare @columnsDecl varchar(max) = ''''
declare @printVars varchar(max) = ''''

DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR 
select column_name, data_type, character_maximum_length, ORDINAL_POSITION  from ' + @database + '.INFORMATION_SCHEMA.COLUMNS where table_name = ''' + @table + '''
OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos WHILE @@FETCH_STATUS = 0 BEGIN

if(@oldCPos = ' + @position + ')
begin
    exec(''alter table Test add [' + @column + '] ' + @datatype + ' null'')
end

if(@oldCDataType != ''timestamp'')
begin

    set @columns += @oldC + '' , '' 
    set @columnVars += ''@'' + @oldC + '' , ''

    if(@oldCLen is null)
    begin
        if(@oldCDataType != ''uniqueidentifier'')
        begin
            set @printVars += '' print convert('' + @oldCDataType + '',@'' + @oldC + '')'' 
            set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', '' 
            exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
        end
        else
        begin
            set @printVars += '' print convert(varchar(50),@'' + @oldC + '')'' 
            set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', '' 
            exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
        end
    end
    else
    begin 
        if(@oldCLen < 0)
        begin
            set @oldCLen = 4000
        end
        set @printVars += '' print @'' + @oldC 
        set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + ''('' + convert(character,@oldCLen) + '') , '' 
        exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + ''('' + @oldCLen + '') null'')
    end
end

if exists (select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = ''Test'' and column_name = ''dummy'')
begin
    alter table Test drop column dummy
end

FETCH NEXT FROM MY_CURSOR INTO  @oldC, @oldCDataType, @oldCLen, @oldCPos END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR

set @columns = reverse(substring(reverse(@columns), charindex('','',reverse(@columns)) +1, len(@columns)))
set @columnVars = reverse(substring(reverse(@columnVars), charindex('','',reverse(@columnVars)) +1, len(@columnVars)))
set @columnsDecl = reverse(substring(reverse(@columnsDecl), charindex('','',reverse(@columnsDecl)) +1, len(@columnsDecl)))
set @columns = replace(replace(REPLACE(@columns, ''       '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnVars = replace(replace(REPLACE(@columnVars, ''       '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnsDecl = replace(replace(REPLACE(@columnsDecl, ''  '', ''''), char(9) + char(9),'' ''),char(9), '''')
set @printVars = REVERSE(substring(reverse(@printVars), charindex(''+'',reverse(@printVars))+1, len(@printVars))) 

create table query (id int identity(1,1), string varchar(max))

insert into query values  (''declare '' + @columnsDecl + ''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR '')

insert into query values   (''select '' + @columns + '' from ' + @database + '._.' + @table + ''')

insert into query values  (''OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' WHILE @@FETCH_STATUS = 0 BEGIN '')

insert into query values   (@printVars )

insert into query values   ( '' insert into Test ('')
insert into query values   (@columns) 
insert into query values   ( '') values ( '' + @columnVars + '')'')

insert into query values  (''FETCH NEXT FROM MY_CURSOR INTO  '' + @columnVars + '' END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR'')

declare @path varchar(100) = ''C:\query.sql''
declare @query varchar(500) = ''bcp "select string from query order by id" queryout '' + @path + '' -t, -c -S  '' + @@servername +  '' -T''

exec master..xp_cmdshell @query

set @query  = ''sqlcmd -S '' + @@servername + '' -i '' + @path

EXEC xp_cmdshell  @query

set @query = ''del ''  + @path

exec xp_cmdshell @query

drop table ' + @database + '._.' + @table + '

select * into ' + @database + '._.' + @table + ' from Test 

drop table query
drop table Test  ')

END

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b

Note the difference is.nan when it's a matrix vs. is.na when it's a data frame.

Doing

#...
b[is.nan(b)] <- 0
#...

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

How to get a random number between a float range?

Use random.uniform(a, b):

>>> random.uniform(1.5, 1.9)
1.8733202628557872

Round double value to 2 decimal places

For Swift there is a simple solution if you can't either import Foundation, use round() and/or does not want a String (usually the case when you're in Playground):

var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0

result: 31.726

How to have multiple CSS transitions on an element?

It's possible to make the multiple transitions set with different values for duration, delay and timing function. To split different transitions use ,

button{
  transition: background 1s ease-in-out 2s, width 2s linear;
  -webkit-transition: background 1s ease-in-out 2s, width 2s linear; /* Safari */
}

Reference: https://kolosek.com/css-transition/

Error:Unable to locate adb within SDK in Android Studio

if you have adb problem go to tools->sdk manager -> install missed sdk tools

my problem was solved using these way

indexOf method in an object array?

I will prefer to use findIndex() method:

 var index = myArray.findIndex('hello','stevie');

index will give you the index number.

How to subtract X days from a date using Java calendar?

Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.

FYI in Joda Time you could do

DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);

How to iterate over the keys and values with ng-repeat in AngularJS?

I don't think there's a builtin function in angular for doing this, but you can do this by creating a separate scope property containing all the header names, and you can fill this property automatically like this:

var data = {
  foo: 'a',
  bar: 'b'
};

$scope.objectHeaders = [];

for ( property in data ) {
  $scope.objectHeaders.push(property); 
}

// Output: [ 'foo', 'bar' ]

C++ queue - simple example

std::queue<myclass*> that's it

Regex to get string between curly braces

Try

/{(.*?)}/

That means, match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops * being greedy). The parentheses let you extract the matched portion.

Another way would be

/{([^}]*)}/

This matches any character except a } char (another way of not being greedy)

Renaming columns in Pandas

Since you only want to remove the $ sign in all column names, you could just do:

df = df.rename(columns=lambda x: x.replace('$', ''))

OR

df.rename(columns=lambda x: x.replace('$', ''), inplace=True)

Get selected value in dropdown list using JavaScript

Another solution is:

document.getElementById('elementId').selectedOptions[0].value

Angular cli generate a service and include the provider in one step

run the below code in Terminal

makesure You are inside your project folder in terminal

ng g s servicename --module=app.module

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

Highcharts - how to have a chart with dynamic height?

Alternatively, you can directly use javascript's window.onresize

As example, my code (using scriptaculos) is :

window.onresize = function (){
    var w = $("form").getWidth() + "px";
    $('gfx').setStyle( { width : w } );
}

Where form is an html form on my webpage and gfx the highchart graphics.

How to easily initialize a list of Tuples?

c# 7.0 lets you do this:

  var tupleList = new List<(int, string)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

If you don't need a List, but just an array, you can do:

  var tupleList = new(int, string)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

And if you don't like "Item1" and "Item2", you can do:

  var tupleList = new List<(int Index, string Name)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

or for an array:

  var tupleList = new (int Index, string Name)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

which lets you do: tupleList[0].Index and tupleList[0].Name

Framework 4.6.2 and below

You must install System.ValueTuple from the Nuget Package Manager.

Framework 4.7 and above

It is built into the framework. Do not install System.ValueTuple. In fact, remove it and delete it from the bin directory.

note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.

Container is running beyond memory limits

While working with spark in EMR I was having the same problem and setting maximizeResourceAllocation=true did the trick; hope it helps someone. You have to set it when you create the cluster. From the EMR docs:

aws emr create-cluster --release-label emr-5.4.0 --applications Name=Spark \
--instance-type m3.xlarge --instance-count 2 --service-role EMR_DefaultRole --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole --configurations https://s3.amazonaws.com/mybucket/myfolder/myConfig.json

Where myConfig.json should say:

[
  {
    "Classification": "spark",
    "Properties": {
      "maximizeResourceAllocation": "true"
    }
  }
]

Find size of object instance in bytes in c#

For anyone looking for a solution that doesn't require [Serializable] classes and where the result is an approximation instead of exact science. The best method I could find is json serialization into a memorystream using UTF32 encoding.

private static long? GetSizeOfObjectInBytes(object item)
{
    if (item == null) return 0;
    try
    {
        // hackish solution to get an approximation of the size
        var jsonSerializerSettings = new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateTimeZoneHandling = DateTimeZoneHandling.Utc,
            MaxDepth = 10,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };
        var formatter = new JsonMediaTypeFormatter { SerializerSettings = jsonSerializerSettings };
        using (var stream = new MemoryStream()) { 
            formatter.WriteToStream(item.GetType(), item, stream, Encoding.UTF32);
            return stream.Length / 4; // 32 bits per character = 4 bytes per character
        }
    }
    catch (Exception)
    {
        return null;
    }
}

No, this won't give you the exact size that would be used in memory. As previously mentioned, that is not possible. But it'll give you a rough estimation.

Note that this is also pretty slow.

How do I set the selenium webdriver get timeout?

The solution of driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS) will work on the pages with synch loading. This does not solve, however, the problem on pages loading stuff in async, then the tests will fail all the time if we set the pageLoadTimeOut.

Google Chrome Full Black Screen

i have resolved this by following steps.

1) Go to customise icon in the top right corner chrome.
2) click on more tools option.
3) Click task manager.
4) Kill/end process GPU process

This has resolved my issue of black screen in chrome.

ImportError: No module named 'Queue'

It's because of the Python version. In Python 3 it's import Queue as queue; on the contrary in Python 2.x it's import queue. If you want it for both environments you may use something below as mentioned here

try:
   import queue
except ImportError:
   import Queue as queue

Console.WriteLine does not show up in Output window

When issue happening on Mac VS 2017 (Which I faced).

  1. Go to Project >> "Your Project name" options.
  2. An option window will pop up
  3. Go to RUN >> Default menu option
  4. Tick the "Run on external console" option TRUE and say OK

Run your application code now.

How to set a default value for an existing column

Hoodaticus's solution was perfect, thank you, but I also needed it to be re-runnable and found this way to check if it had been done...

IF EXISTS(SELECT * FROM information_schema.columns 
           WHERE table_name='myTable' AND column_name='myColumn' 
             AND Table_schema='myDBO' AND column_default IS NULL) 
BEGIN 
  ALTER TABLE [myDBO].[myTable] ADD DEFAULT 0 FOR [myColumn] --Hoodaticus
END

How to get a float result by dividing two integer values using T-SQL?

Because SQL Server performs integer division. Try this:

select 1 * 1.0 / 3

This is helpful when you pass integers as params.

select x * 1.0 / y

Using find to locate files that match one of multiple patterns

I had a similar need. This worked for me:

find ../../ \( -iname 'tmp' -o -iname 'vendor' \) -prune -o \( -iname '*.*rb' -o -iname '*.rjs' \) -print

href="javascript:" vs. href="javascript:void(0)"

Using 'javascript:void 0' will do cause problem in IE

when you click the link, it will trigger onbeforeunload event of window !

<!doctype html>
<html>
<head>
</head>
<body>
<a href="javascript:void(0);" >Click me!</a>
<script>
window.onbeforeunload = function() {
    alert( 'oops!' );
};
</script>
</body>
</html>

How do I convert from a money datatype in SQL server?

You can try like this:

SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)

Linking dll in Visual Studio

I find it useful to understand the underlying tools. These are cl.exe (compiler) and link.exe (linker). You need to tell the compiler the signatures of the functions you want to call in the dynamic library (by including the library's header) and you need to tell the linker what the library is called and how to call it (by including the "implib" or import library).

This is roughly the same process gcc uses for linking to dynamic libraries on *nix, only the library object file differs.

Knowing the underlying tools means you can more quickly find the appropriate settings in the IDE and allows you to check that the commandlines generated are correct.

Example

Say A.exe depends B.dll. You need to include B's header in A.cpp (#include "B.h") then compile and link with B.lib:

cl A.cpp /c /EHsc
link A.obj B.lib

The first line generates A.obj, the second generates A.exe. The /c flag tells cl not to link and /EHsc specifies what kind of C++ exception handling the binary should use (there's no default, so you have to specify something).

If you don't specify /c cl will call link for you. You can use the /link flag to specify additional arguments to link and do it all at once if you like:

cl A.cpp /EHsc /link B.lib

If B.lib is not on the INCLUDE path you can give a relative or absolute path to it or add its parent directory to your include path with the /I flag.

If you're calling from cygwin (as I do) replace the forward slashes with dashes.

If you write #pragma comment(lib, "B.lib") in A.cpp you're just telling the compiler to leave a comment in A.obj telling the linker to link to B.lib. It's equivalent to specifying B.lib on the link commandline.

Calculate AUC in R?

Combining code from ISL 9.6.3 ROC Curves, along with @J. Won.'s answer to this question and a few more places, the following plots the ROC curve and prints the AUC in the bottom right on the plot.

Below probs is a numeric vector of predicted probabilities for binary classification and test$label contains the true labels of the test data.

require(ROCR)
require(pROC)

rocplot <- function(pred, truth, ...) {
  predob = prediction(pred, truth)
  perf = performance(predob, "tpr", "fpr")
  plot(perf, ...)
  area <- auc(truth, pred)
  area <- format(round(area, 4), nsmall = 4)
  text(x=0.8, y=0.1, labels = paste("AUC =", area))

  # the reference x=y line
  segments(x0=0, y0=0, x1=1, y1=1, col="gray", lty=2)
}

rocplot(probs, test$label, col="blue")

This gives a plot like this:

enter image description here

how to mysqldump remote db from local machine

Bassed on this page here:

Compare two MySQL databases

I modified it so you can use ddbb in diferent hosts.


#!/bin/sh

echo "Usage: dbdiff [user1:pass1@dbname1:host] [user2:pass2@dbname2:host] [ignore_table1:ignore_table2...]"

dump () {
  up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
  mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname -h $host $table > $2
}

rm -f /tmp/db.diff

# Compare
up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
for table in `mysql -u $user -p$pass $dbname -h $host -N -e "show tables" --batch`; do
  if [ "`echo $3 | grep $table`" = "" ]; then
    echo "Comparing '$table'..."
    dump $1 /tmp/file1.sql
    dump $2 /tmp/file2.sql
    diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff
  else
    echo "Ignored '$table'..."
  fi
done
less /tmp/db.diff
rm -f /tmp/file1.sql /tmp/file2.sql

TSQL Default Minimum DateTime

I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1/1/1753'
)

:before and background-image... should it work?

you can set an image URL for the content prop instead of the background-image.

content: url(/img/border-left3.png);

How to call URL action in MVC with javascript function?

Within your onDropDownChange handler, just make a jQuery AJAX call, passing in any data you need to pass up to your URL. You can handle successful and failure calls with the success and error options. In the success option, use the data contained in the data argument to do whatever rendering you need to do. Remember these are asynchronous by default!

function onDropDownChange(e) {
    var url = '/Home/Index/' + e.value;
    $.ajax({
      url: url,
      data: {}, //parameters go here in object literal form
      type: 'GET',
      datatype: 'json',
      success: function(data) { alert('got here with data'); },
      error: function() { alert('something bad happened'); }
    });
}

jQuery's AJAX documentation is here.

When to favor ng-if vs. ng-show/ng-hide?

ng-if on ng-include and on ng-controller will have a big impact matter on ng-include it will not load the required partial and does not process unless flag is true on ng-controller it will not load the controller unless flag is true but the problem is when a flag gets false in ng-if it will remove from DOM when flag gets true back it will reload the DOM in this case ng-show is better, for one time show ng-if is better

Git: force user and password prompt

Addition to third answer: If you're using non-english Windows, you can find "Credentials Manager" through "Control panel" > "User Accounts" > "Credentials Manager" Icon of Credentials Manager

Include an SVG (hosted on GitHub) in MarkDown

The purpose of raw.github.com is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.

When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.

Examples

All of the ways stated below will work.

I copied the SVG image from the question to a repo on github in order to create the examples below

Linking to files using relative paths (Works, but obviously only on github.com / github.io)

Code

![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">

Result

See the working example on github.com.

Linking to RAW files

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text

Linking to RAW files using ?sanitize=true

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">

Result

Alt text

Linking to files hosted on github.io

Code

![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text


Some comments regarding changes that happened along the way:

  • Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>) are removed.

    To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true to the SVG's raw URL.

  • As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.

  • The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017

Combination of async function + await + setTimeout

The quick one-liner, inline way

 await new Promise(resolve => setTimeout(resolve, 1000));

How do I make the text box bigger in HTML/CSS?

there are many options that would change the height of an input box. padding, font-size, height would all do this. different combinations of these produce taller input boxes with different styles. I suggest just changing the font-size (and font-family for looks) and add some padding to make it even taller and also more appealing. I will give you an example of all three style though:

#signin input {
font-size:20px;
}

OR

#signin input {
padding:10px;
}

OR

#signin input {
height:24px;
}

This is the combination of the three that I recommend:

#signin input {
font-size:20px;font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-weight: 300;
padding:10px;
}

How to get the selected date of a MonthCalendar control in C#

Using SelectionRange you will get the Start and End date.

private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
    var startDate = monthCalendar1.SelectionRange.Start.ToString("dd MMM yyyy");
    var endDate = monthCalendar1.SelectionRange.End.ToString("dd MMM yyyy");
}

If you want to update the maximum number of days that can be selected, then set MaxSelectionCount property. The default is 7.

// Only allow 21 days to be selected at the same time.
monthCalendar1.MaxSelectionCount = 21;

Border for an Image view in Android?

You can use 9 patch in Android Studio to make borders!

I was looking for a solution but I did not find any so I skipped that part.

Then I went to the Google images of Firebase assets and I accidentally discovered that they use 9patch.

9patch in action

Here's the link: https://developer.android.com/studio/write/draw9patch

You just need to drag where the edges are.

It's just like border edge in Unity.

Each for object?

_x000D_
_x000D_
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
  console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

//output
a: 1
b: 2

How to convert string to string[]?

A string holds one value, but a string[] holds many strings, as it's an array of string.

See more here

How do you transfer or export SQL Server 2005 data to Excel

Create the excel data source and insert the values,

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=D:\testing.xls;', 
'SELECT * FROM [SheetName$]') select * from SQLServerTable

More informations are available here http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this:

 Select 
    Id, 
    Salt, 
    Password, 
    BannedEndDate, 
    (Select Count(*) 
        From LoginFails 
        Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
 From Users 
 Where username = '" + LoginModel.Username + "'

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

Horizontal scroll css?

use max-width instead of width

max-width:530px;

demo:http://jsfiddle.net/FPBWr/161/

Wireshark vs Firebug vs Fiddler - pros and cons?

None of the above, if you are on a Mac. Use Charles Proxy. It's the best network/request information collecter that I have ever come across. You can view and edit all outgoing requests, and see the responses from those requests in several forms, depending on the type of the response. It costs 50 dollars for a license, but you can download the trial version and see what you think.

If your on Windows, then I would just stay with Fiddler.

Use basic authentication with jQuery and Ajax

Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.

$.ajaxSetup({
  headers: {
    'Authorization': "Basic XXXXX"
  }
});

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

Try remove lines of your theme:

<item name="android:windowIsTranslucent">true</item>

and

<item name="android:windowIsFloating">true</item>

after this, add android:screenOrientation="portrait" in your activity.

How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

Add a unique id to all your instances, i.e.

public interface Idable {
  int id();
}

public class IdGenerator {
  private static int id = 0;
  public static synchronized int generate() { return id++; }
}

public abstract class AbstractSomething implements Idable {
  private int id;
  public AbstractSomething () {
    this.id = IdGenerator.generate();
  }
  public int id() { return id; }
}

Extend from AbstractSomething and query this property. Will be safe inside a single vm (assuming no game playing with classloaders to get around statics).

How to add border around linear layout except at the bottom?

Save this xml and add as a background for the linear layout....

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <stroke android:width="4dp" android:color="#FF00FF00" /> 
    <solid android:color="#ffffff" /> 
    <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
    <corners android:radius="4dp" /> 
</shape>

Hope this helps! :)

How to word wrap text in HTML?

Try this

_x000D_
_x000D_
div{_x000D_
  display: block;_x000D_
  display: -webkit-box;_x000D_
  height: 20px;_x000D_
  margin: 3px auto;_x000D_
  font-size: 14px;_x000D_
  line-height: 1.4;_x000D_
  -webkit-line-clamp: 1;_x000D_
  -webkit-box-orient: vertical;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
_x000D_
_x000D_

the property text-overflow: ellipsis add ... and line-clamp show the number of lines.

Error while trying to run project: Unable to start program. Cannot find the file specified

For me, it was... the AntiVirus! Kaspersky Endpoint security 10. It seems that the frequent compilations and the changing of the exe, caused it to block the file.

Apply global variable to Vuejs

you can use Vuex to handle all your global data

BATCH file asks for file or folder

xcopy /s/y J:\"My Name"\"FILES IN TRANSIT"\JOHN20101126\"Missing file"\Shapes.atc C:\"Documents and Settings"\"His name"\"Application Data"\Autodesk\"AutoCAD 2010"\"R18.0"\enu\Support\*.*"

..should do it.

Good idea to do an:

IF NOT EXIST "C:\Documents and Settings\His name\Application Data\Autodesk\AutoCAD 2010\R18.0\enu\Support\Shapes.atc" ECHO/ && ECHO/ && ECHO * * * * * COPY FAILED - Call JustME at 555-555-1212 && ECHO/ && pause

(assuming you've done a rename of previous version to .old)

XCOPY  /Z  <----- restartable mode - good for large files.

What is a Python egg?

The .egg file is a distribution format for Python packages. It’s just an alternative to a source code distribution or Windows exe. But note that for pure Python, the .egg file is completely cross-platform.

The .egg file itself is essentially a .zip file. If you change the extension to “zip”, you can see that it will have folders inside the archive.

Also, if you have an .egg file, you can install it as a package using easy_install

Example: To create an .egg file for a directory say mymath which itself may have several python scripts, do the following step:

# setup.py
from setuptools import setup, find_packages
setup(
    name = "mymath",
    version = "0.1",
    packages = find_packages()
    )

Then, from the terminal do:

 $ python setup.py bdist_egg

This will generate lot of outputs, but when it’s completed you’ll see that you have three new folders: build, dist, and mymath.egg-info. The only folder that we care about is the dist folder where you'll find your .egg file, mymath-0.1-py3.5.egg with your default python (installation) version number(mine here: 3.5)

Source: Python library blog

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

Even if fileno(FILE *) may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.

To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)

How do I convert an integer to string as part of a PostgreSQL query?

Because the number can be up to 15 digits, you'll need to cast to an 64 bit (8-byte) integer. Try this:

SELECT * FROM table
WHERE myint = mytext::int8

The :: cast operator is historical but convenient. Postgres also conforms to the SQL standard syntax

myint = cast ( mytext as int8)

If you have literal text you want to compare with an int, cast the int to text:

SELECT * FROM table
WHERE myint::varchar(255) = mytext

Regular Expression for any number greater than 0?

If you only want non-negative integers, try: ^\d+$

curl.h no such file or directory

To those who use centos and have stumbled upon this post :

 $ yum install curl-devel

and when compiling your program example.cpp, link to the curl library:

 $ g++ example.cpp -lcurl -o example

"-o example" creates the executable example instead of the default a.out.

The next line runs example:

 $ ./example

Splitting a Java String by the pipe symbol using split("|")

You can also use .split("[|]").

(I used this instead of .split("\\|"), which didn't work for me.)

Combining the results of two SQL queries as separate columns

You can use a CROSS JOIN:

SELECT *
FROM (  SELECT SUM(Fdays) AS fDaysSum 
        FROM tblFieldDays 
        WHERE tblFieldDays.NameCode=35 
        AND tblFieldDays.WeekEnding=1) A -- use you real query here
CROSS JOIN (SELECT SUM(CHdays) AS hrsSum 
            FROM tblChargeHours 
            WHERE tblChargeHours.NameCode=35 
            AND tblChargeHours.WeekEnding=1) B -- use you real query here

Check if a number is int or float

You can do it with simple if statement

To check for float

if type(a)==type(1.1)

To check for integer type

if type(a)==type(1)

How to remove gem from Ruby on Rails application?

How about something like:

gem dependency devise --pipe | cut -d \  -f 1 | xargs gem uninstall -a

(this assumes that you're not using bundler - but I guess you're not since removing from your bundle gemspec would solve the problem)

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

If like me you recently moved certain classes to different packages ect. and you use android navigation. Make sure to change the argType to you match you new package address. from:

app:argType="com.example.app.old.Item" 

to:

app:argType="com.example.app.new.Item" 

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

create procedure <procedure_name>(p_cur out sys_refcursor) as begin open p_cur for select * from <table_name> end;

How to find lines containing a string in linux

The usual way to do this is with grep, which uses a pattern to match lines:

grep 'pattern' file

Each line which matches the pattern will be output. If you want to search for fixed strings only, use grep -F 'pattern' file.

Find duplicate records in a table using SQL Server

with x as   (select  *,rn = row_number()
            over(PARTITION BY OrderNo,item  order by OrderNo)
            from    #temp1)

select * from x
where rn > 1

you can remove duplicates by replacing select statement by

delete x where rn > 1

Convert string to date in bash

We can use date -d option

1) Change format to "%Y-%m-%d" format i.e 20121212 to 2012-12-12

date -d '20121212' +'%Y-%m-%d'

2)Get next or last day from a given date=20121212. Like get a date 7 days in past with specific format

date -d '20121212 -7 days' +'%Y-%m-%d'

3) If we are getting date in some variable say dat

dat2=$(date -d "$dat -1 days" +'%Y%m%d')

html5 - canvas element - Multiple layers

You might also checkout http://www.concretejs.com which is a modern, lightweight, Html5 canvas framework that enables hit detection, layering, and lots of other peripheral things. You can do things like this:

var wrapper = new Concrete.Wrapper({
  width: 500,
  height: 300,
  container: el
});

var layer1 = new Concrete.Layer();
var layer2 = new Concrete.Layer();

wrapper.add(layer1).add(layer2);

// draw stuff
layer1.sceneCanvas.context.fillStyle = 'red';
layer1.sceneCanvas.context.fillRect(0, 0, 100, 100);

// reorder layers
layer1.moveUp();

// destroy a layer
layer1.destroy();

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Is it possible to insert multiple rows at a time in an SQLite database?

I wrote some ruby code to generate a single 500 element multi-row insert from a series of insert statements which was considerably faster than running the individual inserts. Then I tried simply wrapping the multiple inserts into a single transaction and found that I could get the same kind of speed up with considerably less code.

BEGIN TRANSACTION;
INSERT INTO table VALUES (1,1,1,1);
INSERT INTO table VALUES (2,2,2,2);
...
COMMIT;

Chrome javascript debugger breakpoints don't do anything?

I met this several times, at first it works well by localhost, suddenly, the breakpoints don't work, i switch to 127.0.0.1, then it works again. Hope helps.

How to force NSLocalizedString to use a specific language

Maybe you should complement with this (on .pch file after #import ):

extern NSBundle* bundle; // Declared on Language.m

#ifdef NSLocalizedString
    #undef NSLocalizedString
    // Delete this line to avoid warning
    #warning "Undefining NSLocalizedString"
#endif

#define NSLocalizedString(key, comment) \
    [bundle localizedStringForKey:(key) value:@"" table:nil]

Access POST values in Symfony2 request object

The field data can be accessed in a controller with: Listing 12-34

$form->get('dueDate')->getData();

In addition, the data of an unmapped field can also be modified directly: Listing 12-35

$form->get('dueDate')->setData(new \DateTime());

page 164 symfony2 book(generated on October 9, 2013)

How to set environment variables in Jenkins?

EnvInject Plugin aka (Environment Injector Plugin) gives you several options to set environment variables from Jenkins configuration.

By selecting Inject environment variables to the build process you will get:

  • Properties File Path
  • Properties Content
  • Script File Path

  • Script Content

  • and finally Evaluated Groovy script.


Evaluated Groovy script gives you possibility to set environment variable based on result of executed command:

  • with execute method:
    return [HOSTNAME_SHELL: 'hostname'.execute().text, 
        DATE_SHELL: 'date'.execute().text,
        ECHO_SHELL: 'echo hello world!'.execute().text
    ]
  • or with explicit Groovy code:
    return [HOSTNAME_GROOVY: java.net.InetAddress.getLocalHost().getHostName(),
        DATE_GROOVY: new Date()
    ] 

(More details about each method could be found in build-in help (?))


Unfortunately you can't do the same from Script Content as it states:

Execute a script file aimed at setting an environment such as creating folders, copying files, and so on. Give the script file content. You can use the above properties variables. However, adding or overriding environment variables in the script doesn't have any impacts in the build job.

How to set custom location for local installation of npm package?

For OSX, you can go to your user's $HOME (probably /Users/yourname/) and, if it doesn't already exist, create an .npmrc file (a file that npm uses for user configuration), and create a directory for your npm packages to be installed in (e.g., /Users/yourname/npm). In that .npmrc file, set "prefix" to your new npm directory, which will be where "globally" installed npm packages will be installed; these "global" packages will, obviously, be available only to your user account.

In .npmrc:

prefix=${HOME}/npm

Then run this command from the command line:

npm config ls -l

It should give output on both your own local configuration and the global npm configuration, and you should see your local prefix configuration reflected, probably near the top of the long list of output.

For security, I recommend this approach to configuring your user account's npm behavior over chown-ing your /usr/local folders, which I've seen recommended elsewhere.

How do I sort a table in Excel if it has cell references in it?

Not sure if this will satisfy all, but I found a simple workaround that fixed the problem for me. Move all your referenced cells/formulas to a different sheet so that you aren't referencing any cells in the sheet that has the table to be sorted. If you do this, you can sort away!

Is it fine to have foreign key as primary key?

Foreign keys are almost always "Allow Duplicates," which would make them unsuitable as Primary Keys.

Instead, find a field that uniquely identifies each record in the table, or add a new field (either an auto-incrementing integer or a GUID) to act as the primary key.

The only exception to this are tables with a one-to-one relationship, where the foreign key and primary key of the linked table are one and the same.

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

I was using the $('div').attr('style', ''); technique and it wasn't working in IE8.

I outputted the style attribute using alert() and it was not stripping out inline styles.

.removeAttr ended up doing the trick in IE8.

How to get query parameters from URL in Angular 5?

If you're not using Angular router try, querystring. Install it

npm install --save querystring

to your project. In your component do something like this

import * as qs from 'querystring';
...
ngOnInit() {
   const params = qs.parse(window.location.search.substring(1));
   ...
}

The substring(1) is necessary because if you have something like this '/mypage?foo=bar' then the key name for will be ?foo

URL encode sees “&” (ampersand) as “&amp;” HTML entity

There is HTML and URI encodings. &amp; is & encoded in HTML while %26 is & in URI encoding.

So before URI encoding your string you might want to HTML decode and then URI encode it :)

var div = document.createElement('div');
div.innerHTML = '&amp;AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);

result %26AndOtherHTMLEncodedStuff

Hope this saves you some time

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

Update-Package -reinstall Microsoft.Web.Infrastructure didn't work for me, as I kept receiving errors that it was already installed.

I had to navigate to the Microsoft.Web.Infrastructure.1.0.0.0 folder in the packages folder and manually delete that folder.

After doing this, running Install-Package Microsoft.Web.Infrastructure installed it.

Note: CopyLocal was automatically set to true.

How to check for empty value in Javascript?

The counter in your for loop appears incorrect (or we're missing some code). Here's a working Fiddle.

This code:

//Where is counter[0] initialized?
for (i ; i < counter[0].value; i++)

Should be replaced with:

var timeTempCount = 5; //I'm not sure where you're getting this value so I set it.

for (var i = 0; i <= timeTempCount; i++)

Deserialize JSON into C# dynamic object?

Use DataSet(C#) with JavaScript. A simple function for creating a JSON stream with DataSet input. Create JSON content like (multi table dataset):

[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]

Just client side, use eval. For example,

var d = eval('[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]')

Then use:

d[0][0].a // out 1 from table 0 row 0

d[1][1].b // out 59 from table 1 row 1

// Created by Behnam Mohammadi And Saeed Ahmadian
public string jsonMini(DataSet ds)
{
    int t = 0, r = 0, c = 0;
    string stream = "[";

    for (t = 0; t < ds.Tables.Count; t++)
    {
        stream += "[";
        for (r = 0; r < ds.Tables[t].Rows.Count; r++)
        {
            stream += "{";
            for (c = 0; c < ds.Tables[t].Columns.Count; c++)
            {
                stream += ds.Tables[t].Columns[c].ToString() + ":'" +
                          ds.Tables[t].Rows[r][c].ToString() + "',";
            }
            if (c>0)
                stream = stream.Substring(0, stream.Length - 1);
            stream += "},";
        }
        if (r>0)
            stream = stream.Substring(0, stream.Length - 1);
        stream += "],";
    }
    if (t>0)
        stream = stream.Substring(0, stream.Length - 1);
    stream += "];";
    return stream;
}

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

To get the definition of the SQL codes, the easiest way is to use db2 cli!

at the unix or dos command prompt, just type

db2 "? SQL302"

this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)

hope this helped.

Is there a NumPy function to return the first index of something in an array?

An alternative to selecting the first element from np.where() is to use a generator expression together with enumerate, such as:

>>> import numpy as np
>>> x = np.arange(100)   # x = array([0, 1, 2, 3, ... 99])
>>> next(i for i, x_i in enumerate(x) if x_i == 2)
2

For a two dimensional array one would do:

>>> x = np.arange(100).reshape(10,10)   # x = array([[0, 1, 2,... 9], [10,..19],])
>>> next((i,j) for i, x_i in enumerate(x) 
...            for j, x_ij in enumerate(x_i) if x_ij == 2)
(0, 2)

The advantage of this approach is that it stops checking the elements of the array after the first match is found, whereas np.where checks all elements for a match. A generator expression would be faster if there's match early in the array.

How to find the largest file in a directory and its subdirectories?

Try the following one-liner (display top-20 biggest files):

ls -1Rs | sed -e "s/^ *//" | grep "^[0-9]" | sort -nr | head -n20

or (human readable sizes):

ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20

Works fine under Linux/BSD/OSX in comparison to other answers, as find's -printf option doesn't exist on OSX/BSD and stat has different parameters depending on OS. However the second command to work on OSX/BSD properly (as sort doesn't have -h), install sort from coreutils or remove -h from ls and use sort -nr instead.

So these aliases are useful to have in your rc files:

alias big='du -ah . | sort -rh | head -20'
alias big-files='ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20'

Calculating days between two dates with Java

When I run your program, it doesn't even get me to the point where I can enter the second date.

This is simpler and less error prone.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test001 {

    public static void main(String[] args) throws Exception {

        BufferedReader br = null;

        br = new BufferedReader(new InputStreamReader(System.in));
        SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy");

        System.out.println("Insert first date : ");
        Date dt1 = sdf.parse(br.readLine().trim());

        System.out.println("Insert second date : ");
        Date dt2 = sdf.parse(br.readLine().trim());

        long diff = dt2.getTime() - dt1.getTime();

        System.out.println("Days: " + diff / 1000L / 60L / 60L / 24L);

        if (br != null) {
            br.close();
        }
    }
}

How using try catch for exception handling is best practice

With Exceptions, I try the following:

First, I catch special types of exceptions like division by zero, IO operations, and so on and write code according to that. For example, a division by zero, depending the provenience of the values I could alert the user (example a simple calculator in that in a middle calculation (not the arguments) arrives in a division by zero) or to silently treat that exception, logging it and continue processing.

Then I try to catch the remaining exceptions and log them. If possible allow the execution of code, otherwise alert the user that a error happened and ask them to mail a error report.

In code, something like this:

try{
    //Some code here
}
catch(DivideByZeroException dz){
    AlerUserDivideByZerohappened();
}
catch(Exception e){
    treatGeneralException(e);
}
finally{
    //if a IO operation here i close the hanging handlers for example
}

Load local javascript file in chrome for testing?

Use Chrome browser and with the Web Server for Chrome extension, set a default folder and put your linked html/js files in there, browse to 127.0.0.1:8887 (0r whatever the port is set at) in Chrome and open the developers panel & console. You can then interact with your html/js scripts in the console.

What exactly is \r in C language?

It's Carriage Return. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx

The following repeats the loop until the user has pressed the Return key.

while(ch!='\r')
{
  ch=getche();
}

Python: find position of element in array

In the NumPy array, you can use where like this:

np.where(npArray == 20)

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

dir.Delete(true); // true => recursive delete

Where does forever store console.log output?

Based on bryanmac's answer. I'm just saving all logs into one file and then reading it with tail. Simple, but effective way to do this.

forever -o common.log -e common.log index.js && tail -f common.log

Call int() function on every list element?

just a point,

numbers = [int(x) for x in numbers]

the list comprehension is more natural, while

numbers = map(int, numbers)

is faster.

Probably this will not matter in most cases

Useful read: LP vs map

Can't import database through phpmyadmin file size too large

If you are using MySQL in Xampp then do the steps below.

Find the following in XAMPP control panel>Apach-Config> PHP (php.ini) file

  • post_max_size = 8M

  • upload_max_filesize = 2M

  • max_execution_time = 30
  • ut_time = 60enter code here memory_limit = 8M

And change their sizes according to your need. I'm using these values

post_max_size = 30M
upload_max_filesize = 30M
max_execution_time = 4500
max_input_time = 4500
memory_limit = 850M

Are there any disadvantages to always using nvarchar(MAX)?

firstly I thought about this, but then thought again. There are performance implications, but equally it does serve as a form of documentation to have an idea what size the fields really are. And it does enforce when that database sits in a larger ecosystem. In my opinion the key is to be permissive but only within reason.

ok, here's my feelings simply on the issue of business and data layer logic. It depends, if your DB is a shared resource between systems that share business logic then of course it seems a natural place to enforce such logic, but its not the BEST way to do it, the BEST way is to provide an API, this allows the interaction to be tested and keeps business logic where it belongs, it keeps systems decoupled, it keeps your tiers within a system decoupled. If however your database is supposed to be serving only one application, then lets get AGILE in thinking, what's true now? design for now. If and when such access is needed, provide an API to that data.

obviously though, this is just the ideal, if you are working with an existing system the likelyhood is that you will need to do it differently at least in the short term.

What's the difference between '$(this)' and 'this'?

Yes, you need $(this) for jQuery functions, but when you want to access basic javascript methods of the element that don't use jQuery, you can just use this.

Random number in range [min - max] using PHP

rand(1,20)

Docs for PHP's rand function are here:

http://php.net/manual/en/function.rand.php

Use the srand() function to set the random number generator's seed value.

right click context menu for datagridview

Follow the steps:

  1. Create a context menu like: Sample context menu

  2. User needs to right click on the row to get this menu. We need to handle the _MouseClick event and _CellMouseDown event.

selectedBiodataid is the variable that contains the selected row information.

Here is the code:

private void dgrdResults_MouseClick(object sender, MouseEventArgs e)
{   
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {                      
        contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
    }   
}

private void dgrdResults_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    //handle the row selection on right click
    if (e.Button == MouseButtons.Right)
    {
        try
        {
            dgrdResults.CurrentCell = dgrdResults.Rows[e.RowIndex].Cells[e.ColumnIndex];
            // Can leave these here - doesn't hurt
            dgrdResults.Rows[e.RowIndex].Selected = true;
            dgrdResults.Focus();

            selectedBiodataId = Convert.ToInt32(dgrdResults.Rows[e.RowIndex].Cells[1].Value);
        }
        catch (Exception)
        {

        }
    }
}

and the output would be:

Final output

Debugging iframes with Chrome developer tools

In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame

How to delete large data of table in SQL without log?

Another use:

SET ROWCOUNT 1000 -- Buffer

DECLARE @DATE AS DATETIME = dateadd(MONTH,-7,GETDATE())

DELETE LargeTable  WHERE readTime < @DATE
WHILE @@ROWCOUNT > 0
BEGIN
   DELETE LargeTable  WHERE readTime < @DATE
END
SET ROWCOUNT 0

Optional;

If transaction log is enabled, disable transaction logs.

ALTER DATABASE dbname SET RECOVERY SIMPLE;

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

In my case adding multiDexEnabled true in Android/build/build.gradle file compiled the files.

I will look into removing this in the future, as in the documentation it says 'Before configuring your app to enable use of 64K or more method references, you should take steps to reduce the total number of references called by your app code, including methods defined by your app code or included libraries.'

defaultConfig {
  applicationId "com.peoplesenergyapp"
  minSdkVersion rootProject.ext.minSdkVersion
  targetSdkVersion rootProject.ext.targetSdkVersion
  versionCode 1
  versionName "1.0"
  multiDexEnabled true // <-add this 
}

How to get a cross-origin resource sharing (CORS) post request working

This is a little late to the party, but I have been struggling with this for a couple of days. It is possible and none of the answers I found here have worked. It's deceptively simple. Here's the .ajax call:

_x000D_
_x000D_
    <!DOCTYPE HTML>_x000D_
    <html>_x000D_
    <head>_x000D_
    <body>_x000D_
     <title>Javascript Test</title>_x000D_
     <script src="http://code.jquery.com/jquery-latest.min.js"></script>_x000D_
     <script type="text/javascript">_x000D_
     $(document).domain = 'XXX.com';_x000D_
     $(document).ready(function () {_x000D_
     $.ajax({_x000D_
        xhrFields: {cors: false},_x000D_
        type: "GET",_x000D_
        url: "http://XXXX.com/test.php?email='[email protected]'",_x000D_
        success: function (data) {_x000D_
           alert(data);_x000D_
        },_x000D_
        error: function (x, y, z) {_x000D_
           alert(x.responseText + " :EEE: " + x.status);_x000D_
        }_x000D_
    });_x000D_
    });_x000D_
    </script> _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Here's the php on the server side:

_x000D_
_x000D_
    <html>_x000D_
    <head>_x000D_
     <title>PHP Test</title>_x000D_
     </head>_x000D_
    <body>_x000D_
      <?php_x000D_
      header('Origin: xxx.com');_x000D_
      header('Access-Control-Allow-Origin:*');_x000D_
      $servername = "sqlxxx";_x000D_
      $username = "xxxx";_x000D_
      $password = "sss";_x000D_
      $conn = new mysqli($servername, $username, $password);_x000D_
      if ($conn->connect_error) {_x000D_
        die( "Connection failed: " . $conn->connect_error);_x000D_
      }_x000D_
      $sql = "SELECT email, status, userdata  FROM msi.usersLive";_x000D_
      $result = $conn->query($sql);_x000D_
      if ($result->num_rows > 0) {_x000D_
      while($row = $result->fetch_assoc()) {_x000D_
        echo $row["email"] . ":" . $row["status"] . ":" . $row["userdata"] .  "<br>";_x000D_
      }_x000D_
    } else {_x000D_
      echo "{ }";_x000D_
    }_x000D_
    $conn->close();_x000D_
    ?>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

adb doesn't show nexus 5 device

I have suffered the same issue and was able to solve it by simply changing on my Android device (Nexus 5X) in Developer options > Select USB Configuration to RNDIS (USB Ethernet)

Django Multiple Choice Field / Checkbox Select Multiple

The models.CharField is a CharField representation of one of the choices. What you want is a set of choices. This doesn't seem to be implemented in django (yet).

You could use a many to many field for it, but that has the disadvantage that the choices have to be put in a database. If you want to use hard coded choices, this is probably not what you want.

There is a django snippet at http://djangosnippets.org/snippets/1200/ that does seem to solve your problem, by implementing a ModelField MultipleChoiceField.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

No route matches "/users/sign_out" devise rails 3

Lots of solutions are there. but mostly use this,

<%= link_to 'Sign out', destroy_user_session_path, method: :delete %>

or config devise.rb with proper sign_out method

In devise.rb

config.sign_out_via = :delete ( or  :get which u like to use.) 

Are there constants in JavaScript?

Yet there is no exact cross browser predefined way to do it , you can achieve it by controlling the scope of variables as showed on other answers.

But i will suggest to use name space to distinguish from other variables. this will reduce the chance of collision to minimum from other variables.

Proper namespacing like

var iw_constant={
     name:'sudhanshu',
     age:'23'
     //all varibale come like this
}

so while using it will be iw_constant.name or iw_constant.age

You can also block adding any new key or changing any key inside iw_constant using Object.freeze method. However its not supported on legacy browser.

ex:

Object.freeze(iw_constant);

For older browser you can use polyfill for freeze method.


If you are ok with calling function following is best cross browser way to define constant. Scoping your object within a self executing function and returning a get function for your constants ex:

var iw_constant= (function(){
       var allConstant={
             name:'sudhanshu',
             age:'23'
             //all varibale come like this

       };

       return function(key){
          allConstant[key];
       }
    };

//to get the value use iw_constant('name') or iw_constant('age')


** In both example you have to be very careful on name spacing so that your object or function shouldn't be replaced through other library.(If object or function itself wil be replaced your whole constant will go)

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

What's the best way to generate a UML diagram from Python source code?

vipera is a small application designer, and uml is included. You can see it in:

vipera

Best regards.

How can I make a div not larger than its contents?

We can use any of the two ways on the div element:

display: table;

or,

display: inline-block; 

I prefer to use display: table;, because it handles, all extra spaces on its own. While display: inline-block needs some extra space fixing.

Unioning two tables with different number of columns

Add extra columns as null for the table having less columns like

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2

Link to the issue number on GitHub within a commit message

github adds a reference to the commit if it contains #issuenbr (discovered this by chance).

How to access Anaconda command prompt in Windows 10 (64-bit)

To run Anaconda Prompt using icon, I made an icon and put

%windir%\System32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3 The file location would be different in each computer.

at icon -> right click -> Property -> Shortcut -> Target

I see %HOMEPATH% at icon -> right click -> Property -> Start in

OS: Windows 10, Library: Anaconda 10 (64 bit)

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

"static const" vs "#define" vs "enum"

We looked at the produced assembler code on the MBF16X... Both variants result in the same code for arithmetic operations (ADD Immediate, for example).

So const int is preferred for the type check while #define is old style. Maybe it is compiler-specific. So check your produced assembler code.

Run an Ansible task only when the variable contains a specific string

use this

when: "{{ 'value' in variable1}}"

instead of

when: "'value' in {{variable1}}"

Also for string comparison you can use

when: "{{ variable1 == 'value' }}"

Easiest way to mask characters in HTML(5) text input

  1. Basic validation can be performed by choosing the type attribute of input elements. For example: <input type="email" /> <input type="URL" /> <input type="number" />

  2. using pattern attribute like: <input type="text" pattern="[1-4]{5}" />

  3. required attribute <input type="text" required />

  4. maxlength: <input type="text" maxlength="20" />

  5. min & max: <input type="number" min="1" max="4" />

What is the difference between Step Into and Step Over in a debugger

Consider the following code with your current instruction pointer (the line that will be executed next, indicated by ->) at the f(x) line in g(), having been called by the g(2) line in main():

public class testprog {
    static void f (int x) {
        System.out.println ("num is " + (x+0)); // <- STEP INTO
    }

    static void g (int x) {
->      f(x); //
        f(1); // <----------------------------------- STEP OVER
    }

    public static void main (String args[]) {
        g(2);
        g(3); // <----------------------------------- STEP OUT OF
    }
}

If you were to step into at that point, you will move to the println() line in f(), stepping into the function call.

If you were to step over at that point, you will move to the f(1) line in g(), stepping over the function call.

Another useful feature of debuggers is the step out of or step return. In that case, a step return will basically run you through the current function until you go back up one level. In other words, it will step through f(x) and f(1), then back out to the calling function to end up at g(3) in main().

Give all permissions to a user on a PostgreSQL database

GRANT USAGE ON SCHEMA schema_name TO user;

Wamp Server not goes to green color

Click wamp icon :

1- apache -> httpd.conf (A notepad file will be opened)

2- Find 80

3 -Replace with 81

Listen 12.34.56.78:81 Listen 0.0.0.0:81 Listen [::0]:81

4- Restart wamp services

!!Done

How is a JavaScript hash map implemented?

Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

javascript date + 7 days

_x000D_
_x000D_
var future = new Date(); // get today date_x000D_
future.setDate(future.getDate() + 7); // add 7 days_x000D_
var finalDate = future.getFullYear() +'-'+ ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) +'-'+ future.getDate();_x000D_
console.log(finalDate);
_x000D_
_x000D_
_x000D_

Char array declaration and initialization in C

Yes, this is a kind of inconsistency in the language.

The "=" in myarray = "abc"; is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc"; it's an initialization of the array. There's no way for "late initialization".

You should just remember this rule.

Apply function to pandas groupby

Try:

g = pd.DataFrame(['A','B','A','C','D','D','E'])

# Group by the contents of column 0 
gg = g.groupby(0)  

# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())

# Add a new column that is the count / total number of elements    
histo[1] = histo.astype(np.float)/len(g) 

print histo

Output:

   0         1
0             
A  2  0.285714
B  1  0.142857
C  1  0.142857
D  2  0.285714
E  1  0.142857

php search array key and get value

Here is an example straight from PHP.net

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

in the foreach you can do a comparison of each key to something that you are looking for

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

Quick Update, effective from February 15th, 2015, we cannot submit apps to the store that were developed using an SDK prior to iOS 8. So, keeping that in mind , its better to not to worry about this issue as many people have suggested that apps made in Swift can be deployed to OS X 10.9 and iOS 7.0 as well.

How do you push a tag to a remote repository using Git?

git push --follow-tags

This is a sane option introduced in Git 1.8.3:

git push --follow-tags

It pushes both commits and only tags that are both:

  • annotated
  • reachable (an ancestor) from the pushed commits

This is sane because:

It is for those reasons that --tags should be avoided.

Git 2.4 has added the push.followTags option to turn that flag on by default which you can set with:

git config --global push.followTags true

or by adding followTags = true to the [push] section of your ~/.gitconfig file.

jQuery validation plugin: accept only alphabetical characters?

Just a small addition to Nick's answer (which works great !) :

If you want to allow spaces in between letters, for example , you may restrict to enter only letters in full name, but it should allow space as well - just list the space as below with a comma. And in the same way if you need to allow any other specific character:

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please");       

How to get the selected value from drop down list in jsp?

use jquery

$("#item").change(function({
    var x=$(this).val();
});

Your value will be in x variable, use this variable value in your jsp, like this {x} this statement will give the value

Structure of a PDF file?

I'm trying to do pretty much the same thing. The PDF reference is a very difficult document to read. This tutorial is a better start I think.

vbscript output to console

Create a .vbs with the following code, which will open your main .vbs:

Set objShell = WScript.CreateObject("WScript.shell") 
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""

Here is my main .vbs

Option Explicit
Dim i
for i = 1 To 5
     Wscript.Echo i
     Wscript.Sleep 5000
Next

How to capitalize the first letter in a String in Ruby

Use capitalize. From the String documentation:

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"

Bootstrap 3: Using img-circle, how to get circle from non-square image?

the problem mainly is because the width have to be == to the height, and in the case of bs, the height is set to auto so here is a fix for that in js instead

function img_circle() {
    $('.img-circle').each(function() {
        $w = $(this).width();
        $(this).height($w);
    });
}

$(document).ready(function() {
    img_circle();
});

$(window).resize(function() {
    img_circle();
});

Docker: Multiple Dockerfiles in project

In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.

How to run test cases in a specified file?

When running a single test I usually do:

go test -run TestSomethingReallyCool ./folder1/folder2/ -v -count 1

-count 1 also ensures that the test is ran every time instead of being cached. Useful when you are testing against race conditions and have a test that fails only sometimes. In Go versions not using modules the same could be achieved by setting GOCACHE=off but this interacts poorly with Go modules.

Causes of getting a java.lang.VerifyError

I fixed this error on Android by making the project I was importing a library, as described here http://developer.android.com/tools/projects/projects-eclipse.html#SettingUpLibraryProject

Previously, I was just referencing the project (not making it a library) and I was getting this strange VerifyError.

Hope it helps someone.

How to install Visual Studio 2015 on a different drive

I use Xamarin with Visual Studio, and I prefer to move only some large android to another directory with(copy these folders to destination before create hardlinks):

mklink \J "C:\Users\yourUser\.android" "E:\yourFolder\.android"

mklink \J "C:\Program Files (x86)\Android" "E:\yourFolder\Android"

DataGridView.Clear()

Try this

DataGridView1.DataSource=ds;
ds.Clear();

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

It will move all .txt files on the desktop to the folder TextFiles.

How to copy data from one HDFS to another HDFS?

distcp command use for copying from one cluster to another cluster in parallel. You have to set the path for namenode of src and path for namenode of dst, internally it use mapper.

Example:

$ hadoop distcp <src> <dst>

there few options you can set for distcp

-m for no. of mapper for copying data this will increase speed of copying.

-atomic for auto commit the data.

-update will only update data that is in old version.

There are generic command for copying files in hadoop are -cp and -put but they are use only when the data volume is less.

Remove attribute "checked" of checkbox

Try:

$("#captureAudio")[0].checked = false;

How do I convert a float number to a whole number in JavaScript?

Performance

Today 2020.11.28 I perform tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.

Results

  • for all browsers all solutions (except B and K) gives very similar speed results
  • solutions B and K are slow

enter image description here

Details

I perform test case which you can run HERE

Below snippet presents differences between solutions A B C D E F G H I J K L

_x000D_
_x000D_
function A(float) {
    return Math.trunc( float );
}

function B(float) {
    return parseInt(float);
}

function C(float) {
    return float | 0;
}

function D(float) {
    return ~~float;
}

function E(float) {
    return float >> 0;
}

function F(float) {
    return float - float%1;
}

function G(float) {
    return float ^ 0;
}

function H(float) {
    return Math.floor( float );
}

function I(float) {
    return Math.ceil( float );
}

function J(float) {
    return Math.round( float );
}

function K(float) {
    return float.toFixed(0);
}

function L(float) {
    return float >>> 0;
}






// ---------
// TEST
// ---------

[A,B,C,D,E,F,G,H,I,J,K,L]
  .forEach(f=> console.log(`${f.name} ${f(1.5)} ${f(-1.5)} ${f(2.499)} ${f(-2.499)}`))
_x000D_
This snippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

Make sure you create the project with conda environment option selected.

My problem solved by recreate the project and select "conda" from "New environment using" options

see image:

New environment setting

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

I follwed the same tutorial but after some months I strangely got the error "403 Access Denied" while tryed to use Manager App. In this case I was using the ipaddress:8080 in the address bar and Tomcat Manager App didin't prompting for user/password. In case of localhost:8080 the error was "401", the dialogbox asking for username and password was displayed but the user not recognized.

I tried all the previous suggestions / solutions without lucky. The only way I found is been to repeat again the entire tutorial overwriting also the files. When finished, I found again the old deployed project into the webapps directory. Now Apache Tomcat/8.5.16 Manager App are working again. I do not know what happened I didn't understand also because I'm a newbie in Tomcat user

Is generator.next() visible in Python 3?

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

import six

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

Render HTML in React Native

Edit Jan 2021: The React Native docs currently recommend React Native WebView:

<WebView
    originWhitelist={['*']}
    source={{ html: '<p>Here I am</p>' }}
/>

https://github.com/react-native-webview/react-native-webview


Edit March 2017: the html prop has been deprecated. Use source instead:

<WebView source={{html: '<p>Here I am</p>'}} />

https://facebook.github.io/react-native/docs/webview.html#html

Thanks to Justin for pointing this out.


Edit Feb 2017: the PR was accepted a while back, so to render HTML in React Native, simply:

<WebView html={'<p>Here I am</p>'} />

Original Answer:

I don't think this is currently possible. The behavior you're seeing is expected, since the Text component only outputs... well, text. You need another component that outputs HTML - and that's the WebView.

Unfortunately right now there's no way of just directly setting the HTML on this component:

https://github.com/facebook/react-native/issues/506

However I've just created this PR which implements a basic version of this feature so hopefully it'll land in some form soonish.

create table in postgreSQL

Please try this:

CREATE TABLE article (
  article_id bigint(20) NOT NULL serial,
  article_name varchar(20) NOT NULL,
  article_desc text NOT NULL,
  date_added datetime default NULL,
  PRIMARY KEY (article_id)
);

jQuery to retrieve and set selected option value of html select element

$('#myId').val() should do it, failing that I would try:

$('#myId option:selected').val()

Cancel a UIView animation?

Use:

#import <QuartzCore/QuartzCore.h>

.......

[myView.layer removeAllAnimations];

How do I test if a recordSet is empty? isNull?

A simple way is to write it:

Dim rs As Object
Set rs = Me.Recordset.Clone
If Me.Recordset.RecordCount = 0 then 'checks for number of records
   msgbox "There is no records" 
End if

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

It's because the tab is a naming container aswell... your update should be update="Search:insTable:display" What you can do aswell is just place your dialog outside the form and still inside the tab then it would be: update="Search:display"

What is the opposite of :hover (on mouse leave)?

The opposite is using :not

e.g.

selection:not(:hover) { rules }

const vs constexpr on variables

constexpr indicates a value that's constant and known during compilation.
const indicates a value that's only constant; it's not compulsory to know during compilation.

int sz;
constexpr auto arraySize1 = sz;    // error! sz's value unknown at compilation
std::array<int, sz> data1;         // error! same problem

constexpr auto arraySize2 = 10;    // fine, 10 is a compile-time constant
std::array<int, arraySize2> data2; // fine, arraySize2 is constexpr

Note that const doesn’t offer the same guarantee as constexpr, because const objects need not be initialized with values known during compilation.

int sz;
const auto arraySize = sz;       // fine, arraySize is const copy of sz
std::array<int, arraySize> data; // error! arraySize's value unknown at compilation

All constexpr objects are const, but not all const objects are constexpr.

If you want compilers to guarantee that a variable has a value that can be used in contexts requiring compile-time constants, the tool to reach for is constexpr, not const.

Excel: Search for a list of strings within a particular string using array formulas?

In case others may find this useful: I found that by adding an initial empty cell to my list of search terms, a zero value will be returned instead of error.

={INDEX(SearchTerms!$A$1:$A$38,MAX(IF(ISERROR(SEARCH(SearchTerms!$A$1:$A$38,SearchCell)),0,1)*((SearchTerms!$B$1:$B$38)+1)))}

NB: Column A has the search terms, B is the row number index.

Android, How to read QR code in my application?

Easy QR Code Library

A simple Android Easy QR Code Library. It is very easy to use, to use this library follow these steps.

For Gradle:

Step 1. Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency:

dependencies {
        compile 'com.github.mrasif:easyqrlibrary:v1.0.0'
}

For Maven:

Step 1. Add the JitPack repository to your build file:

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

Step 2. Add the dependency:

<dependency>
    <groupId>com.github.mrasif</groupId>
    <artifactId>easyqrlibrary</artifactId>
    <version>v1.0.0</version>
</dependency>

For SBT:

Step 1. Add the JitPack repository to your build.sbt file:

resolvers += "jitpack" at "https://jitpack.io"

Step 2. Add the dependency:

libraryDependencies += "com.github.mrasif" % "easyqrlibrary" % "v1.0.0"

For Leiningen:

Step 1. Add it in your project.clj at the end of repositories:

:repositories [["jitpack" "https://jitpack.io"]]

Step 2. Add the dependency:

:dependencies [[com.github.mrasif/easyqrlibrary "v1.0.0"]]

Add this in your layout xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="No QR Data"/>
    <Button
        android:id="@+id/btnQRScan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="QR Scan"/>

</LinearLayout>

Add this in your activity java files:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView tvData;
    Button btnQRScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvData=findViewById(R.id.tvData);
        btnQRScan=findViewById(R.id.btnQRScan);

        btnQRScan.setOnClickListener(this);
    }

    @Override
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btnQRScan: {
                Intent intent=new Intent(MainActivity.this, QRScanner.class);
                startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);
            } break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case EasyQR.QR_SCANNER_REQUEST: {
                if (resultCode==RESULT_OK){
                    tvData.setText(data.getStringExtra(EasyQR.DATA));
                }
            } break;
        }
    }
}

For customized scanner screen just add these lines when you start the scanner Activity.

Intent intent=new Intent(MainActivity.this, QRScanner.class);
intent.putExtra(EasyQR.IS_TOOLBAR_SHOW,true);
intent.putExtra(EasyQR.TOOLBAR_DRAWABLE_ID,R.drawable.ic_audiotrack_dark);
intent.putExtra(EasyQR.TOOLBAR_TEXT,"My QR");
intent.putExtra(EasyQR.TOOLBAR_BACKGROUND_COLOR,"#0588EE");
intent.putExtra(EasyQR.TOOLBAR_TEXT_COLOR,"#FFFFFF");
intent.putExtra(EasyQR.BACKGROUND_COLOR,"#000000");
intent.putExtra(EasyQR.CAMERA_MARGIN_LEFT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_TOP,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_RIGHT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_BOTTOM,50);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);

You are done. Ref. Link: https://mrasif.github.io/easyqrlibrary

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Change your code to.

<?php
$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".$rows['user'];
?>

There was syntax error in your query.

Java: How to Indent XML Generated by Transformer

I used the Xerces (Apache) library instead of messing with Transformer. Once you add the library add the code below.

OutputFormat format = new OutputFormat(document);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer outxml = new FileWriter(new File("out.xml"));
XMLSerializer serializer = new XMLSerializer(outxml, format);
serializer.serialize(document);

What's a concise way to check that environment variables are set in a Unix shell script?

${MyVariable:=SomeDefault}

If MyVariable is set and not null, it will reset the variable value (= nothing happens).
Else, MyVariable is set to SomeDefault.

The above will attempt to execute ${MyVariable}, so if you just want to set the variable do:

MyVariable=${MyVariable:=SomeDefault}

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

The solutions posted so far only deal with part of the problem, converting DOS/Windows' CRLF into Unix's LF; the part they're missing is that DOS use CRLF as a line separator, while Unix uses LF as a line terminator. The difference is that a DOS file (usually) won't have anything after the last line in the file, while Unix will. To do the conversion properly, you need to add that final LF (unless the file is zero-length, i.e. has no lines in it at all). My favorite incantation for this (with a little added logic to handle Mac-style CR-separated files, and not molest files that're already in unix format) is a bit of perl:

perl -pe 'if ( s/\r\n?/\n/g ) { $f=1 }; if ( $f || ! $m ) { s/([^\n])\z/$1\n/ }; $m=1' PCfile.txt

Note that this sends the Unixified version of the file to stdout. If you want to replace the file with a Unixified version, add perl's -i flag.

Android change SDK version in Eclipse? Unable to resolve target android-x

If you're using eclipse you can open default.properties file in your workspace and change the project target to the new sdk (target=android-8 for 2.2). I accidentally selected the 1.5 sdk for my version and didn't catch it until much later, but updating that and restarting eclipse seemed to have done the trick.

How do I add a margin between bootstrap columns without wrapping

The simple way to do this is doing a div within a div

_x000D_
_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
   <div class="server-action-menu" id="server_1">Server 1_x000D_
   </div>_x000D_
 </div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
   <div class="server-action-menu" id="server_1">Server 2_x000D_
   </div>_x000D_
 </div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
   <div class="server-action-menu" id="server_1">Server 3_x000D_
   </div>_x000D_
 </div>
_x000D_
_x000D_
_x000D_

Remove/ truncate leading zeros by javascript/jquery

You should use the "radix" parameter of the "parseInt" function : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt

parseInt('015', 10) => 15

if you don't use it, some javascript engine might use it as an octal parseInt('015') => 0

How to add a new audio (not mixing) into a video using ffmpeg?

None of these solutions quite worked for me. My original audio was being overwritten, or I was getting an error like "failed to map memory" with the more complex 'amerge' example. It seems I needed -filter_complex amix.

ffmpeg -i videowithaudioyouwanttokeep.mp4 -i audiotooverlay.mp3 -vcodec copy -filter_complex amix -map 0:v -map 0:a -map 1:a -shortest -b:a 144k out.mkv

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

this error I was able to remove after adding profile:

<profile>
            <id>surefire-windows-fork-disable</id>
            <activation>
                <os>
                    <family>Windows</family>
                </os>
            </activation>
            <build>
                <pluginManagement>
                    <plugins>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-surefire-plugin</artifactId>
                            <configuration>
                                <forkCount>0</forkCount>
                                <useSystemClassLoader>false</useSystemClassLoader>
                            </configuration>
                        </plugin>
                    </plugins>
                </pluginManagement>
            </build>
        </profile>

seems that this is a windows problem regarding maven surefire forks

How to add a progress bar to a shell script?

Using suggestions listed above, I decided to implement my own progress bar.

#!/usr/bin/env bash

main() {
  for (( i = 0; i <= 100; i=$i + 1)); do
    progress_bar "$i"
    sleep 0.1;
  done
  progress_bar "done"
  exit 0
}

progress_bar() {
  if [ "$1" == "done" ]; then
    spinner="X"
    percent_done="100"
    progress_message="Done!"
    new_line="\n"
  else
    spinner='/-\|'
    percent_done="${1:-0}"
    progress_message="$percent_done %"
  fi

  percent_none="$(( 100 - $percent_done ))"
  [ "$percent_done" -gt 0 ] && local done_bar="$(printf '#%.0s' $(seq -s ' ' 1 $percent_done))"
  [ "$percent_none" -gt 0 ] && local none_bar="$(printf '~%.0s' $(seq -s ' ' 1 $percent_none))"

  # print the progress bar to the screen
  printf "\r Progress: [%s%s] %s %s${new_line}" \
    "$done_bar" \
    "$none_bar" \
    "${spinner:x++%${#spinner}:1}" \
    "$progress_message"
}

main "$@"

How to add a constant column in a Spark DataFrame?

In spark 2.2 there are two ways to add constant value in a column in DataFrame:

1) Using lit

2) Using typedLit.

The difference between the two is that typedLit can also handle parameterized scala types e.g. List, Seq, and Map

Sample DataFrame:

val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,"c"))).toDF("id", "col1")

+---+----+
| id|col1|
+---+----+
|  0|   a|
|  1|   b|
+---+----+

1) Using lit: Adding constant string value in new column named newcol:

import org.apache.spark.sql.functions.lit
val newdf = df.withColumn("newcol",lit("myval"))

Result:

+---+----+------+
| id|col1|newcol|
+---+----+------+
|  0|   a| myval|
|  1|   b| myval|
+---+----+------+

2) Using typedLit:

import org.apache.spark.sql.functions.typedLit
df.withColumn("newcol", typedLit(("sample", 10, .044)))

Result:

+---+----+-----------------+
| id|col1|           newcol|
+---+----+-----------------+
|  0|   a|[sample,10,0.044]|
|  1|   b|[sample,10,0.044]|
|  2|   c|[sample,10,0.044]|
+---+----+-----------------+

How can I stop Chrome from going into debug mode?

For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.

For me it was the "breakOnLoad": true line in VS Code launch.json config.

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

How to blur background images in Android

You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/onboardingimg1">
    <View
        android:id="@+id/opacityFilter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black"
        android:layout_alignParentBottom="true"
        android:alpha="0.7">
    </View>


</RelativeLayout>

How to use SortedMap interface in Java?

I would use TreeMap, which implements SortedMap. It is designed exactly for that.

Example:

Map<Integer, String> map = new TreeMap<Integer, String>();

// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.

How to export SQL Server 2005 query to CSV

For adhoc queries:

Show results in grid mode (CTRL+D), run query, click top left hand box in results grid, paste to Excel, save as CSV. You may be able to paste directly into a text file (can't try it now)

Or "Results to file" has options too for CSV

Or "Results to text" with comma separators

All settings under Tool..Options and Query.. options (I think, can't check) too

Insert Data Into Temp Table with Query

This is possible. Try this way:

Create Global Temporary Table 
BossaDoSamba 
On Commit Preserve Rows 
As 
select ArtistName, sum(Songs) As NumberOfSongs 
 from Spotfy 
    where ArtistName = 'BossaDoSamba'
 group by ArtistName;

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

if you use Bootstrap 2.2.1 then maybe is this what you are looking for.

Sample file index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
    <link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
    <menu>_x000D_
        <div class="navbar navbar-default navbar-fixed-top">_x000D_
            <div class="container">_x000D_
                <div class="navbar-header">_x000D_
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                    </button>_x000D_
                    <a class="navbar-brand" href="/">Application name</a>_x000D_
                </div>_x000D_
                <div class="navbar-collapse collapse">_x000D_
                    <ul class="nav navbar-nav">_x000D_
                        <li><a href="/">Home</a></li>_x000D_
                        <li><a href="/Home/About">About</a></li>_x000D_
                        <li><a href="/Home/Contact">Contact</a></li>_x000D_
                    </ul>_x000D_
                    <ul class="nav navbar-nav navbar-right">_x000D_
                        <li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
                        <li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
                    </ul>_x000D_
_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </menu>_x000D_
_x000D_
    <nav>_x000D_
        <div class="col-md-2">_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
        </div>_x000D_
_x000D_
    </nav>_x000D_
    <content>_x000D_
       <div class="col-md-10">_x000D_
_x000D_
               <h2>About.</h2>_x000D_
               <h3>Your application description page.</h3>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <hr />_x000D_
       </div>_x000D_
    </content>_x000D_
_x000D_
    <footer>_x000D_
        <div class="navbar navbar-default navbar-fixed-bottom">_x000D_
            <div class="container" style="font-size: .8em">_x000D_
                <p class="navbar-text">_x000D_
                    &copy; Some info_x000D_
                </p>_x000D_
            </div>_x000D_
        </div>_x000D_
    </footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_ File Content/Site.css
_x000D_
_x000D_
body {_x000D_
    padding-bottom: 70px;_x000D_
    padding-top: 70px;_x000D_
}
_x000D_
_x000D_
_x000D_

Disable JavaScript error in WebBrowser control

I just found this :

 private static bool TrySetSuppressScriptErrors(WebBrowser webBrowser, bool value)
    {
        FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
        if (field != null)
        {
            object axIWebBrowser2 = field.GetValue(webBrowser);
            if (axIWebBrowser2 != null)
            {
                axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { value });
                return true;
            }
        }

        return false;
    }

usage example to set webBrowser to silent : TrySetSuppressScriptErrors(webBrowser,true)

Is CSS Turing complete?

As per this article, it's not. The article also argues that it's not a good idea to make it one.

To quote from one of the comments:

So, I do not believe that CSS is turing complete. There is no capability to define a function in CSS. In order for a system to be turing-complete it has to be possible to write an interpreter: a function that interprets expressions that denote programs to execute. CSS has no variables that are directly accessible to the user; so you cannot even model the structure that represents the program to be interpreted in CSS.

How to get local server host and port in Spring Boot?

I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.

You need to add the maven dependency first:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

Then you can use the ApplicationInfoManager service in any of your Spring beans.

@Autowired
private ApplicationInfoManager applicationInfoManager;
...

InstanceInfo applicationInfo = applicationInfoManager.getInfo();

The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.

Flask raises TemplateNotFound error even though template file exists

I think Flask uses the directory templates by default. So your code should be like this

suppose this is your hello.py

from flask import Flask,render_template

app=Flask(__name__,template_folder='template')


@app.route("/")
def home():
    return render_template('home.html')

@app.route("/about/")
def about():
    return render_template('about.html')

if __name__=="__main__":
    app.run(debug=True)

And you work space structure like

project/
    hello.py        
    template/
         home.html
         about.html    
    static/
           js/
             main.js
           css/
               main.css

also you have create two html files with name of home.html and about.html and put those files in templates folder.

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

How to convert object to Dictionary<TKey, TValue> in C#?

    public static KeyValuePair<object, object > Cast<K, V>(this KeyValuePair<K, V> kvp)
    {
        return new KeyValuePair<object, object>(kvp.Key, kvp.Value);
    }

    public static KeyValuePair<T, V> CastFrom<T, V>(Object obj)
    {
        return (KeyValuePair<T, V>) obj;
    }

    public static KeyValuePair<object , object > CastFrom(Object obj)
    {
        var type = obj.GetType();
        if (type.IsGenericType)
        {
            if (type == typeof (KeyValuePair<,>))
            {
                var key = type.GetProperty("Key");
                var value = type.GetProperty("Value");
                var keyObj = key.GetValue(obj, null);
                var valueObj = value.GetValue(obj, null);
                return new KeyValuePair<object, object>(keyObj, valueObj);
            }
        }
        throw new ArgumentException(" ### -> public static KeyValuePair<object , object > CastFrom(Object obj) : Error : obj argument must be KeyValuePair<,>");
    }

From the OP:

Instead of converting my whole Dictionary, i decided to keep my obj dynamic the whole time. When i access the keys and values of my Dictionary with a foreach later, i use foreach(dynamic key in obj.Keys) and convert the keys and values to strings simply.

Why is the use of alloca() not considered good practice?

As noted in this newsgroup posting, there are a few reasons why using alloca can be considered difficult and dangerous:

  • Not all compilers support alloca.
  • Some compilers interpret the intended behaviour of alloca differently, so portability is not guaranteed even between compilers that support it.
  • Some implementations are buggy.

Why can't I see the "Report Data" window when creating reports?

I was also same problem in Visual Studio 2013, Then Suddenly got an Idea.. Click on Report to make focus on it. Simple Press Alt+Ctrl+D

How to simplify a null-safe compareTo() implementation?

If you want a simple Hack:

arrlist.sort((o1, o2) -> {
    if (o1.getName() == null) o1.setName("");
    if (o2.getName() == null) o2.setName("");

    return o1.getName().compareTo(o2.getName());
})

if you want put nulls to end of the list just change this in above metod

return o2.getName().compareTo(o1.getName());

Explicit Return Type of Lambda

You can have more than one statement when still return:

[]() -> your_type {return (
        your_statement,
        even_more_statement = just_add_comma,
        return_value);}

http://www.cplusplus.com/doc/tutorial/operators/#comma

How to send a pdf file directly to the printer using JavaScript?

This is actually a lot easier using a dataURI, because you can just call print on the returned window object.

// file is a File object, this will also take a blob
const dataUrl = window.URL.createObjectURL(file);

// Open the window
const pdfWindow = window.open(dataUrl);

// Call print on it
pdfWindow.print();

This opens the pdf in a new tab and then pops the print dialog up.

Use Device Login on Smart TV / Console

Implement Login for Devices

Facebook Login for Devices is for devices that directly make HTTP calls over the internet. The following are the API calls and responses your device can make.

1. Enable Login for Devices

Change Settings > Advanced > OAuth Settings > Login from Devices to 'Yes'.

2. Generate a Code which is required for facebook device identification

When the person clicks Log in with Facebook, you device should make an HTTP POST to:

POST https://graph.facebook.com/oauth/device?
       type=device_code
       &amp;client_id=<YOUR_APP_ID>
       &amp;scope=<COMMA_SEPARATED_PERMISSION_NAMES> // e.g.public_profile,user_likes

The response comes in this form:

{
  "code": "92a2b2e351f2b0b3503b2de251132f47",
  "user_code": "A1NWZ9",
  "verification_uri": "https://www.facebook.com/device",
  "expires_in": 420,
  "interval": 5
}

This response means:

  • Display the string “A1NWZ9” on your device
  • Tell the person to go to “facebook.com/device” and enter this code
  • The code expires in 420 seconds. You should cancel the login flow after that time if you do not receive an access token
  • Your device should poll the Device Login API every 5 seconds to see if the authorization has been successful

3. Display the Code

Your device should display the user_code and tell people to visit the verification_uri such as facebook.com/device on their PC or smartphone. See the Design Guidelines.

4. Poll for Authorization

Your device should poll the Device Login API to see if the person successfully authorized your application. You should do this at the interval in the response to your call in Step 1, which is every 5 seconds. Your device should poll to:

POST https://graph.facebook.com/oauth/device?
       type=device_token
       &amp;client_id=<YOUR_APP_ID> 
       &amp;code=<LONG_CODE_FROM_STEP_1> //e.g."92a2b2e351f2b0b3503b2de251132f47"

You will get 200 HTTP code i.e User has successfully authorized the device. The device can now use the access_token value to make authenticated API calls.

5. Confirm Successful Login

Your device should display their name and if available, a profile picture until they click Continue. To get the person's name and profile picture, your device should make a standard Graph API call:

GET https://graph.facebook.com/v2.3/me?
      fields=name,picture&amp;
      access_token=<USER_ACCESS_TOKEN>

Response:

{
  "name": "John Doe", 
  "picture": {
    "data": {
      "is_silhouette": false, 
      "url": "https://fbcdn.akamaihd.net/hmac...ile.jpg"
    }
  }, 
  "id": "2023462875238472"
}

6. Store Access Tokens

Your device should persist the access token to make other requests to the Graph API.

Device Login access tokens may be valid for up to 60 days but may be invalided in a number of scenarios. For example when a person changes their Facebook password their access token is invalidated.

If the token is invalid, your device should delete the token from its memory. The person using your device needs to perform the Device Login flow again from Step 1 to retrieve a new, valid token.

database attached is read only

If you have tried all of this and still no luck, try the detach/attach again.

Passing a varchar full of comma delimited values to a SQL Server IN function

Thanks, for your function I Used IT........................ This is my EXAMPLE

**UPDATE [RD].[PurchaseOrderHeader]
SET     [DispatchCycleNumber] ='10'
 WHERE  OrderNumber in(select * FROM XA.fn_SplitOrderIDs(@InvoiceNumberList))**


CREATE FUNCTION [XA].[fn_SplitOrderIDs]
(
    @OrderList varchar(500)
)
RETURNS 
@ParsedList table
(
    OrderID int
)
AS
BEGIN
    DECLARE @OrderID varchar(10), @Pos int

    SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
    SET @Pos = CHARINDEX(',', @OrderList, 1)

    IF REPLACE(@OrderList, ',', '') <> ''
    BEGIN
        WHILE @Pos > 0
        BEGIN
                SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
                IF @OrderID <> ''
                BEGIN
                        INSERT INTO @ParsedList (OrderID) 
                        VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
                END
                SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
                SET @Pos = CHARINDEX(',', @OrderList, 1)

        END
    END 
    RETURN
END

How does "cat << EOF" work in bash?

The cat <<EOF syntax is very useful when working with multi-line text in Bash, eg. when assigning multi-line string to a shell variable, file or a pipe.

Examples of cat <<EOF syntax usage in Bash:

1. Assign multi-line string to a shell variable

$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)

The $sql variable now holds the new-line characters too. You can verify with echo -e "$sql".

2. Pass multi-line string to a file in Bash

$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF

The print.sh file now contains:

#!/bin/bash
echo $PWD
echo /home/user

3. Pass multi-line string to a pipe in Bash

$ cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF

The b.txt file contains bar and baz lines. The same output is printed to stdout.