Programs & Examples On #Setlocale

How to change the integrated terminal in visual studio code or VSCode

If you want to change the external terminal to the new windows terminal, here's how.

pip install - locale.Error: unsupported locale setting

Ubuntu:

$ sudo vi /etc/default/locale

Add below setting at the end of file.

LC_ALL = en_US.UTF-8

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

Converting Float to Dollars and Cents

Personally, I like this much better (which, granted, is just a different way of writing the currently selected "best answer"):

money = float(1234.5)
print('$' + format(money, ',.2f'))

Or, if you REALLY don't like "adding" multiple strings to combine them, you could do this instead:

money = float(1234.5)
print('${0}'.format(format(money, ',.2f')))

I just think both of these styles are a bit easier to read. :-)

(of course, you can still incorporate an If-Else to handle negative values as Eric suggests too)

Python locale error: unsupported locale setting

if I understand correctly, the main source of error here is the exact syntax of the locale-name. Especially as it seems to differ between distributions. I've seen mentioned here in different answers/comments:

de_DE.utf8
de_DE.UTF-8

Even though this is obviously the same for a human being, the same does not hold for your standard deterministic algorithm.

So you will probably do something along the lines of:

DESIRED_LOCALE=de
DESIRED_LOCALE_COUNTRY=DE
DESIRED_CODEPAGE_RE=\.[Uu][Tt][Ff].?8
if [ $(locale -a | grep -cE "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}") -eq 1 ]
then
    export LC_ALL=$(locale -a | grep -m1 -E "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}")
    export LANG=$LC_ALL
else
    echo "Not exactly one desired locale definition found: $(locale -a | grep -E "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}")" >&2
fi

UTF-8 problems while reading CSV file with fgetcsv

Try this:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>

How to convert wstring into string?

This solution is inspired in dk123's solution, but uses a locale dependent codecvt facet. The result is in locale encoded string instead of UTF-8 (if it is not set as locale):

std::string w2s(const std::wstring &var)
{
   static std::locale loc("");
   auto &facet = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(loc);
   return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).to_bytes(var);
}

std::wstring s2w(const std::string &var)
{
   static std::locale loc("");
   auto &facet = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(loc);
   return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).from_bytes(var);
}

I was searching for it, but I can't find it. Finally I found that I can get the right facet from std::locale using the std::use_facet() function with the right typename. Hope this helps.

How do I remove accents from characters in a PHP string?

In laravel you can simply use str_slug($accentedPhrase) and if you care about dash (-) that this method substitute with space you can use str_replace('-', ' ', str_slug($accentedPhrase))

How to read from stdin line by line in Node

In my case the program (elinks) returned lines that looked empty, but in fact had special terminal characters, color control codes and backspace, so grep options presented in other answers did not work for me. So I wrote this small script in Node.js. I called the file tight, but that's just a random name.

#!/usr/bin/env node

function visible(a) {
    var R  =  ''
    for (var i = 0; i < a.length; i++) {
        if (a[i] == '\b') {  R -= 1; continue; }  
        if (a[i] == '\u001b') {
            while (a[i] != 'm' && i < a.length) i++
            if (a[i] == undefined) break
        }
        else R += a[i]
    }
    return  R
}

function empty(a) {
    a = visible(a)
    for (var i = 0; i < a.length; i++) {
        if (a[i] != ' ') return false
    }
    return  true
}

var readline = require('readline')
var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false })

rl.on('line', function(line) {
    if (!empty(line)) console.log(line) 
})

Python string prints as [u'String']

pass the output to str() function and it will remove the convert the unicode output. also by printing the output it will remove the u'' tags from it.

Superscript in CSS only?

If you are changing the font size, you might want to stop shrinking sizes with this rule:

sup sub, sub sup, sup sup, sub sub{font-size:1em !important;}

Set default host and port for ng serve in config file

If you want to specifically have your local ip address open when running ng serve you can do the following:

npm install internal-ip-cli --save
ng serve --open --host $(./node_modules/.bin/internal-ip --ipv4)

How to check whether a variable is a class or not?

There are some working solutions here already, but here's another one:

>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True

how to get all markers on google-maps-v3

For an specific cluster use: getMarkers() Gets the array of markers in the clusterer.

For all the markers in the map use: getTotalMarkers() Gets the array of markers in the clusterer.

Count textarea characters

Here is simple code. Hope it is working

_x000D_
_x000D_
$(document).ready(function() {_x000D_
var text_max = 99;_x000D_
$('#textarea_feedback').html(text_max + ' characters remaining');_x000D_
_x000D_
$('#textarea').keyup(function() {_x000D_
    var text_length = $('#textarea').val().length;_x000D_
    var text_remaining = text_max - text_length;_x000D_
_x000D_
    $('#textarea_feedback').html(text_remaining + ' characters remaining');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>_x000D_
<div id="textarea_feedback"></div>
_x000D_
_x000D_
_x000D_

How do you change the launcher logo of an app in Android Studio?

Click app/manifests/AndroidManifest.xml You see android:icon="@mipmap/your image name"

Also change android:roundicon="@mipmap/your image name" Example: android:icon="@mipmap/image" that's all

Factorial using Recursion in Java

In my opinion, and that being the opinion of someone with beginner level knowledge of java, I would suggest that the n == 1 to be changed to n <= 1 or (n == 0)||(n==1) because the factorial of 0 is 1.

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

RegEx to exclude a specific string constant

You have to use a negative lookahead assertion.

(?!^ABC$)

You could for example use the following.

(?!^ABC$)(^.*$)

If this does not work in your editor, try this. It is tested to work in ruby and javascript:

^((?!ABC).)*$

window.close() doesn't work - Scripts may close only the windows that were opened by it

You can't close a current window or any window or page that is opened using '_self' But you can do this

var customWindow = window.open('', '_blank', '');
    customWindow.close();

Round up to Second Decimal Place in Python

def round_up(number, ndigits=None):
    # start by just rounding the number, as sometimes this rounds it up
    result = round(number, ndigits if ndigits else 0)
    if result < number:
        # whoops, the number was rounded down instead, so correct for that
        if ndigits:
            # use the type of number provided, e.g. float, decimal, fraction
            Numerical = type(number)
            # add the digit 1 in the correct decimal place
            result += Numerical(10) ** -ndigits
            # may need to be tweaked slightly if the addition was inexact
            result = round(result, ndigits)
        else:
            result += 1 # same as 10 ** -0 for precision of zero digits
    return result

assert round_up(0.022499999999999999, 2) == 0.03
assert round_up(0.1111111111111000, 2) == 0.12

assert round_up(1.11, 2) == 1.11
assert round_up(1e308, 2) == 1e308

Execute external program

borrowed this shamely from here

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}

More information here

Other issues on how to pass commands here and here

MongoDb query condition on comparing 2 fields

If your query consists only of the $where operator, you can pass in just the JavaScript expression:

db.T.find("this.Grade1 > this.Grade2");

For greater performance, run an aggregate operation that has a $redact pipeline to filter the documents which satisfy the given condition.

The $redact pipeline incorporates the functionality of $project and $match to implement field level redaction where it will return all documents matching the condition using $$KEEP and removes from the pipeline results those that don't match using the $$PRUNE variable.


Running the following aggregate operation filter the documents more efficiently than using $where for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where, which can slow down the query:

db.T.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$gt": [ "$Grade1", "$Grade2" ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

which is a more simplified version of incorporating the two pipelines $project and $match:

db.T.aggregate([
    {
        "$project": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
            "Grade1": 1,
            "Grade2": 1,
            "OtherFields": 1,
            ...
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

With MongoDB 3.4 and newer:

db.T.aggregate([
    {
        "$addFields": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

Posting a File and Associated Data to a RESTful WebService preferably as JSON

I asked a similar question here:

How do I upload a file with metadata using a REST web service?

You basically have three choices:

  1. Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
  2. Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.
  3. Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

Register .NET Framework 4.5 in IIS 7.5

Hosting asp.net 4.5/4.5.1 Web application on Local IIS 1)Be Sure IIS Installation before Visual Installation Installataion then aspnet_regiis will already registerd with IIS

If Not Install IIS and then Register aspnet_regiis with IIS by cmd Editor

For VS2012 and 32 bit OS Run Below code on command editor :

1)Install IIS First & then

2)

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319   

  C:\Windows\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i

For VS2012 and 64 bit OS Below code on command editor:

1)Install IIS First & then

2)

cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319    
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319> aspnet_regiis -i

BY Following Above Steps Current Version of VS2012 registered with IIS Hosting (VS2012 Web APP)

Create VS2012 Web Application(WebForm/MVC) then Build Application Right Click On WebApplication(WebForm/MVC) go to 'Properties' Click On 'Web' Tab on then 'Use Local IIS Web Server' Then Uncheck 'Use IIS Express' (If Visul Studio 2013 Select 'Local IIS' from Dropdown) Provide Project Url like "http://localhost/MvcDemoApp" Then Click On 'Create Virtual Directory' Button Then Open IIS by Prssing 'Window + R' Run Command and type 'inetmgr' and 'Enter' (or 'OK' Button) Then Expand 'Sites->Default Web Site' you Hosted Successfully. If Still Gets any Server Error like 'The resource cannot be found.' Then Include following code in web.config

 <configuration>
     <system.webServer>
         <modules runAllManagedModulesForAllRequests="true"></modules>

And Run Application

If still problem occurs Check application pool by : In iis Right click on application->Manage Application->Advanced setting->General. you see the application pool. then close advance setting window. click on 'Application Pools' you will see the all application pools in middle window. Right click on application pool in which application hosted(DefaultAppPool). click 'Basic Setting' -> Change .Net FrameWork Version to->.Net FrameWork v4.0.30349

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

Spring security CORS Filter

In my case, I just added this class and use @EnableAutConfiguration:

@Component
public class SimpleCORSFilter extends GenericFilterBean {
    /**
     * The Logger for this class.
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        logger.info("> doFilter");

        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, resp);

        logger.info("< doFilter");
    }
}

how to convert .java file to a .class file

From the command line, run

javac ClassName.java

How to prevent caching of my Javascript file?

You can add a random (or datetime string) as query string to the url that points to your script. Like so:

<script type="text/javascript" src="test.js?q=123"></script> 

Every time you refresh the page you need to make sure the value of 'q' is changed.

Javascript Print iframe contents only

an alternate option, which may or may not be suitable, but cleaner if it is:

If you always want to just print the iframe from the page, you can have a separate "@media print{}" stylesheet that hides everything besides the iframe. Then you can just print the page normally.

How to get an array of unique values from an array containing duplicates in JavaScript?

I like to use this. There is nothing wrong with using the for loop, I just like using the build-in functions. You could even pass in a boolean argument for typecast or non typecast matching, which in that case you would use a for loop (the filter() method/function does typecast matching (===))

Array.prototype.unique =
function()
{
    return this.filter(
        function(val, i, arr)
        {
            return (i <= arr.indexOf(val));
        }
    );
}

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

By default, the classes in the csv module use Windows-style line terminators (\r\n) rather than Unix-style (\n). Could this be what’s causing the apparent double line breaks?

If so, you can override it in the DictWriter constructor:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)

How to exclude a directory from ant fileset, based on directories contents

There is actually an example for this type of issue in the Ant documentation. It makes use of Selectors (mentioned above) and mappers. See last example in http://ant.apache.org/manual/Types/dirset.html :

<dirset id="dirset" dir="${workingdir}">
   <present targetdir="${workingdir}">
        <mapper type="glob" from="*" to="*/${markerfile}" />
   </present>
</dirset>

Selects all directories somewhere under ${workingdir} which contain a ${markerfile}.

Reading CSV files using C#

private static DataTable ConvertCSVtoDataTable(string strFilePath)
        {
            DataTable dt = new DataTable();
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string[] headers = sr.ReadLine().Split(',');
                foreach (string header in headers)
                {
                    dt.Columns.Add(header);
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(',');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt.Rows.Add(dr);
                }

            }

            return dt;
        }

        private static void WriteToDb(DataTable dt)
        {
            string connectionString =
                "Data Source=localhost;" +
                "Initial Catalog=Northwind;" +
                "Integrated Security=SSPI;";

            using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("spInsertTest", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add("@policyID", SqlDbType.Int).Value = 12;
                        cmd.Parameters.Add("@statecode", SqlDbType.VarChar).Value = "blagh2";
                        cmd.Parameters.Add("@county", SqlDbType.VarChar).Value = "blagh3";

                        con.Open();
                        cmd.ExecuteNonQuery();
                    }
                }

         }

ViewDidAppear is not called when opening app from background

Just have your view controller register for the UIApplicationWillEnterForegroundNotification notification and react accordingly.

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

Hash === @some_var #=> return Boolean

this can also be used with case statement

case @some_var
when Hash
   ...
when Array
   ...
end

Route [login] not defined

If someone getting this from a rest client (ex. Postman) - You need to set the Header to Accept application/json.

To do this on postman, click on the Headers tab, and add a new key 'Accept' and type the value 'application/json'.

How do I invoke a Java method when given the method name as a string?

If you do the call several times you can use the new method handles introduced in Java 7. Here we go for your method returning a String:

Object obj = new Point( 100, 200 );
String methodName = "toString";  
Class<String> resultType = String.class;

MethodType mt = MethodType.methodType( resultType );
MethodHandle methodHandle = MethodHandles.lookup().findVirtual( obj.getClass(), methodName, mt );
String result = resultType.cast( methodHandle.invoke( obj ) );

System.out.println( result );  // java.awt.Point[x=100,y=200]

How to create a Calendar table for 100 years in Sql

This SQL Server User Defined Function resolves the problem efficiently.No recursion, no complex loops. It takes a very short time to generate.

ALTER FUNCTION [GA].[udf_GenerateCalendar]
(
     @StartDate  DATE        -- StartDate
   , @EndDate    DATE        -- EndDate
)
RETURNS @Results TABLE 
       (
           Date       DATE 
       )
AS

/**********************************************************
Purpose:   Generate a sequence of dates based on StartDate and EndDate 
***********************************************************/

BEGIN

    DECLARE @counter INTEGER = 1 

    DECLARE @days table(
        day INTEGER NOT NULL 
    )

    DECLARE @months table(
        month INTEGER NOT NULL 
    )

    DECLARE @years table(
        year INTEGER NOT NULL 
    )

    DECLARE @calendar table(
        Date DATE NOT NULL 
    )


    -- Populate generic days 
    SET @counter = 1 
    WHILE @counter <= 31 
    BEGIN 
        INSERT INTO @days 
        SELECT @counter dia 

        SELECT @counter = @counter + 1 
    END 

    -- Populate generic months 
    SET @counter = 1 
    WHILE @counter <= 12 
    BEGIN 
        INSERT INTO @months 
        SELECT @counter month 

        SELECT @counter = @counter + 1 
    END 

    -- Populate generic years 
    SET @counter = YEAR(@StartDate) 
    WHILE @counter <= YEAR(@EndDate) 
    BEGIN 
        INSERT INTO @years 
        SELECT @counter year 

        SELECT @counter = @counter + 1 
    END 

    INSERT @calendar (Date) 
    SELECT Date 
    FROM ( 
        SELECT 
            CONVERT(Date, [Date], 102) AS Date 
        FROM ( 
            SELECT 
                CAST(
                    y.year * 10000 
                    + m.month * 100 
                    + d.day 
                    AS VARCHAR(8)) AS Date 
            FROM @days d, @months m, @years y 
            WHERE 
                ISDATE(CAST(
                    y.year * 10000 
                    + m.month * 100 
                    + d.day 
                    AS VARCHAR(8)) 
                    ) = 1 
        ) A 
    ) A 

    INSERT @Results (Date) 
    SELECT Date 
    FROM @calendar 
    WHERE Date BETWEEN @StartDate AND @EndDate

   RETURN 
/*
DECLARE @StartDate DATE = '2015-08-01'
DECLARE @EndDate   DATE = '2015-08-31'
select * from [GA].[udf_GenerateCalendar](@StartDate, @EndDate)
*/
END

XSS filtering function in PHP

I have a similar problem. I need users to submit html content to a profile page with a great WYSIWYG editor (Redactorjs!), i wrote the following function to clean the submitted html:

    <?php function filterxss($str) {
//Initialize DOM:
$dom = new DOMDocument();
//Load content and add UTF8 hint:
$dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">'.$str);
//Array holds allowed attributes and validation rules:
$check = array('src'=>'#(http://[^\s]+(?=\.(jpe?g|png|gif)))#i','href'=>'|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i');
//Loop all elements:
foreach($dom->getElementsByTagName('*') as $node){
    for($i = $node->attributes->length -1; $i >= 0; $i--){
        //Get the attribute:
        $attribute = $node->attributes->item($i);
        //Check if attribute is allowed:
        if( in_array($attribute->name,array_keys($check))) {
            //Validate by regex:    
            if(!preg_match($check[$attribute->name],$attribute->value)) { 
                //No match? Remove the attribute
                $node->removeAttributeNode($attribute); 
            }
        }else{
            //Not allowed? Remove the attribute:
            $node->removeAttributeNode($attribute);
        }
    }
}
var_dump($dom->saveHTML()); } ?>

The $check array holds all the allowed attributes and validation rules. Maybe this is useful for some of you. I haven't tested is yet, so tips are welcome

Escaping Strings in JavaScript

You can also use this

_x000D_
_x000D_
let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
_x000D_
_x000D_

MySQL Join Where Not Exists

There are three possible ways to do that.

  1. Option

    SELECT  lt.* FROM    table_left lt
    LEFT JOIN
        table_right rt
    ON      rt.value = lt.value
    WHERE   rt.value IS NULL
    
  2. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   lt.value NOT IN
    (
    SELECT  value
    FROM    table_right rt
    )
    
  3. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   NOT EXISTS
    (
    SELECT  NULL
    FROM    table_right rt
    WHERE   rt.value = lt.value
    )
    

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

How do I scroll to an element within an overflowed Div?

I write these 2 functions to make my life easier:

function scrollToTop(elem, parent, speed) {
    var scrollOffset = parent.scrollTop() + elem.offset().top;
    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

function scrollToCenter(elem, parent, speed) {
    var elOffset = elem.offset().top;
    var elHeight = elem.height();
    var parentViewTop = parent.offset().top;
    var parentHeight = parent.innerHeight();
    var offset;

    if (elHeight >= parentHeight) {
        offset = elOffset;
    } else {
        margin = (parentHeight - elHeight)/2;
        offset = elOffset - margin;
    }

    var scrollOffset = parent.scrollTop() + offset - parentViewTop;

    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

And use them:

scrollToTop($innerListItem, $parentDiv, 200);
// or
scrollToCenter($innerListItem, $parentDiv, 200);

MySQL: selecting rows where a column is null

As all are given answers I want to add little more. I had also faced the same issue.

Why did your query fail? You have,

SELECT pid FROM planets WHERE userid = NULL;

This will not give you the expected result, because from mysql doc

In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.

Emphasis mine.

To search for column values that are NULL, you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression

Solution

SELECT pid FROM planets WHERE userid IS NULL; 

To test for NULL, use the IS NULL and IS NOT NULL operators.

How can I detect when an Android application is running in the emulator?

This code works for me

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tm.getNetworkOperatorName();
if("Android".equals(networkOperator)) {
    // Emulator
}
else {
    // Device
}

In case that device does not have sim card, It retuns empty string:""

Since Android emulator always retuns "Android" as network operator, I use above code.

bootstrap multiselect get selected values

Shorter version:

$('#multiselect1').multiselect({
    ...
    onChange: function() {
        console.log($('#multiselect1').val());
    }
}); 

How to use PrintWriter and File classes in Java?

You should have a clear idea of exceptions in java. In java there are checked exceptions and unchecked exceptions.

Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.

NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:

CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.

How to resolve: 1.Put your code in try catch block:

2.use throws keyword as shown by other guys above.

Advice:Read more about Exceptions.(I personally love this topic)

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

passing JSON data to a Spring MVC controller

Add the following dependencies

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.7</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.7</version>
</dependency>

Modify request as follows

$.ajax({ 
    url:urlName,    
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser          
    processData:false, //To avoid making query String instead of JSON
    success: function(resposeJsonObject){
        // Success Message Handler
    }
});

Controller side

@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {

   Person person=personService.savedata(jsonString);
   return person;
}

@RequestBody - Covert Json object to java
@ResponseBody- convert Java object to json

Print ArrayList

Add toString() method to your address class then do

System.out.println(Arrays.toString(houseAddress));

Create a new workspace in Eclipse

You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.

You can then import project to your workspace, copy paste project to your new workspace folder, then

File?Import?Existing project in to workspace?select project.

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    {{msg}}
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>

    </div>
     <h1>here</h1>
  </body>

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';
  }
});

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $scope.name = 'World';

  $scope.go = function(item) {
    sharedProperties.setListName(item);


  }

  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();
  }
});

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        },
        setListName: function(name) {
            list_name = name;
        }
    };


});

* Edit *

Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

Better/Faster to Loop through set or list?

Just use a set. Its semantics are exactly what you want: a collection of unique items.

Technically you'll be iterating through the list twice: once to create the set, once for your actual loop. But you'd be doing just as much work or more with any other approach.

Convert Base64 string to an image file?

This code worked for me.

_x000D_
_x000D_
<?php_x000D_
$decoded = base64_decode($base64);_x000D_
$file = 'invoice.pdf';_x000D_
file_put_contents($file, $decoded);_x000D_
_x000D_
if (file_exists($file)) {_x000D_
    header('Content-Description: File Transfer');_x000D_
    header('Content-Type: application/octet-stream');_x000D_
    header('Content-Disposition: attachment; filename="'.basename($file).'"');_x000D_
    header('Expires: 0');_x000D_
    header('Cache-Control: must-revalidate');_x000D_
    header('Pragma: public');_x000D_
    header('Content-Length: ' . filesize($file));_x000D_
    readfile($file);_x000D_
    exit;_x000D_
}_x000D_
?>
_x000D_
_x000D_
_x000D_

Pandas DataFrame column to list

You can use the Series.to_list method.

For example:

import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
                   'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})

print(df['a'].to_list())

Output:

[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]

To drop duplicates you can do one of the following:

>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]

How do I pass multiple ints into a vector at once?

You can also use Boost.Assignment:

const list<int> primes = list_of(2)(3)(5)(7)(11);

vector<int> v; 
v += 1,2,3,4,5,6,7,8,9;

Check if string is in a pandas dataframe

You should check the value of your line of code like adding checking length of it.

if(len(a['Names'].str.contains('Mel'))>0):
    print("Name Present")

It says that TypeError: document.getElementById(...) is null

You can use JQuery to ensure that all elements of the documents are ready before it starts the client side scripting

$(document).ready(
    function()
    {
        document.getElementById(elmId).innerHTML = value;
    }
);

How to convert R Markdown to PDF?

Updated Answer (10 Feb 2013)

rmarkdown package: There is now an rmarkdown package available on github that interfaces with Pandoc. It includes a render function. The documentation makes it pretty clear how to convert rmarkdown to pdf among a range of other formats. This includes including output formats in the rmarkdown file or running supplying an output format to the rend function. E.g.,

render("input.Rmd", "pdf_document")

Command-line: When I run render from the command-line (e.g., using a makefile), I sometimes have issues with pandoc not being found. Presumably, it is not on the search path. The following answer explains how to add pandoc to the R environment.

So for example, on my computer running OSX, where I have a copy of pandoc through RStudio, I can use the following:

Rscript -e "Sys.setenv(RSTUDIO_PANDOC='/Applications/RStudio.app/Contents/MacOS/pandoc');library(rmarkdown);  library(utils); render('input.Rmd', 'pdf_document')"

Old Answer (circa 2012)

So, a number of people have suggested that Pandoc is the way to go. See notes below about the importance of having an up-to-date version of Pandoc.

Using Pandoc

I used the following command to convert R Markdown to HTML (i.e., a variant of this makefile), where RMDFILE is the name of the R Markdown file without the .rmd component (it also assumes that the extension is .rmd and not .Rmd).

RMDFILE=example-r-markdown  
Rscript -e "require(knitr); require(markdown); knit('$RMDFILE.rmd', '$RMDFILE.md'); markdownToHTML('$RMDFILE.md', '$RMDFILE.html', options=c('use_xhml'))"

and then this command to convert to pdf

Pandoc -s example-r-markdown.html -o example-r-markdown.pdf


A few notes about this:

  • I removed the reference in the example file which exports plots to imgur to host images.
  • I removed a reference to an image that was hosted on imgur. Figures appear to need to be local.
  • The options in the markdownToHTML function meant that image references are to files and not to data stored in the HTML file (i.e., I removed 'base64_images' from the option list).
  • The resulting output looked like this. It has clearly made a very LaTeX style document in contrast to what I get if I print the HTML file to pdf from a browser.

Getting up-to-date version of Pandoc

As mentioned by @daroczig, it's important to have an up-to-date version of Pandoc in order to output pdfs. On Ubuntu as of 15th June 2012, I was stuck with version 1.8.1 of Pandoc in the package manager, but it seems from the change log that for pdf support you need at least version 1.9+ of Pandoc.

Thus, I installed caball-install. And then ran:

cabal update
cabal install pandoc

Pandoc was installed in ~/.cabal/bin/pandoc Thus, when I ran pandoc it was still seeing the old version. See here for adding to the path.

How to download image using requests

You can either use the response.raw file object, or iterate over the response.

To use the response.raw file-like object will not, by default, decode compressed responses (with GZIP or deflate). You can force it to decompress for you anyway by setting the decode_content attribute to True (requests sets it to False to control decoding itself). You can then use shutil.copyfileobj() to have Python stream the data to a file object:

import requests
import shutil

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)        

To iterate over the response use a loop; iterating like this ensures that data is decompressed by this stage:

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        for chunk in r:
            f.write(chunk)

This'll read the data in 128 byte chunks; if you feel another chunk size works better, use the Response.iter_content() method with a custom chunk size:

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        for chunk in r.iter_content(1024):
            f.write(chunk)

Note that you need to open the destination file in binary mode to ensure python doesn't try and translate newlines for you. We also set stream=True so that requests doesn't download the whole image into memory first.

SQL Server query to find all permissions/access for all users in a database

Can't comment on accepted answer so I'll add some comments here:

  • I second Brad on schemas issue. From MS reference sys.objects table contains only schema-scoped objects. So to get info about "higher level" objects (i.e. schemas in our case) you need to use sys.schemas table.
  • For [ObjectType] it's better to use obj.type_desc only for OBJECT_OR_COLUMN permission class. For all other cases use perm.[class_desc]
  • Another type of permission which is not handled so well with this query is IMPERSONATE. To get info about impersonations one should LEFT JOIN with sys.database_principals on perm.major_id = imp.principal_id
  • With my experience it's better to replace sys.login_token with sys.server_principals as it will show also SQL Logins, not only Windows ones
  • One should add 'G' to allowed principal types to allow Windows groups
  • Also, one can exclude users sys and INFORMATION_SCHEMA from resulting table, as these users are used only for service

I'll post first piece of script with all proposed fixes, other parts should be changed as well:

SELECT  
    [UserName] = ulogin.[name],
    [UserType] = CASE princ.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                    WHEN 'G' THEN 'Windows Group'
                 END,  
    [DatabaseUserName] = princ.[name],       
    [Role] = null,      
    [PermissionType] = perm.[permission_name],       
    [PermissionState] = perm.[state_desc],       
    [ObjectType] = CASE perm.[class] 
                        WHEN 1 THEN obj.type_desc               -- Schema-contained objects
                        ELSE perm.[class_desc]                  -- Higher-level objects
                   END,       
    [ObjectName] = CASE perm.[class] 
                        WHEN 1 THEN OBJECT_NAME(perm.major_id)  -- General objects
                        WHEN 3 THEN schem.[name]                -- Schemas
                        WHEN 4 THEN imp.[name]                  -- Impersonations
                   END,
    [ColumnName] = col.[name]
FROM    
    --database user
    sys.database_principals princ  
LEFT JOIN
    --Login accounts
    sys.server_principals ulogin on princ.[sid] = ulogin.[sid]
LEFT JOIN        
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = princ.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col ON col.[object_id] = perm.major_id 
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
LEFT JOIN
    sys.schemas schem ON schem.[schema_id] = perm.[major_id]
LEFT JOIN
    sys.database_principals imp ON imp.[principal_id] = perm.[major_id]
WHERE 
    princ.[type] IN ('S','U','G') AND
    -- No need for these system accounts
    princ.[name] NOT IN ('sys', 'INFORMATION_SCHEMA')

Path to Powershell.exe (v 2.0)

I think $PsHome has the information you're after?

PS .> $PsHome
C:\Windows\System32\WindowsPowerShell\v1.0

PS .> Get-Help about_automatic_variables

TOPIC
    about_Automatic_Variables ...

Set value of hidden input with jquery

You don't need to set name , just giving an id is enough.

<input type="hidden" id="testId" />

and than with jquery you can use 'val()' method like below:

 $('#testId').val("work");

Get Image Height and Width as integer values?

list($width, $height) = getimagesize($filename)

Or,

$data = getimagesize($filename);
$width = $data[0];
$height = $data[1];

Recover unsaved SQL query scripts

I was able to recover my files from the following location:

C:\Users\<yourusername>\Documents\SQL Server Management Studio\Backup Files\Solution1

There should be different recovery files per tab. I'd say look for the files for the date you lost them.

Sanitizing strings to make them URL and filename safe?

I found this larger function in the Chyrp code:

/**
 * Function: sanitize
 * Returns a sanitized string, typically for URLs.
 *
 * Parameters:
 *     $string - The string to sanitize.
 *     $force_lowercase - Force the string to lowercase?
 *     $anal - If set to *true*, will remove all non-alphanumeric characters.
 */
function sanitize($string, $force_lowercase = true, $anal = false) {
    $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
                   "}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
                   "—", "–", ",", "<", ".", ">", "/", "?");
    $clean = trim(str_replace($strip, "", strip_tags($string)));
    $clean = preg_replace('/\s+/', "-", $clean);
    $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
    return ($force_lowercase) ?
        (function_exists('mb_strtolower')) ?
            mb_strtolower($clean, 'UTF-8') :
            strtolower($clean) :
        $clean;
}

and this one in the wordpress code

/**
 * Sanitizes a filename replacing whitespace with dashes
 *
 * Removes special characters that are illegal in filenames on certain
 * operating systems and special characters requiring special escaping
 * to manipulate at the command line. Replaces spaces and consecutive
 * dashes with a single dash. Trim period, dash and underscore from beginning
 * and end of filename.
 *
 * @since 2.1.0
 *
 * @param string $filename The filename to be sanitized
 * @return string The sanitized filename
 */
function sanitize_file_name( $filename ) {
    $filename_raw = $filename;
    $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
    $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
    $filename = str_replace($special_chars, '', $filename);
    $filename = preg_replace('/[\s-]+/', '-', $filename);
    $filename = trim($filename, '.-_');
    return apply_filters('sanitize_file_name', $filename, $filename_raw);
}

Update Sept 2012

Alix Axel has done some incredible work in this area. His phunction framework includes several great text filters and transformations.

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

C# Base64 String to JPEG Image

Front :

  <Image Name="camImage"/>

Back:

 public async void Base64ToImage(string base64String)
        {
            // read stream
            var bytes = Convert.FromBase64String(base64String);
            var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();

            // decode image
            var decoder = await BitmapDecoder.CreateAsync(image);
            image.Seek(0);

            // create bitmap
            var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
            await output.SetSourceAsync(image);

            camImage.Source = output;
        }

How to Export-CSV of Active Directory Objects?

From a Windows Server OS execute the following command for a dump of the entire Active Director:

csvde -f test.csv

This command is very broad and will give you more than necessary information. To constrain the records to only user records, you would instead want:

csvde -f test.csv -r objectClass=user 

You can further restrict the command to give you only the fields you need relevant to the search requested such as:

csvde -f test.csv -r objectClass=user -l DN, sAMAccountName, department, memberOf

If you have an Exchange server and each user associated with a live person has a mailbox (as opposed to generic accounts for kiosk / lab workstations) you can use mailNickname in place of sAMAccountName.

Integrity constraint violation: 1452 Cannot add or update a child row:

If you are adding new foreign key to an existing table and the columns are not null and not assigned default value, you will get this error,

Either you need to make it nullable or assign default value, or delete all the existing records to solve it.

How would you count occurrences of a string (actually a char) within a string?

string source = "/once/upon/a/time/";
int count = 0, n = 0;
while ((n = source.IndexOf('/', n) + 1) != 0) count++;

A variation on Richard Watson's answer, slightly faster with improving efficiency the more times the char occurs in the string, and less code!

Though I must say, without extensively testing every scenario, I did see a very significant speed improvement by using:

int count = 0;
for (int n = 0; n < source.Length; n++) if (source[n] == '/') count++;

How to add multiple jar files in classpath in linux

You use the -classpath argument. You can use either a relative or absolute path. What that means is you can use a path relative to your current directory, OR you can use an absolute path that starts at the root /.

Example:

bash$ java -classpath path/to/jar/file MyMainClass

In this example the main function is located in MyMainClass and would be included somewhere in the jar file.

For compiling you need to use javac

Example:

bash$ javac -classpath path/to/jar/file MyMainClass.java

You can also specify the classpath via the environment variable, follow this example:

bash$ export CLASSPATH="path/to/jar/file:path/tojar/file2"
bash$ javac MyMainClass.java

For any normally complex java project you should look for the ant script named build.xml

LINQ to SQL - Left Outer Join with multiple join conditions

It seems to me there is value in considering some rewrites to your SQL code before attempting to translate it.

Personally, I'd write such a query as a union (although I'd avoid nulls entirely!):

SELECT f.value
  FROM period as p JOIN facts AS f ON p.id = f.periodid
WHERE p.companyid = 100
      AND f.otherid = 17
UNION
SELECT NULL AS value
  FROM period as p
WHERE p.companyid = 100
      AND NOT EXISTS ( 
                      SELECT * 
                        FROM facts AS f
                       WHERE p.id = f.periodid
                             AND f.otherid = 17
                     );

So I guess I agree with the spirit of @MAbraham1's answer (though their code seems to be unrelated to the question).

However, it seems the query is expressly designed to produce a single column result comprising duplicate rows -- indeed duplicate nulls! It's hard not to come to the conclusion that this approach is flawed.

JPA : How to convert a native query result set to POJO class collection

JPA provides an SqlResultSetMapping that allows you to map whatever returns from your native query into an Entity or a custom class.

EDIT JPA 1.0 does not allow mapping to non-entity classes. Only in JPA 2.1 a ConstructorResult has been added to map return values a java class.

Also, for OP's problem with getting count it should be enough to define a result set mapping with a single ColumnResult

Can I check if Bootstrap Modal Shown / Hidden?

When modal hide? we check like this :

$('.yourmodal').on('hidden.bs.modal', function () {
    // do something here
})

$(...).datepicker is not a function - JQuery - Bootstrap

 <script type="text/javascript">

    var options={
            format: 'mm/dd/yyyy',
            todayHighlight: true,
            autoclose: true,
        };

    $('#datetimepicker').datepicker(options);

</script>

ADB No Devices Found

For the Blu Studio 5.5s ADB drivers, you have to go through this hoop. I am certain it is the same with all Blu phones or maybe for all non-Google mfg phones, I am not sure. First of all if you connect the Blu device with USB cable and USB Debuggin off, you will see that Windows 7 loads a generic driver for you to copy on/off files to the phone and SD storage. This will appear when the USB cable is first plugged in and appears as a device icon under Control Panel, Device Manager, Portable Devices, BLU STUDIO 5.5 S (or the device you are working with). Do not bother getting the hardware ID yet - just observe that this happens (which indicates you are good so far and don't have a bad cable or something).

Go to the phone and switch on USB Debugging in the Developer section of your phone. Notice that an additional item appears as an undefined device now in the device manager list, it will have the yellow exclamation mark and it may have the same name of the phone listed as you saw under Portable Devices. Ignore this item for the moment. Now, without doing anything to the phone (it should be already in USB debug mode) go back to the Portable Devices in Device Manager and right-click the BLU STUDIO 5.5 S or whatever phone you are working with that is listed there without the exclamation mark (listed under Portable Devices). Right click on the icon under Portable Devices, in this example the name that appears is BLU STUDIO 5.5 S. On that icon select Properties, Details, and under the pull down, select Hardware IDs and copy down what you see.

For BLU STUDIO 5.5 S I get:

USB\VID_0BB4&PID_0C02&REV_0216&MI_00
USB\VID_0BB4&PID_0C02&MI_00

(Note if you do this out of turn, the HW ID will be different with the phone USB debugging turned off. You want to copy the value that it changes to when the USB debugging is ON)

Now do as the instructions say above, of course customizing the lines you add the the INF file with those relating to your own phone, not the Nexus 10. Here is what to customize; when you downloaded the SDK you should have a file structure expanded from the ZIP such as this:

\adt-bundle-windows-x86_64-20140321\sdk\extras\google\usb_driver

Find the file named: android_winusb.inf in the usb_driver folder Make a copy of it and name it anything, such as myname.inf Edit the myname.inf and add the lines as instructed above only modified for your particular phone. For example, for the BLU STUDIO 5.5 S, I added the following 2 lines as instructed in the 2 locations as instructed.

;BLU STUDIO 5.5 S
%SingleAdbInterface%        = USB_Install, USB\VID_0BB4&PID_0C02&REV_0216&MI_00
%CompositeAdbInterface%     = USB_Install, USB\VID_0BB4&PID_0C02&MI_00

Note that you add these lines to both the 32 and 64 bit sections, matching how the example in the tutorial reads.

Now go back up to the unknown device that appeared in Device Manager when you switched on device USB debugging and right click on this item (has yellow exclamation mark), right click on it and then select Update Driver Software, and then Browse My Computer, Let Me Pick, click on the Have Disk button and browse to find the myname.inf. Continue to agree to all the prompts warning you it might not be the right driver. As the final step, Windows should have identified the device as Android ADB Interface and once that is done, you should be able to go back, open your CMD window and run the command "adb devices" as instructed in this tutorial and now you should see that the phone is now discovered and communicating.

Now you can go have fun with the adb command.

How do I insert a JPEG image into a python Tkinter window?

Try this:

import tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

path = "Aaron.jpg"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)

#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()

Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager

Detect all changes to a <input type="text"> (immediately) using JQuery

We actually don't need to setup loops for detecting javaScript changes. We already setting up many event listeners to the element we want to detect. just triggering any un harmful event will make the job.

$("input[name='test-element']").on("propertychange change click keyup input paste blur", function(){
console.log("yeh thats worked!");
});

$("input[name='test-element']").val("test").trigger("blur");

and ofc this is only available if you have the full control on javascript changes on your project.

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had this issue after converting my Write-Host cmdlets to Write-Information and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.

Write-Host this is a good idea $here
Write-Information this is a good idea $here <=BAD

This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...

Write-Information ("this is a good idea $here") <=GOOD

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

Find and replace Android studio

I think the previous answers missed the most important (non-trivial) aspect of the OP's question, i.e., how to perform the search/replace in a "time saving" manner, meaning once, not three times, and "maintain case" originally present.

On the pane, check "[X] Preserve Case" before clicking the Replace All button

This performs a case-aware "smart" replacement in one pass:

apple -> orange
Apple -> Orange
APPLE -> ORANGE

Also, for peace of mind, don't forget to check the code into the VCS before performing sweeping project-wide replacements.

Load a UIView from nib in Swift

Here is a clean and declarative way of programmatically loading a view using a protocol and protocol extension (Swift 4.2):

protocol XibLoadable {
    associatedtype CustomViewType
    static func loadFromXib() -> CustomViewType
}

extension XibLoadable where Self: UIView {
    static func loadFromXib() -> Self {
        let nib = UINib(nibName: "\(self)", bundle: Bundle(for: self))
        guard let customView = nib.instantiate(withOwner: self, options: nil).first as? Self else {
            // your app should crash if the xib doesn't exist
            preconditionFailure("Couldn't load xib for view: \(self)")
        }
        return customView
    }
}

And you can use this like so:

// don't forget you need a xib file too
final class MyView: UIView, XibLoadable { ... }

// and when you want to use it
let viewInstance = MyView.loadFromXib()

Some additional considerations:

  1. Make sure your custom view's xib file has the view's Custom Class set (and outlets/actions set from there), not the File Owner's.
  2. You can use this protocol/extension external to your custom view or internal. You may want to use it internally if you have some other setup work when initializing your view.
  3. Your custom view class and xib file need to have the same name.

Close Bootstrap Modal

This works well

$(function () {
   $('#modal').modal('toggle');
});

However, when you have multiple modals stacking on top one another it is not effective, so instead , this works

data-dismiss="modal"

What is the path that Django uses for locating and loading templates?

I also had issues with this part of the tutorial (used tutorial for version 1.7).

My mistake was that I only edited the 'Django administration' string, and did not pay enough attention to the manual.

This is the line from django/contrib/admin/templates/admin/base_site.html:

<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>

But after some time and frustration it became clear that there was the 'site_header or default:_' statement, which should be removed. So after removing the statement (like the example in the manual everything worked like expected).

Example manual:

<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>

Font Awesome icon inside text input element

You could use a wrapper. Inside the wrapper, add the font awesome element i and the input element.

<div class="wrapper">
    <i class="fa fa-icon"></i>
    <input type="button">
</div>

then set the wrapper's position to relative:

.wrapper { position: relative; }

and then set the i element's position to absolute, and set the correct place for it:

i.fa-icon { position: absolute; top: 10px; left: 50px; }

(It's a hack, I know, but it gets the job done.)

Fastest way to find second (third...) highest/lowest value in vector or column

I found that removing the max element first and then do another max runs in comparable speed:

system.time({a=runif(1000000);m=max(a);i=which.max(a);b=a[-i];max(b)})
   user  system elapsed 
  0.092   0.000   0.659 

system.time({a=runif(1000000);n=length(a);sort(a,partial=n-1)[n-1]})
   user  system elapsed 
  0.096   0.000   0.653 

scale fit mobile web content using viewport meta tag

In the head add this

//Include jQuery
<meta id="Viewport" name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">

<script type="text/javascript">
$(function(){
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
  var ww = ( $(window).width() < window.screen.width ) ? $(window).width() : window.screen.width; //get proper width
  var mw = 480; // min width of site
  var ratio =  ww / mw; //calculate ratio
  if( ww < mw){ //smaller than minimum size
   $('#Viewport').attr('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=yes, width=' + ww);
  }else{ //regular size
   $('#Viewport').attr('content', 'initial-scale=1.0, maximum-scale=2, minimum-scale=1.0, user-scalable=yes, width=' + ww);
  }
}
});
</script>

Sort dataGridView columns in C# ? (Windows Form)

There's a method on the DataGridView called "Sort":

this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);

This will programmatically sort your datagridview.

Can I set background image and opacity in the same property?

I have used the answer of @Dan Eastwell and it works very well. The code is similar to his code but with some additions.

.granddata {
    position: relative;
    margin-left :0.5%;
    margin-right :0.5%;
}
.granddata:after {
    content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-image: url("/Images/blabla.jpg");
    width: 100%;
    height: 100%;
    opacity: 0.2;
    z-index: -1;
    background-repeat: no-repeat;
    background-position: center;
    background-attachment:fixed;
}

powershell - extract file name and extension

If is from a text file and and presuming name file are surrounded by white spaces this is a way:

$a = get-content c:\myfile.txt

$b = $a | select-string -pattern "\s.+\..{3,4}\s" | select -ExpandProperty matches | select -ExpandProperty value

$b | % {"File name:{0} - Extension:{1}" -f $_.substring(0, $_.lastindexof('.')) , $_.substring($_.lastindexof('.'), ($_.length - $_.lastindexof('.'))) }

If is a file you can use something like this based on your needs:

$a = dir .\my.file.xlsx # or $a = get-item c:\my.file.xlsx 

$a
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\ps


Mode           LastWriteTime       Length Name
----           -------------       ------ ----
-a---      25/01/10    11.51          624 my.file.xlsx


$a.BaseName
my.file
$a.Extension
.xlsx

MySQL Cannot drop index needed in a foreign key constraint

Because you have to have an index on a foreign key field you can just create a simple index on the field 'AID'

CREATE INDEX aid_index ON mytable (AID);

and only then drop the unique index 'AID'

ALTER TABLE mytable DROP INDEX AID;

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

Creating a zero-filled pandas data frame

If you already have a dataframe, this is the fastest way:

In [1]: columns = ["col{}".format(i) for i in range(10)]
In [2]: orig_df = pd.DataFrame(np.ones((10, 10)), columns=columns)
In [3]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
10000 loops, best of 3: 60.2 µs per loop

Compare to:

In [4]: %timeit d = pd.DataFrame(0, index = np.arange(10), columns=columns)
10000 loops, best of 3: 110 µs per loop

In [5]: temp = np.zeros((10, 10))
In [6]: %timeit d = pd.DataFrame(temp, columns=columns)
10000 loops, best of 3: 95.7 µs per loop

Getting path of captured image in Android using camera intent

Try like this

Pass Camera Intent like below

Intent intent = new Intent(this);
startActivityForResult(intent, REQ_CAMERA_IMAGE);

And after capturing image Write an OnActivityResult as below

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        imageView.setImageBitmap(photo);
        knop.setVisibility(Button.VISIBLE);


        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), photo);

        // CALL THIS METHOD TO GET THE ACTUAL PATH
        File finalFile = new File(getRealPathFromURI(tempUri));

        System.out.println(mImageCaptureUri);
    }  
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    String path = "";
    if (getContentResolver() != null) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            path = cursor.getString(idx);
            cursor.close();
        }
    }
    return path;
}

And check log

Edit:

Lots of people are asking how to not get a thumbnail. You need to add this code instead for the getImageUri method:

public Uri getImageUri(Context inContext, Bitmap inImage) {
    Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
    return Uri.parse(path);
}

The other method Compresses the file. You can adjust the size by changing the number 1000,1000

How do I set hostname in docker-compose?

This issue is still open here: https://github.com/docker/compose/issues/2925

You can set hostname but it is not reachable from other containers. So it is mostly useless.

Using two CSS classes on one element

Another option is to use Descendant selectors

HTML:

<div class="social">
<p class="first">burrito</p>
<p class="last">chimichanga</p>
</div>

Reference first one in CSS: .social .first { color: blue; }

Reference last one in CSS: .social .last { color: green; }

Jsfiddle: https://jsfiddle.net/covbtpaq/153/

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

My App.config looks as below:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

I noticed that there is localDB in the path that you mentioned above and has the version v11.0. So I entered (LocalDB\V11.0) in Add Connection dialogue and it worked for me.

Predefined type 'System.ValueTuple´2´ is not defined or imported

We were seeing this same issue in one of our old projects that was targeting Framework 4.5.2. I tried several scenarios including all of the ones listed above: target 4.6.1, add System.ValueTuple package, delete bin, obj, and .vs folders. No dice. Repeat the same process for 4.7.2. Then tried removing the System.ValueTuple package since I was targeting 4.7.2 as one commenter suggested. Still nothing. Checked csproj file reference path. Looks right. Even dropped back down to 4.5.2 and installing the package again. All this with several VS restarts and deleting the same folders several times. Literally nothing worked.

I had to refactor to use a struct instead. I hope others don't continue to run into this issue in the future but thought this might be helpful if you end up as stumped up as we were.

Is it possible to change the package name of an Android app on Google Play?

As far as I can tell what you could do is "retire" your previous app and redirect all users to your new app. This procedure is not supported by Google (tsk... tsk...), but it could be implemented in four steps:

  1. Change the current application to show a message to the users about the upgrade and redirect them to the new app listing. Probably a full screen message would do with some friendly text. This message could be triggered remotely ideally, but a cut-off date can be used too. (But then that will be a hard deadline for you, so be careful... ;))

  2. Release the modified old app as an upgrade, maybe with some feature upgrades/bug fixes too, to "sweeten the deal" to the users. Still there is no guarantee that all users will upgrade, but probably the majority will do.

  3. Prepare your new app with the updated package name and upload it to the store, then trigger the message in the old app (or just wait until it expires, if that was your choice).

  4. Unpublish the old app in Play Store to avoid any new installs. Unpublishing an app doesn't mean the users who already installed it won't have access to it anymore, but at least the potential new users won't find it on the market.

Not ideal and can be annoying to the users, sometimes even impossible to implement due to the status/possibilities of the app. But since Google left us no choice this is the only way to migrate the users of the old apps to a "new" one (even if it is not really new). Not to mention that if you don't have access to the sources and code signing details for the old app then all you could do is hoping that he users will notice the new app...

If anybody figured out a better way by all means: please do tell.

Remove a marker from a GoogleMap

Make a global variable to keep track of marker

private Marker currentLocationMarker;

//Remove old marker

            if (null != currentLocationMarker) {
                currentLocationMarker.remove();
            }

// Add updated marker in and move the camera

            currentLocationMarker = mMap.addMarker(new MarkerOptions().position(
                    new LatLng(getLatitude(), getLongitude()))
                    .title("You are now Here").visible(true)
                    .icon(Utils.getMarkerBitmapFromView(getActivity(), R.drawable.auto_front))
                    .snippet("Updated Location"));

            currentLocationMarker.showInfoWindow();

set up device for development (???????????? no permissions)

Please DO NOT follow solutions suggesting to use sudo (sudo adb start-server)! This run adb as root (administrator) and it is NOT supposed to run like that!!! It's a BAD workaround!

Everything running as root can do anything in your system, if it creates or modify a file can change its permission to be only used by root. Again, DON'T!

The right thing to do is set up your system to make the USER have the permission, check out this guide i wrote on how to do it properly.

How do I abort the execution of a Python script?

You can either use:

import sys
sys.exit(...)

or:

raise SystemExit(...)

The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).

Why is the jquery script not working?

Samuel Liew is right. sometimes jquery conflict with the other jqueries. to solve this problem you need to put them in such a order that they may not conflict with each other. do one thing: open your application in google chrome and inspect bottom right corner with red marked errors. which kind of error that is?

How do I center a window onscreen in C#?

Use this:

this.CenterToScreen();  // This will take care of the current form

Loop through an array of strings in Bash?

Single line looping,

 declare -a listOfNames=('db_a' 'db_b' 'db_c')
 for databaseName in ${listOfNames[@]}; do echo $databaseName; done;

you will get an output like this,

db_a
db_b
db_c

How can I check for NaN values?

All the methods to tell if the variable is NaN or None:

None type

In [1]: from numpy import math

In [2]: a = None
In [3]: not a
Out[3]: True

In [4]: len(a or ()) == 0
Out[4]: True

In [5]: a == None
Out[5]: True

In [6]: a is None
Out[6]: True

In [7]: a != a
Out[7]: False

In [9]: math.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)
TypeError: a float is required

In [10]: len(a) == 0
Traceback (most recent call last):
  File "<ipython-input-10-65b72372873e>", line 1, in <module>
    len(a) == 0
TypeError: object of type 'NoneType' has no len()

NaN type

In [11]: b = float('nan')
In [12]: b
Out[12]: nan

In [13]: not b
Out[13]: False

In [14]: b != b
Out[14]: True

In [15]: math.isnan(b)
Out[15]: True

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

What is difference between @RequestBody and @RequestParam?

map HTTP request header Content-Type, handle request body.

  • @RequestParam ? application/x-www-form-urlencoded,

  • @RequestBody ? application/json,

  • @RequestPart ? multipart/form-data,


What does axis in pandas mean?

one of easy ways to remember axis 1 (columns), vs axis 0 (rows) is the output you expect.

  • if you expect an output for each row you use axis='columns',
  • on the other hand if you want an output for each column you use axis='rows'.

Delete item from array and shrink array

You can't resize the array, per se, but you can create a new array and efficiently copy the elements from the old array to the new array using some utility function like this:

public static int[] removeElement(int[] original, int element){
    int[] n = new int[original.length - 1];
    System.arraycopy(original, 0, n, 0, element );
    System.arraycopy(original, element+1, n, element, original.length - element-1);
    return n;
}

A better approach, however, would be to use an ArrayList (or similar List structure) to store your data and then use its methods to remove elements as needed.

Angular 5, HTML, boolean on checkbox is checked

You can use this:

<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">

Here, record is the model for current row and status is boolean value.

Declaring and initializing arrays in C

The OP left out some crucial information from the question and only put it in a comment to an answer.

I need to initialize after declaring, because will be different depending on a condition, I mean something like this int myArray[SIZE]; if(condition1) { myArray{x1, x2, x3, ...} } else if(condition2) { myArray{y1, y2, y3, ...} } . . and so on...

With this in mind, all of the possible arrays will need to be stored into data somewhere anyhow, so no memcpy is needed (or desired), only a pointer and a 2d array are required.

//static global since some compilers build arrays from instruction data
//... notably not const though so they can later be modified if needed
#define SIZE 8
static int myArrays[2][SIZE] = {{0,1,2,3,4,5,6,7},{7,6,5,4,3,2,1,0}};

static inline int *init_myArray(_Bool conditional){
  return myArrays[conditional];
}

// now you can use:
//int *myArray = init_myArray(1 == htons(1)); //any boolean expression

The not-inlined version gives this resulting assembly on x86_64:

init_myArray(bool):
        movzx   eax, dil
        sal     rax, 5
        add     rax, OFFSET FLAT:myArrays
        ret
myArrays:
        .long   0
        .long   1
        .long   2
        .long   3
        .long   4
        .long   5
        .long   6
        .long   7
        .long   7
        .long   6
        .long   5
        .long   4
        .long   3
        .long   2
        .long   1
        .long   0

For additional conditionals/arrays, just change the 2 in myArrays to the desired number and use similar logic to get a pointer to the right array.

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Well this is because ArrayList resulting from Arrays.asList() is not of the type java.util.ArrayList . Arrays.asList() creates an ArrayList of type java.util.Arrays$ArrayList which does not extend java.util.ArrayList but only extends java.util.AbstractList

MVC4 input field placeholder

This works:

@Html.TextBox("name", null,  new { placeholder = "Text" })

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

How to link an image and target a new window

<a href="http://www.google.com" target="_blank">
  <img width="220" height="250" border="0" align="center"  src=""/>
</a>

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

Char array to hex string C++

You could use std::hex

Eg.

std::cout << std::hex << packet;

Cannot enqueue Handshake after invoking quit

I think this issue is similar to mine:

  1. Connect to MySQL
  2. End MySQL service (should not quit node script)
  3. Start MySQL service, Node reconnects to MySQL
  4. Query the DB -> FAIL (Cannot enqueue Query after fatal error.)

I solved this issue by recreating a new connection with the use of promises (q).

mysql-con.js

'use strict';
var config          = require('./../config.js');
var colors          = require('colors');
var mysql           = require('mysql');
var q               = require('q');
var MySQLConnection = {};

MySQLConnection.connect = function(){
    var d = q.defer();
    MySQLConnection.connection = mysql.createConnection({
        host                : 'localhost',
        user                : 'root',
        password            : 'password',
        database            : 'database'
    });

    MySQLConnection.connection.connect(function (err) {
        if(err) {
            console.log('Not connected '.red, err.toString().red, ' RETRYING...'.blue);
            d.reject();
        } else {
            console.log('Connected to Mysql. Exporting..'.blue);
            d.resolve(MySQLConnection.connection);
        }
    });
    return d.promise;
};

module.exports = MySQLConnection;

mysqlAPI.js

var colors          = require('colors');
var mysqlCon        = require('./mysql-con.js');
mysqlCon.connect().then(function(con){
   console.log('connected!');
    mysql = con;
    mysql.on('error', function (err, result) {
        console.log('error occurred. Reconneting...'.purple);
        mysqlAPI.reconnect();
    });
    mysql.query('SELECT 1 + 1 AS solution', function (err, results) {
            if(err) console.log('err',err);
            console.log('Works bro ',results);
    });
});

mysqlAPI.reconnect = function(){
    mysqlCon.connect().then(function(con){
      console.log("connected. getting new reference");
        mysql = con;
        mysql.on('error', function (err, result) {
            mysqlAPI.reconnect();
        });
    }, function (error) {
      console.log("try again");
        setTimeout(mysqlAPI.reconnect, 2000);
    });
};

I hope this helps.

HTML: Select multiple as dropdown

    <select name="select_box"  multiple>
        <option>123</option>
        <option>456</option>
        <option>789</option>
     </select>

Order columns through Bootstrap4

This can also be achieved with the CSS "Order" property and a media query.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

How do I concatenate multiple C++ strings on one line?

The actual problem was that concatenating string literals with + fails in C++:

string s;
s += "Hello world, " + "nice to see you, " + "or not.";
The above code produces an error.

In C++ (also in C), you concatenate string literals by just placing them right next to each other:

string s0 = "Hello world, " "nice to see you, " "or not.";
string s1 = "Hello world, " /*same*/ "nice to see you, " /*result*/ "or not.";
string s2 = 
    "Hello world, " /*line breaks in source code as well as*/ 
    "nice to see you, " /*comments don't matter*/ 
    "or not.";

This makes sense, if you generate code in macros:

#define TRACE(arg) cout << #arg ":" << (arg) << endl;

...a simple macro that can be used like this

int a = 5;
TRACE(a)
a += 7;
TRACE(a)
TRACE(a+7)
TRACE(17*11)

(live demo ...)

or, if you insist in using the + for string literals (as already suggested by underscore_d):

string s = string("Hello world, ")+"nice to see you, "+"or not.";

Another solution combines a string and a const char* for each concatenation step

string s;
s += "Hello world, "
s += "nice to see you, "
s += "or not.";

Create a custom callback in JavaScript

Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.

The basics

function doSomething(callback) {
    // ...

    // Call the callback
    callback('stuff', 'goes', 'here');
}

function foo(a, b, c) {
    // I'm the callback
    alert(a + " " + b + " " + c);
}

doSomething(foo);

That will call doSomething, which will call foo, which will alert "stuff goes here".

Note that it's very important to pass the function reference (foo), rather than calling the function and passing its result (foo()). In your question, you do it properly, but it's just worth pointing out because it's a common error.

More advanced stuff

Sometimes you want to call the callback so it sees a specific value for this. You can easily do that with the JavaScript call function:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback) {
    // Call our callback, but using our own instance as the context
    callback.call(this);
}

function foo() {
    alert(this.name);
}

var t = new Thing('Joe');
t.doSomething(foo);  // Alerts "Joe" via `foo`

You can also pass arguments:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
    // Call our callback, but using our own instance as the context
    callback.call(this, salutation);
}

function foo(salutation) {
    alert(salutation + " " + this.name);
}

var t = new Thing('Joe');
t.doSomething(foo, 'Hi');  // Alerts "Hi Joe" via `foo`

Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply to do that:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback) {
    // Call our callback, but using our own instance as the context
    callback.apply(this, ['Hi', 3, 2, 1]);
}

function foo(salutation, three, two, one) {
    alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}

var t = new Thing('Joe');
t.doSomething(foo);  // Alerts "Hi Joe - 3 2 1" via `foo`

Why is my Spring @Autowired field null?

The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.

The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.

The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.

I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking

Inject your beans

The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:

@Controller
public class MileageFeeController {

    @Autowired
    private MileageFeeCalculator calc;

    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        return calc.mileageCharge(miles);
    }
}

If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.

Tag that works by injecting the @MileageFeeCalculator service object: working-inject-bean

Use @Configurable

If you really need objects created with new to be autowired, you can use the Spring @Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (@EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.

@Service
@Configurable
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService;

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile());
    }
}

Tag that works by using @Configurable on the service object: working-configurable

Manual bean lookup: not recommended

This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.

To do this, you need a class to which Spring can give a reference to the ApplicationContext object:

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;   
    }

    public static ApplicationContext getContext() {
        return context;
    }
}

Then your legacy code can call getContext() and retrieve the beans it needs:

@Controller
public class MileageFeeController {    
    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
        return calc.mileageCharge(miles);
    }
}

Tag that works by manually looking up the service object in the Spring context: working-manual-lookup

Java Object Null Check for method

This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.

For JDK 7 users, Here using

Objects.requireNotNull(object[, optionalMessage]);

is not safe. This function throws NullPointerException if it finds null object and which is a RunTimeException.

That will terminate the whole program!!. So better check null using == or !=.

Also, use List instead of Array. Although access speed is same, yet using Collections over Array has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector without rewriting all your code.

public static double calculateInventoryTotal(List<Book> books) {
    if (books == null || books.isEmpty()) {
        return 0;
    }

    double total = 0;

    for (Book book : books) {
        if (book != null) {
            total += book.getPrice();
        }
    }
    return total;
}

Also, I would like to upvote @1ac0 answer. We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.

Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException. It defined a new class called Optional. Have a look at this for detail

Finally, Pardon my bad English.

How to use bootstrap datepicker

Couldn't get bootstrap datepicker to work until I wrap the textbox with position relative element as shown here:

<span style="position: relative">
 <input  type="text" placeholder="click to show datepicker"  id="pickyDate"/>
</span>

Get first key in a (possibly) associative array?

The best way that worked for me was

array_shift(array_keys($array))

array_keys gets array of keys from initial array and then array_shift cuts from it first element value. You will need PHP 5.4+ for this.

iPhone - Get Position of UIView within entire UIWindow

For me this code worked best:

private func getCoordinate(_ view: UIView) -> CGPoint {
    var x = view.frame.origin.x
    var y = view.frame.origin.y
    var oldView = view

    while let superView = oldView.superview {
        x += superView.frame.origin.x
        y += superView.frame.origin.y
        if superView.next is UIViewController {
            break //superView is the rootView of a UIViewController
        }
        oldView = superView
    }

    return CGPoint(x: x, y: y)
}

printing a two dimensional array in python

using indices, for loops and formatting:

import numpy as np

def printMatrix(a):
   print "Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]"
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%6.f" %a[i,j],
      print
   print      


def printMatrixE(a):
   print "Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]"
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print("%6.3f" %a[i,j]),
      print
   print      


inf = float('inf')
A = np.array( [[0,1.,4.,inf,3],
     [1,0,2,inf,4],
     [4,2,0,1,5],
     [inf,inf,1,0,3],
     [3,4,5,3,0]])

printMatrix(A)    
printMatrixE(A)    

which yields the output:

Matrix[5][5]
     0      1      4    inf      3
     1      0      2    inf      4
     4      2      0      1      5
   inf    inf      1      0      3
     3      4      5      3      0

Matrix[5][5]
 0.000  1.000  4.000    inf  3.000
 1.000  0.000  2.000    inf  4.000
 4.000  2.000  0.000  1.000  5.000
   inf    inf  1.000  0.000  3.000
 3.000  4.000  5.000  3.000  0.000

AngularJS - How to use $routeParams in generating the templateUrl?

Router:-

...
.when('/enquiry/:page', {
    template: '<div ng-include src="templateUrl" onload="onLoad()"></div>',
    controller: 'enquiryCtrl'
})
...

Controller:-

...
// template onload event
$scope.onLoad = function() {
    console.log('onLoad()');
    f_tcalInit();  // or other onload stuff
}

// initialize
$scope.templateUrl = 'ci_index.php/adminctrl/enquiry/'+$routeParams.page;
...

I believe it is a weakness in angularjs that $routeParams is NOT visible inside the router. A tiny enhancement would make a world of difference during implementation.

How can I load the contents of a text file into a batch file variable?

You can use:

set content=
for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i

Powershell folder size of folders without listing Subdirectories

This is similar to https://stackoverflow.com/users/3396598/kohlbrr answer, but I was trying to get the total size of a single folder and found that the script doesn't count the files in the Root of the folder you are searching. This worked for me.

$startFolder = "C:\Users";
$totalSize = 0;

$colItems = Get-ChildItem $startFolder
foreach ($i in $colItems)
{
    $subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
    $totalSize = $totalSize + $subFolderItems.sum / 1MB

}

$startFolder + " | " + "{0:N2}" -f ($totalSize) + " MB"

How to restore the menu bar in Visual Studio Code

If you are like me - you did this by inadvertently hitting F11 - toggling fullscreen mode. https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf

How can I get the current page name in WordPress?

If you're looking to access the current page from within your functions.php file (so, before the loop, before $post is populated, before $wp_query is initialized, etc...) you really have no choice but to access the server variables themselves and extract the requested page from the query string.

$page_slug = trim( $_SERVER["REQUEST_URI"] , '/' )

Note that this is a "dumb" solution. It doesn't know, for instance that the page with the slug 'coming-soon' is also p=6. And it assumes that your permalink settings are set to pagename (which they should be anyway!).

Still, can be a useful little trick if you have a controlled scenario. I'm using this in a situation where I wish to redirect non-logged in visitors to a "coming soon" page; but I have to make sure that I'm not throwing them into the dreaded "redirect loop", so I need to exclude the "coming soon" page from this rule:

global $pagenow;
if (
        ! is_admin() &&
        'wp-login.php' != $pagenow &&
        'coming-soon' != trim( $_SERVER["REQUEST_URI"] , '/' ) &&
        ! is_user_logged_in()
){
   wp_safe_redirect( 'coming-soon' );
}

When should you NOT use a Rules Engine?

That's certainly a good start. The other thing with rules engines is that some things are well-understood, deterministic, and straight-forward. Payroll withholding is (or use to be) like that. You could express it as rules that would be resolved by a rules engine, but you could express the same rules as a fairly simple table of values.

So, workflow engines are good when you're expressing a longer-term process that will have persistent data. Rules engines can do a similar thing, but you have to do a lot of added complexity.

Rules engines are good when you have complicated knowledge bases and need search. Rules engines can resolve complicated issues, and can be adapted quickly to changing situations, but impose a lot of complexity on the base implementation.

Many decision algorithms are simple enough to express as a simple table-driven program without the complexity implied by a real rules engine.

PHP/MySQL Insert null values

For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.

For example:

mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail

Saving numpy array to txt file row wise

just

' '.join(a)

and write this output to a file.

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

In order to simulate the issue that you are facing, I created the following sample using SSIS 2008 R2 with SQL Server 2008 R2 backend. The example is based on what I gathered from your question. This example doesn't provide a solution but it might help you to identify where the problem could be in your case.

Created a simple CSV file with two columns namely order number and order date. As you had mentioned in your question, values of both the columns are qualified with double quotes (") and also the lines end with Line Feed (\n) with the date being the last column. The below screenshot was taken using Notepad++, which can display the special characters in a file. LF in the screenshot denotes Line Feed.

Orders file

Created a simple table named dbo.Destination in the SQL Server database to populate the CSV file data using SSIS package. Create script for the table is given below.

CREATE TABLE [dbo].[Destination](
    [OrderNumber] [varchar](50) NULL,
    [OrderDate] [date] NULL
) ON [PRIMARY]
GO

On the SSIS package, I created two connection managers. SQLServer was created using the OLE DB Connection to connect to the SQL Server database. FlatFile is a flat file connection manager.

Connections

Flat file connection manager was configured to read the CSV file and the settings are shown below. The red arrows indicate the changes made.

Provided a name to the flat file connection manager. Browsed to the location of the CSV file and selected the file path. Entered the double quote (") as the text qualifier. Changed the Header row delimiter from {CR}{LF} to {LF}. This header row delimiter change also reflects on the Columns section.

Flat File General

No changes were made in the Columns section.

Flat File Columns

Changed the column name from Column0 to OrderNumber.

Advanced column OrderNumber

Changed the column name from Column1 to OrderDate and also changed the data type to date [DT_DATE]

Advanced column OrderDate

Preview of the data within the flat file connection manager looks good.

Data Preview

On the Control Flow tab of the SSIS package, placed a Data Flow Task.

Control Flow

Within the Data Flow Task, placed a Flat File Source and an OLE DB Destination.

Data Flow Task

The Flat File Source was configured to read the CSV file data using the FlatFile connection manager. Below three screenshots show how the flat file source component was configured.

Flat File Source Connection Manager

Flat File Source Columns

Flat File Source Error Output

The OLE DB Destination component was configured to accept the data from Flat File Source and insert it into SQL Server database table named dbo.Destination. Below three screenshots show how the OLE DB Destination component was configured.

OLE DB Destination Connection Manager

OLE DB Destination Mappings

OLE DB Destination Error Output

Using the steps mentioned in the below 5 screenshots, I added a data viewer on the flow between the Flat File Source and OLE DB Destination.

Right click

Data Flow Path Editor New

Configure Data Viewer

Data Flow Path Editor Added

Data Viewer visible

Before running the package, I verified the initial data present in the table. It is currently empty because I created this using the script provided at the beginning of this post.

Empty Table

Executed the package and the package execution temporarily paused to display the data flowing from Flat File Source to OLE DB Destination in the data viewer. I clicked on the run button to proceed with the execution.

Data Viewer Pause

The package executed successfully.

Successful execution

Flat file source data was inserted successfully into the table dbo.Destination.

Data in table

Here is the layout of the table dbo.Destination. As you can see, the field OrderDate is of data type date and the package still continued to insert the data correctly.

Destination layout

This post even though is not a solution. Hopefully helps you to find out where the problem could be in your scenario.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

A comment for the top answer about setting font-size to 16px asked how that is a solution, what if you want bigger/smaller font.

I don't know about you all, but using px for font sizes is not the best way to go, you should be using em.

I ran into this issue on my responsive site where my text field is larger than 16 pixels. I had my form container set to 2rem and my input field set to 1.4em. In my mobile queries I change html font-size depending on the viewport. Since the default html is 10, my input field calculates to 28px on desktop

To remove the auto-zoom I had to change my input to 1.6em. This increased my font size to 32px. Just slightly higher and hardly noticeable. On my iPhone 4&5 I change my html font-size to 15px for portrait and back to 10px for landscape. It appeard that the sweet spot for that pixel size was 48px which is why I changed to from 1.4em (42px) to 1.6em (48px).

The thing you need to do is find the sweet spot on font-size and then convert it backwards in your rem/em sizes.

Python virtualenv questions

After creating virtual environment copy the activate.bat file from Script folder of python and paste to it your environment and open cmd from your virtual environment and run activate.bat file.enter image description here

Center Contents of Bootstrap row container

Try this, it works!

<div class="row">
    <div class="center">
        <div class="col-xs-12 col-sm-4">
            <p>hi 1!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 2!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 3!</p>
        </div>
    </div>
</div>

Then, in css define the width of center div and center in a document:

.center {
    margin: 0 auto;
    width: 80%;
}

Simplest way to detect a mobile device in PHP

function isMobileDev(){
    if(isset($_SERVER['HTTP_USER_AGENT']) and !empty($_SERVER['HTTP_USER_AGENT'])){
       $user_ag = $_SERVER['HTTP_USER_AGENT'];
       if(preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis',$user_ag)){
          return true;
       };
    };
    return false;
}

IF - ELSE IF - ELSE Structure in Excel

=IF(CR<=10, "RED", if(CR<50, "YELLOW", if(CR<101, "GREEN")))

CR = ColRow (Cell) This is an example. In this example when value in Cell is less then or equal to 10 then RED word will appear on that cell. In the same manner other if conditions are true if first if is false.

Java: parse int value from a char

String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

Excel formula to get week number in month (having Monday)

Jonathan from the ExcelCentral forums suggests:

=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1 

This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:

=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1

For weeks beginning on Tuesday, use:

=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1

etc.

I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).

What is the default encoding of the JVM?

You can use this to print out the JVM defaults

import java.nio.charset.Charset;
import java.io.InputStreamReader;
import java.io.FileInputStream;

public class PrintCharSets {
        public static void main(String[] args) throws Exception {
                System.out.println("file.encoding=" + System.getProperty("file.encoding"));
                System.out.println("Charset.defaultCharset=" + Charset.defaultCharset());
                System.out.println("InputStreamReader.getEncoding=" + new InputStreamReader(new FileInputStream("./PrintCharSets.java")).getEncoding());
        }
}

Compile and Run

javac PrintCharSets.java && java PrintCharSets

In Git, what is the difference between origin/master vs origin master?

There are actually three things here: origin master is two separate things, and origin/master is one thing. Three things total.

Two branches:

  • master is a local branch
  • origin/master is a remote branch (which is a local copy of the branch named "master" on the remote named "origin")

One remote:

  • origin is a remote

Example: pull in two steps

Since origin/master is a branch, you can merge it. Here's a pull in two steps:

Step one, fetch master from the remote origin. The master branch on origin will be fetched and the local copy will be named origin/master.

git fetch origin master

Then you merge origin/master into master.

git merge origin/master

Then you can push your new changes in master back to origin:

git push origin master

More examples

You can fetch multiple branches by name...

git fetch origin master stable oldstable

You can merge multiple branches...

git merge origin/master hotfix-2275 hotfix-2276 hotfix-2290

React native ERROR Packager can't listen on port 8081

Take the terminal and type

fuser 8081/tcp

You will get a Process id which is using port 8081 Now kill the process

kill <pid>

Use SELECT inside an UPDATE query

I know this topic is old, but I thought I could add something to it.

I could not make an Update with Select query work using SQL in MS Access 2010. I used Tomalak's suggestion to make this work. I had a screenshot, but am apparently too much of a newb on this site to be able to post it.

I was able to do this using the Query Design tool, but even as I was looking at a confirmed successful update query, Access was not able to show me the SQL that made it happen. So I could not make this work with SQL code alone.

I created and saved my select query as a separate query. In the Query Design tool, I added the table I'm trying to update the the select query I had saved (I put the unique key in the select query so it had a link between them). Just as Tomalak had suggested, I changed the Query Type to Update. I then just had to choose the fields (and designate the table) I was trying to update. In the "Update To" fields, I typed in the name of the fields from the select query I had brought in.

This format was successful and updated the original table.

Reading Datetime value From Excel sheet

You need to convert the date format from OLE Automation to the .net format by using DateTime.FromOADate.

double d = double.Parse(b);
DateTime conv = DateTime.FromOADate(d);

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

If you are using material-ui, go to type definition of the component, which is being underlined by TypeScript. Most likely you will see something like this

export { default } from './ComponentName';

You have 2 options to resolve the error:

1.Add .default when using the component in JSX:

import ComponentName from './ComponentName'

const Component = () => <ComponentName.default />

2.Rename the component, which is being exported as "default", when importing:

import { default as ComponentName } from './ComponentName'

const Component = () => <ComponentName />

This way you don't need to specify .default every time you use the component.

Is there a way to change the spacing between legend items in ggplot2?

To add spacing between entries in a legend, adjust the margins of the theme element legend.text.

To add 30pt of space to the right of each legend label (may be useful for a horizontal legend):

p + theme(legend.text = element_text(
    margin = margin(r = 30, unit = "pt")))

To add 30pt of space to the left of each legend label (may be useful for a vertical legend):

p + theme(legend.text = element_text(
    margin = margin(l = 30, unit = "pt")))

for a ggplot2 object p. The keywords are legend.text and margin.

[Note about edit: When this answer was first posted, there was a bug. The bug has now been fixed]

How do you replace all the occurrences of a certain character in a string?

The problem is you're not doing anything with the result of replace. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.

line[8] = line[8].replace(letter, "")

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

Visualizing decision tree in scikit-learn

sklearn.tree.export_graphviz doesn't return anything, and so by default returns None.

By doing dotfile = tree.export_graphviz(...) you overwrite your open file object, which had been previously assigned to dotfile, so you get an error when you try to close the file (as it's now None).

To fix it change your code to

...
dotfile = open("D:/dtree2.dot", 'w')
tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
...

How to load a tsv file into a Pandas DataFrame?

data = pd.read_csv('your_dataset.tsv', delimiter = '\t', quoting = 3)

You can use a delimiter to separate data, quoting = 3 helps to clear quotes in datasst

How to update array value javascript?

How about;

function keyValue(key, value){
    this.Key = key;
    this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
    this.Key = newKey;
    this.Value = newValue;  
};

array[1].updateTo("xxx", "999");   

Append integer to beginning of list in Python

You can use Unpack list:

a = 5

li = [1,2,3]

li = [a, *li]

=> [5, 1, 2, 3]

Android: Rotate image in imageview by an angle

Follow the below answer for continuous rotation of an imageview

int i=0;

If rotate button clicked

imageView.setRotation(i+90);
i=i+90;

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

How to find Max Date in List<Object>?

LocalDate maxDate = dates.stream()
                            .max( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

LocalDate minDate = dates.stream()
                            .min( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

Insert using LEFT JOIN and INNER JOIN

you can't use VALUES clause when inserting data using another SELECT query. see INSERT SYNTAX

INSERT INTO user
(
 id, name, username, email, opted_in
)
(
    SELECT id, name, username, email, opted_in
    FROM user
         LEFT JOIN user_permission AS userPerm
            ON user.id = userPerm.user_id
);

If REST applications are supposed to be stateless, how do you manage sessions?

The fundamental explanation is:

No client session state on the server.

By stateless it means that the server does not store any state about the client session on the server side.

The client session is stored on the client. The server is stateless means that every server can service any client at any time, there is no session affinity or sticky sessions. The relevant session information is stored on the client and passed to the server as needed.

That does not preclude other services that the web server talks to from maintaining state about business objects such as shopping carts, just not about the client's current application/session state.

The client's application state should never be stored on the server, but passed around from the client to every place that needs it.

That is where the ST in REST comes from, State Transfer. You transfer the state around instead of having the server store it. This is the only way to scale to millions of concurrent users. If for no other reason than because millions of sessions is millions of sessions.

The load of session management is amortized across all the clients, the clients store their session state and the servers can service many orders of magnitude or more clients in a stateless fashion.

Even for a service that you think will only need in the 10's of thousands of concurrent users, you still should make your service stateless. Tens of thousands is still tens of thousands and there will be time and space cost associated with it.

Stateless is how the HTTP protocol and the web in general was designed to operate and is an overall simpler implementation and you have a single code path instead of a bunch of server side logic to maintain a bunch of session state.

There are some very basic implementation principles:

These are principles not implementations, how you meet these principles may vary.

In summary, the five key principles are:

  1. Give every “thing” an ID
  2. Link things together
  3. Use standard methods
  4. Resources with multiple representations
  5. Communicate statelessly

There is nothing about authentication or authorization in the REST dissertation.

Because there is nothing different from authenticating a request that is RESTful from one that is not. Authentication is irrelevant to the RESTful discussion.

Explaining how to create a stateless application for your particular requirements, is too-broad for StackOverflow.

Implementing Authentication and Authorization as it pertains to REST is even more so too-broad and various approaches to implementations are explained in great detail on the internet in general.

Comments asking for help/info on this will/should just be flagged as No Longer Needed.

How to make an unaware datetime timezone aware in python

Python 3.9 adds the zoneinfo module so now only the standard library is needed!

from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)

Attach a timezone:

>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'

Attach the system's local timezone:

>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'

Subsequently it is properly converted to other timezones:

>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'

Wikipedia list of available time zones


Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

There is a backport to allow use of zoneinfo in Python 3.6 to 3.8:

pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

How do I update Anaconda?

This can update the Python instance only:

conda update python

Duplicate Symbols for Architecture arm64

I've messed up my pods while downgrading a pod and I've managed to resolve the issue with duplicate symbols for architecture arm64 by removing the pods and installing them again with:

pod deintegrate
pod install

How to run a makefile in Windows?

Here is my quick and temporary way to run a Makefile

  • download make from SourceForge: gnuwin32
  • install it
  • go to the install folder

C:\Program Files (x86)\GnuWin32\bin

  • copy the all files in the bin to the folder that contains Makefile

libiconv2.dll libintl3.dll make.exe

  • open the cmd (you can do it with right click with shift) in the folder that contains Makefile and run

make.exe

done.

Plus, you can add arguments after the command, such as

make.exe skel

How to change options of <select> with jQuery?

For some odd reason this part

$el.empty(); // remove old options

from CMS solution didn't work for me, so instead of that I've simply used this

el.html(' ');

And it's works. So my working code now looks like that:

var newOptions = {
    "Option 1":"option-1",
    "Option 2":"option-2"
};

var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
    $el.append($("<option></option>")
    .attr("value", value).text(key));
});

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

Try this:

Write mongodb instead of mongod

sudo service mongodb status

How to get current user in asp.net core

Perhaps I didn't see the answer, but this is how I do it.

  1. .Net Core --> Properties --> launchSettings.json

You need to have change these values

"windowsAuthentication": true, // needs to be true
"anonymousAuthentication": false,  // needs to be false 

Startup.cs --> ConfigureServices(...)

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

MVC or Web Api Controller

private readonly IHttpContextAccessor _httpContextAccessor;
//constructor then
_httpContextAccessor = httpContextAccessor;

Controller method:

string userName = _httpContextAccessor.HttpContext.User.Identity.Name;

Result is userName e.g. = Domain\username

Difference between logical addresses, and physical addresses?

A logical address is a reference to memory location independent of the current assignment of data to memory. A physical address or absolute address is an actual location in main memory.

It is in chapter 7.2 of Stallings.

Generate random int value from 3 to 6

Here is the simple and single line of code

For this use the SQL Inbuild RAND() function.

Here is the formula to generate random number between two number (RETURN INT Range)

Here a is your First Number (Min) and b is the Second Number (Max) in Range

SELECT FLOOR(RAND()*(b-a)+a)

Note: You can use CAST or CONVERT function as well to get INT range number.

( CAST(RAND()*(25-10)+10 AS INT) )

Example:

SELECT FLOOR(RAND()*(25-10)+10);

Here is the formula to generate random number between two number (RETURN DECIMAL Range)

SELECT RAND()*(b-a)+a;

Example:

SELECT RAND()*(25-10)+10;

More details check this: https://www.techonthenet.com/sql_server/functions/rand.php

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

SQL Server: combining multiple rows into one row

_x000D_
_x000D_
declare @maxColumnCount int=0;
 declare @Query varchar(max)='';
 declare @DynamicColumnName nvarchar(MAX)='';

-- table type variable that store all values of column row no
 DECLARE @TotalRows TABLE( row_count int)
 INSERT INTO @TotalRows (row_count)
 SELECT (ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc)) as row_no FROM tblExportPartProforma

-- Get the MAX value from @TotalRows table
 set @maxColumnCount= (select max(row_count) from @TotalRows)
 
-- loop to create Dynamic max/case and store it into local variable 
 DECLARE @cnt INT = 1;
 WHILE @cnt <= @maxColumnCount
 BEGIN
   set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then InvoiceType end )as InvoiceType'+cast(@cnt as varchar)+''
      set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then BankRefno end )as BankRefno'+cast(@cnt as varchar)+''
            set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceived end )as AmountReceived'+cast(@cnt as varchar)+''

      set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceivedDate end )as AmountReceivedDate'+cast(@cnt as varchar)+''


   SET @cnt = @cnt + 1;
END;

-- Create dynamic CTE and store it into local variable @query 
  set @Query='
     with CTE_tbl as
     (
       SELECT InvoiceNo,InvoiceType,BankRefno,AmountReceived,AmountReceivedDate,
       ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc) as row_no
       FROM tblExportPartProforma
      )
  select
     InvoiceNo
     '+@DynamicColumnName+'
     FROM CTE_tbl
     group By InvoiceNo'

-- Execute the Query
 execute (@Query)
_x000D_
_x000D_
_x000D_

deleting rows in numpy array

I might be too late to answer this question, but wanted to share my input for the benefit of the community. For this example, let me call your matrix 'ANOVA', and I am assuming you're just trying to remove rows from this matrix with 0's only in the 5th column.

indx = []
for i in range(len(ANOVA)):
    if int(ANOVA[i,4]) == int(0):
        indx.append(i)

ANOVA = [x for x in ANOVA if not x in indx]

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

Adapting dplyr::ntile to take advantage of data.table optimizations provides a faster solution.

library(data.table)
setDT(temp)
temp[order(value) , quartile := floor( 1 + 4 * (.I-1) / .N)]

Probably doesn't qualify as cleaner, but it's faster and one-line.

Timing on bigger data set

Comparing this solution to ntile and cut for data.table as proposed by @docendo_discimus and @MichaelChirico.

library(microbenchmark)
library(dplyr)

set.seed(123)

n <- 1e6
temp <- data.frame(name=sample(letters, size=n, replace=TRUE), value=rnorm(n))
setDT(temp)

microbenchmark(
    "ntile" = temp[, quartile_ntile := ntile(value, 4)],
    "cut" = temp[, quartile_cut := cut(value,
                                       breaks = quantile(value, probs = seq(0, 1, by=1/4)),
                                       labels = 1:4, right=FALSE)],
    "dt_ntile" = temp[order(value), quartile_ntile_dt := floor( 1 + 4 * (.I-1)/.N)]
)

Gives:

Unit: milliseconds
     expr      min       lq     mean   median       uq      max neval
    ntile 608.1126 647.4994 670.3160 686.5103 691.4846 712.4267   100
      cut 369.5391 373.3457 375.0913 374.3107 376.5512 385.8142   100
 dt_ntile 117.5736 119.5802 124.5397 120.5043 124.5902 145.7894   100

How to create a generic array in Java?

You could create an Object array and cast it to E everywhere. Yeah, it's not very clean way to do it but it should at least work.

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Since ?99 the matching between format specifiers and floating-point argument types in C is consistent between printf and scanf. It is

  • %f for float
  • %lf for double
  • %Lf for long double

It just so happens that when arguments of type float are passed as variadic parameters, such arguments are implicitly converted to type double. This is the reason why in printf format specifiers %f and %lf are equivalent and interchangeable. In printf you can "cross-use" %lf with float or %f with double.

But there's no reason to actually do it in practice. Don't use %f to printf arguments of type double. It is a widespread habit born back in C89/90 times, but it is a bad habit. Use %lf in printf for double and keep %f reserved for float arguments.

UINavigationBar Hide back Button Text

In iOS 11, we found that setting UIBarButtonItem appearance's text font/color to a very small value or clear color will result other bar item to disappear (system does not honor the class of UIBarButton item anymore, it will convert it to a _UIModernBarButton). Also setting the offset of back text to offscreen will result flash during interactive pop.

So we swizzled addSubView:

+ (void)load {
    if (@available(iOS 11, *)) {
        [NSClassFromString(@"_UIBackButtonContainerView")     jr_swizzleMethod:@selector(addSubview:) withMethod:@selector(MyiOS11BackButtonNoTextTrick_addSubview:) error:nil];
    }
}

- (void)MyiOS11BackButtonNoTextTrick_addSubview:(UIView *)view {
    view.alpha = 0;
    if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (id)view;
        [button setTitle:@" " forState:UIControlStateNormal];
    }
    [self MyiOS11BackButtonNoTextTrick_addSubview:view];
}

How can I get the current contents of an element in webdriver

My answer is based on this answer: How can I get the current contents of an element in webdriver just more like copy-paste.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))


element = driver.find_element_by_css_selector('.description.expand_description > p')
element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
driver.quit()

Is there a php echo/print equivalent in javascript

We would create our own function in js like echo "Hello world".

function echo( ...s ) // rest operator
 { 
   for(var i = 0; i < s.length; i++ ) {

    document.write(s[i] + ' '); // quotes for space

   }

 } 

  // Now call to this function like echo

 echo('Hellow', "World");

Note: (...) rest operator dotes for access more parameters in one as object/array, to get value from object/array we should iterate the whole object/array by using for loop, like above and s is name i just kept you can write whatever you want.

How to set data attributes in HTML elements

[jQuery] .data() vs .attr() vs .extend()

The jQuery method .data() updates an internal object managed by jQuery through the use of the method, if I'm correct.

If you'd like to update your data-attributes with some spread, use --

$('body').attr({ 'data-test': 'text' });

-- otherwise, $('body').attr('data-test', 'text'); will work just fine.

Another way you could accomplish this is using --

$.extend( $('body')[0].dataset, { datum: true } );

-- which restricts any attribute change to HTMLElement.prototype.dataset, not any additional HTMLElement.prototype.attributes.

Firebase (FCM) how to get token

If are using some auth function of firebase, you can take token using this:

//------GET USER TOKEN-------
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
mUser.getToken(true)
        .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
            public void onComplete(@NonNull Task<GetTokenResult> task) {
                if (task.isSuccessful()) {
                    String idToken = task.getResult().getToken();
                      // ...
                }
            }
        });

Work well if user are logged. getCurrentUser()

How do I get the time difference between two DateTime objects using C#?

What you need is to use the DateTime classs Subtract method, which returns a TimeSpan.

var dateOne = DateTime.Now;
var dateTwo = DateTime.Now.AddMinutes(-5);
var diff = dateTwo.Subtract(dateOne);
var res = String.Format("{0}:{1}:{2}", diff.Hours,diff.Minutes,diff.Seconds));

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Convert IQueryable<> type object to List<T> type?

The List class's constructor can convert an IQueryable for you:

public static List<TResult> ToList<TResult>(this IQueryable source)
{
    return new List<TResult>(source);
}

or you can just convert it without the extension method, of course:

var list = new List<T>(queryable);

How to compare two maps by their values

Since you asked about ready-made Api's ... well Apache's commons. collections library has a CollectionUtils class that provides easy-to-use methods for Collection manipulation/checking, such as intersection, difference, and union.

Find all elements with a certain attribute value in jquery

You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:

<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...

You can use the code:

var abc = $('div[id^=abc]')

This will return a DOM array of divs which have id starting with abc:

<div id="abc_1"></div>
<div id="abc_2"></div>

Here is the demo: http://jsfiddle.net/mCuWS/

Convert Xml to Table SQL Server

The sp_xml_preparedocument stored procedure will parse the XML and the OPENXML rowset provider will show you a relational view of the XML data.

For details and more examples check the OPENXML documentation.

As for your question,

DECLARE @XML XML
SET @XML = '<rows><row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row></rows>'

DECLARE @handle INT  
DECLARE @PrepareXmlStatus INT  

EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML  

SELECT  *
FROM    OPENXML(@handle, '/rows/row', 2)  
    WITH (
    IdInvernadero INT,
    IdProducto INT,
    IdCaracteristica1 INT,
    IdCaracteristica2 INT,
    Cantidad INT,
    Folio INT
    )  


EXEC sp_xml_removedocument @handle 

What is the http-header "X-XSS-Protection"?

X-XSS-Protection is a HTTP header understood by Internet Explorer 8 (and newer versions). This header lets domains toggle on and off the "XSS Filter" of IE8, which prevents some categories of XSS attacks. IE8 has the filter activated by default, but servers can switch if off by setting

   X-XSS-Protection: 0

See also http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

How to navigate back to the last cursor position in Visual Studio Code?

As an alternative to the keyboard shortcuts, here's an extension named "Back and Forward buttons" that adds the forward and back buttons to the status bar:

https://marketplace.visualstudio.com/items?itemName=grimmer.vscode-back-forward-button

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

Android, How to create option Menu

please see :==

private int group1Id = 1;

int homeId = Menu.FIRST;
int profileId = Menu.FIRST +1;
int searchId = Menu.FIRST +2;
int dealsId = Menu.FIRST +3;
int helpId = Menu.FIRST +4;
int contactusId = Menu.FIRST +5;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(group1Id, homeId, homeId, "").setIcon(R.drawable.home_menu);
    menu.add(group1Id, profileId, profileId, "").setIcon(R.drawable.profile_menu);
    menu.add(group1Id, searchId, searchId, "").setIcon(R.drawable.search_menu);
    menu.add(group1Id, dealsId, dealsId, "").setIcon(R.drawable.deals_menu);
    menu.add(group1Id, helpId, helpId, "").setIcon(R.drawable.help_menu);
    menu.add(group1Id, contactusId, contactusId, "").setIcon(R.drawable.contactus_menu);

    return super.onCreateOptionsMenu(menu); 
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
        // write your code here
        Toast msg = Toast.makeText(MainHomeScreen.this, "Menu 1", Toast.LENGTH_LONG);
        msg.show();
        return true;

    case 2:
        // write your code here
        return true;

    case 3:
        // write your code here
        return true;

    case 4:
        // write your code here
        return true;

    case 5:
        // write your code here
        return true;

    case 6:
        // write your code here
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This error is usually observed when your machine is low on disk space. Steps to be followed to avoid this error message

  1. Resetting the read-only index block on the index:

    $ curl -X PUT -H "Content-Type: application/json" http://127.0.0.1:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
    
    Response
    ${"acknowledged":true}
    
  2. Updating the low watermark to at least 50 gigabytes free, a high watermark of at least 20 gigabytes free, and a flood stage watermark of 10 gigabytes free, and updating the information about the cluster every minute

     Request
     $curl -X PUT "http://127.0.0.1:9200/_cluster/settings?pretty" -H 'Content-Type: application/json' -d' { "transient": { "cluster.routing.allocation.disk.watermark.low": "50gb", "cluster.routing.allocation.disk.watermark.high": "20gb", "cluster.routing.allocation.disk.watermark.flood_stage": "10gb", "cluster.info.update.interval": "1m"}}'
    
      Response
      ${
       "acknowledged" : true,
       "persistent" : { },
       "transient" : {
       "cluster" : {
       "routing" : {
       "allocation" : {
       "disk" : {
         "watermark" : {
           "low" : "50gb",
           "flood_stage" : "10gb",
           "high" : "20gb"
         }
       }
     }
    }, 
    "info" : {"update" : {"interval" : "1m"}}}}}
    

After running these two commands, you must run the first command again so that the index does not go again into read-only mode

jquery json to string?

Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.

JSON.stringify({a:1,b:2}, null, 2)

gives

"{\n  \"a\": 1,\n  \"b\": 2\n}"

which prints as

{
  "a": 1,
  "b": 2
}

As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :

The replacer parameter can either be a function or an array of String/Numbers. It steps through each member within the JSON object to let you decide what value each member should be changed to. As a function it can return:

  • A number, string, or Boolean, which replaces the property's original value with the returned one.
  • An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
  • Null, which causes the property to be removed.

As an array, the values defined inside it corresponds to the names of the properties inside the JSON object that should be retained when converted into a JSON object.

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

This is often caused by an attempt to process a null object. An example, trying to empty a Bindable list that is null will trigger the exception:

public class MyViewModel {
    [BindableProperty]
    public virtual IList<Products> ProductsList{ get; set; }

    public MyViewModel ()
    {
        ProductsList.Clear(); // here is the problem
    }
}

This could easily be fixed by checking for null:

if (ProductsList!= null) ProductsList.Clear();

Git - Undo pushed commits

2020 Simple way :

git reset <commit_hash>

(The hash of the last commit you want to keep).

You will keep the now uncommitted changes locally.

If you want to push again, you have to do :

git push -f

Applying an ellipsis to multiline text

I finally found a solution to do what I want. As p a paragraphe and article the wrapper. If you want to apply ellipsis to p depending on article height (which also depends on window height), you need to get the height of the article, the line-height of the p and then articleHeight/lineHeight to find the number of line-clamp that can be added dynamically then.

The only thing is the line-height should be declared in the css file.

Check the following code. If you change the height of the window, the line-clamp will change. Can be great to create a plug-in aiming to do that.

jsfiddle

_x000D_
_x000D_
function lineclamp() {_x000D_
  var lineheight = parseFloat($('p').css('line-height'));_x000D_
  var articleheight = $('article').height(); _x000D_
  var calc = parseInt(articleheight/lineheight);_x000D_
  $("p").css({"-webkit-line-clamp": "" + calc + ""});_x000D_
}_x000D_
_x000D_
_x000D_
$(document).ready(function() {_x000D_
    lineclamp();_x000D_
});_x000D_
_x000D_
$( window ).resize(function() {_x000D_
  lineclamp();_x000D_
});
_x000D_
article {_x000D_
  height:60%;_x000D_
  background:red;_x000D_
  position:absolute;_x000D_
}_x000D_
_x000D_
p {_x000D_
  margin:0;_x000D_
  line-height:120%;_x000D_
  display: -webkit-box;_x000D_
  -webkit-box-orient: vertical;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<article>_x000D_
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque lorem ligula, lacinia a justo sed, porttitor vulputate risus. In non feugiat risus. Sed vitae urna nisl. Duis suscipit volutpat sollicitudin. Donec ac massa elementum massa condimentum mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla sollicitudin sapien at enim sodales dapibus. Pellentesque sed nisl eu sem aliquam tempus nec ut leo. Quisque rutrum nulla nec aliquam placerat. Fusce a massa ut sem egestas imperdiet. Sed sollicitudin id dolor egestas malesuada. Quisque placerat lobortis ante, id ultrices ipsum hendrerit nec. Quisque quis ultrices erat.Nulla gravida ipsum nec sapien pellentesque pharetra. Suspendisse egestas aliquam nunc vel egestas. Nullam scelerisque purus interdum lectus consectetur mattis. Aliquam nunc erat, accumsan ut posuere eu, vehicula consequat ipsum. Fusce vel ex quis sem tristique imperdiet vel in mi. Cras leo orci, fermentum vitae volutpat vitae, convallis semper libero. Phasellus a volutpat diam. Ut pulvinar purus felis, eu vehicula enim aliquet vitae. Suspendisse quis lorem facilisis ante interdum euismod et vitae risus. Vestibulum varius nulla et enim malesuada fringilla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque lorem ligula, lacinia a justo sed, porttitor vulputate risus. In non feugiat risus. Sed vitae urna nisl. Duis suscipit volutpat sollicitudin. Donec ac massa elementum massa condimentum mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla sollicitudin sapien at enim sodales dapibus. Pellentesque sed nisl eu sem aliquam tempus nec ut leo. Quisque rutrum nulla nec aliquam placerat. Fusce a massa ut sem egestas imperdiet. Sed sollicitudin id dolor egestas malesuada. Quisque placerat lobortis ante, id ultrices ipsum hendrerit nec.</p></article>
_x000D_
_x000D_
_x000D_

How can I wait for set of asynchronous callback functions?

Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).

If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all, without any external libraries:

function asyncAction(i) {
    return new Promise(function(resolve, reject) {
        var result = calculateResult();
        if (result.hasError()) {
            return reject(result.error);
        }
        return resolve(result);
    });
}

var promises = [];
for (var i=0; i < 10; i++) {
    promises.push(asyncAction(i));
}

Promise.all(promises).then(function AcceptHandler(results) {
    handleResults(results),
}, function ErrorHandler(error) {
    handleError(error);
});

How can I export data to an Excel file

You can use ExcelDataReader to read existing Excel file:

using (var stream = File.Open("C:\\temp\\input.xlsx", FileMode.Open, FileAccess.Read))
{
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        while (reader.Read())
        {
            for (var i = 0; i < reader.FieldCount; i++)
            {
                var value = reader.GetValue(i)?.ToString();
            }
        }
    }
}

After you collected all data needed you can try my SwiftExcel library to export it to the new Excel file:

using (var ew = new ExcelWriter("C:\\temp\\output.xlsx"))
{
    for (var i = 1; i < 10; i++)
    {
        ew.Write("your_data", i, 1);
    }
}

Nuget commands to install both libraries:

Install-Package ExcelDataReader

Install-Package SwiftExcel

Handling the null value from a resultset in JAVA

To treat validation when a field is null in the database, you could add the following condition.

String name = (oRs.getString ("name_column"))! = Null? oRs.getString ("name_column"): "";

with this you can validate when a field is null and do not mark an exception.