Programs & Examples On #Pdfrenderer

An application or API that is capable of drawing a PDF to various display mediums (computer monitor, image files, printers).

android: stretch image in imageview to fit screen

use this:

ImageView.setAdjustViewBounds(true);

Escape double quotes for JSON in Python

Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:

>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}

Oracle - how to remove white spaces?

It looks like you are executing the query in sqlplus. Sqlplus needs to ensure that there is enough room in the column spacing so the maximum string size can be displayed(255). Usually, the solution is to use the column formatting options(Run prior to the query: column A format A20) to reduce the maximum string size (lines that exceed this length will be displayed over multiple lines).

Extract / Identify Tables from PDF python

After many fruitful hours of exploring OCR libraries, bounding boxes and clustering algorithms - I found a solution so simple it makes you want to cry!

I hope you are using Linux;

pdftotext -layout NAME_OF_PDF.pdf

AMAZING!!

Now you have a nice text file with all the information lined up in nice columns, now it is trivial to format into a csv etc..

It is for times like this that I love Linux, these guys came up with AMAZING solutions to everything, and put it there for FREE!

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

Another possible way to do this:

In system tray, right click on docker icon, then click on Switch to Linux containers.

(Docker for Windows, Community Edition, version 18.03.1)

How to export data with Oracle SQL Developer?

If, at some point, you only need to export a single result set, just right click "on the data" (any column of any row) there you will find an export option. The wizard exports the complete result set regardless of what you selected

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

Try this one -

"SELECT 
       ID, Salt, password, BannedEndDate
     , (
          SELECT COUNT(1)
          FROM dbo.LoginFails l
          WHERE l.UserName = u.UserName
               AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
      ) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"

Angularjs on page load call function

You should call this function from the controller.

angular.module('App', [])
  .controller('CinemaCtrl', ['$scope', function($scope) {
    myFunction();
  }]);

Even with normal javascript/html your function won't run on page load as all your are doing is defining the function, you never call it. This is really nothing to do with angular, but since you're using angular the above would be the "angular way" to invoke the function.

Obviously better still declare the function in the controller too.

Edit: Actually I see your "onload" - that won't get called as angular injects the HTML into the DOM. The html is never "loaded" (or the page is only loaded once).

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Widget _bottom() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Expanded(
          child: Container(
            color: Colors.amberAccent,
            width: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: new List<int>.generate(50, (index) => index + 1)
                    .map((item) {
                  return Text(
                    item.toString(),
                    style: TextStyle(fontSize: 20),
                  );
                }).toList(),
              ),
            ),
          ),
        ),
        Container(
          color: Colors.blue,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'BoTToM',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 33),
              ),
            ],
          ),
        ),
      ],
    );
  }

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

Android: upgrading DB version and adding new table

You can use SQLiteOpenHelper's onUpgrade method. In the onUpgrade method, you get the oldVersion as one of the parameters.

In the onUpgrade use a switch and in each of the cases use the version number to keep track of the current version of database.

It's best that you loop over from oldVersion to newVersion, incrementing version by 1 at a time and then upgrade the database step by step. This is very helpful when someone with database version 1 upgrades the app after a long time, to a version using database version 7 and the app starts crashing because of certain incompatible changes.

Then the updates in the database will be done step-wise, covering all possible cases, i.e. incorporating the changes in the database done for each new version and thereby preventing your application from crashing.

For example:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1:
        String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " + "name_of_column_to_be_added" + " INTEGER";
        db.execSQL(sql);
        break;

    case 2:
        String sql = "SOME_QUERY";
        db.execSQL(sql);
        break;
    }

}

Windows batch: call more than one command in a FOR loop?

SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)).

A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.

FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF

:loopbody
ECHO %1
DEL %1
GOTO :EOF

Why does this CSS margin-top style not work?

Not exactly sure why, but changing the inner CSS to

display: inline-block;

seems to work.

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

The port is already being used by some other process as @Diego Pino said u can use lsof on unix to locate the process and kill the respective one, if you are on windows use netstat -ano to get all the pids of the process and the ports that everyone acquires. search for your intended port and kill.

to be very easy just restart your machine , if thats possible :)

Execute Python script via crontab

Just use crontab -e and follow the tutorial here.

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

How to filter for multiple criteria in Excel?

Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.

The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.

=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")

Like I said, not as elegant as the advanced filters but options are always good.

What is the difference between AF_INET and PF_INET in socket programming?

AF_INET = Address Format, Internet = IP Addresses

PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP

AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part sticking with AF_INET for socket programming over a network is the safest option.

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.

PF_INET refers to anything in the protocol, usually sockets/ports.

Select Specific Columns from Spark DataFrame

i liked dehasis approach, because it allowed me to select, rename and convert columns in one step. However I had to adjust it to make it work for me in PySpark:

from pyspark.sql.functions import col

spark.read.csv(path).select(
      col('_c0').alias("stn").cast('String'),
      col('_c1').alias("wban").cast('String'),
      col('_c2').alias("lat").cast('Double'),
      col('_c3').alias("lon").cast('Double')
    )
      .where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

Add these lines to your web.config file:

<system.data>
    <DbProviderFactories>
               <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory,MySql.Data,  Version=6.6.4.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D"/>
    </DbProviderFactories>
</system.data>

Change your provider from MySQL to SQL Server or whatever database provider you are connecting to.

How to define static property in TypeScript interface

Another option not mentioned here is defining variable with a type representing static interface and assigning to it class expression:

interface MyType {
    instanceMethod(): void;
}

interface MyTypeStatic {
    new(): MyType;
    staticMethod(): void;
}

// ok
const MyTypeClass: MyTypeStatic = class MyTypeClass {
    public static staticMethod() { }
    instanceMethod() { }
}

// error: 'instanceMethod' is missing
const MyTypeClass1: MyTypeStatic = class MyTypeClass {
    public static staticMethod() { }
}

// error: 'staticMethod' is missing
const MyTypeClass2: MyTypeStatic = class MyTypeClass {
    instanceMethod() { }
}

The effect is same as in answer with decorators, but without overhead of decorators

Playground

Relevant suggestion/discussion on GitHub

Grant SELECT on multiple tables oracle

If you want to grant to both tables and views try:

SELECT DISTINCT
    || OWNER
    || '.'
    || TABLE_NAME
    || ' to db_user;'
FROM
    ALL_TAB_COLS 
WHERE
    TABLE_NAME LIKE 'TABLE_NAME_%';

For just views try:

SELECT
    'grant select on '
    || OWNER
    || '.'
    || VIEW_NAME
    || ' to REPORT_DW;'
FROM
    ALL_VIEWS
WHERE
    VIEW_NAME LIKE 'VIEW_NAME_%';

Copy results and execute.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

Is the Javascript date object always one day off?

The best way to handle this without using more conversion methods,

 var mydate='2016,3,3';
 var utcDate = Date.parse(mydate);
 console.log(" You're getting back are 20.  20h + 4h = 24h :: "+utcDate);

Now just add GMT in your date or you can append it.

 var  mydateNew='2016,3,3'+ 'GMT';
 var utcDateNew = Date.parse(mydateNew);
 console.log("the right time that you want:"+utcDateNew)

Live: https://jsfiddle.net/gajender/2kop9vrk/1/

Jquery resizing image

And old post... bit still. Resizing is one thing, but it can leave resized images uncentered, and looking a bit unorganised. So I added a few lines to the original post to add a left margin to centralise any resized images.

$(".schs_bonsai_image_slider_image").each(function()
{
    var maxWidth = 787; // Max width for the image
    var maxHeight = 480;    // Max height for the image
    var ratio = 0;  // Used for aspect ratio
    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height

    // Check if the current width is larger than the max
    if(width > maxWidth)
    {
        ratio = maxWidth / width;   // get ratio for scaling image
        $(this).css("width", maxWidth); // Set new width
        $(this).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
        width = width * ratio;    // Reset width to match scaled image
    }
    // Check if current height is larger than max
    if(height > maxHeight)
    {
        ratio = maxHeight / height; // get ratio for scaling image
        $(this).css("height", maxHeight);   // Set new height
        $(this).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
        height = height * ratio;    // Reset height to match scaled image
    }
    var newwidth = $(this).width();
    var parentwidth=$(this).parent().width();
    var widthdiff=(parentwidth-newwidth)/2;
    $(this).css("margin-left",widthdiff);
});

MAX(DATE) - SQL ORACLE

SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
    SELECT MAX(p2.PAYM_DATE)
    FROM user_payments as p2
    WHERE p2.USER_ID = p.USER_ID
)

When should iteritems() be used instead of items()?

dict.iteritems was removed because dict.items now does the thing dict.iteritems did in python 2.x and even improved it a bit by making it an itemview.

Adding Jar files to IntellijIdea classpath

Go to File-> Project Structure-> Libraries and click green "+" to add the directory folder that has the JARs to CLASSPATH. Everything in that folder will be added to CLASSPATH.

Update:

It's 2018. It's a better idea to use a dependency manager like Maven and externalize your dependencies. Don't add JAR files to your project in a /lib folder anymore.

Screenshot

Python script to do something at the same time every day

APScheduler might be what you are after.

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])

# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])

https://apscheduler.readthedocs.io/en/latest/

You can just get it to schedule another run by building that into the function you are scheduling.

super() in Java

Some facts:

  1. super() is used to call the immediate parent.
  2. super() can be used with instance members, i.e., instance variables and instance methods.
  3. super() can be used within a constructor to call the constructor of the parent class.

OK, now let’s practically implement these points of super().

Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java.

Program 1

class Base
{
    int a = 100;
}

class Sup1 extends Base
{
    int a = 200;
    void Show()
    {
        System.out.println(a);
        System.out.println(a);
    }
    public static void main(String[] args)
    {
        new Sup1().Show();
    }
}

Output:

200
200

Now check out program 2 and try to figure out the main difference.

Program 2

class Base
{
    int a = 100;
}

class Sup2 extends Base
{
    int a = 200;
    void Show()
    {
        System.out.println(super.a);
        System.out.println(a);
    }
    public static void main(String[] args)
    {
        new Sup2().Show();
    }
}

Output:

100
200

In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent.

OK, now check out the difference between program 3 and program 4.

Program 3

class Base
{
    int a = 100;
    void Show()
    {
        System.out.println(a);
    }
}

class Sup3 extends Base
{
    int a = 200;
    void Show()
    {
        System.out.println(a);
    }
    public static void Main(String[] args)
    {
        new Sup3().Show();
    }
}

Output:

200

Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution.

Program 4

class Base
{
    int a = 100;
    void Show()
    {
        System.out.println(a);
    }
}

class Sup4 extends Base
{
    int a = 200;
    void Show()
    {
        super.Show();
        System.out.println(a);
    }
    public static void Main(String[] args)
    {
        new Sup4().Show();
    }
}

Output:

100
200

Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.

How to add meta tag in JavaScript

$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');

or

var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);

Though I'm not certain it will have an affect as it will be generated after the page is loaded

If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx

This may allow other meta tags, if you're lucky

Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx

C# Remove object from list of objects

First you have to find out the object in the list. Then you can remove from the list.

       var item = myList.Find(x=>x.ItemName == obj.ItemName);
       myList.Remove(item);

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

Locate config.inc.php file under C:\xampp\phpMyAdmin and open it in any editor. Find the following line:

$cfg['Servers'][$i]['password'] = '  ';

Enter the chosen password inside the quotes. Also, in order to make localhost/phpmyadmin ask for a username and password, find the following line:

$cfg['Servers'][$i]['auth_type'] = 'config';

Change the above line to:

$cfg['Servers'][$i]['auth_type'] = 'cookie';

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

I had this problem when I wanted to make a vnc connection via a tunnel. But the vncserver was not running. I solved it by opening the channel on the remote machine with vncserver :3.

PDOException SQLSTATE[HY000] [2002] No such file or directory

In my case i had no problem at all, just forgot to start the mysql service...

sudo service mysqld start

How to test Spring Data repositories?

With JUnit5 and @DataJpaTest test will look like (kotlin code):

@DataJpaTest
@ExtendWith(value = [SpringExtension::class])
class ActivityJpaTest {

    @Autowired
    lateinit var entityManager: TestEntityManager

    @Autowired
    lateinit var myEntityRepository: MyEntityRepository

    @Test
    fun shouldSaveEntity() {
        // when
        val savedEntity = myEntityRepository.save(MyEntity(1, "test")

        // then 
        Assertions.assertNotNull(entityManager.find(MyEntity::class.java, savedEntity.id))
    }
}

You could use TestEntityManager from org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager package in order to validate entity state.

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

Getting fb.me URL

I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

Change type of varchar field to integer: "cannot be cast automatically to type integer"

If you've accidentally or not mixed integers with text data you should at first execute below update command (if not above alter table will fail):

UPDATE the_table SET col_name = replace(col_name, 'some_string', '');

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

Unsigned values in C

When you initialize unsigned int a to -1; it means that you are storing the 2's complement of -1 into the memory of a.
Which is nothing but 0xffffffff or 4294967295.

Hence when you print it using %x or %u format specifier you get that output.

By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.

Like with unsigned int: the range is from 0 to 4,294,967,295 and int: the range is from -2,147,483,648 to 2,147,483,647

For more info on signedness refer this

Postgresql 9.2 pg_dump version mismatch

Macs have a builtin /usr/bin/pg_dump command that is used as default.

With the postgresql install you get another binary at /Library/PostgreSQL/<version>/bin/pg_dump

C# SQL Server - Passing a list to a stored procedure

Make a datatable with one column instead of List and add strings to the table. You can pass this datatable as structured type and perform another join with title field of your table.

How to escape braces (curly brackets) in a format string in .NET

Almost there! The escape sequence for a brace is {{ or }} so for your example you would use:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

Validate Dynamically Added Input fields

In case you have a form you can add a class name as such:

<form id="my-form">
  <input class="js-input" type="text" name="samplename" />
  <input class="js-input" type="text" name="samplename" />
  <input class="submit" type="submit" value="Submit" />
</form>

you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:

$(document).ready(function() {
  $.validator.addClassRules('js-input', {
    required: true,
  });
  //validate the form
  $('#my-form').validate();
});

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

Print in one line dynamically

"By the way...... How to refresh it every time so it print mi in one place just change the number."

It's really tricky topic. What zack suggested ( outputting console control codes ) is one way to achieve that.

You can use (n)curses, but that works mainly on *nixes.

On Windows (and here goes interesting part) which is rarely mentioned (I can't understand why) you can use Python bindings to WinAPI (http://sourceforge.net/projects/pywin32/ also with ActivePython by default) - it's not that hard and works well. Here's a small example:

import win32console, time

output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]

for i in "\\|/-\\|/-":
    output_handle.WriteConsoleOutputCharacter( i, pos )
    time.sleep( 1 )

Or, if you want to use print (statement or function, no difference):

import win32console, time

output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]

for i in "\\|/-\\|/-":
    print i
    output_handle.SetConsoleCursorPosition( pos )
    time.sleep( 1 )

win32console module enables you to do many more interesting things with windows console... I'm not a big fan of WinAPI, but recently I realized that at least half of my antipathy towards it was caused by writing WinAPI code in C - pythonic bindings are much easier to use.

All other answers are great and pythonic, of course, but... What if I wanted to print on previous line? Or write multiline text, than clear it and write the same lines again? My solution makes that possible.

How to insert 1000 rows at a time

You can of course use a loop, or you can insert them in a single statement, e.g.

Insert into db
(names,email,password) 
Values
('abc','def','mypassword')
,('ghi','jkl','mypassword2')
,('mno','pqr','mypassword3')

It really depends where you're getting your data from.

If you use a loop, wrapping it in a transaction will make it a bit faster.

UPDATE

What if i want to insert unique names?

If you want to insert unique names, then you need to generate data with unique names. One way to do this is to use Visual Studio to generate test data.

How to change 1 char in the string?

Strings are immutable, meaning you can't change a character. Instead, you create new strings.

What you are asking can be done several ways. The most appropriate solution will vary depending on the nature of the changes you are making to the original string. Are you changing only one character? Do you need to insert/delete/append?

Here are a couple ways to create a new string from an existing string, but having a different first character:

str = 'M' + str.Remove(0, 1);

str = 'M' + str.Substring(1);

Above, the new string is assigned to the original variable, str.

I'd like to add that the answers from others demonstrating StringBuilder are also very appropriate. I wouldn't instantiate a StringBuilder to change one character, but if many changes are needed StringBuilder is a better solution than my examples which create a temporary new string in the process. StringBuilder provides a mutable object that allows many changes and/or append operations. Once you are done making changes, an immutable string is created from the StringBuilder with the .ToString() method. You can continue to make changes on the StringBuilder object and create more new strings, as needed, using .ToString().

Passing capturing lambda as function pointer

Not a direct answer, but a slight variation to use the "functor" template pattern to hide away the specifics of the lambda type and keeps the code nice and simple.

I was not sure how you wanted to use the decide class so I had to extend the class with a function that uses it. See full example here: https://godbolt.org/z/jtByqE

The basic form of your class might look like this:

template <typename Functor>
class Decide
{
public:
    Decide(Functor dec) : _dec{dec} {}
private:
    Functor _dec;
};

Where you pass the type of the function in as part of the class type used like:

auto decide_fc = [](int x){ return x > 3; };
Decide<decltype(decide_fc)> greaterThanThree{decide_fc};

Again, I was not sure why you are capturing x it made more sense (to me) to have a parameter that you pass in to the lambda) so you can use like:

int result = _dec(5); // or whatever value

See the link for a complete example

How do I change the number of open files limit in Linux?

1) Add the following line to /etc/security/limits.conf

webuser hard nofile 64000

then login as webuser

su - webuser

2) Edit following two files for webuser

append .bashrc and .bash_profile file by running

echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile

3) Log out, then log back in and verify that the changes have been made correctly:

$ ulimit -a | grep open
open files                      (-n) 64000

Thats it and them boom, boom boom.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

Face recognition Library

You can try open MVG library, It can be used for multiple interfaces too.

ASP.NET postback with JavaScript

Have you tried passing the Update panel's client id to the __doPostBack function? My team has done this to refresh an update panel and as far as I know it worked.

__doPostBack(UpdatePanelClientID, '**Some String**');

Update multiple rows in same query using PostgreSQL

Came across similar scenario and the CASE expression was useful to me.

UPDATE reports SET is_default = 
case 
 when report_id = 123 then true
 when report_id != 123 then false
end
WHERE account_id = 321;

Reports - is a table here, account_id is same for the report_ids mentioned above. The above query will set 1 record (the one which matches the condition) to true and all the non-matching ones to false.

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

Pandas - How to flatten a hierarchical index in columns

You could also do as below. Consider df to be your dataframe and assume a two level index (as is the case in your example)

df.columns = [(df.columns[i][0])+'_'+(datadf_pos4.columns[i][1]) for i in range(len(df.columns))]

Algorithm to detect overlapping periods

Simple check to see if two time periods overlap:

bool overlap = a.start < b.end && b.start < a.end;

or in your code:

bool overlap = tStartA < tEndB && tStartB < tEndA;

(Use <= instead of < if you change your mind about wanting to say that two periods that just touch each other overlap.)

How to include vars file in a vars file with ansible?

You can put your servers in the default_step group and those vars will apply to it:

# inventory file
[default_step]
prod2
web_v2

Then just move your default_step.yml file to group_vars/default_step.yml.

Break string into list of characters in Python

I'm a bit late it seems to be, but...

a='hello'
print list(a)
# ['h','e','l','l', 'o']

How to get POST data in WebAPI?

After spending a good bit of time today trying to wrap my brain around the (significant but powerful) paradigm shift between old ways of processing web form data and how it is done with WebAPI, I thought I'd add my 2 cents to this discussion.

What I wanted to do (which is pretty common for web form processing of a POST) is to be able to grab any of the form values I want, in any order. Say like you can do if you have your data in a System.Collections.Specialized.NameValueCollection. But turns out, in WebAPI, the data from a POST comes back at you as a stream. So you can't directly do that.

But there is a cool little class named FormDataCollection (in System.Net.Http.Formatting) and what it will let you do is iterate through your collection once.

So I wrote a simple utility method that will run through the FormDataCollection once and stick all the values into a NameValueCollection. Once this is done, you can jump all around the data to your hearts content.

So in my ApiController derived class, I have a post method like this:

    public void Post(FormDataCollection formData)
    {
        NameValueCollection valueMap = WebAPIUtils.Convert(formData);

        ... my code that uses the data in the NameValueCollection
    }

The Convert method in my static WebAPIUtils class looks like this:

    /// <summary>
    /// Copy the values contained in the given FormDataCollection into 
    /// a NameValueCollection instance.
    /// </summary>
    /// <param name="formDataCollection">The FormDataCollection instance. (required, but can be empty)</param>
    /// <returns>The NameValueCollection. Never returned null, but may be empty.</returns>
    public static NameValueCollection Convert(FormDataCollection formDataCollection)
    {
        Validate.IsNotNull("formDataCollection", formDataCollection);

        IEnumerator<KeyValuePair<string, string>> pairs = formDataCollection.GetEnumerator();

        NameValueCollection collection = new NameValueCollection();

        while (pairs.MoveNext())
        {
            KeyValuePair<string, string> pair = pairs.Current;

            collection.Add(pair.Key, pair.Value);
        }

        return collection;
     }

Hope this helps!

How to create Windows EventLog source from command line?

Try PowerShell 2.0's EventLog cmdlets

Throwing this in for PowerShell 2.0 and upwards:

  • Run New-EventLog once to register the event source:

    New-EventLog -LogName Application -Source MyApp
    
  • Then use Write-EventLog to write to the log:

    Write-EventLog 
        -LogName Application 
        -Source MyApp 
        -EntryType Error 
        -Message "Immunity to iocaine powder not detected, dying now" 
        -EventId 1
    

How to check the installed version of React-Native

You can run this command in Terminal:

react-native --version

This will give react-native CLI version

Or check in package.json under

"dependencies": {
    "react": "16.11.0",
    "react-native": "0.62.2",
}

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

Beyond the problematic use of async as pointed out by @Servy, the other issue is that you need to explicitly get T from Task<T> by calling Task.Result. Note that the Result property will block async code, and should be used carefully.

Try:

private async void button1_Click(object sender, EventArgs e)
{
    var s = await methodAsync();
    MessageBox.Show(s.Result);
}

estimating of testing effort as a percentage of development time

Some years ago, in a safety critical field, I have heard something like one day for unit testing ten lines of code.

I have also observed 50% of effort for development and 50% for testing (not only unit testing).

Validation of file extension before uploading file

If you're needing to test remote urls in an input field, you can try testing a simple regex with the types that you're interested in.

$input_field = $('.js-input-field-class');

if ( !(/\.(gif|jpg|jpeg|tiff|png)$/i).test( $input_field.val() )) {
  $('.error-message').text('This URL is not a valid image type. Please use a url with the known image types gif, jpg, jpeg, tiff or png.');
  return false;
}

This will capture anything ending in .gif, .jpg, .jpeg, .tiff or .png

I should note that some popular sites like Twitter append a size attribute to the end of their images. For instance, the following would fail this test even though it's a valid image type:

https://pbs.twimg.com/media/BrTuXT5CUAAtkZM.jpg:large

Because of that, this isn't a perfect solution. But it will get you to about 90% of the way.

optional parameters in SQL Server stored proc?

Yes, it is. Declare parameter as so:

@Sort varchar(50) = NULL

Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).

How to show the Project Explorer window in Eclipse

Try to close Eclipse IDE and reopen it and

click on window->show view->project explorer

Facebook page automatic "like" URL (for QR Code)

The answers above seem partly outdated.

The URL builder on https://developers.facebook.com/docs/plugins/like-button/ worked nicely for me.

You can configure, preview and the get the code/URL in different flavors: HTML5, XFBML, IFRAME, URL

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Position: absolute and parent height?

This kind of layout problem can be solved with flexbox now, avoiding the need to know heights or control layout with absolute positioning, or floats. OP's main question was how to get a parent to contain children of unknown height, and they wanted to do it within a certain layout. Setting height of the parent container to "fit-content" does this; using "display: flex" and "justify-content: space-between" produces the section/column layout I think the OP was trying to create.

<section id="foo">
    <header>Foo</header>
    <article>
        <div class="main one"></div>
        <div class="main two"></div>
    </article>
</section>    

<div style="clear:both">Clear won't do.</div>

<section id="bar">
    <header>bar</header>
    <article>
        <div class="main one"></div><div></div>
        <div class="main two"></div>
    </article>
</section> 

* { text-align: center; }
article {
    height: fit-content ;
    display: flex;
    justify-content: space-between;
    background: whitesmoke;
}
article div { 
    background: yellow;     
    margin:20px;
    width: 30px;
    height: 30px;
    }

.one {
    background: red;
}

.two {
    background: blue;
}

I modified the OP's fiddle: http://jsfiddle.net/taL4s9fj/

css-tricks on flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

jquery animate background position

I guess it might be because it is expecting a single value?

taken from the animate page on jQuery:

Animation Properties and Values

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

Razor View Without Layout

I think it's better work with individual "views", Im trying to move from PHP to MVC4, its really hard but im on the right way...

Answering your question, if you'll work individual pages, just edit the _ViewStart.cshtml

@{
  Layout = null;
}

Another tip if you're getting some issues with CSS path...

Put "../" before of the url

This are the 2 problems that i get today, and I resolve in that way!

Regards;

Regex to remove letters, symbols except numbers

You can use \D which means non digits.

var removedText = self.val().replace(/\D+/g, '');

jsFiddle.

You could also use the HTML5 number input.

<input type="number" name="digit" />

jsFiddle.

Selecting multiple columns with linq query and lambda expression

using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;

as Name = Fname + " " + LName;

See my below code which is working as expected; hope this is useful;

Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}

no need to declare the 'contact'

Reordering arrays

You could always use the sort method, if you don't know where the record is at present:

playlist.sort(function (a, b) {
    return a.artist == "Lalo Schifrin" 
               ? 1    // Move it down the list
               : 0;   // Keep it the same
});

"The operation is not valid for the state of the transaction" error and transaction scope

For me, this error came up when I was trying to rollback a transaction block after encountering an exception, inside another transaction block.

All I had to do to fix it was to remove my inner transaction block.

Things can get quite messy when using nested transactions, best to avoid this and just restructure your code.

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

Here's an answer to a 2-year old question in case it helps anyone else with the same problem.

Based upon the information you've provided, a permissions issue on the file (or files) would be one cause of the same 500 Internal Server Error.

To check whether this is the problem (if you can't get more detailed information on the error), navigate to the directory in Terminal and run the following command:

ls -la

If you see limited permissions - e.g. -rw-------@ against your file, then that's your problem.

The solution then is to run chmod 644 on the problem file(s) or chmod 755 on the directories. See this answer - How do I set chmod for a folder and all of its subfolders and files? - for a detailed explanation of how to change permissions.

By way of background, I had precisely the same problem as you did on some files that I had copied over from another Mac via Google Drive, which transfer had stripped most of the permissions from the files.

The screenshot below illustrates. The index.php file with the -rw-------@ permissions generates a 500 Internal Server Error, while the index_finstuff.php (precisely the same content!) with -rw-r--r--@ permissions is fine. Changing the permissions on the index.php immediately resolves the problem.

In other words, your PHP code and the server may both be fine. However, the limited read permissions on the file may be forbidding the server from displaying the content, causing the 500 Internal Server Error message to be displayed instead.

enter image description here

How to list only top level directories in Python?

being a newbie here i can't yet directly comment but here is a small correction i'd like to add to the following part of ??O?????'s answer :

If you prefer full pathnames, then use this function:

def listdirs(folder):  
  return [
    d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
    if os.path.isdir(d)
]

for those still on python < 2.4: the inner construct needs to be a list instead of a tuple and therefore should read like this:

def listdirs(folder):  
  return [
    d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]
    if os.path.isdir(d)
  ]

otherwise one gets a syntax error.

Easy way to concatenate two byte arrays

You can use third party libraries for Clean Code like Apache Commons Lang and use it like:

byte[] bytes = ArrayUtils.addAll(a, b);

What does \u003C mean?

Those are unicode escapes. The general unicode escapes looks like \uxxxx where xxxx are the hexadecimal digits of the ASCI characters. They are used mainly to insert special characters inside a javascript string.

Hexadecimal value 0x00 is a invalid character

In my case, it took some digging, but found it.

My Context

I'm looking at exception/error logs from the website using Elmah. Elmah returns the state of the server at the of time the exception, in the form of a large XML document. For our reporting engine I pretty-print the XML with XmlWriter.

During a website attack, I noticed that some xmls weren't parsing and was receiving this '.', hexadecimal value 0x00, is an invalid character. exception.

NON-RESOLUTION: I converted the document to a byte[] and sanitized it of 0x00, but it found none.

When I scanned the xml document, I found the following:

...
<form>
...
<item name="SomeField">
   <value
     string="C:\boot.ini&#x0;.htm" />
 </item>
...

There was the nul byte encoded as an html entity &#x0; !!!

RESOLUTION: To fix the encoding, I replaced the &#x0; value before loading it into my XmlDocument, because loading it will create the nul byte and it will be difficult to sanitize it from the object. Here's my entire process:

XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("&#x0;", "[0x00]");  // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);

string formattedXml = null;

// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    OmitXmlDeclaration = true,
    Indent = true,
    IndentChars = "\t",
    NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    xml.Save(writer);
    formattedXml = sb.ToString();
}

LESSON LEARNED: sanitize for illegal bytes using the associated html entity, if your incoming data is html encoded on entry.

What's the best way to add a full screen background image in React Native

Oh God Finally I find a great way for React-Native V 0.52-RC and native-base:

Your Content Tag Should be something like this: //==============================================================

<Content contentContainerStyle={styles.container}>
    <ImageBackground
        source={require('./../assets/img/back.jpg')}
        style={styles.backgroundImage}>
        <Text>
            Some text here ...
        </Text>
    </ImageBackground>
</Content>

And Your essential style is : //==============================================================

container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
},
backgroundImage:{
    flex : 1,
    width : '100%'
}

It works fine friends ... have fun

Check last modified date of file in C#

Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.

The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.

  [TestMethod]
  public void TestLastModifiedTimeStamps()
  {
     var tempFile = Path.GetTempFileName();
     var lastModified = File.GetLastWriteTime(tempFile);
     using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {

     }
     Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
  }

See File.GetLastWriteTime seems to be returning 'out of date' value

Your options:

a) live with the occasional omissions.

b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).

c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.

/// <summary>
/// type to set signals or check for them using a central file 
/// </summary>
public class FileSignal
{
    /// <summary>
    /// path to the central file for signal control
    /// </summary>
    public string FilePath { get; private set; }

    /// <summary>
    /// numbers of retries when not able to retrieve (exclusive) file access
    /// </summary>
    public int MaxCollisions { get; private set; }

    /// <summary>
    /// timespan to wait until next try
    /// </summary>
    public TimeSpan SleepOnCollisionInterval { get; private set; }

    /// <summary>
    /// Timestamp of the last signal
    /// </summary>
    public DateTime LastSignal { get; private set; }

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
    /// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
    public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
    {
        FilePath = filePath;
        MaxCollisions = maxCollisions;
        SleepOnCollisionInterval = sleepOnCollisionInterval;
        LastSignal = GetSignalTimeStamp();
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>        
    public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
    {
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>        
    public FileSignal(string filePath) : this(filePath, 10)
    {
    }

    private Stream GetFileStream(FileAccess fileAccess)
    {
        var i = 0;
        while (true)
        {
            try
            {
                return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
            }
            catch (Exception e)
            {
                i++;
                if (i >= MaxCollisions)
                {
                    throw e;
                }
                Thread.Sleep(SleepOnCollisionInterval);
            };
        };
    }

    private DateTime GetSignalTimeStamp()
    {
        if (!File.Exists(FilePath))
        {
            return DateTime.MinValue;
        }
        using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if(stream.Length == 0)
            {
                return DateTime.MinValue;
            }
            using (var reader = new BinaryReader(stream))
            {
                return DateTime.FromBinary(reader.ReadInt64());
            };                
        }
    }

    /// <summary>
    /// overwrites the existing central file and writes the current time into it.
    /// </summary>
    public void Signal()
    {
        LastSignal = DateTime.Now;
        using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(LastSignal.ToBinary());
            }
        }
    }

    /// <summary>
    /// returns true if the file signal has changed, otherwise false.
    /// </summary>        
    public bool CheckIfSignalled()
    {
        var signal = GetSignalTimeStamp();
        var signalTimestampChanged = LastSignal != signal;
        LastSignal = signal;
        return signalTimestampChanged;
    }
}

Some tests for it:

    [TestMethod]
    public void TestSignal()
    {
        var fileSignal = new FileSignal(Path.GetTempFileName());
        var fileSignal2 = new FileSignal(fileSignal.FilePath);
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        fileSignal.Signal();
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsTrue(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
    }

How can I convert IPV6 address to IPV4 address?

Here is the code you are looking for in javascript. Well you know you can't convert all of the ipv6 addresses

<script>
function parseIp6(str)
{
  //init
  var ar=new Array;
  for(var i=0;i<8;i++)ar[i]=0;
  //check for trivial IPs
  if(str=="::")return ar;
  //parse
  var sar=str.split(':');
  var slen=sar.length;
  if(slen>8)slen=8;
  var j=0;
  for(var i=0;i<slen;i++){
    //this is a "::", switch to end-run mode
    if(i && sar[i]==""){j=9-slen+i;continue;}
    ar[j]=parseInt("0x0"+sar[i]);
    j++;
  }

  return ar;
}
function ipcnvfrom6(ip6)
{
  var ip6=parseIp6(ip6);
  var ip4=(ip6[6]>>8)+"."+(ip6[6]&0xff)+"."+(ip6[7]>>8)+"."+(ip6[7]&0xff);
  return ip4;
}
alert(ipcnvfrom6("::C0A8:4A07"));
</script>

How to run a SQL query on an Excel table?

You can experiment with the native DB driver for Excel in language/platform of your choice. In Java world, you can try with http://code.google.com/p/sqlsheet/ which provides a JDBC driver for working with Excel sheets directly. Similarly, you can get drivers for the DB technology for other platforms.

However, I can guarantee that you will soon hit a wall with the number of features these wrapper libraries provide. Better way will be to use Apache HSSF/POI or similar level of library but it will need more coding effort.

How to add key,value pair to dictionary?

May be some time this also will be helpful

import collections
#Write you select statement here and other things to fetch the data.
 if rows:
            JArray = []
            for row in rows:

                JArray2 = collections.OrderedDict()
                JArray2["id"]= str(row['id'])
                JArray2["Name"]= row['catagoryname']
                JArray.append(JArray2)

            return json.dumps(JArray)

Example Output:

[
    {
        "id": 14
        "Name": "someName1"
    },
    {
        "id": 15
        "Name": "someName2"
    }
]

Driver executable must be set by the webdriver.ie.driver system property

  1. You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

  2. Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

    File file = new File("C:/Selenium/iexploredriver.exe");
    System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    WebDriver driver = new InternetExplorerDriver();
    

Basically, you have to set this property before you initialize driver

How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String
     }]

or

trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
{
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 
  }
});

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
{
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                  },
                  {
                     "lat": 50.3293284,
                     "lng": 6.9389634
                  }
               ]//'inserted Array containing the list of object'
      }
});

.keyCode vs. .which

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.

http://jaywcjlove.github.io/hotkeys/

hotkeys('ctrl+a,ctrl+b,r,f', function(event,handler){
    switch(handler.key){
        case "ctrl+a":alert('you pressed ctrl+a!');break;
        case "ctrl+b":alert('you pressed ctrl+b!');break;
        case "r":alert('you pressed r!');break;
        case "f":alert('you pressed f!');break;
    }
});

hotkeys understands the following modifiers: ?, shift, option, ?, alt, ctrl, control, command, and ?.

The following special keys can be used for shortcuts: backspace, tab, clear, enter, return, esc, escape, space, up, down, left, right, home, end, pageup, pagedown, del, delete and f1 through f19.

Multiplying Two Columns in SQL Server

In a query you can just do something like:

SELECT ColumnA * ColumnB FROM table

or

SELECT ColumnA - ColumnB FROM table

You can also create computed columns in your table where you can permanently use your formula.

Disable a Button

Let's say in Swift 4 you have a button set up for a segue as an IBAction like this @IBAction func nextLevel(_ sender: UIButton) {} and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:

var appMode = 0

@IBAction func mySegue(_ sender: UIButton) {

    if appMode == 1 {  // avoid crash if button pressed during other app actions and/or conditions
        let conflictingAction = sender as UIButton
        conflictingAction.isEnabled = false
    }
}

Please note that you will likely have other conditions within if appMode == 0 and/or if appMode == 1 that will still occur and NOT conflict with the mySegue button. Thus, AVOIDING A CRASH.

are there dictionaries in javascript like python?

I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");

//returns "Bar"
dict.get(bar);

//returns "Foo"
dict.get(foo);

//returns undefined, as {} !== foo and {} !== bar
dict.get({});

Failed to instantiate module error in Angular js

I got this error due to not pointing the script to the correct path. So make absolutely sure that you are pointing to the correct path in you html file.

Hide separator line on one UITableViewCell

As (many) others have pointed out, you can easily hide all UITableViewCell separators by simply turning them off for the entire UITableView itself; eg in your UITableViewController

- (void)viewDidLoad {
    ...
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    ...
}

Unfortunately, its a real PITA to do on a per-cell basis, which is what you are really asking.

Personally, I've tried numerous permutations of changing the cell.separatorInset.left, again, as (many) others have suggested, but the problem is, to quote Apple (emphasis added):

"...You can use this property to add space between the current cell’s contents and the left and right edges of the table. Positive inset values move the cell content and cell separator inward and away from the table edges..."

So if you try to 'hide' the separator by shoving it offscreen to the right, you can end up also indenting your cell's contentView too. As suggested by crifan, you can then try to compensate for this nasty side-effect by setting cell.indentationWidth and cell.indentationLevel appropriately to move everything back, but I've found this to also be unreliable (content still getting indented...).

The most reliable way I've found is to over-ride layoutSubviews in a simple UITableViewCell subclass and set the right inset so that it hits the left inset, making the separator have 0 width and so invisible [this needs to be done in layoutSubviews to automatically handle rotations]. I also add a convenience method to my subclass to turn this on.

@interface MyTableViewCellSubclass()
@property BOOL separatorIsHidden;
@end

@implementation MyTableViewCellSubclass

- (void)hideSeparator
{
    _separatorIsHidden = YES;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (_separatorIsHidden) {
        UIEdgeInsets inset = self.separatorInset;
        inset.right = self.bounds.size.width - inset.left;
        self.separatorInset = inset;
    }
}

@end

Caveat: there isn't a reliable way to restore the original right inset, so you cant 'un-hide' the separator, hence why I'm using an irreversible hideSeparator method (vs exposing separatorIsHidden). Please note the separatorInset persists across reused cells so, because you can't 'un-hide', you need to keep these hidden-separator cells isolated in their own reuseIdentifier.

Python Pandas - Find difference between two data frames

Perhaps a simpler one-liner, with identical or different column names. Worked even when df2['Name2'] contained duplicate values.

newDf = df1.set_index('Name1')
           .drop(df2['Name2'], errors='ignore')
           .reset_index(drop=False)

Should I use window.navigate or document.location in JavaScript?

You can move your page using

window.location.href =Url;

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        e.preventDefault();_x000D_
        if (x < max_fields) {_x000D_
            x++;_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
        }_x000D_
    });_x000D_
_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
        e.preventDefault();_x000D_
        $(this).parent('div').remove();_x000D_
        x--;_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    </button>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Refer Demo Here

Excel: Creating a dropdown using a list in another sheet?

That cannot be done in excel 2007. The list must be in the same sheet as your data. It might work in later versions though.

Creating a list of objects in Python

It shouldn't be necessary to recreate the SimpleClass object each time, as some are suggesting, if you're simply using it to output data based on its attributes. However, you're not actually creating an instance of the class; you're simply creating a reference to the class object itself. Therefore, you're adding a reference to the same class attribute to the list (instead of instance attribute), over and over.

Instead of:

x = SimpleClass

you need:

x = SimpleClass()

using batch echo with special characters

The answer from Joey was not working for me. After executing

  echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

I got this error bash: syntax error near unexpected token `>'

This solution worked for me:

 echo "<?xml version=\"1.0\" encoding=\"utf-8\">" > myfile.txt

See also http://www.robvanderwoude.com/escapechars.php

Is it valid to define functions in JSON results?

The problem is that JSON as a data definition language evolved out of JSON as a JavaScript Object Notation. Since Javascript supports eval on JSON, it is legitimate to put JSON code inside JSON (in that use-case). If you're using JSON to pass data remotely, then I would say it is bad practice to put methods in the JSON because you may not have modeled your client-server interaction well. And, further, when wishing to use JSON as a data description language I would say you could get yourself into trouble by embedding methods because some JSON parsers were written with only data description in mind and may not support method definitions in the structure.

Wikipedia JSON entry makes a good case for not including methods in JSON, citing security concerns:

Unless you absolutely trust the source of the text, and you have a need to parse and accept text that is not strictly JSON compliant, you should avoid eval() and use JSON.parse() or another JSON specific parser instead. A JSON parser will recognize only JSON text and will reject other text, which could contain malevolent JavaScript. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

How to escape single quotes in MySQL

You should escape the special characters using the \ character.

This is Ashok's Pen.

Becomes:

This is Ashok\'s Pen.

JavaScript/jQuery - "$ is not defined- $function()" error

Im using Asp.Net Core 2.2 with MVC and Razor cshtml My JQuery is referenced in a layout page I needed to add the following to my view.cshtml:

@section Scripts {
$script-here
}

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

This is the hardware serial number. To access it on

  • Android Q (>= SDK 29) android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE is required. Only system apps can require this permission. If the calling package is the device or profile owner then the READ_PHONE_STATE permission suffices.

  • Android 8 and later (>= SDK 26) use android.os.Build.getSerial() which requires the dangerous permission READ_PHONE_STATE. Using android.os.Build.SERIAL returns android.os.Build.UNKNOWN.

  • Android 7.1 and earlier (<= SDK 25) and earlier android.os.Build.SERIAL does return a valid serial.

It's unique for any device. If you are looking for possibilities on how to get/use a unique device id you should read here.

For a solution involving reflection without requiring a permission see this answer.

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.

In versions pre-G++ 4.7, you'll have to use -std=c++0x, for more recent versions you can use -std=c++11.

How do I store data in local storage using Angularjs?

Use ngStorage For All Your AngularJS Local Storage Needs. Please note that this is NOT a native part of the Angular JS framework.

ngStorage contains two services, $localStorage and $sessionStorage

angular.module('app', [
   'ngStorage'
]).controller('Ctrl', function(
    $scope,
    $localStorage,
    $sessionStorage
){});

Check the Demo

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

What does the C++ standard state the size of int, long type to be?

As mentioned the size should reflect the current architecture. You could take a peak around in limits.h if you want to see how your current compiler is handling things.

extract the date part from DateTime in C#

DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date

if you want to compare dates, ignoring the time part, make an use of DateTime.Year and DateTime.DayOfYear properties.

code snippet

DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
    Console.WriteLine("d1 < d2");
else
    if (d1.DayOfYear < d2.DayOfYear)
        Console.WriteLine("d1 < d2");

inner join in linq to entities

Not 100% sure about the relationship between these two entities but here goes:

IList<Splitting> res = (from s in [data source]
                        where s.Customer.CompanyID == [companyID] &&
                              s.CustomerID == [customerID]
                        select s).ToList();

IList<Splitting> res = [data source].Splittings.Where(
                           x => x.Customer.CompanyID == [companyID] &&
                                x.CustomerID == [customerID]).ToList();

Can I add a custom attribute to an HTML tag?

_x000D_
_x000D_
var demo = document.getElementById("demo")_x000D_
console.log(demo.dataset.myvar)_x000D_
// or_x000D_
alert(demo.dataset.myvar)_x000D_
//this will show in console the value of myvar
_x000D_
<div id="demo" data-myvar="foo">anything</div>
_x000D_
_x000D_
_x000D_

Overwriting txt file in java

SOLVED

My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.

File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();

File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");

String source = textArea.getText();
System.out.println(source);

try {
    FileWriter f2 = new FileWriter(fnew, false);
    f2.write(source);
    f2.close();

} catch (IOException e) {
    e.printStackTrace();
}   

how to break the _.each function in underscore.js

Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.

How to call a parent class function from derived class function?

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

Can't clone a github repo on Linux via HTTPS

You can manual disable ssl verfiy, and try again. :)

git config --global http.sslverify false

MVC 4 Razor adding input type date

 @Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })

 or type = "time"

 it will display a calendar
 it will not work if you give @Html.EditorFor()

Check if a JavaScript string is a URL

This is defiantly not the most effective approach, but it is readable and easy to form to whatever you need. And it's easier to add regex/complexity from here. So here is a very pragmatic approach

const validFirstBits = ["ftp://", "http://", "https://", "www."];
const invalidPatterns = [" ", "//.", ".."];

export function isUrl(word) {
// less than www.1.dk
if (!word || word.length < 8) return false;

// Let's check and see, if our candidate starts with some of our valid first bits
const firstBitIsValid = validFirstBits.some(bit => word.indexOf(bit) === 0);
if (!firstBitIsValid) return false;

const hasInvalidPatterns = invalidPatterns.some(
    pattern => word.indexOf(pattern) !== -1,
);

if (hasInvalidPatterns) return false;

const dotSplit = word.split(".");
if (dotSplit.length > 1) {
    const lastBit = dotSplit.pop(); // string or undefined
    if (!lastBit) return false;
    const length = lastBit.length;
    const lastBitIsValid =
        length > 1 || (length === 1 && !isNaN(parseInt(lastBit)));
    return !!lastBitIsValid;
}

    return false;
}

TEST:

import { isUrl } from "./foo";

describe("Foo", () => {
    test("should validate correct urls correctly", function() {
        const validUrls = [
            "http://example.com",
            "http://example.com/blah",
            "http://127.0.0.1",
            "http://127.0.0.1/wow",
            "https://example.com",
            "https://example.com/blah",
            "https://127.0.0.1:1234",
            "ftp://example.com",
            "ftp://example.com/blah",
            "ftp://127.0.0.1",
            "www.example.com",
            "www.example.com/blah",
        ];

        validUrls.forEach(url => {
            expect(isUrl(url) && url).toEqual(url);
        });
    });

    test("should validate invalid urls correctly", function() {
        const inValidUrls = [
            "http:// foo.com",
            "http:/foo.com",
            "http://.foo.com",
            "http://foo..com",
            "http://.com",
            "http://foo",
            "http://foo.c",
        ];

        inValidUrls.forEach(url => {
            expect(!isUrl(url) && url).toEqual(url);
        });
    });
});

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;
}

zsh compinit: insecure directories

  1. run compaudit and it will give you a list of directories it thinks are insecure

  2. sudo chown -R username:root target_directory

  3. sudo chmod -R 755 target_directory

No connection could be made because the target machine actively refused it (PHP / WAMP)

Just Go to your Control-panel and start Apache & MySQL Services.

How to get height of entire document with JavaScript?

Add References properly

In my case I was using a ASCX page and the aspx page that contains the ascx control is not using the references properly. I just pasted the following code and it worked :

<script src="../js/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
<script src="../js/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../js/jquery-1.5.1.js" type="text/javascript"></script>

Java Strings: "String s = new String("silly");"

In Java the syntax "text" creates an instance of class java.lang.String. The assignment:

String foo = "text";

is a simple assignment, with no copy constructor necessary.

MyString bar = "text";

Is illegal whatever you do because the MyString class isn't either java.lang.String or a superclass of java.lang.String.

How does Go update third-party packages?

@tux answer is great, just wanted to add that you can use go get to update a specific package:

go get -u full_package_name

Only variable references should be returned by reference - Codeigniter

this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015

How to handle the modal closing event in Twitter Bootstrap?

If your modal div is dynamically added then use( For bootstrap 3 and 4)

$(document).on('hide.bs.modal','#modal-id', function () {
                alert('');
 //Do stuff here
});

This will work for non-dynamic content also.

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

Click "File > New > Image Asset"

Asset Type -> Choose -> Image

Browse your image

Set the other properties

Press Next

You will see the 4 different pixel-sizes of your images for use as a launcher-icon

Press Finish !

Adb install failure: INSTALL_CANCELED_BY_USER

If your switch Install by USB on and you are getting "the device is temporarily restricted" error, then apply any of the default mobile themes. If any other developer theme is applied then it will not Allow you to switch Install by USB on. This works for me.

Find element in List<> that contains a value

I would use .Equals() for comparison instead of ==.

Like so:

MyClass item = MyList.Find(item => item.name.Equals("foo"));

Particularly because it gives you options like StringComparison, which is awesome. Example:

MyClass item = MyList.Find(item => item.name.Equals("foo", StringComparison.InvariantCultureIgnoreCase);

This enables your code to ignore special characters, upper and lower case. There are more options.

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

How to extract year and month from date in PostgreSQL without using to_char() function?

1st Option

date_trunc('month', timestamp_column)::date

It will maintain the date format with all months starting at day one.

Example:

2016-08-01
2016-09-01
2016-10-01
2016-11-01
2016-12-01
2017-01-01

2nd Option

to_char(timestamp_column, 'YYYY-MM')

This solution proposed by @yairchu worked fine in my case. I really wanted to discard 'day' info.

How to check what version of jQuery is loaded?

// My original 'goto' means to get the version
$.fn.jquery

// Another *similar* option
$().jQuery

// If there is concern that there may be multiple implementations of `$` then:
jQuery.fn.jquery

Recently I have had issues using $.fn.jquery/$().jQuery on a few sites so I wanted to note a third simple command to pull the jQuery version.

If you get back a version number -- usually as a string -- then jQuery is loaded and that is what version you're working with. If not loaded then you should get back undefined or maybe even an error.

Pretty old question and I've seen a few people that have already mentioned my answer in comments. However, I find that sometimes great answers that are left as comments can go unnoticed; especially when there are a lot of comments to an answer you may find yourself digging through piles of them looking for a gem. Hopefully this helps someone out!

How do I rename a file using VBScript?

You can rename the file using FSO by moving it: MoveFile Method.

Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "A.txt", "B.txt"

Angular 4 - get input value

You can use (keyup) or (change) events, see example below:

in HTML:

<input (keyup)="change($event)">

Or

<input (change)="change($event)">

in Component:

change(event) {console.log(event.target.value);}

Declaring variables in Excel Cells

You can use (hidden) cells as variables. E.g., you could hide Column C, set C1 to

=20

and use it as

=c1*20

Alternatively you can write VBA Macros which set and read a global variable.

Edit: AKX renders my Answer partially incorrect. I had no idea you could name cells in Excel.

'mat-form-field' is not a known element - Angular 5 & Material2

You're only exporting it in your NgModule, you need to import it too

@NgModule({
  imports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
 ]
  exports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
  ],
  declarations: [
    SearchComponent,
  ],
})export class MaterialModule {};

better yet

const modules = [
        MatButtonModule,
        MatFormFieldModule,
        MatInputModule,
        MatRippleModule
];

@NgModule({
  imports: [...modules],
  exports: [...modules]
  ,
})export class MaterialModule {};

update

You're declaring component (SearchComponent) depending on Angular Material before all Angular dependency are imported

Like BrowserAnimationsModule

Try moving it to MaterialModule, or before it

How to change progress bar's progress color in Android

simply use:

PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
    mode = PorterDuff.Mode.MULTIPLY;
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
    progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(Color.RED));
} else {
    Drawable progressDrawable;
    progressDrawable = (progressBar.isIndeterminate() ? progressBar.getIndeterminateDrawable() : progressBar.getProgressDrawable()).mutate();
    progressDrawable.setColorFilter(context.getResources().getColor(Color.RED), mode);
    progressBar.setProgressDrawable(progressDrawable);
}

how to add script src inside a View when using Layout

If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in footer to the header section and write the javascript / jquery code as you want:

@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    $(document).ready(function () {
        var divLength = $('div').length;
        alert(divLength);
    });
</script>

How can I get a web site's favicon?

You can do it without programming. Just open the web site, right-click and select "view source" to open the HTML code of that site. Then in the text editor search for "favicon" - it will direct you to something looking like

<link rel="icon" href='/SOMERELATIVEPATH/favicon.ico' type="image/x-icon" />

take the string in href and append it to the web site's base URL (let's assume it is "http://WEBSITE/"), so it looks like

http://WEBSITE/SOMERELATIVEPATH/favicon.ico

which is the absolute path to the favicon. If you didn't find it this way, it can be as well in the root in which case the URL is http://WEBSITE/favicon.ico.

Take the URL you determined and insert it into the following code:

<html>
  <head>
   <title>Capture Favicon</title>   
  </head>
  <body>
    <a href='http://WEBSITE/SOMERELATIVEPATH/favicon.ico' alt="Favicon"/>Favicon</a> 
  </body>
</html>

Save this HTML code locally (e.g. on your desktop) as GetFavicon.html and then double-click on it to open it. It will display only a link named Favicon. Right-click on this link and select "Save target as..." to save the Favicon on your local PC - and you're done!

HTTP Error 503, the service is unavailable

It could be that the user identity is outdated, especially if you've tried starting a stopped app pool and the next request again fails.

In IIS, go to the Application Pools under the Server, then find the correct Application Pool for your web site, and click on it. On the Advanced Settings menu to the right, select Identity and change it and enter new user and password. Click on your Application Pool again, and select Recycle to restart it.

You can also try looking at the error message in Event Viewer, under Windows Logs, Application, Details tab.

Performance of FOR vs FOREACH in PHP

My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy... The time difference is going to be minimal in most cases.

The big thing to watch for is:

for ($i = 0; $i < count($array); $i++) {

That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...

As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...

As for the iterators, foreach is equivalent to:

$it->rewind();
while ($it->valid()) {
    $key = $it->key();     // If using the $key => $value syntax
    $value = $it->current();

    // Contents of loop in here

    $it->next();
}

As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil...

Edit: Based upon the comment, I decided to do a quick benchmark run...

$a = array();
for ($i = 0; $i < 10000; $i++) {
    $a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v) {
    $a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {
    $v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}    
echo "Completed in ", microtime(true) - $start, " Seconds\n";

And the results:

Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you're modifying the array in the loop, it's several times faster to use references...

And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...

Start service in Android

Intent serviceIntent = new Intent(this,YourActivity.class);

startService(serviceIntent);

add service in manifist

<service android:enabled="true" android:name="YourActivity.class" />

for running service on oreo and greater devices use for ground service and show notification to user

or use geofencing service for location update in background reference http://stackoverflow.com/questions/tagged/google-play-services

How to keep the console window open in Visual C++?

Actually, the real solution is the selection of the project template itself. You MUST select Win32 Console Application in older VS, or fill in the project name first and then double click on Windows Desktop wizard and then select Win32 console application. Then select empty project at this point. This then allows for what the original questioner really wanted without adding extra stopping point and hold code. I went through this problem as well. The answer is also at MSDN site.

How to use an array list in Java?

Java 8 introduced default implementation of forEach() inside the Iterable interface , you can easily do it by declarative approach .

  List<String> values = Arrays.asList("Yasir","Shabbir","Choudhary");

  values.forEach( value -> System.out.println(value));

Here is the code of Iterable interface

  default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

Reference

Create a Date with a set timezone without using a string representation

getTimeZoneOffset is minus for UTC + z.

var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
    d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
}

How do I make a redirect in PHP?

try this one

 $url = $_SERVER['HTTP_REFERER'];
 redirect($url);

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Typescript: How to define type for a function callback used in a method parameter?

You can declare the callback as 1) function property or 2) method:

interface ParamFnProp {
    callback: (a: Animal) => void; // function property
}

interface ParamMethod {
    callback(a: Animal): void; // method
}

There is an important typing difference since TS 2.6:

You get stronger ("sound") types in --strict or --strictFunctionTypes mode, when a function property is declared. Let's take an example:

const animalCallback = (a: Animal): void => { } // Animal is the base type for Dog
const dogCallback = (d: Dog): void => { } 
// function property variant
const param11: ParamFnProp = { callback: dogCallback } // error: not assignable
const param12: ParamFnProp = { callback: animalCallback } // works

// method variant
const param2: ParamMethod = { callback: dogCallback } // now it works again ...

Technically spoken, methods are bivariant and function properties contravariant in their arguments under strictFunctionTypes. Methods are still checked more permissively (even if not sound) to be a bit more practical in combination with built-in types like Array.

Summary

  • There is a type difference between function property and method declaration
  • Choose a function property for stronger types, if possible

Playground sample code

How can I enable or disable the GPS programmatically on Android?

Above correct answer is very old it needs something new so Here is answer

As in last update we have androidx support so first include dependency in your app level build.gradle file

implementation 'com.google.android.gms:play-services-location:17.0.0'

then add in your manifest file:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

don't forget to take user consent for these permissions if you are releasing

now here is code just use it

 protected void createLocationRequest() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);

    SettingsClient client = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());



    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...

            Toast.makeText(MainActivity.this, "Gps already open", 
                                          Toast.LENGTH_LONG).show();
            Log.d("location settings",locationSettingsResponse.toString());
        }
    });

    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (e instanceof ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    resolvable.startResolutionForResult(MainActivity.this,
                            REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error.
                }
            }
        }
    });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==REQUEST_CHECK_SETTINGS){

        if(resultCode==RESULT_OK){

            Toast.makeText(this, "Gps opened", Toast.LENGTH_SHORT).show();
            //if user allows to open gps
            Log.d("result ok",data.toString());

        }else if(resultCode==RESULT_CANCELED){

            Toast.makeText(this, "refused to open gps", 
                                         Toast.LENGTH_SHORT).show();
            // in case user back press or refuses to open gps
            Log.d("result cancelled",data.toString());
        }
    }
}

if something goes wrong please ping me

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.

Maven Could not resolve dependencies, artifacts could not be resolved

I had this problem as well, it turned out it was because of NetBeans adding something to my pom.xml file. Double check nothing was added since previous successful deployments.

How do format a phone number as a String in Java?

String formatterPhone = String.format("%s-%s-%s", phoneNumber.substring(0, 3), phoneNumber.substring(3, 6), phoneNumber.substring(6, 10));

How to refresh activity after changing language (Locale) inside application

You can use recreate(); to restart your activity when Language change.

I am using following code to restart activity when language change:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Configuration config = getBaseContext().getResources().getConfiguration();

String lang = settings.getString("lang_list", "");

if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) {
      recreate();  //this is used for recreate activity
      Locale locale = new Locale(lang);
      Locale.setDefault(locale);
      config.locale = locale;
      getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}

Updating a JSON object using Javascript

$(document).ready(function(){        
    var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}];

    $.each(jsonObj,function(i,v){       
      if (v.Id == 3) {
        v.Username = "Thomas";
        return false;
      }
    });

alert("New Username: " + jsonObj[2].Username);

});

Typedef function pointer?

Without the typedef word, in C++ the declaration would declare a variable FunctionFunc of type pointer to function of no arguments, returning void.

With the typedef it instead defines FunctionFunc as a name for that type.

how to use ng-option to set default value of select element

This answer is more usefull when you are bringing data from a DB, make modifications and then persist the changes.

 <select  ng-options="opt.id as opt.name for opt in users" ng-model="selectedUser"></select>

Check the example here:

http://plnkr.co/edit/HrT5vUMJOtP9esGngbIV

How to encode the plus (+) symbol in a URL

Is you want a plus (+) symbol in the body you have to encode it as 2B.

For example: Try this

Python datetime to string without microsecond component

If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:

>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'

See the documentation of datetime.strftime() for an explanation of the % directives.

Downloading folders from aws s3, cp or sync?

Just used version 2 of the AWS CLI. For the s3 option, there is also a --dryrun option now to show you what will happen:

aws s3 --dryrun cp s3://bucket/filename /path/to/dest/folder --recursive

What is the reason for a red exclamation mark next to my project in Eclipse?

If your IDE doesn't find JRE from the path you given. Then you manually need to add JRE path in eclipse to remove red exclamation mark from the project. To do this please follow below steps :-

Go to to Properties>Java Build Path>Libraries> Click on Edit

Then Select Alternate JRE and click on Finish.

Note : If you don't have Java Run time Environment (JRE) installed, please install.

RuntimeWarning: invalid value encountered in divide

You are dividing by rr which may be 0.0. Check if rr is zero and do something reasonable other than using it in the denominator.

How to create a custom navigation drawer in android

I used below layout and able to achieve custom layout in Navigation View.

<android.support.design.widget.NavigationView
        android:id="@+id/navi_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start|top"
        android:background="@color/navigation_view_bg_color"
        app:theme="@style/NavDrawerTextStyle">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/drawer_header" />

            <include layout="@layout/navigation_drawer_menu" />
        </LinearLayout>
</android.support.design.widget.NavigationView> 

memcpy() vs memmove()

The memory in memcpy cannot overlap or you risk undefined behaviour, while the memory in memmove can overlap.

char a[16];
char b[16];

memcpy(a,b,16);           // valid
memmove(a,b,16);          // Also valid, but slower than memcpy.
memcpy(&a[0], &a[1],10);  // Not valid since it overlaps.
memmove(&a[0], &a[1],10); // valid. 

Some implementations of memcpy might still work for overlapping inputs but you cannot count of that behaviour. While memmove must allow for overlapping.

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

Open a facebook link by native Facebook app on iOS

This will open the URL in Safari:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=317"]];

For the iphone, you can launch the Facebook app if installed by using a url starting with fb://

More information can be found here: http://iphonedevtools.com/?p=302 also here: http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

Stolen from the above site:

fb://profile – Open Facebook app to the user’s profile
fb://friends – Open Facebook app to the friends list
fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)
fb://feed – Open Facebook app to the News Feed
fb://events – Open Facebook app to the Events page
fb://requests – Open Facebook app to the Requests list
fb://notes - Open Facebook app to the Notes page
fb://albums – Open Facebook app to Photo Albums list

To launch the above URLs:

NSURL *theURL = [NSURL URLWithString:@"fb://<insert function here>"];
[[UIApplication sharedApplication] openURL:theURL];

Make absolute positioned div expand parent div height

You answered the question by yourself: "I know that absolute positioned elements are removed from the flow, thus ignored by other elements." So you can't set the parents height according to an absolutely positioned element.

You either use fixed heights or you need to involve JS.

What's the best way to join on the same table twice?

The first method is the proper approach and will do what you need. However, with the inner joins, you will only select rows from Table1 if both phone numbers exist in Table2. You may want to do a LEFT JOIN so that all rows from Table1 are selected. If the phone numbers don't match, then the SomeOtherFields would be null. If you want to make sure you have at least one matching phone number you could then do WHERE t2.PhoneNumber IS NOT NULL OR t3.PhoneNumber IS NOT NULL

The second method could have a problem: what happens if Table2 has both PhoneNumber1 and PhoneNumber2? Which row will be selected? Depending on your data, foreign keys, etc. this may or may not be a problem.

How to sum array of numbers in Ruby?

Ruby 2.4+ / Rails - array.sum i.e. [1, 2, 3].sum # => 6

Ruby pre 2.4 - array.inject(:+) or array.reduce(:+)

*Note: The #sum method is a new addition to 2.4 for enumerable so you will now be able to use array.sum in pure ruby, not just Rails.

Strict Standards: Only variables should be assigned by reference PHP 5.4

You should remove the & (ampersand) symbol, so that line 4 will look like this:

$conn = ADONewConnection($config['db_type']);

This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0

library not found for -lPods

Are you opening the workspace (that was generated by CocoaPods) instead of the xcodeproj?

Asp.net Validation of viewstate MAC failed

If you're using a web farm and running the same application on multiple computers, you need to define the machine key explicitly in the machine.config file:

<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decryptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />

Put it under the <system.web> tag.

The AutoGenerate for the machine code can not be used. To generate your own machineKey see this powershell script: https://support.microsoft.com/en-us/kb/2915218#bookmark-appendixa

display:inline vs display:block

a block or inline-block can have a width (e.g. width: 400px) while inline element is not affected by width. inline element can span to the next line of text (example http://codepen.io/huijing/pen/PNMxXL resize your browser window to see that) while block element can't.

 .inline {
      background: lemonchiffon;
      div {
        display: inline;
        border: 1px dashed darkgreen;
      }

How do you change text to bold in Android?

From the XML you can set the textStyle to bold as below

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Bold text"
   android:textStyle="bold"/>

You can set the TextView to bold programmatically as below

textview.setTypeface(Typeface.DEFAULT_BOLD);

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

PHP - print all properties of an object

var_dump($obj); 

If you want more info you can use a ReflectionClass:

http://www.phpro.org/manual/language.oop5.reflection.html

Convert string to date in Swift

make global function

func convertDateFormat(inputDate: String) -> String {

     let olDateFormatter = DateFormatter()
     olDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

     let oldDate = olDateFormatter.date(from: inputDate)

     let convertDateFormatter = DateFormatter()
     convertDateFormatter.dateFormat = "MMM dd yyyy h:mm a"

     return convertDateFormatter.string(from: oldDate!)
}

Called function and pass value in it

get_OutputStr = convertDateFormat(inputDate: "2019-03-30T05:30:00+0000")

and here is output

Feb 25 2020 4:51 PM



 

What is the standard Python docstring format?

It's Python; anything goes. Consider how to publish your documentation. Docstrings are invisible except to readers of your source code.

People really like to browse and search documentation on the web. To achieve that, use the documentation tool Sphinx. It's the de-facto standard for documenting Python projects. The product is beautiful - take a look at https://python-guide.readthedocs.org/en/latest/ . The website Read the Docs will host your docs for free.

Bootstrap change carousel height

For Bootstrap 4

In the same line as image add height: 300px;

<img src="..." style="height: 300px;" class="d-block w-100" alt="image">

Declaring a custom android UI element using XML

It seems that Google has updated its developer page and added various trainings there.

One of them deals with the creation of custom views and can be found here

How to identify all stored procedures referring a particular table

Try This

   SELECT DISTINCT so.name
    FROM syscomments sc
    INNER JOIN sysobjects so ON sc.id=so.id
    WHERE sc.TEXT LIKE '%your table name%'

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

How to copy a file to multiple directories using the gnu cp command

If you want to do it without a forked command:

tee <inputfile file2 file3 file4 ... >/dev/null

Traversing text in Insert mode

You seem to misuse vim, but that's likely due to not being very familiar with it.

The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.

Here's a couple of use-cases:

  • You accidentally typed "accifentally". No problem, the sequence EscFfrdA will correct the mistake and bring you back to where you were editing. The Ff movement will move your cursor backwards to the first encountered "f" character. Compare that with Ctrl+DeldEnd, which does virtually the same in a casual editor, but takes more keystrokes and makes you move your hand out of the alphanumeric area of the keyboard.
  • You accidentally typed "you accidentally typed", but want to correct it to "you intentionally typed". Then Esc2bcw will erase the word you want to fix and bring you to insert mode, so you can immediately retype it. To get back to editing, just press A instead of End, so you don't have to move your hand to reach the End key.
  • You accidentally typed "mouse" instead of "mice". No problem - the good old Ctrl+w will delete the previous word without leaving insert mode. And it happens to be much faster to erase a small word than to fix errors within it. I'm so used to it that I had closed the browser page when I was typing this message...!
  • Repetition count is largely underused. Before making a movement, you can type a number; and the movement will be repeated this number of times. For example, 15h will bring your cursor 15 characters back and 4j will move your cursor 4 lines down. Start using them and you'll get used to it soon. If you made a mistake ten characters back from your cursor, you'll find out that pressing the key 10 times is much slower than the iterative approach to moving the cursor. So you can instead quickly type the keys 12h (as a rough of guess how many characters back that you need to move your cursor), and immediately move forward twice with ll to quickly correct the error.

But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.

How to sort an array of associative arrays by value of a given key in PHP?

From Sort an array of associative arrays by value of given key in php:

by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order. Example :

$array = array(
  array('price'=>'1000.50','product'=>'test1'),
  array('price'=>'8800.50','product'=>'test2'),
  array('price'=>'200.0','product'=>'test3')
);

function cmp($a, $b) {
  return $a['price'] > $b['price'];
}

usort($array, "cmp");
print_r($array);

Output:

Array
 (
    [0] => Array
        (
            [price] => 200.0
            [product] => test3
        )

    [1] => Array
        (
            [price] => 1000.50
            [product] => test1
        )

    [2] => Array
        (
            [price] => 8800.50
            [product] => test2
        )
  )

How to include js file in another js file?

You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:

var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);

There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // script is now loaded and executed.
    // put your dependent JS here.
});

The developers of this app have not set up this app properly for Facebook Login?

do setup by following bellow link and domain name you need to mention as like wht you have mentioned in facebook app domain name.

Go to https://developers.facebook.com/

Click on the Apps menu on the top bar.

Increase heap size in Java

Can I increase the heap memory to 75% of physical memory(6GB Heap).

Yes you can. In fact, you can increase to more than the amount of physical memory, if you want to.

Whether it is a good idea to do this depends on how much else is running on your system. In particular, if the "working set" of the applications and services that are currently running significantly exceeds the available physical memory, your system is liable to "thrash", spending a lot of time moving virtual memory pages to and from disk. The net effect is that the system gets horribly slow.

How to copy files from host to Docker container?

I tried most of the (upvoted) solutions here but in docker 17.09 (in 2018) there is no longer /var/lib/docker/aufs folder.

This simple docker cp solved this task.

docker cp c:\path\to\local\file container_name:/path/to/target/dir/

How to get container_name?

 docker ps 

There is a NAMES section. Don't use aIMAGE.

SQL: Return "true" if list of records exists?

You can use a SELECT CASE statement like so:

select case when EXISTS (
 select 1 
 from <table>
 where <condition>
 ) then TRUE else FALSE end

It returns TRUE when your query in the parents exists.

Javascript get Object property Name

I was searching to get a result for this either and I ended up with;

const MyObject = {
    SubObject: {
        'eu': [0, "asd", true, undefined],
        'us': [0, "asd", false, null],
        'aus': [0, "asd", false, 0]
    }
};

For those who wanted the result as a string:

Object.keys(MyObject.SubObject).toString()

output: "eu,us,aus"

For those who wanted the result as an array:

Array.from(Object.keys(MyObject))

output: Array ["eu", "us", "aus"]

For those who are looking for a "contains" type method: as numeric result:

console.log(Object.keys(MyObject.SubObject).indexOf("k"));

output: -1

console.log(Object.keys(MyObject.SubObject).indexOf("eu"));

output: 0

console.log(Object.keys(MyObject.SubObject).indexOf("us"));

output: 3

as boolean result:

console.log(Object.keys(MyObject.SubObject).includes("eu"));

output: true


In your case;

_x000D_
_x000D_
var myVar = { typeA: { option1: "one", option2: "two" } }_x000D_
_x000D_
    // Example 1_x000D_
    console.log(Object.keys(myVar.typeA).toString()); // Result: "option1, option2"_x000D_
_x000D_
    // Example 2_x000D_
    console.log(Array.from(Object.keys(myVar.typeA))); // Result: Array ["option1", "option2" ]_x000D_
    _x000D_
    // Example 3 as numeric_x000D_
    console.log((Object.keys(myVar.typeA).indexOf("option1")>=0)?'Exist!':'Does not exist!'); // Result: Exist!_x000D_
    _x000D_
    // Example 3 as boolean_x000D_
    console.log(Object.keys(myVar.typeA).includes("option2")); // Result: True!_x000D_
    _x000D_
    // if you would like to know about SubObjects_x000D_
    for(var key in myVar){_x000D_
      // do smt with SubObject_x000D_
      console.log(key); // Result: typeA_x000D_
    }_x000D_
_x000D_
    // if you already know your "SubObject"_x000D_
    for(var key in myVar.typeA){_x000D_
      // do smt with option1, option2_x000D_
      console.log(key); // Result: option1 // Result: option2_x000D_
    }
_x000D_
_x000D_
_x000D_

How can I convert a dictionary into a list of tuples?

>>> a={ 'a': 1, 'b': 2, 'c': 3 }

>>> [(x,a[x]) for x in a.keys() ]
[('a', 1), ('c', 3), ('b', 2)]

>>> [(a[x],x) for x in a.keys() ]
[(1, 'a'), (3, 'c'), (2, 'b')]