Programs & Examples On #Lwp

The World-Wide Web library for Perl - LWP is a set of Perl modules which provides a simple and consistent application programming interface (API) to the World-Wide Web.

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

How to avoid HTTP error 429 (Too Many Requests) python

I've found out a nice workaround to IP blocking when scraping sites. It lets you run a Scraper indefinitely by running it from Google App Engine and redeploying it automatically when you get a 429.

Check out this article

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

Checking for empty or null JToken in a JObject

To check whether a property exists on a JObject, you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).

JToken token = jObject["param"];
if (token != null)
{
    // the "param" property exists
}

If you have a JToken in hand and you want to see if it is non-empty, well, that depends on what type of JToken it is and how you define "empty". I usually use an extension method like this:

public static class JsonExtensions
{
    public static bool IsNullOrEmpty(this JToken token)
    {
        return (token == null) ||
               (token.Type == JTokenType.Array && !token.HasValues) ||
               (token.Type == JTokenType.Object && !token.HasValues) ||
               (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
               (token.Type == JTokenType.Null);
    }
}

%matplotlib line magic causes SyntaxError in Python script

There are several reasons as to why this wouldn't work.

It is possible that matplotlib is not properly installed. have you tried running:

conda install matplotlib

If that doesn't work, look at your %PATH% environment variable, does it contain your libraries and python paths?

Similar problem on github anaconda

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

Batch file to delete files older than N days

This one did it for me. It works with a date and you can substract the wanted amount in years to go back in time:

@echo off

set m=%date:~-7,2%
set /A m
set dateYear=%date:~-4,4%
set /A dateYear -= 2
set DATE_DIR=%date:~-10,2%.%m%.%dateYear% 

forfiles /p "C:\your\path\here\" /s /m *.* /d -%DATE_DIR% /c "cmd /c del @path /F"

pause

the /F in the cmd /c del @path /F forces the specific file to be deleted in some the cases the file can be read-only.

the dateYear is the year Variable and there you can change the substract to your own needs

Count the number of Occurrences of a Word in a String

If you just want the count of "male cat" then I would just do it like this:

String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);

and if you want to make sure that "female cat" is not matched then use \\b word boundaries in the split regex:

int c = str.split("\\bmale cat\\b").length - 1;

How to call a method with a separate thread in Java?

Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        // code goes here.
    }
});  
t1.start();

or

new Thread(new Runnable() {
     @Override
     public void run() {
          // code goes here.
     }
}).start();

or

new Thread(() -> {
    // code goes here.
}).start();

or

Executors.newSingleThreadExecutor().execute(new Runnable() {
    @Override
    public void run() {
        myCustomMethod();
    }
});

or

Executors.newCachedThreadPool().execute(new Runnable() {
    @Override
    public void run() {
        myCustomMethod();
    }
});

In VBA get rid of the case sensitivity when comparing words?

It is a bit of hack but will do the task.

Function equalsIgnoreCase(str1 As String, str2 As String) As Boolean
    equalsIgnoreCase = LCase(str1) = LCase(str2)
End Function

Sublime Text 2: How to delete blank/empty lines

Another way, you can use the command line cc.dbl of ConyEdit (a plugin) to delete blank lines or empty lines.

How to hide html source & disable right click and text copy?

It's a horrible thing to do, as everybody else has said, but if you really are intent on doing it, use this code, and put a load of returns at the top of the page's source:

<html>
  <head>
    <script>
      function disableClick(){
        document.onclick=function(event){
          if (event.button == 2) {
            alert('Right Click Message');
            return false;
          }
        }
      }
    </script>
  </head>
  <body onLoad="disableClick()">
  </body>
</html>

vertical-align with Bootstrap 3

For latest version of bootstrap you can use align-items-center. Use align-items utilities on flexbox containers to change the alignment of flex items on the cross axis (the y-axis to start, x-axis if flex-direction: column). Choose from start, end, center, baseline, or stretch (browser default).

<div class="d-flex align-items-center">
    ...
</div>

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

In mysql 5.7 the auth mechanism changed, documentation can be found in the official manual here.

Using the system root user (or sudo) you can connect to the mysql database with the mysql 'root' user via CLI. All other users will work, too.

In phpmyadmin however, all mysql users will work, but not the mysql 'root' user.

This comes from here:

$ mysql -Ne "select Host,User,plugin from mysql.user where user='root';"
+-----------+------+-----------------------+
| localhost | root | auth_socket |
|  hostname | root | mysql_native_password |
+-----------+------+-----------------------+

To 'fix' this security feature, do:

mysql -Ne "update mysql.user set plugin='mysql_native_password' where User='root' and Host='localhost'; flush privileges;"

More on this can also be found here in the manual.

How to draw text using only OpenGL methods?

Drawing text in plain OpenGL isn't a straigth-forward task. You should probably have a look at libraries for doing this (either by using a library or as an example implementation).

Some good starting points could be GLFont, OpenGL Font Survey and NeHe Tutorial for Bitmap Fonts (Windows).

Note that bitmaps are not the only way of achieving text in OpenGL as mentioned in the font survey.

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

Python method for reading keypress?

I really did not want to post this as a comment because I would need to comment all answers and the original question.

All of the answers seem to rely on MSVCRT Microsoft Visual C Runtime. If you would like to avoid that dependency :

In case you want cross platform support, using the library here:

https://pypi.org/project/getkey/#files

https://github.com/kcsaff/getkey

Can allow for a more elegant solution.

Code example:

from getkey import getkey, keys
key = getkey()
if key == keys.UP:
  ...  # Handle the UP key
elif key == keys.DOWN:
  ...  # Handle the DOWN key
elif key == 'a':
  ...  # Handle the `a` key
elif key == 'Y':
  ...  # Handle `shift-y`
else:
  # Handle other text characters
  buffer += key
  print(buffer)

Use table name in MySQL SELECT "AS"

To declare a string literal as an output column, leave the Table off and just use Test. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta(), the table name will be an empty string because it isn't associated with a table.

SELECT
  `field1`, 
  `field2`, 
  'Test' AS `field3` 
FROM `Test`;

Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.

If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:

SELECT
  field1,
  field2,
  field3
FROM 
  /* subquery wraps all fields to put the literal inside a table */
  (SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test

Now field3 will come in the output as Test.field3.

Jackson - best way writes a java list to a json array

In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.

List<Apartment> aptList =  new ArrayList<Apartment>();
    Apartment aptmt = null;
    for(int i=0;i<5;i++){
         aptmt= new Apartment();
         aptmt.setAptName("Apartment Name : ArrowHead Ranch");
         aptmt.setAptNum("3153"+i);
         aptmt.setPhase((i+1));
         aptmt.setFloorLevel(i+2);
         aptList.add(aptmt);
    }
mapper.writeValueAsString(aptList)

Render HTML to PDF in Django site

If you have context data along with css and js in your html template. Than you have good option to use pdfjs.

In your code you can use like this.

from django.template.loader import get_template
import pdfkit
from django.conf import settings

context={....}
template = get_template('reports/products.html')
html_string = template.render(context)
pdfkit.from_string(html_string, os.path.join(settings.BASE_DIR, "media", 'products_report-%s.pdf'%(id)))

In your HTML you can link extranal or internal css and js, it will generate best quality of pdf.

Pass variables by reference in JavaScript

Simple Object

_x000D_
_x000D_
function foo(x) {
  // Function with other context
  // Modify `x` property, increasing the value
  x.value++;
}

// Initialize `ref` as object
var ref = {
  // The `value` is inside `ref` variable object
  // The initial value is `1`
  value: 1
};

// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);

console.log(ref.value); // Prints "3"
_x000D_
_x000D_
_x000D_


Custom Object

Object rvar

_x000D_
_x000D_
/**
 * Aux function to create by-references variables
 */
function rvar(name, value, context) {
  // If `this` is a `rvar` instance
  if (this instanceof rvar) {
    // Inside `rvar` context...
    
    // Internal object value
    this.value = value;
    
    // Object `name` property
    Object.defineProperty(this, 'name', { value: name });
    
    // Object `hasValue` property
    Object.defineProperty(this, 'hasValue', {
      get: function () {
        // If the internal object value is not `undefined`
        return this.value !== undefined;
      }
    });
    
    // Copy value constructor for type-check
    if ((value !== undefined) && (value !== null)) {
      this.constructor = value.constructor;
    }
    
    // To String method
    this.toString = function () {
      // Convert the internal value to string
      return this.value + '';
    };
  } else {
    // Outside `rvar` context...
    
    // Initialice `rvar` object
    if (!rvar.refs) {
      rvar.refs = {};
    }
    
    // Initialize context if it is not defined
    if (!context) {
      context = window;
    }
    
    // Store variable
    rvar.refs[name] = new rvar(name, value, context);
    
    // Define variable at context
    Object.defineProperty(context, name, {
      // Getter
      get: function () { return rvar.refs[name]; },
      // Setter
      set: function (v) { rvar.refs[name].value = v; },
      // Can be overrided?
      configurable: true
    });

    // Return object reference
    return context[name];
  }
}

// Variable Declaration

  // Declare `test_ref` variable
  rvar('test_ref_1');

  // Assign value `5`
  test_ref_1 = 5;
  // Or
  test_ref_1.value = 5;

  // Or declare and initialize with `5`:
  rvar('test_ref_2', 5);

// ------------------------------
// Test Code

// Test Function
function Fn1 (v) { v.value = 100; }

// Declare
rvar('test_ref_number');

// First assign
test_ref_number = 5;
console.log('test_ref_number.value === 5', test_ref_number.value === 5);

// Call function with reference
Fn1(test_ref_number);
console.log('test_ref_number.value === 100', test_ref_number.value === 100);

// Increase value
test_ref_number++;
console.log('test_ref_number.value === 101', test_ref_number.value === 101);

// Update value
test_ref_number = test_ref_number - 10;
console.log('test_ref_number.value === 91', test_ref_number.value === 91);

// Declare and initialize
rvar('test_ref_str', 'a');
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');

// Update value
test_ref_str += 'bc';
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');

// Declare other...
rvar('test_ref_number', 5);
test_ref_number.value === 5; // true

// Call function
Fn1(test_ref_number);
test_ref_number.value === 100; // true

// Increase value
test_ref_number++;
test_ref_number.value === 101; // true

// Update value
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91; // true

test_ref_str.value === "a"; // true

// Update value
test_ref_str += 'bc';
test_ref_str.value === "abc"; // true 
_x000D_
_x000D_
_x000D_

The simplest way to resize an UIImage?

This is an UIImage extension compatible with Swift 3 and Swift 4 which scales image to given size with an aspect ratio

extension UIImage {

    func scaledImage(withSize size: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
        return UIGraphicsGetImageFromCurrentImageContext()!
    }

    func scaleImageToFitSize(size: CGSize) -> UIImage {
        let aspect = self.size.width / self.size.height
        if size.width / aspect <= size.height {
            return scaledImage(withSize: CGSize(width: size.width, height: size.width / aspect))
        } else {
            return scaledImage(withSize: CGSize(width: size.height * aspect, height: size.height))
        }
    }

}

Example usage

let image = UIImage(named: "apple")
let scaledImage = image.scaleImageToFitSize(size: CGSize(width: 45.0, height: 45.0))

Rails raw SQL example

I want to work with exec_query of the ActiveRecord class, because it returns the mapping of the query transforming into object, so it gets very practical and productive to iterate with the objects when the subject is Raw SQL.

Example:

values = ActiveRecord::Base.connection.exec_query("select * from clients")
p values

and return this complete query:

[{"id": 1, "name": "user 1"}, {"id": 2, "name": "user 2"}, {"id": 3, "name": "user 3"}]

To get only list of values

p values.rows

[[1, "user 1"], [2, "user 2"], [3, "user 3"]]

To get only fields columns

p values.columns

["id", "name"]

How to get difference between two rows for a column field?

If you really want to be sure of orders, use "Row_Number()" and compare next record of current record (take a close look at "on" clause)

T1.ID + 1 = T2.ID

You are basically joining next row with current row, without specifying "min" or doing "top". If you have a small number of records, other solutions by "Dems" or "Quassanoi" will work fine.

with T2 as (
    select  ID = ROW_NUMBER() over (order by rowInt),
            rowInt, Value
    from    myTable
)
select  T1.RowInt, T1.Value, Diff = IsNull(T2.Value, 0) - T1.Value
from    (   SELECT  ID = ROW_NUMBER() over (order by rowInt), *
            FROM    myTable ) T1
        left join T2 on T1.ID + 1 = T2.ID
ORDER BY T1.ID

How to configure Git post commit hook

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.

running php script (php function) in linux bash

just run in linux terminal to get phpinfo .

   php -r 'phpinfo();'

and to run file like index.php

    php -f index.php

Check if string contains \n Java

If the string was constructed in the same program, I would recommend using this:

String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);

But if you are specced to use \n, this driver illustrates what to do:

class NewLineTest {
    public static void main(String[] args) {
        String hasNewline = "this has a newline\n.";
        String noNewline = "this doesn't";

        System.out.println(hasNewline.contains("\n"));
        System.out.println(hasNewline.contains("\\n"));
        System.out.println(noNewline.contains("\n"));
        System.out.println(noNewline.contains("\\n"));

    }

}

Resulted in

true
false
false
false

In reponse to your comment:

class NewLineTest {
    public static void main(String[] args) {
        String word = "test\n.";
        System.out.println(word.length());
        System.out.println(word);
        word = word.replace("\n","\n ");
        System.out.println(word.length());
        System.out.println(word);

    }

}

Results in

6
test
.
7
test
 .

Why are iframes considered dangerous and a security risk?

I'm assuming cross-domain iFrame since presumably the risk would be lower if you controlled it yourself.

  • Clickjacking is a problem if your site is included as an iframe
  • A compromised iFrame could display malicious content (imagine the iFrame displaying a login box instead of an ad)
  • An included iframe can make certain JS calls like alert and prompt which could annoy your user
  • An included iframe can redirect via location.href (yikes, imagine a 3p frame redirecting the customer from bankofamerica.com to bankofamerica.fake.com)
  • Malware inside the 3p frame (java/flash/activeX) could infect your user

Eliminate extra separators below UITableView

uitableview extra separator line hide extra separators lines hide in swift 3.0

 self.tbltableView.tableFooterView = UIView(frame: .zero)

How to use SQL Order By statement to sort results case insensitive?

You can also do ORDER BY TITLE COLLATE NOCASE.

Edit: If you need to specify ASC or DESC, add this after NOCASE like

ORDER BY TITLE COLLATE NOCASE ASC

or

ORDER BY TITLE COLLATE NOCASE DESC

What's wrong with nullable columns in composite primary keys?

The answer by Tony Andrews is a decent one. But the real answer is that this has been a convention used by relational database community and is NOT a necessity. Maybe it is a good convention, maybe not.

Comparing anything to NULL results in UNKNOWN (3rd truth value). So as has been suggested with nulls all traditional wisdom concerning equality goes out the window. Well that's how it seems at first glance.

But I don't think this is necessarily so and even SQL databases don't think that NULL destroys all possibility for comparison.

Run in your database the query SELECT * FROM VALUES(NULL) UNION SELECT * FROM VALUES(NULL)

What you see is just one tuple with one attribute that has the value NULL. So the union recognized here the two NULL values as equal.

When comparing a composite key that has 3 components to a tuple with 3 attributes (1, 3, NULL) = (1, 3, NULL) <=> 1 = 1 AND 3 = 3 AND NULL = NULL The result of this is UNKNOWN.

But we could define a new kind of comparison operator eg. ==. X == Y <=> X = Y OR (X IS NULL AND Y IS NULL)

Having this kind of equality operator would make composite keys with null components or non-composite key with null value unproblematic.

How to draw vertical lines on a given plot in matplotlib

The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline

import matplotlib.pyplot as plt

plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)

OR

xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
    plt.axvline(x=xc)

You can use many of the keywords available for other plot commands (e.g. color, linestyle, linewidth ...). You can pass in keyword arguments ymin and ymax if you like in axes corrdinates (e.g. ymin=0.25, ymax=0.75 will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline) and rectangles (axvspan).

How to get response from S3 getObject in Node.js?

When doing a getObject() from the S3 API, per the docs the contents of your file are located in the Body property, which you can see from your sample output. You should have code that looks something like the following

const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary

var getParams = {
    Bucket: 'abc', // your bucket name,
    Key: 'abc.txt' // path to the object you're looking for
}

s3.getObject(getParams, function(err, data) {
    // Handle any error and exit
    if (err)
        return err;

  // No error happened
  // Convert Body from a Buffer to a String

  let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});

You may not need to create a new buffer from the data.Body object but if you need you can use the sample above to achieve that.

Spin or rotate an image on hover

It's very simple.

  1. You add an image.
  2. You create a css property to this image.

    img { transition: all 0.3s ease-in-out 0s; }
    
  3. You add an animation like that:

    img:hover
    {
        cursor: default;
        transform: rotate(360deg);
        transition: all 0.3s ease-in-out 0s;
    }
    

HTML Agility pack - parsing tables

How about something like: Using HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        Console.WriteLine("row");
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            Console.WriteLine("cell: " + cell.InnerText);
        }
    }
}

Note that you can make it prettier with LINQ-to-Objects if you want:

var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
            from row in table.SelectNodes("tr").Cast<HtmlNode>()
            from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
            select new {Table = table.Id, CellText = cell.InnerText};

foreach(var cell in query) {
    Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}

MySQL: how to get the difference between two timestamps in seconds

How about "TIMESTAMPDIFF":

SELECT TIMESTAMPDIFF(SECOND,'2009-05-18','2009-07-29') from `post_statistics`

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff

How to Disable landscape mode in Android?

Add android:screenOrientation="portrait" to the activity you want to disable landscape mode.

How to make an android app to always run in background?

On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)

Just go to Settings>PermissionsAutostart

100% width Twitter Bootstrap 3 template

In BOOTSTRAP 4 you can use

<div class="row m-0">
my fullwidth div
</div>

... if you just use a .row without the .m-0 as a top level div, you will have unwanted margin, which makes the page wider than the browser window and cause a horizontal scrollbar.

Java Initialize an int array in a constructor

why not simply

public Date(){
    data = new int[]{0,0,0};
}

the reason you got the error is because int[] data = ... declares a new variable and hides the field data

however it should be noted that the contents of the array are already initialized to 0 (the default value of int)

How to undo a SQL Server UPDATE query?

Considering that you already have a full backup I’d just restore that backup into separate database and migrate the data from there.

If your data has changed after the latest backup then what you recover all data that way but you can try to recover that by reading transaction log.

If your database was in full recovery mode than transaction log has enough details to recover updates to your data after the latest backup.

You might want to try with DBCC LOG, fn_log functions or with third party log reader such as ApexSQL Log

Unfortunately there is no easy way to read transaction log because MS doesn’t provide documentation for this and stores the data in its proprietary format.

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

I have been faced with this problem.

The cause is your table doesn't have a primary key field.

And I have a simple solution: Set a field to primary key to specific field that suits your business logic.

For example, I have database thesis_db and field thesis_id, I will press button Primary (key icon) to set thesis_id to become primary key field:

enter image description here

document.getElementById(id).focus() is not working for firefox or chrome

Add a control, where you want to set focus then change its property like below

<asp:TextBox ID="txtDummy" runat="server" Text="" Width="2" ReadOnly="true" BorderStyle="None" BackColor="Transparent"></asp:TextBox>

In the codebehind, just call like below txtDummy.Focus()

this method is working in all browser.

Efficient way to update all rows in a table

The usual way is to use UPDATE:

UPDATE mytable
   SET new_column = <expr containing old_column>

You should be able to do this is a single transaction.

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

How can I execute a python script from an html button?

It is discouraged and problematic yet doable. What you need is a custom URI scheme ie. You need to register and configure it on your machine and then hook an url with that scheme to the button.

URI scheme is the part before :// in an URI. Standard URI schemes are for example https or ftp or file. But there are custom like fx. mongodb. What you need is your own e.g. mypythonscript. It can be configured to exec the script or even just python with the script name in the params etc. It is of course a tradeoff between flexibility and security.

You can find more details in the links:

https://support.shotgunsoftware.com/hc/en-us/articles/219031308-Launching-applications-using-custom-browser-protocols

https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx

EDIT: Added more details about what an custom scheme is.

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.

How do I check if a cookie exists?

If you're using jQuery, you can use the jquery.cookie plugin.

Getting the value for a particular cookie is done as follows:

$.cookie('MyCookie'); // Returns the cookie value

wait until all threads finish their work in java

The existing answers said could join() each thread.

But there are several ways to get the thread array / list:

  • Add the Thread into a list on creation.
  • Use ThreadGroup to manage the threads.

Following code will use the ThreadGruop approach. It create a group first, then when create each thread specify the group in constructor, later could get the thread array via ThreadGroup.enumerate()


Code

SyncBlockLearn.java

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * synchronized block - learn,
 *
 * @author eric
 * @date Apr 20, 2015 1:37:11 PM
 */
public class SyncBlockLearn {
    private static final int TD_COUNT = 5; // thread count
    private static final int ROUND_PER_THREAD = 100; // round for each thread,
    private static final long INC_DELAY = 10; // delay of each increase,

    // sync block test,
    @Test
    public void syncBlockTest() throws InterruptedException {
        Counter ct = new Counter();
        ThreadGroup tg = new ThreadGroup("runner");

        for (int i = 0; i < TD_COUNT; i++) {
            new Thread(tg, ct, "t-" + i).start();
        }

        Thread[] tArr = new Thread[TD_COUNT];
        tg.enumerate(tArr); // get threads,

        // wait all runner to finish,
        for (Thread t : tArr) {
            t.join();
        }

        System.out.printf("\nfinal count: %d\n", ct.getCount());
        Assert.assertEquals(ct.getCount(), TD_COUNT * ROUND_PER_THREAD);
    }

    static class Counter implements Runnable {
        private final Object lkOn = new Object(); // the object to lock on,
        private int count = 0;

        @Override
        public void run() {
            System.out.printf("[%s] begin\n", Thread.currentThread().getName());

            for (int i = 0; i < ROUND_PER_THREAD; i++) {
                synchronized (lkOn) {
                    System.out.printf("[%s] [%d] inc to: %d\n", Thread.currentThread().getName(), i, ++count);
                }
                try {
                    Thread.sleep(INC_DELAY); // wait a while,
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.printf("[%s] end\n", Thread.currentThread().getName());
        }

        public int getCount() {
            return count;
        }
    }
}

The main thread will wait for all threads in the group to finish.

Android, How to create option Menu

import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

public class AndroidWalkthroughApp2 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // show menu when menu button is pressed
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // display a message when a button was pressed
        String message = "";
        if (item.getItemId() == R.id.option1) {
            message = "You selected option 1!";
        }
        else if (item.getItemId() == R.id.option2) {
            message = "You selected option 2!";
        }
        else {
            message = "Why would you select that!?";
        }

        // show message via toast
        Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
        toast.show();

        return true;
    }
}

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

And just to give you yet another option, you can use NOT ISNULL(archived) as your WHERE filter.

phpMyAdmin + CentOS 6.0 - Forbidden

I have faced the same problem when I tape the URL

https://www.nameDomain.com/phpmyadmin

the forbidden message shows up, because of the rules on /use/share/phpMyAdmin directory I fix it by adding in this file /etc/httpd/conf.d/phpMyAdmin.conf in this section

<Directory /usr/share/phpMyAdmin/>
    ....
</Directory>

these line of rules

<Directory /usr/share/phpMyAdmin/>
   Order Deny,Allow
   Deny from All
   Allow from 127.0.0.1
   Allow from ::1
   Allow from All
   ...
</Directory>

you save the file, then you restart the apache service whatever method you choose service httpd graceful or service httpd restart it depends on your policy

for security reasons you can specify one connection by setting one IP address if your IP does not change, else if your IP changes every time you have to change it also.

<Directory /usr/share/phpMyAdmin/>
   Order Deny,Allow
   Deny from All
   Allow from 127.0.0.1
   Allow from ::1
   Allow from 105.105.105.254 ## set here your IP address
   ...
</Directory>

What is Linux’s native GUI API?

Strictly speaking, the API of Linux consists of its system calls. These are all of the kernel functions that can be called by a user-mode (non-kernel) program. This is a very low-level interface that allows programs to do things like open and read files. See http://en.wikipedia.org/wiki/System_call for a general introduction.

A real Linux system will also have an entire "stack" of other software running on it, in order to provide a graphical user interface and other features. Each element of this stack will offer its own API.

Show two digits after decimal point in c++

This will be possible with setiosflags(ios::showpoint).

Select the top N values by group

I prefer @Ista solution, cause needs no extra package and is simple.
A modification of the data.table solution also solve my problem, and is more general.
My data.frame is

> str(df)
'data.frame':   579 obs. of  11 variables:
 $ trees     : num  2000 5000 1000 2000 1000 1000 2000 5000 5000 1000 ...
 $ interDepth: num  2 3 5 2 3 4 4 2 3 5 ...
 $ minObs    : num  6 4 1 4 10 6 10 10 6 6 ...
 $ shrinkage : num  0.01 0.001 0.01 0.005 0.01 0.01 0.001 0.005 0.005 0.001     ...
 $ G1        : num  0 2 2 2 2 2 8 8 8 8 ...
 $ G2        : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ qx        : num  0.44 0.43 0.419 0.439 0.43 ...
 $ efet      : num  43.1 40.6 39.9 39.2 38.6 ...
 $ prec      : num  0.606 0.593 0.587 0.582 0.574 0.578 0.576 0.579 0.588 0.585 ...
 $ sens      : num  0.575 0.57 0.573 0.575 0.587 0.574 0.576 0.566 0.542 0.545 ...
 $ acu       : num  0.631 0.645 0.647 0.648 0.655 0.647 0.619 0.611 0.591 0.594 ...

The data.table solution needs order on i to do the job:

> require(data.table)
> dt1 <- data.table(df)
> dt2 = dt1[order(-efet, G1, G2), head(.SD, 3), by = .(G1, G2)]
> dt2
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 5:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 6:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 7:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
 8:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
 9:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
10:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
11:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
12:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
13:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635
14:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621  

By some reason, it does not order the way pointed (probably because ordering by the groups). So, another ordering is done.

> dt2[order(G1, G2)]
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621
 5:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 6:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 7:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 8:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
 9:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
10:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
11:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
12:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
13:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
14:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635

CSS body background image fixed to full screen even when zooming in/out

Use Directly like this

.bg-div{
     background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
}

or call CSS separately like

.bg-div{
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How to escape indicator characters (i.e. : or - ) in YAML

If you're using @ConfigurationProperties with Spring Boot 2 to inject maps with keys that contain colons then you need an additional level of escaping using square brackets inside the quotes because spring only allows alphanumeric and '-' characters, stripping out the rest. Your new key would look like this:

"[8.11.32.120:8000]": GoogleMapsKeyforThisDomain

See this github issue for reference.

Vertical align in bootstrap table

As of Bootstrap 4 this is now much easier using the included utilities instead of custom CSS. You simply have to add the class align-middle to the td-element:

<table>
  <tbody>
    <tr>
      <td class="align-baseline">baseline</td>
      <td class="align-top">top</td>
      <td class="align-middle">middle</td>
      <td class="align-bottom">bottom</td>
      <td class="align-text-top">text-top</td>
      <td class="align-text-bottom">text-bottom</td>
    </tr>
  </tbody>
</table>

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

How to set the Default Page in ASP.NET?

Tip #84: Did you know… How to set a Start page for your Web Site in Visual Web Developer?

Simply right click on the page you want to be the start page and say "set as start page".

As noted in the comment below by Adam Tuliper - MSFT, this only works for debugging, not deployment.

How to connect to MySQL Database?

you can use Package Manager to add it as package and it is the easiest way to do. You don't need anything else to work with mysql database.

Or you can run below command in Package Manager Console

PM> Install-Package MySql.Data

NUGET Mysql.Data

PHP - find entry by object property from an array of objects

Way to instantly get first value:

$neededObject = array_reduce(
    $arrayOfObjects,
    function ($result, $item) use ($searchedValue) {
        return $item->id == $searchedValue ? $item : $result;
    }
);

How to delete the contents of a folder?

You can simply do this:

import os
import glob

files = glob.glob('/YOUR/PATH/*')
for f in files:
    os.remove(f)

You can of course use an other filter in you path, for example : /YOU/PATH/*.txt for removing all text files in a directory.

Resetting MySQL Root Password with XAMPP on Localhost

For me much better way is to do it using terminal rather then PhpMyAdmin UI.

The answer is copied from "https://gist.github.com/susanBuck/39d1a384779f3d596afb19fcad6b598c" which I have tried and it works always, try it out..

  • Open C:\xampp\mysql\bin\my.ini (MySQL config file)
  • Find the line [mysqld] and right below it add skip-grant-tables. Example:

    [mysqld] skip-grant-tables port= 3306 socket = "C:/xampp/mysql/mysql.sock" basedir = "C:/xampp/mysql" tmpdir = "C:/xampp/tmp" [...etc...]

  • This should allow you to access MySQL if you don't know your password.

  • Stop and start MySQL from XAMPP to make this change take effect.
  • Next, in command line, connect to MySQL:

C:\xampp\mysql\bin\mysql.exe --user=root

  • Once in MySQL command line "select" the mysql database:

USE mysql;

  • Then, the following command will list all your MySQL users:

SELECT * FROM user \G;

  • You can scan through the rows to see what the root user's password is set to. There will be a few root users listed, with different hosts.
  • To set root user's to have a password of your choice, run this command:

UPDATE user SET password = PASSWORD('secret_pass') WHERE user = 'root';

  • -OR- To set all root user's to have a blank password, run this command:

UPDATE user SET password = '' WHERE user = 'root';

When you're done, run exit; to exit the MySQL command line.

Next, re-enable password checking by removing skip-grant-tables from C:\xampp\mysql\bin\my.ini.

Save changes, restart MySQL from XAMPP.

Find and Replace text in the entire table using a MySQL query

the best you export it as sql file and open it with editor such as visual studio code and find and repalace your words. i replace in 1 gig file sql in 1 minutes for 16 word that total is 14600 word. its the best way. and after replace it save and import it again. do not forget compress it with zip for import.

Using Mockito to test abstract classes

You can achieve this by using a spy (use the latest version of Mockito 1.8+ though).

public abstract class MyAbstract {
  public String concrete() {
    return abstractMethod();
  }
  public abstract String abstractMethod();
}

public class MyAbstractImpl extends MyAbstract {
  public String abstractMethod() {
    return null;
  }
}

// your test code below

MyAbstractImpl abstractImpl = spy(new MyAbstractImpl());
doReturn("Blah").when(abstractImpl).abstractMethod();
assertTrue("Blah".equals(abstractImpl.concrete()));

How to detect lowercase letters in Python?

You should use raw_input to take a string input. then use islower method of str object.

s = raw_input('Type a word')
l = []
for c in s.strip():
    if c.islower():
        print c
        l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)

Just do -

dir(s)

and you will find islower and other attributes of str

Get current working directory in a Qt application

I'm running Qt 5.5 under Windows and the default constructor of QDir appears to pick up the current working directory, not the application directory.

I'm not sure if the getenv PWD will work cross-platform and I think it is set to the current working directory when the shell launched the application and doesn't include any working directory changes done by the app itself (which might be why the OP is seeing this behavior).

So I thought I'd add some other ways that should give you the current working directory (not the application's binary location):

// using where a relative filename will end up
QFileInfo fi("temp");
cout << fi.absolutePath() << endl;

// explicitly using the relative name of the current working directory
QDir dir(".");
cout << dir.absolutePath() << endl;

How to set the maximum memory usage for JVM?

The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)

I've never used it. Maybe you'll find it useful.

Delete column from SQLite table

I've made a Python function where you enter the table and column to remove as arguments:

def removeColumn(table, column):
    columns = []
    for row in c.execute('PRAGMA table_info(' + table + ')'):
        columns.append(row[1])
    columns.remove(column)
    columns = str(columns)
    columns = columns.replace("[", "(")
    columns = columns.replace("]", ")")
    for i in ["\'", "(", ")"]:
        columns = columns.replace(i, "")
    c.execute('CREATE TABLE temptable AS SELECT ' + columns + ' FROM ' + table)
    c.execute('DROP TABLE ' + table)
    c.execute('ALTER TABLE temptable RENAME TO ' + table)
    conn.commit()

As per the info on Duda's and MeBigFatGuy's answers this won't work if there is a foreign key on the table, but this can be fixed with 2 lines of code (creating a new table and not just renaming the temporary table)

How to get a single value from FormGroup

Dot notation will break the type checking, switch to bracket notation. You might also try using the get() method. It also keeps AOT compilation in tact I've read.

this.form.get('controlName').value // safer
this.form.controlName.value // triggers type checking and breaks AOT

Find out how much memory is being used by an object in Python

Try this:

sys.getsizeof(object)

getsizeof() Return the size of an object in bytes. It calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

A recursive recipe

How to build & install GLFW 3 and use it in a Linux project

I solved it in this way

A pkg-config file describes all necessary compile-time and link-time flags and dependencies needed to use a library.

pkg-config --static --libs glfw3

shows me that

-L/usr/local/lib -lglfw3 -lrt -lXrandr -lXinerama -lXi -lXcursor -lGL -lm -ldl -lXrender -ldrm -lXdamage -lX11-xcb -lxcb-glx -lxcb-dri2 -lxcb-dri3 -lxcb-present -lxcb-sync -lxshmfence -lXxf86vm -lXfixes -lXext -lX11 -lpthread -lxcb -lXau -lXdmcp  

I don't know if all these libs are actually necessary for compiling but for me it works...

PHP mySQL - Insert new record into table with auto-increment on primary key

Use the DEFAULT keyword:

$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')";

Also, you can specify the columns, (which is better practice):

$query = "INSERT INTO myTable
          (fname, lname, website)
          VALUES
          ('fname', 'lname', 'website')";

Reference:

How to append rows to an R data frame

Lets take a vector 'point' which has numbers from 1 to 5

point = c(1,2,3,4,5)

if we want to append a number 6 anywhere inside the vector then below command may come handy

i) Vectors

new_var = append(point, 6 ,after = length(point))

ii) columns of a table

new_var = append(point, 6 ,after = length(mtcars$mpg))

The command append takes three arguments:

  1. the vector/column to be modified.
  2. value to be included in the modified vector.
  3. a subscript, after which the values are to be appended.

simple...!! Apologies in case of any...!

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

The easiest way is to use to_datetime:

df['col'] = pd.to_datetime(df['col'])

It also offers a dayfirst argument for European times (but beware this isn't strict).

Here it is in action:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

You can pass a specific format:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Importing a function from a class in another file?

It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.

For example:

def run():
    print "this does nothing"

def chooser():
    return "run"

def main():
    '''works just like:
    run()'''
    eval(chooser())()

The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.

Find Item in ObservableCollection without using a loop

Here comes Linq:

var listItem = list.Single(i => i.Title == title);

It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault.

If you want a collection of items matching the title, there's:

var listItems = list.Where(i => i.Title ==  title);

How to move/rename a file using an Ansible task on a remote system

This may seem like overkill, but if you want to avoid using the command module (which I do, because it using command is not idempotent) you can use a combination of copy and unarchive.

  1. Use tar to archive the file(s) you will need. If you think ahead this actually makes sense. You may want a series of files in a given directory. Create that directory with all of the files and archive them in a tar.
  2. Use the unarchive module. When you do that, along with the destination: and remote_src: keyword, you can place copy all of your files to a temporary folder to start with and then unpack them exactly where you want to.

npm install won't install devDependencies

I had a package-lock.json file from an old version of my package.json, I deleted that and then everything installed correctly.

php stdClass to array

Please use following php function to convert php stdClass to array

get_object_vars($data)

How to set ObjectId as a data type in mongoose

I was looking for a different answer for the question title, so maybe other people will be too.

To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:

const Book = mongoose.model('Book', {
  author: {
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                          // from the Author colection, 
                                          // so you can reference it
    required: true
  },
  title: {
    type: String,
    required: true
  }
});

List file using ls command in Linux with full path

For listing everything with full path, only in current directory

find $PWD -maxdepth 1

Same as above but only matches a particular extension, case insensitive (.sh files in this case)

find $PWD -maxdepth 1 -iregex '.+\.sh'

$PWD is for current directory, it can be replaced with any directory

mydir="/etc/sudoers.d/" ; find $mydir -maxdepth 1

maxdepth prevents find from going into subdirectories, for example you can set it to "2" for listing items in children as well. Simply remove it if you need it recursive.

To limit it to only files, can use -type f option.

find $PWD -maxdepth 1 -type f

What is the correct way to write HTML using Javascript?

You can change the innerHTML or outerHTML of an element on the page instead.

AngularJs .$setPristine to reset form

DavidLn's answer has worked well for me in the past. But it doesn't capture all of setPristine's functionality, which tripped me up this time. Here is a fuller shim:

var form_set_pristine = function(form){
    // 2013-12-20 DF TODO: remove this function on Angular 1.1.x+ upgrade
    // function is included natively

    if(form.$setPristine){
        form.$setPristine();
    } else {
        form.$pristine = true;
        form.$dirty = false;
        angular.forEach(form, function (input, key) {
            if (input.$pristine)
                input.$pristine = true;
            if (input.$dirty) {
                input.$dirty = false;
            }
        });
    }
};

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

An extension to what GenericTypeTea says - Here is a concrete example:

<form onsubmit="return false">

The above form will not submit, whereas...

<form onsubmit="false">

...does nothing, i.e. the form will submit.

Without the return, onsubmit doesn't receive a value and the event is executed just like without any handler at all.

javascript : sending custom parameters with window.open() but its not working

Please find this example code, You could use hidden form with POST to send data to that your URL like below:

function open_win()
{
    var ChatWindow_Height = 650;
    var ChatWindow_Width = 570;

    window.open("Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);

    //Hidden Form
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "http://localhost:8080/login");
    form.setAttribute("target", "chat");

    //Hidden Field
    var hiddenField1 = document.createElement("input");
    var hiddenField2 = document.createElement("input");

    //Login ID
    hiddenField1.setAttribute("type", "hidden");
    hiddenField1.setAttribute("id", "login");
    hiddenField1.setAttribute("name", "login");
    hiddenField1.setAttribute("value", "PreethiJain005");

    //Password
    hiddenField2.setAttribute("type", "hidden");
    hiddenField2.setAttribute("id", "pass");
    hiddenField2.setAttribute("name", "pass");
    hiddenField2.setAttribute("value", "Pass@word$");

    form.appendChild(hiddenField1);
    form.appendChild(hiddenField2);

    document.body.appendChild(form);
    form.submit();

}

Undo git pull, how to bring repos to old state

This is the easiest way to revert you pull changes.

** Warning **

Please backup of your changed files because it will delete the newly created files and folders.

git reset --hard 9573e3e0

Where 9573e3e0 is your {Commit id}

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

For webpack 1 or 2 with Bootstrap 4 you need

new webpack.ProvidePlugin({
   $: 'jquery',
   jQuery: 'jquery',
   Tether: 'tether'
})

Text to speech(TTS)-Android

A minimalistic example to quickly test the TTS system:

private TextToSpeech textToSpeechSystem;

@Override
protected void onStart() {
  super.onStart();
  textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                String textToSay = "Hello world, this is a test message!";
                textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
            }
        }
   });
}

If you don't use localized messages textToSpeechSystem.setLanguage(..) is important as well, since your users probably don't all have English set as their default language so the pronunciation of the words will be wrong. But for testing TTS in general this snippet is enough

Related links: https://developer.android.com/reference/android/speech/tts/TextToSpeech

SQL recursive query on self referencing table (Oracle)

Using the new nested query syntax

with q(name, id, parent_id, parent_name) as (
    select 
      t1.name, t1.id, 
      null as parent_id, null as parent_name 
    from t1
    where t1.id = 1
  union all
    select 
      t1.name, t1.id, 
      q.id as parent_id, q.name as parent_name 
    from t1, q
    where t1.parent_id = q.id
)
select * from q

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

You have to change delimiter before using triggers, stored procedures and so on.

delimiter //
create procedure ProG() 
begin 
SELECT * FROM hs_hr_employee_leave_quota;
end;//
delimiter ;

Declaring abstract method in TypeScript

No, no, no! Please do not try to make your own 'abstract' classes and methods when the language does not support that feature; the same goes for any language feature you wish a given language supported. There is no correct way to implement abstract methods in TypeScript. Just structure your code with naming conventions such that certain classes are never directly instantiated, but without explicitly enforcing this prohibition.

Also, the example above is only going to provide this enforcement at run time, NOT at compile time, as you would expect in Java/C#.

Find an object in array?

For example, if we had an array of numbers:

let numbers = [2, 4, 6, 8, 9, 10]

We could find the first odd number like this:

let firstOdd = numbers.index { $0 % 2 == 1 }

That will send back 4 as an optional integer, because the first odd number (9) is at index four.

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

Add-on software packages.

See http://www.pathname.com/fhs/2.2/fhs-3.12.html for details.

Also described at Wikipedia.

Its use dates back at least to the late 1980s, when it was a standard part of System V UNIX. These days, it's also seen in Linux, Solaris (which is SysV), OSX Cygwin, etc. Other BSD unixes (FreeBSD, NetBSD, etc) tend to follow other rules, so you don't usually see BSD systems with an /opt unless they're administered by someone who is more comfortable in other environments.

How to properly create an SVN tag from trunk?

You are correct in that it's not "right" to add files to the tags folder.

You've correctly guessed that copy is the operation to use; it lets Subversion keep track of the history of these files, and also (I assume) store them much more efficiently.

In my experience, it's best to do copies ("snapshots") of entire projects, i.e. all files from the root check-out location. That way the snapshot can stand on its own, as a true representation of the entire project's state at a particular point in time.

This part of "the book" shows how the command is typically used.

Getting DOM elements by classname

I think the accepted way is better, but I guess this might work as well

function getElementByClass(&$parentNode, $tagName, $className, $offset = 0) {
    $response = false;

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    $tagCount = 0;
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            if ($tagCount == $offset) {
                $response = $temp;
                break;
            }

            $tagCount++;
        }

    }

    return $response;
}

Sort objects in ArrayList by date?

The Date class already implements Comparator interface. Assuming you have the class below:

public class A {

    private Date dateTime;

    public Date getDateTime() {
        return dateTime;
    }

    .... other variables

}

And let's say you have a list of A objects as List<A> aList, you can easily sort it with Java 8's stream API (snippet below):

import java.util.Comparator;
import java.util.stream.Collectors;

...

aList = aList.stream()
        .sorted(Comparator.comparing(A::getDateTime))
        .collect(Collectors.toList())

Proper way to get page content

The wp_trim_words function can limit the characters too by changing the $num_words variable. For anyone who might find useful.

<?php 
$id=58; 
$post = get_post($id); 
$content = apply_filters('the_content', $post->post_content); 

$customExcerpt = wp_trim_words( $content, $num_words = 26, $more = '' );
echo $customExcerpt;  
?>

How to create a dump with Oracle PL/SQL Developer?

Just as an update this can be done by using Toad 9 also.Goto Database>Export>Data Pump Export wizard.At the desitination directory window if you dont find any directory in the dropdown,then you probably have to create a directory object.

CREATE OR REPLACE DIRECTORY data_pmp_dir_test AS '/u01/app/oracle/oradata/pmp_dir_test'; 

See this for an example.

Disable form autofill in Chrome without disabling autocomplete

This might help: https://stackoverflow.com/a/4196465/683114

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

It looks like on load, it finds all inputs with autofill, adds their outerHTML and removes the original, while preserving value and name (easily changed to preserve ID etc)

If this preserves the autofill text, you could just set

var text = "";   /* $(this).val(); */

From the original form where this was posted, it claims to preserve autocomplete. :)

Good luck!

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

Hash === @some_var #=> return Boolean

this can also be used with case statement

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

how to resolve DTS_E_OLEDBERROR. in ssis

I would start by turning off TCP offloading. There have been a few things that cause intermittent connectivity issues and this is the one that is usually the culprit.

Note: I have seen this setting cause problems on Win Server 2003 and Win Server 2008

http://blogs.msdn.com/b/mssqlisv/archive/2008/05/27/sql-server-intermittent-connectivity-issue.aspx

http://technet.microsoft.com/en-us/library/gg162682(v=ws.10).aspx

http://blogs.msdn.com/b/psssql/archive/2008/10/01/windows-scalable-networking-pack-possible-performance-and-concurrency-impacts-to-sql-server-workloads.aspx

Single selection in RecyclerView

I want to share the similar thing I have achieved, may be it will help someone. below code is from the application to select an address from a list of addresses that are displayed in cardview(cvAddress), so that on click of particular item(cardview) the imageView inside the item should set to different resource(select/unselect)

    @Override
public void onBindViewHolder(final AddressHolder holder, final int position)
{
    holderList.add(holder);
    holder.tvAddress.setText(addresses.get(position).getAddress());
    holder.cvAddress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            selectCurrItem(position);
        }
    });
}

private void selectCurrItem(int position)
{
    int size = holderList.size();
    for(int i = 0; i<size; i++)
    {
        if(i==position)
            holderList.get(i).ivSelect.setImageResource(R.drawable.select);
        else
            holderList.get(i).ivSelect.setImageResource(R.drawable.unselect);
    }
}

I don't know this is best solution or not but this worked for me.

Android: where are downloaded files saved?

Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard (or some variation of that name) which is usually symlinked to to a directory in /storage like /storage/sdcard0 or /storage/0 sometimes the emulated storage is mounted to /sdcard and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Since the filesystems and sdcard support varies among devices.

see similar question for more info how to access downloads folder in android?

Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard

How to plot multiple functions on the same figure, in Matplotlib?

Perhaps a more pythonic way of doing so.

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

Pdf.js: rendering a pdf file using a base64 file source instead of url

from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js

/**
 * This is the main entry point for loading a PDF and interacting with it.
 * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
 * is used, which means it must follow the same origin rules that any XHR does
 * e.g. No cross domain requests without CORS.
 *
 * @param {string|TypedAray|object} source Can be an url to where a PDF is
 * located, a typed array (Uint8Array) already populated with data or
 * and parameter object with the following possible fields:
 *  - url   - The URL of the PDF.
 *  - data  - A typed array with PDF data.
 *  - httpHeaders - Basic authentication headers.
 *  - password - For decrypting password-protected PDFs.
 *
 * @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
 */

So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).

But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746

var BASE64_MARKER = ';base64,';

function convertDataURIToBinary(dataURI) {
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  var raw = window.atob(base64);
  var rawLength = raw.length;
  var array = new Uint8Array(new ArrayBuffer(rawLength));

  for(var i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

tl;dr

var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I dont know if you solved this issue, but i had same issue, if the instance is local you must check the permission to access the file, but if you are accessing from your computer to a server (remote access) you have to specify the path in the server, so that means to include the file in a server directory, that solved my case

example:

BULK INSERT Table
FROM 'C:\bulk\usuarios_prueba.csv' -- This is server path not local
WITH 
  (
     FIELDTERMINATOR =',',
     ROWTERMINATOR ='\n'
  );

The Use of Multiple JFrames: Good or Bad Practice?

I'd like to counter the "not user friendly" argument with an example that I have just been involved with.

In our application we have a main window where the users run various 'programs' as separate tabs. As much as possible we have tried to keep our application to this single window.

One of the 'programs' they run presents a list of reports that have been generated by the system, and the user can click on an icon on each line to pop open a report viewer dialog. This viewer is showing the equivalent of the portrait/landscape A4 page(s) of the report, so the users like this window to be quite big, almost filling their screens.

A few months ago we started getting requests from our customers to make these report viewer windows modeless, so that they could have multiple reports open at the same time.

For some time I resisted this request as I did not think this was a good solution. However, my mind was changed when I found out how the users were getting around this 'deficiency' of our system.

They were opening a viewer, using the 'Save As' facility to save the report as a PDF to a specific directory, using Acrobat Reader to open the PDF file, and then they would do the same with the next report. They would have multiple Acrobat Readers running with the various report outputs that they wanted to look at.

So I relented and made the viewer modeless. This means that each viewer has a task-bar icon.

When the latest version was released to them last week, the overwhelming response from them is that they LOVE it. It's been one of our most popular recent enhancements to the system.

So you go ahead and tell your users that what they want is bad, but ultimately it won't do you any favours.

SOME NOTES:

  • It seems to be best practice to use JDialog's for these modeless windows
  • Use the constructors that use the new ModalityType rather than the boolean modal argument. This is what gives these dialogs the task-bar icon.
  • For modeless dialogs, pass a null parent to the constructor, but locate them relative to their 'parent' window.
  • Version 6 of Java on Windows has a bug which means that your main window can become 'always on top' without you telling it. Upgrade to version 7 to fix this

Iterating a JavaScript object's properties using jQuery

$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

XMLHttpRequest module not defined/found

XMLHttpRequest is a built-in object in web browsers.

It is not distributed with Node; you have to install it separately,

  1. Install it with npm,

    npm install xmlhttprequest
    
  2. Now you can require it in your code.

    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    

That said, the http module is the built-in tool for making HTTP requests from Node.

Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.

How can I avoid running ActiveRecord callbacks?

You can use sneaky-save gem: https://rubygems.org/gems/sneaky-save.

Note this cannot help in saving associations along without validations. It throws error 'created_at cannot be null' as it directly inserts the sql query unlike a model. To implement this, we need to update all auto generated columns of db.

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
        ...
    }
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            doStuff();
            if(conditionToExitReceived) // what im waiting for...
                break;
        }
        //perform cleanup if there is any...
    }
}

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
    thread.start();
}
private void (startThread){
    new ThreadA(args).Run();
}

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

Laravel-5 how to populate select box from database with id value and name value

For Laravel 5 :

$items = Items::lists('name', 'id');

Push an item onto the beginning of the collection.

$items->prepend($value, $key = null);

Android Overriding onBackPressed()

Try This Its working

  @Override
public void onBackPressed(){
        super.onBackPressed();
         Intent i=new Intent(Intent.ACTION_MAIN);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        finish();
}

How to get table cells evenly spaced?

I'm also open to suggestion on how to tidy this up, if there are any? :-)

Well, you could not use the span element, for semantic reasons. And you don't have to define the class PerformanceCell. The cells and rows can be accessed by using PerformanceTable tr {} and PerformanceTable tr {}, respectively.

For the spacing part, I have got the same problem several times. I shamefully admit I avoided the problem, so I am very curious to any answers too.

How can I write a byte array to a file in Java?

         File file = ...
         byte[] data = ...
         try{
            FileOutputStream fos = FileOutputStream(file);
            fos.write(data);
            fos.flush();
            fos.close();
         }catch(Exception e){
          }

but if the bytes array length is more than 1024 you should use loop to write the data.

Easiest way to flip a boolean value?

This seems to be a free-for-all ... Heh. Here's another varation, which I guess is more in the category "clever" than something I'd recommend for production code:

flipVal ^= (wParam == VK_F11);
otherVal ^= (wParam == VK_F12);

I guess it's advantages are:

  • Very terse
  • Does not require branching

And a just as obvious disadvantage is

  • Very terse

This is close to @korona's solution using ?: but taken one (small) step further.

package javax.servlet.http does not exist

This error occurs when you compile a java program using classes that support the Servlet API. The compiler searches for the library (included in a .jar file) by using the CLASSPATH. You can specify this when you compile using -classpath or -cp options as noted in other responses, but you should set up your environment to define the classpath as needed.

Set the CLASSPATH environment variable to reference the location of servlet-api.jar, which depends on your setup (OS, how you installed, etc.)

Assuming you're using Tomcat and have installed it in one of 20 possible ways, the APIs used by servlets will be installed on your system, relative to wherever Tomcat is installed. For historical reasons, Tomcat is also known as "Catalina", so you can use the command "catalina" to run certain commands, and alone, it will report, amongst other things the CATALINA_BASE. For example on my Mac using Tomcat installed using homebrew it's

Using CATALINA_BASE:   /usr/local/Cellar/tomcat/8.5.9/libexec

The location of the Tomcat servlet libraries is under this in the lib directory. Set CATALINA_BASE, then set CLASSPATH using the base as a start, for example for Linux or OSX you might set this in .profile, or .bash_profile like so:

export CATALINA_BASE=/usr/local/Cellar/tomcat/8.5.9/libexec
export CLASSPATH=$CATALINA_BASE/lib/servlet-api.jar:$CLASSPATH

Exit the terminal/shell and come back in to run the profile. You should be able to see that the variable is set by using the echo command, e.g.

echo $CLASSPATH

or in Windows

echo %CLASSPATH%

If it displays the full path to the jar `javac WebTest.java' compile your class.

Other answers are correct -- set up your IDE (Eclipse, IntelliJ) to know about Tomcat or build with Maven and you'll save pain.

Convert System.Drawing.Color to RGB and Hex Value

e.g.

 ColorTranslator.ToHtml(Color.FromArgb(Color.Tomato.ToArgb()))

This can avoid the KnownColor trick.

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

varchar [ ( n | max ) ]

Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

Get generic type of class at runtime

As others mentioned, it's only possible via reflection in certain circumstances.

If you really need the type, this is the usual (type-safe) workaround pattern:

public class GenericClass<T> {

     private final Class<T> type;

     public GenericClass(Class<T> type) {
          this.type = type;
     }

     public Class<T> getMyType() {
         return this.type;
     }
}

Set IDENTITY_INSERT ON is not working

You might be just missing the column list, as the message says

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON

INSERT INTO [MyDB].[dbo].[Equipment]
            (COL1,
             COL2)
SELECT COL1,
       COL2
FROM   [MyDBQA].[dbo].[Equipment]

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF 

Fastest way to implode an associative array with keys

You can use http_build_query() to do that.

Generates a URL-encoded query string from the associative (or indexed) array provided.

How do I correctly clone a JavaScript object?

let clone = Object.assign( Object.create( Object.getPrototypeOf(obj)), obj)

ES6 solution if you want to (shallow) clone a class instance and not just a property object.

Remove spaces from a string in VB.NET

"Spaces" in the original post could refer to whitespace, and no answer yet shows how to remove ALL whitespace from a string. For that regular expressions are the most flexible approach I've found.

Below is a console application where you can see the difference between replacing just spaces or all whitespace.

You can find more about .NET regular expressions at http://msdn.microsoft.com/en-us/library/hs600312.aspx and http://msdn.microsoft.com/en-us/library/az24scfc.aspx

Imports System.Text.RegularExpressions
Module TestRegExp
    Sub Main()
        ' Use to match all whitespace (note the lowercase s matters)
        Dim regWhitespace As New Regex("\s")

        ' Use to match space characters only
        Dim regSpace As New Regex(" ")

        Dim testString As String = "First Line" + vbCrLf + _
        "Second line followed by 2 tabs" + vbTab + vbTab + _
        "End of tabs"

        Console.WriteLine("Test string :")
        Console.WriteLine(testString)

        Console.WriteLine("Replace all whitespace :")
        ' This prints the string on one line with no spacing at all
        Console.WriteLine(regWhitespace.Replace(testString, String.Empty))

        Console.WriteLine("Replace all spaces :")
        ' This removes spaces, but retains the tabs and new lines
        Console.WriteLine(regSpace.Replace(testString, String.Empty))

        Console.WriteLine("Press any key to finish")
        Console.ReadKey()
    End Sub
End Module

python for increment inner loop

for a in range(1):

    for b in range(3):
        a = b*2
        print(a)

As per your question, you want to iterate the outer loop with help of the inner loop.

  1. In outer loop, we are iterating the inner loop 1 time.
  2. In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.

    Output:
    0
    2
    4
    

add new element in laravel collection object

It looks like you have everything correct according to Laravel docs, but you have a typo

$item->push($product);

Should be

$items->push($product);

I also want to think the actual method you're looking for is put

$items->put('products', $product);

.NET unique object identifier

RuntimeHelpers.GetHashCode() may help (MSDN).

How to show alert message in mvc 4 controller?

It is not possible to display alerts from the controller. Because MVC views and controllers are entirely separated from each other. You can only display information in the view only. So it is required to pass the information to be displayed from controller to view by using either ViewBag, ViewData or TempData. If you are trying to display the content stored in TempData["Message"], It is possible to perform in the view page by adding few javascript lines.

<script>
  alert(@TempData["Message"]);
</script>

Properly escape a double quote in CSV

If a value contains a comma, a newline character or a double quote, then the string must be enclosed in double quotes. E.g: "Newline char in this field \n".

You can use below online tool to escape "" and , operators. https://www.freeformatter.com/csv-escape.html#ad-output

Python Infinity - Any caveats?

You can still get not-a-number (NaN) values from simple arithmetic involving inf:

>>> 0 * float("inf")
nan

Note that you will normally not get an inf value through usual arithmetic calculations:

>>> 2.0**2
4.0
>>> _**2
16.0
>>> _**2
256.0
>>> _**2
65536.0
>>> _**2
4294967296.0
>>> _**2
1.8446744073709552e+19
>>> _**2
3.4028236692093846e+38
>>> _**2
1.157920892373162e+77
>>> _**2
1.3407807929942597e+154
>>> _**2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
OverflowError: (34, 'Numerical result out of range')

The inf value is considered a very special value with unusual semantics, so it's better to know about an OverflowError straight away through an exception, rather than having an inf value silently injected into your calculations.

How to create border in UIButton?

The problem setting the layer's borderWidth and borderColor is that the when you touch the button the border doesn't animate the highlight effect.

Of course, you can observe the button's events and change the border color accordingly but that feels unnecessary.

Another option is to create a stretchable UIImage and setting it as the button's background image. You can create an Image set in your Images.xcassets like this:

Images.xcassets

Then, you set it as the button's background image:

Button properties

If your image is a template image you can set tint color of the button and the border will change:

Final Button

Now the border will highlight with the rest of the button when touched.

Powershell remoting with ip-address as target

On your machine* run 'Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$ipaddress"

*Machine from where you are running PSSession

How to use registerReceiver method?

The whole code if somebody need it.

void alarm(Context context, Calendar calendar) {
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);

    final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
    IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

    AlarmReceiver mReceiver = new AlarmReceiver();
    context.registerReceiver(mReceiver, intentFilter);

    Intent anotherIntent = new Intent(SOME_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
    alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

    Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}

class AlarmReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent arg1) {
        Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
    }
}

How should I load files into my Java application?

public byte[] loadBinaryFile (String name) {
    try {

        DataInputStream dis = new DataInputStream(new FileInputStream(name));
        byte[] theBytes = new byte[dis.available()];
        dis.read(theBytes, 0, dis.available());
        dis.close();
        return theBytes;
    } catch (IOException ex) {
    }
    return null;
} // ()

plot different color for different categorical levels using matplotlib

You can convert the categorical column into a numerical one by using the commands:

#we converting it into categorical data
cat_col = df['column_name'].astype('categorical') 

#we are getting codes for it 
cat_col = cat_col.cat.codes 

# we are using c parameter to change the color.
plt.scatter(df['column1'],df['column2'], c=cat_col) 

How to write a basic swap function in Java

Swapping by using pointer is not possible in java. However, you can implement swapping by passing array containing two objects.

Code goes like this:

public class Swap {
    public static void swap(String [] a){
        String temp;
        temp = a[0];
        a[0] = a[1];
        a[1] = temp;
    }
    public static void main(String [] args){
        String [] foo = new String[2];
        foo[0] = "str1";
        foo[1] = "str2";
        swap(foo);
        System.out.println("First value: "+ foo[0]);
        System.out.println("Second value: "+ foo[1]);
    }
}

Output:

First value: str2
Second value: str1

Ignore cells on Excel line graph

if the data is the result of a formula, then it will never be empty (even if you set it to ""), as having a formula is not the same as an empty cell

There are 2 methods, depending on how static the data is.

The easiest fix is to clear the cells that return empty strings, but that means you will have to fix things if data changes

the other fix involves a little editing of the formula, so instead of setting it equal to "", you set it equal to NA().
For example, if you have =IF(A1=0,"",B1/A1), you would change that to =IF(A1=0,NA(),B1/A1).
This will create the gaps you desire, and will also reflect updates to the data so you don't have to keep fixing it every time

How to format a string as a telephone number in C#

Try this

string result;
if ( (!string.IsNullOrEmpty(phoneNumber)) && (phoneNumber.Length >= 10 ) )
    result = string.Format("{0:(###)###-"+new string('#',phoneNumber.Length-6)+"}",
    Convert.ToInt64(phoneNumber)
    );
else
    result = phoneNumber;
return result;

Cheers.

What are WSDL, SOAP and REST?

A WSDL document describes a webservice. It specifies the location of the service and the methods of the service using these major elements: data types using in webservice data elements for each operation describe the operations that can be performed and the messages envolved

SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate operating systems to communicate using http and xml.

SQL Server check case-sensitivity?

SQL Server is not case sensitive. SELECT * FROM SomeTable is the same as SeLeCT * frOM soMetaBLe.

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

Alternative solution that uses .query() method:

In [5]: df.query("countries in @countries")
Out[5]:
  countries
1        UK
3     China

In [6]: df.query("countries not in @countries")
Out[6]:
  countries
0        US
2   Germany

Script Tag - async & defer

I think Jake Archibald presented us some insights back in 2013 that might add even more positiveness to the topic:

https://www.html5rocks.com/en/tutorials/speed/script-loading/

The holy grail is having a set of scripts download immediately without blocking rendering and execute as soon as possible in the order they were added. Unfortunately HTML hates you and won’t let you do that.

(...)

The answer is actually in the HTML5 spec, although it’s hidden away at the bottom of the script-loading section. "The async IDL attribute controls whether the element will execute asynchronously or not. If the element's "force-async" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "force-async" flag must first be unset…".

(...)

Scripts that are dynamically created and added to the document are async by default, they don’t block rendering and execute as soon as they download, meaning they could come out in the wrong order. However, we can explicitly mark them as not async:

[
    '//other-domain.com/1.js',
    '2.js'
].forEach(function(src) {
    var script = document.createElement('script');
    script.src = src;
    script.async = false;
    document.head.appendChild(script);
});

This gives our scripts a mix of behaviour that can’t be achieved with plain HTML. By being explicitly not async, scripts are added to an execution queue, the same queue they’re added to in our first plain-HTML example. However, by being dynamically created, they’re executed outside of document parsing, so rendering isn’t blocked while they’re downloaded (don’t confuse not-async script loading with sync XHR, which is never a good thing).

The script above should be included inline in the head of pages, queueing script downloads as soon as possible without disrupting progressive rendering, and executes as soon as possible in the order you specified. “2.js” is free to download before “1.js”, but it won’t be executed until “1.js” has either successfully downloaded and executed, or fails to do either. Hurrah! async-download but ordered-execution!

Still, this might not be the fastest way to load scripts:

(...) With the example above the browser has to parse and execute script to discover which scripts to download. This hides your scripts from preload scanners. Browsers use these scanners to discover resources on pages you’re likely to visit next, or discover page resources while the parser is blocked by another resource.

We can add discoverability back in by putting this in the head of the document:

<link rel="subresource" href="//other-domain.com/1.js">
<link rel="subresource" href="2.js">

This tells the browser the page needs 1.js and 2.js. link[rel=subresource] is similar to link[rel=prefetch], but with different semantics. Unfortunately it’s currently only supported in Chrome, and you have to declare which scripts to load twice, once via link elements, and again in your script.

Correction: I originally stated these were picked up by the preload scanner, they're not, they're picked up by the regular parser. However, preload scanner could pick these up, it just doesn't yet, whereas scripts included by executable code can never be preloaded. Thanks to Yoav Weiss who corrected me in the comments.

Settings to Windows Firewall to allow Docker for Windows to share drive

I was not using any third party firewalls when running into this error. I was convinced it was a Windows Firewall issue, though disabling Windows Firewall did not work for me. I finally found this blog post after much research: Docker on windows 10 error: A firewall is blocking file Sharing ...

It ended up NOT having to do with the built in Windows Firewall.

The Fix

  1. Uncheck File and Printer Sharing for Microsoft Networks from the vEthernet (DockerNAT) network adapter (you can find the connection in the Windows Network and Sharing Center).
  2. Recheck it and make sure it is enabled.

.NET String.Format() to add commas in thousands place for a number

The most voted answer was great and has been helpful for about 7 years. With the introduction of C# 6.0 and specifically the String Interpolation there's a neater and, IMO safer, way to do what has been asked to add commas in thousands place for a number:

var i = 5222000;
var s = $"{i:n} is the number"; // results to > 5,222,000.00 is the number
s = $"{i:n0} has no decimal"; // results to > 5,222,000 has no decimal

Where the variable i is put in place of the placeholder (i.e. {0}). So there's no need to remember which object goes to which position. The formatting (i.e. :n) hasn't changed. For a complete feature of what's new, you may go to this page.

Failed to connect to mailserver at "localhost" port 25

Change SMTP=localhost to SMTP=smtp.gmail.com

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

Yes you can:

Use this method to prevent errors:

<script> 
query=location.hash;
document.cookie= 'anchor'+query;
</script>

And of course in PHP, explode that puppy and get one of the values

$split = explode('/', $_COOKIE['anchor']);
print_r($split[1]); //to test it, use print_r. this line will print the value after the anchortag

adding and removing classes in angularJs using ng-click

I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):

<div class="form-group col-md-12">
    <div ng-class="{'bg-info':     (!transport_type)}"    ng-click="transport_type=false">CARS</div>
    <div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
    <div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>

PostgreSQL: Show tables in PostgreSQL

To view foreign tables in psql, run \dE

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

The following technique worked for me:

1) Right click on the project Solution -> Click on Clean solution

2) Right click on the project Solution -> Click on Rebuild solution

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

Using this code to multiple order by in single query.

$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get(); 
return $query->result();

C# constructors overloading

public Point2D(Point2D point) : this(point.X, point.Y) { }

How do I use PHP to get the current year?

If you are using the Carbon PHP API extension for DateTime, you can achieve it easy:

<?php echo Carbon::now()->year; ?>

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

The error message is misleading. The problem has nothing to do with symlinks really. It is usually only that docker cannot find the Dockerfile describing the build.

Typical reasons are these:

  • Dockerfile has wrong name.
    It must be called Dockerfile. If it is called, for instance, dockerfile, .Dockerfile, Dockerfile.txt, or other, it will not be found.
  • Dockerfile is not in context.
    If you say docker build contextdir, the Dockerfile must be at contextdir/Dockerfile. If you have it in, say, ./Dockerfile instead, it will not be found.
  • Dockerfile does not exist at all.
    Sounds silly? Well, I got the above error message from my GitLab CI after I had written a nice Dockerfile, but forgotten to check it in. Silly? Sure. Unlikely? No.

Counting number of characters in a file through shell script

The following script is tested and gives exactly the results, that are expected

\#!/bin/bash

echo "Enter the file name"

read file

echo "enter the word to be found"

read word

count=0

for i in \`cat $file`

do

if [ $i == $word ]

then

count=\`expr $count + 1`

fi

done

echo "The number of words are $count"

How do I retrieve an HTML element's actual width and height?

... seems CSS help to put div on center ...

<style>
 .monitor {
 position:fixed;/* ... absolute possible if on :root */
 top:0;bottom:0;right:0;left:0;
 visibility:hidden;
 }
 .wrapper {
 width:200px;/* this is size range */
 height:100px;
 position:absolute;
 left:50%;top:50%;
 visibility:hidden;
 }

 .content {
 position:absolute;
 width: 100%;height:100%;
 left:-50%;top:-50%;
 visibility:visible;
 }

</style>

 <div class="monitor">
  <div class="wrapper">
   <div class="content">

 ... so you hav div 200px*100px on center ...

  </div>
 </div>
</div>

Java: Detect duplicates in ArrayList?

Improved code, using return value of Set#add instead of comparing the size of list and set.

public static <T> boolean hasDuplicate(Iterable<T> all) {
    Set<T> set = new HashSet<T>();
    // Set#add returns false if the set does not change, which
    // indicates that a duplicate element has been added.
    for (T each: all) if (!set.add(each)) return true;
    return false;
}

best practice to generate random token for forgot password

The earlier version of the accepted answer (md5(uniqid(mt_rand(), true))) is insecure and only offers about 2^60 possible outputs -- well within the range of a brute force search in about a week's time for a low-budget attacker:

Since a 56-bit DES key can be brute-forced in about 24 hours, and an average case would have about 59 bits of entropy, we can calculate 2^59 / 2^56 = about 8 days. Depending on how this token verification is implemented, it might be possible to practically leak timing information and infer the first N bytes of a valid reset token.

Since the question is about "best practices" and opens with...

I want to generate identifier for forgot password

...we can infer that this token has implicit security requirements. And when you add security requirements to a random number generator, the best practice is to always use a cryptographically secure pseudorandom number generator (abbreviated CSPRNG).


Using a CSPRNG

In PHP 7, you can use bin2hex(random_bytes($n)) (where $n is an integer larger than 15).

In PHP 5, you can use random_compat to expose the same API.

Alternatively, bin2hex(mcrypt_create_iv($n, MCRYPT_DEV_URANDOM)) if you have ext/mcrypt installed. Another good one-liner is bin2hex(openssl_random_pseudo_bytes($n)).

Separating the Lookup from the Validator

Pulling from my previous work on secure "remember me" cookies in PHP, the only effective way to mitigate the aforementioned timing leak (typically introduced by the database query) is to separate the lookup from the validation.

If your table looks like this (MySQL)...

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id)
);

... you need to add one more column, selector, like so:

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    selector CHAR(16),
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id),
    KEY(selector)
);

Use a CSPRNG When a password reset token is issued, send both values to the user, store the selector and a SHA-256 hash of the random token in the database. Use the selector to grab the hash and User ID, calculate the SHA-256 hash of the token the user provides with the one stored in the database using hash_equals().

Example Code

Generating a reset token in PHP 7 (or 5.6 with random_compat) with PDO:

$selector = bin2hex(random_bytes(8));
$token = random_bytes(32);

$urlToEmail = 'http://example.com/reset.php?'.http_build_query([
    'selector' => $selector,
    'validator' => bin2hex($token)
]);

$expires = new DateTime('NOW');
$expires->add(new DateInterval('PT01H')); // 1 hour

$stmt = $pdo->prepare("INSERT INTO account_recovery (userid, selector, token, expires) VALUES (:userid, :selector, :token, :expires);");
$stmt->execute([
    'userid' => $userId, // define this elsewhere!
    'selector' => $selector,
    'token' => hash('sha256', $token),
    'expires' => $expires->format('Y-m-d\TH:i:s')
]);

Verifying the user-provided reset token:

$stmt = $pdo->prepare("SELECT * FROM account_recovery WHERE selector = ? AND expires >= NOW()");
$stmt->execute([$selector]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($results)) {
    $calc = hash('sha256', hex2bin($validator));
    if (hash_equals($calc, $results[0]['token'])) {
        // The reset token is valid. Authenticate the user.
    }
    // Remove the token from the DB regardless of success or failure.
}

These code snippets are not complete solutions (I eschewed the input validation and framework integrations), but they should serve as an example of what to do.

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

You would have to use the JavascriptExecutor class:

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");

What does a just-in-time (JIT) compiler do?

JVM actually performs compilation steps during runtime for performance reasons. This means that Java doesn't have a clean compile-execution separation. It first does a so called static compilation from Java source code to bytecode. Then this bytecode is passed to the JVM for execution. But executing bytecode is slow so the JVM measures how often the bytecode is run and when it detects a "hotspot" of code that's run very frequently it performs dynamic compilation from bytecode to machinecode of the "hotspot" code (hotspot profiler). So effectively today Java programs are run by machinecode execution.

Swift: Testing optionals for nil

Swift 5 Protocol Extension

Here is an approach using protocol extension so that you can easily inline an optional nil check:

import Foundation

public extension Optional {

    var isNil: Bool {

        guard case Optional.none = self else {
            return false
        }

        return true

    }

    var isSome: Bool {

        return !self.isNil

    }

}

Usage

var myValue: String?

if myValue.isNil {
    // do something
}

if myValue.isSome {
    // do something
}

How to use "Share image using" sharing Intent to share images in android?

All the Above solution doesnot work for me in Android Api 26 & 27 (Oreo), was gettting Error: exposed beyond app through ClipData.Item.getUri. The solution that fits in my situation was

  1. get path uri using FileProvider.getUriForFile(Context,packagename,File) as
void shareImage() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,getPackageName(),deleteFilePath));
        startActivity(Intent.createChooser(intent,"Share with..."));
    }
  1. Define a <provider> in your Manifest.xml as
<provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="com.example.stickerapplication"
      android:exported="false"
      android:grantUriPermissions="true">
      <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths">
       </meta-data>
</provider>
  1. And the last step is to define resource file for your directorys
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>
*Note this solution is for `external storage` `uri`

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I have encountered this problem twice. First time I used VS 2013 and the second time I used VS 2015 with different solution. The first solution on VS 2013 and python 2.7 is:

  1. Click win+R
  2. Enter SET VS90COMNTOOLS=%VS120COMNTOOLS%
  3. Close all windows
  4. Enter pip install again

Now, one year later, I have found an easier method to fix it. This time I use VS 2015 and python 3.4.

  1. Right click on My Computer.
  2. Click Properties
  3. Advanced system settings
  4. Environment variables
  5. Add New system variable
  6. Enter VS100COMNTOOLSto the variable name
  7. Enter the value of VS140COMNTOOLSto the new variable.
  8. Close all windows

Now I'm sure you will ask some question what is the VSXXXCOMNTOOLSand what should I do if I use VS2008 or other compiler.

There is a file python\Lib\distutils\msvc9compiler.py, beginning on line 216 we see

def find_vcvarsall(version):
    """Find the vcvarsall.bat file
    At first it tries to find the productdir of VS 2010 in the registry. If
    that fails it falls back to the VS100COMNTOOLS env var.
    """

It means that you must give the productdir of VS 2010 for it, so if you are using python 2.x and

  • Visual Studio 2010 (VS10):SET VS90COMNTOOLS=%VS100COMNTOOLS%
  • Visual Studio 2012 (VS11):SET VS90COMNTOOLS=%VS110COMNTOOLS%
  • Visual Studio 2013 (VS12):SET VS90COMNTOOLS=%VS120COMNTOOLS%
  • Visual Studio 2015 (VS15):SET VS90COMNTOOLS=%VS140COMNTOOLS%

or if you are using python 3.x and

  • Visual Studio 2010 (VS10):SET VS100COMNTOOLS=%VS100COMNTOOLS%
  • Visual Studio 2012 (VS11):SET VS100COMNTOOLS=%VS110COMNTOOLS%
  • Visual Studio 2013 (VS12):SET VS100COMNTOOLS=%VS120COMNTOOLS%
  • Visual Studio 2015 (VS15):SET VS100COMNTOOLS=%VS140COMNTOOLS%

And it's the same as adding a new system variable. See the second ways.

Update:Sometimes,it still doesn't work.Check your path,ensure that contains VSxxxCOMNTOOLS

Python: Checking if a 'Dictionary' is empty doesn't seem to work

dict = {}
print(len(dict.keys()))

if length is zero means that dict is empty

'True' and 'False' in Python

While the other posters addressed why is True does what it does, I wanted to respond to this part of your post:

I thought Python treats anything with value as True. Why is this happening?

Coming from Java, I got tripped up by this, too. Python does not treat anything with a value as True. Witness:

if 0:
    print("Won't get here")

This will print nothing because 0 is treated as False. In fact, zero of any numeric type evaluates to False. They also made decimal work the way you'd expect:

from decimal import *
from fractions import *

if 0 or 0.0 or 0j or Decimal(0) or Fraction(0, 1):
    print("Won't get here")

Here are the other value which evaluate to False:

if None or False or '' or () or [] or {} or set() or range(0):
    print("Won't get here")

Sources:

  1. Python Truth Value Testing is Awesome
  2. Truth Value Testing (in Built-in Types)

Automatically add all files in a folder to a target using CMake?

Extension for @Kleist answer:

Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB) and file(GLOB_RECURSE). With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.

However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.

Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB) or file(GLOB_RECURSE) for collect the sources.

How to insert close button in popover for Bootstrap

The trick is to get the current Popover with .data('bs.popover').tip():

$('#my_trigger').popover().on('shown.bs.popover', function() {
    // Define elements
    var current_trigger=$(this);
    var current_popover=current_trigger.data('bs.popover').tip();

    // Activate close button
    current_popover.find('button.close').click(function() {
        current_trigger.popover('hide');
    });
});

What permission do I need to access Internet from an Android application?

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Is there a difference between using a dict literal and a dict constructor?

I think you have pointed out the most obvious difference. Apart from that,

the first doesn't need to lookup dict which should make it a tiny bit faster

the second looks up dict in locals() and then globals() and the finds the builtin, so you can switch the behaviour by defining a local called dict for example although I can't think of anywhere this would be a good idea apart from maybe when debugging

How can I completely remove TFS Bindings

Sometime, the binding info is cached

To clear Team Explorer's cache:

Go to C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\2.0
Delete or rename the Cache folder.

This come from a website I could not find now. Thanks for that guy for the tip.

What is the bit size of long on 64-bit Windows?

Microsoft has also defined UINT_PTR and INT_PTR for integers that are the same size as a pointer.

Here is a list of Microsoft specific types - it's part of their driver reference, but I believe it's valid for general programming as well.

How can I determine the status of a job?

This is what I'm using to get the running jobs (principally so I can kill the ones which have probably hung):

SELECT
    job.Name, job.job_ID
    ,job.Originating_Server
    ,activity.run_requested_Date
    ,datediff(minute, activity.run_requested_Date, getdate()) AS Elapsed
FROM
    msdb.dbo.sysjobs_view job 
        INNER JOIN msdb.dbo.sysjobactivity activity
        ON (job.job_id = activity.job_id)
WHERE
    run_Requested_date is not null 
    AND stop_execution_date is null
    AND job.name like 'Your Job Prefix%'

As Tim said, the MSDN / BOL documentation is reasonably good on the contents of the sysjobsX tables. Just remember they are tables in MSDB.

Could not find module "@angular-devkit/build-angular"

Just update the angular version and add the below dependency:

ng update

npm update

npm i @angular-devkit/build-angular

https://www.npmjs.com/package/@angular-devkit/build-angular

How to get the Parent's parent directory in Powershell?

You can use

(get-item $scriptPath).Directoryname

to get the string path or if you want the Directory type use:

(get-item $scriptPath).Directory

Use string value from a cell to access worksheet of same name

By using the ROW() function I can drag this formula vertically. It can also be dragged horizontally since there is no $ before the D.

= INDIRECT("'"&D$2&"'!$B"&ROW())

My layout has sheet names as column headers (B2, C2, D2, etc.) and maps multiple row values from Column B in each sheet.

Description for event id from source cannot be found

Improving on the answer by @Alex, I suggest the following:

            using (EventLog eventLog = new EventLog("Application"))
            {
                //You cannot be sure if the current identity has permissions to register the event source.
                try
                {
                    if (System.Web.HttpRuntime.AppDomainAppId != null)
                    {
                        eventLog.Source = System.Web.HttpRuntime.AppDomainAppId;
                    }
                    else
                    {
                        eventLog.Source = Process.GetCurrentProcess().ProcessName;
                    }
                }
                catch (SecurityException)
                {
                    eventLog.Source = "Application";
                }

                eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 1000);
            }

It is important here not to specify category parameter. If you do, and this is the same for the .NET Runtime so-called magic, the

The description for Event ID <...> from source <...> cannot be found.

is going to appear.

How do I plot only a table in Matplotlib?

If you just wanted to change the example and put the table at the top, then loc='top' in the table declaration is what you need,

the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

Then adjusting the plot with,

plt.subplots_adjust(left=0.2, top=0.8)

A more flexible option is to put the table in its own axis using subplots,

import numpy as np
import matplotlib.pyplot as plt


fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

which looks like this,

enter image description here

You are then free to adjust the locations of the axis as required.

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

Calculate average in java

 System.out.println(result/count) 

you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:

double avg = (double)result / (double)args.length

There are No resources that can be added or removed from the server

Check whether your Java version is compatible with the project. Right click the project>>Properties>>Project Facets>>Java check the version is compatible with your project.

I don't understand -Wl,-rpath -Wl,

You could also write

-Wl,-rpath=.

To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).

Updating MySQL primary key

Next time, use a single "alter table" statement to update the primary key.

alter table xx drop primary key, add primary key(k1, k2, k3);

To fix things:

create table fixit (user_2, user_1, type, timestamp, n, primary key( user_2, user_1, type) );
lock table fixit write, user_interactions u write, user_interactions write;

insert into fixit 
select user_2, user_1, type, max(timestamp), count(*) n from user_interactions u 
group by user_2, user_1, type
having n > 1;

delete u from user_interactions u, fixit 
where fixit.user_2 = u.user_2 
  and fixit.user_1 = u.user_1 
  and fixit.type = u.type 
  and fixit.timestamp != u.timestamp;

alter table user_interactions add primary key (user_2, user_1, type );

unlock tables;

The lock should stop further updates coming in while your are doing this. How long this takes obviously depends on the size of your table.

The main problem is if you have some duplicates with the same timestamp.

Android Device not recognized by adb

For those people to whom none of the answers worked.... try closing the chrome://inspect/#devices tab in chrome if opened... This worked for me.

Clear ComboBox selected text

In c# if you make you comboBox configuration style DropDownList or DropDown then use both of them in this method to clear.

ComboBox1.SelectedIndex = -1;

A top-like utility for monitoring CUDA activity on a GPU

You can use the monitoring program glances with its GPU monitoring plug-in:

  • open source
  • to install: sudo apt-get install -y python-pip; sudo pip install glances[gpu]
  • to launch: sudo glances

enter image description here

It also monitors the CPU, disk IO, disk space, network, and a few other things:

enter image description here

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)

further,

char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

Syntax for if/else condition in SCSS mixin

You could default the parameter to null or false.
This way, it would be shorter to test if a value has been passed as parameter.

@mixin clearfix($width: null) {

  @if not ($width) {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

mat-form-field must contain a MatFormFieldControl

import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

don't forget to add at first of <tabe></table>

 <mat-form-field>
        <mat-label>Filter</mat-label>
        <input matInput (keyup)="applyFilter($event)" placeholder="Ex. Helium" #input>
      </mat-form-field>

don't forget to add at last of <tabe></table>

<tr class="mat-row" *matNoDataRow>
<td class="mat-cell" colspan="4">
   No data matching the filter "{{input.value}}"
</td>
</tr>

Finding second occurrence of a substring in a string in Java

int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

How to enable support of CPU virtualization on Macbook Pro?

Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.

How to check that Intel VT-x is supported in CPU:

  1. Open Terminal application from Application/Utilities

  2. Copy/paste command bellow

sysctl -a | grep machdep.cpu.features

  1. You may see output similar to:

Mac:~ user$ sysctl -a | grep machdep.cpu.features kern.exec: unknown type returned machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM

If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.

Refer to this link on Apple.com to enable hardware support for virtualization:

android - how to convert int to string and place it in a EditText?

try Integer.toString(integer value); method as

ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));

How to store a datetime in MySQL with timezone info

You said:

I want them to always come out as Tanzanian time and not in the local times that various collaborator are in.

If this is the case, then you should not use UTC. All you need to do is to use a DATETIME type in MySQL instead of a TIMESTAMP type.

From the MySQL documentation:

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)

If you are already using a DATETIME type, then you must be not setting it by the local time to begin with. You'll need to focus less on the database, and more on your application code - which you didn't show here. The problem, and the solution, will vary drastically depending on language, so be sure to tag the question with the appropriate language of your application code.

How can I get enum possible values in a MySQL database?

Here is the same function given by Patrick Savalle adapted for the framework Laravel

function get_enum_values($table, $field)
{

   $test=DB::select(DB::raw("show columns from {$table} where field = '{$field}'"));

   preg_match('/^enum\((.*)\)$/', $test[0]->Type, $matches);
   foreach( explode(',', $matches[1]) as $value )
   {
       $enum[] = trim( $value, "'" );   
   }

   return $enum;

}

Moving Average Pandas

In case you are calculating more than one moving average:

for i in range(2,10):
   df['MA{}'.format(i)] = df.rolling(window=i).mean()

Then you can do an aggregate average of all the MA

df[[f for f in list(df) if "MA" in f]].mean(axis=1)